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, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *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 6144 of file costsize.c.

6146 {
6147  Cost indexTotalCost;
6148  Selectivity indexSelectivity;
6149  double T;
6150  double pages_fetched;
6151  double tuples_fetched;
6152  double heap_pages;
6153  long maxentries;
6154 
6155  /*
6156  * Fetch total cost of obtaining the bitmap, as well as its total
6157  * selectivity.
6158  */
6159  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6160 
6161  /*
6162  * Estimate number of main-table pages fetched.
6163  */
6164  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6165 
6166  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6167 
6168  /*
6169  * For a single scan, the number of heap pages that need to be fetched is
6170  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6171  * re-reads needed).
6172  */
6173  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6174 
6175  /*
6176  * Calculate the number of pages fetched from the heap. Then based on
6177  * current work_mem estimate get the estimated maxentries in the bitmap.
6178  * (Note that we always do this calculation based on the number of pages
6179  * that would be fetched in a single iteration, even if loop_count > 1.
6180  * That's correct, because only that number of entries will be stored in
6181  * the bitmap at one time.)
6182  */
6183  heap_pages = Min(pages_fetched, baserel->pages);
6184  maxentries = tbm_calculate_entries(work_mem * 1024L);
6185 
6186  if (loop_count > 1)
6187  {
6188  /*
6189  * For repeated bitmap scans, scale up the number of tuples fetched in
6190  * the Mackert and Lohman formula by the number of scans, so that we
6191  * estimate the number of pages fetched by all the scans. Then
6192  * pro-rate for one scan.
6193  */
6194  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6195  baserel->pages,
6196  get_indexpath_pages(bitmapqual),
6197  root);
6198  pages_fetched /= loop_count;
6199  }
6200 
6201  if (pages_fetched >= T)
6202  pages_fetched = T;
6203  else
6204  pages_fetched = ceil(pages_fetched);
6205 
6206  if (maxentries < heap_pages)
6207  {
6208  double exact_pages;
6209  double lossy_pages;
6210 
6211  /*
6212  * Crude approximation of the number of lossy pages. Because of the
6213  * way tbm_lossify() is coded, the number of lossy pages increases
6214  * very sharply as soon as we run short of memory; this formula has
6215  * that property and seems to perform adequately in testing, but it's
6216  * possible we could do better somehow.
6217  */
6218  lossy_pages = Max(0, heap_pages - maxentries / 2);
6219  exact_pages = heap_pages - lossy_pages;
6220 
6221  /*
6222  * If there are lossy pages then recompute the number of tuples
6223  * processed by the bitmap heap node. We assume here that the chance
6224  * of a given tuple coming from an exact page is the same as the
6225  * chance that a given page is exact. This might not be true, but
6226  * it's not clear how we can do any better.
6227  */
6228  if (lossy_pages > 0)
6229  tuples_fetched =
6230  clamp_row_est(indexSelectivity *
6231  (exact_pages / heap_pages) * baserel->tuples +
6232  (lossy_pages / heap_pages) * baserel->tuples);
6233  }
6234 
6235  if (cost)
6236  *cost = indexTotalCost;
6237  if (tuple)
6238  *tuple = tuples_fetched;
6239 
6240  return pages_fetched;
6241 }
#define Min(x, y)
Definition: c.h:988
#define Max(x, y)
Definition: c.h:982
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:869
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1085
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:934
double clamp_row_est(double nrows)
Definition: costsize.c:202
int work_mem
Definition: globals.c:125
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:938
BlockNumber pages
Definition: pathnodes.h:937
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 4729 of file costsize.c.

4737 {
4738  Selectivity jselec;
4739  Selectivity nselec;
4740  Selectivity avgmatch;
4741  SpecialJoinInfo norm_sjinfo;
4742  List *joinquals;
4743  ListCell *l;
4744 
4745  /*
4746  * In an ANTI join, we must ignore clauses that are "pushed down", since
4747  * those won't affect the match logic. In a SEMI join, we do not
4748  * distinguish joinquals from "pushed down" quals, so just use the whole
4749  * restrictinfo list. For other outer join types, we should consider only
4750  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4751  */
4752  if (IS_OUTER_JOIN(jointype))
4753  {
4754  joinquals = NIL;
4755  foreach(l, restrictlist)
4756  {
4757  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4758 
4759  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4760  joinquals = lappend(joinquals, rinfo);
4761  }
4762  }
4763  else
4764  joinquals = restrictlist;
4765 
4766  /*
4767  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4768  */
4769  jselec = clauselist_selectivity(root,
4770  joinquals,
4771  0,
4772  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4773  sjinfo);
4774 
4775  /*
4776  * Also get the normal inner-join selectivity of the join clauses.
4777  */
4778  norm_sjinfo.type = T_SpecialJoinInfo;
4779  norm_sjinfo.min_lefthand = outerrel->relids;
4780  norm_sjinfo.min_righthand = innerrel->relids;
4781  norm_sjinfo.syn_lefthand = outerrel->relids;
4782  norm_sjinfo.syn_righthand = innerrel->relids;
4783  norm_sjinfo.jointype = JOIN_INNER;
4784  norm_sjinfo.ojrelid = 0;
4785  norm_sjinfo.commute_above_l = NULL;
4786  norm_sjinfo.commute_above_r = NULL;
4787  norm_sjinfo.commute_below = NULL;
4788  /* we don't bother trying to make the remaining fields valid */
4789  norm_sjinfo.lhs_strict = false;
4790  norm_sjinfo.semi_can_btree = false;
4791  norm_sjinfo.semi_can_hash = false;
4792  norm_sjinfo.semi_operators = NIL;
4793  norm_sjinfo.semi_rhs_exprs = NIL;
4794 
4795  nselec = clauselist_selectivity(root,
4796  joinquals,
4797  0,
4798  JOIN_INNER,
4799  &norm_sjinfo);
4800 
4801  /* Avoid leaking a lot of ListCells */
4802  if (IS_OUTER_JOIN(jointype))
4803  list_free(joinquals);
4804 
4805  /*
4806  * jselec can be interpreted as the fraction of outer-rel rows that have
4807  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4808  * the fraction of the Cartesian product that matches. So, the average
4809  * number of matches for each outer-rel row that has at least one match is
4810  * nselec * inner_rows / jselec.
4811  *
4812  * Note: it is correct to use the inner rel's "rows" count here, even
4813  * though we might later be considering a parameterized inner path with
4814  * fewer rows. This is because we have included all the join clauses in
4815  * the selectivity estimate.
4816  */
4817  if (jselec > 0) /* protect against zero divide */
4818  {
4819  avgmatch = nselec * innerrel->rows / jselec;
4820  /* Clamp to sane range */
4821  avgmatch = Max(1.0, avgmatch);
4822  }
4823  else
4824  avgmatch = 1.0;
4825 
4826  semifactors->outer_match_frac = jselec;
4827  semifactors->match_count = avgmatch;
4828 }
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:347
@ 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:2668
#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:866
Cardinality rows
Definition: pathnodes.h:872
Selectivity outer_match_frac
Definition: pathnodes.h:3145
Selectivity match_count
Definition: pathnodes.h:3146
Relids commute_above_r
Definition: pathnodes.h:2838
Relids syn_lefthand
Definition: pathnodes.h:2833
Relids min_righthand
Definition: pathnodes.h:2832
List * semi_rhs_exprs
Definition: pathnodes.h:2845
Relids commute_above_l
Definition: pathnodes.h:2837
JoinType jointype
Definition: pathnodes.h:2835
Relids commute_below
Definition: pathnodes.h:2839
Relids min_lefthand
Definition: pathnodes.h:2831
Relids syn_righthand
Definition: pathnodes.h:2834
List * semi_operators
Definition: pathnodes.h:2844

References clauselist_selectivity(), SpecialJoinInfo::commute_above_l, SpecialJoinInfo::commute_above_r, SpecialJoinInfo::commute_below, 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 2619 of file costsize.c.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2896 {
2897  double output_tuples;
2898  Cost startup_cost;
2899  Cost total_cost;
2900 
2901  output_tuples = numGroups;
2902  startup_cost = input_startup_cost;
2903  total_cost = input_total_cost;
2904 
2905  /*
2906  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2907  * all columns get compared at most of the tuples.
2908  */
2909  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2910 
2911  /*
2912  * If there are quals (HAVING quals), account for their cost and
2913  * selectivity.
2914  */
2915  if (quals)
2916  {
2917  QualCost qual_cost;
2918 
2919  cost_qual_eval(&qual_cost, quals, root);
2920  startup_cost += qual_cost.startup;
2921  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2922 
2923  output_tuples = clamp_row_est(output_tuples *
2925  quals,
2926  0,
2927  JOIN_INNER,
2928  NULL));
2929  }
2930 
2931  path->rows = output_tuples;
2932  path->startup_cost = startup_cost;
2933  path->total_cost = total_cost;
2934 }

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

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

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

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

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

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

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

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

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

4368 {
4369  cost_qual_eval_context context;
4370  ListCell *l;
4371 
4372  context.root = root;
4373  context.total.startup = 0;
4374  context.total.per_tuple = 0;
4375 
4376  /* We don't charge any cost for the implicit ANDing at top level ... */
4377 
4378  foreach(l, quals)
4379  {
4380  Node *qual = (Node *) lfirst(l);
4381 
4382  cost_qual_eval_walker(qual, &context);
4383  }
4384 
4385  *cost = context.total;
4386 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4407
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 1784 of file costsize.c.

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

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

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

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

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

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

2100 {
2101  Cost startup_cost;
2102  Cost run_cost;
2103 
2104  cost_tuplesort(&startup_cost, &run_cost,
2105  tuples, width,
2106  comparison_cost, sort_mem,
2107  limit_tuples);
2108 
2109  if (!enable_sort)
2110  startup_cost += disable_cost;
2111 
2112  startup_cost += input_cost;
2113 
2114  path->rows = tuples;
2115  path->startup_cost = startup_cost;
2116  path->total_cost = startup_cost + run_cost;
2117 }
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 4162 of file costsize.c.

4163 {
4164  QualCost sp_cost;
4165 
4166  /* Figure any cost for evaluating the testexpr */
4167  cost_qual_eval(&sp_cost,
4168  make_ands_implicit((Expr *) subplan->testexpr),
4169  root);
4170 
4171  if (subplan->useHashTable)
4172  {
4173  /*
4174  * If we are using a hash table for the subquery outputs, then the
4175  * cost of evaluating the query is a one-time cost. We charge one
4176  * cpu_operator_cost per tuple for the work of loading the hashtable,
4177  * too.
4178  */
4179  sp_cost.startup += plan->total_cost +
4180  cpu_operator_cost * plan->plan_rows;
4181 
4182  /*
4183  * The per-tuple costs include the cost of evaluating the lefthand
4184  * expressions, plus the cost of probing the hashtable. We already
4185  * accounted for the lefthand expressions as part of the testexpr, and
4186  * will also have counted one cpu_operator_cost for each comparison
4187  * operator. That is probably too low for the probing cost, but it's
4188  * hard to make a better estimate, so live with it for now.
4189  */
4190  }
4191  else
4192  {
4193  /*
4194  * Otherwise we will be rescanning the subplan output on each
4195  * evaluation. We need to estimate how much of the output we will
4196  * actually need to scan. NOTE: this logic should agree with the
4197  * tuple_fraction estimates used by make_subplan() in
4198  * plan/subselect.c.
4199  */
4200  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4201 
4202  if (subplan->subLinkType == EXISTS_SUBLINK)
4203  {
4204  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4205  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4206  }
4207  else if (subplan->subLinkType == ALL_SUBLINK ||
4208  subplan->subLinkType == ANY_SUBLINK)
4209  {
4210  /* assume we need 50% of the tuples */
4211  sp_cost.per_tuple += 0.50 * plan_run_cost;
4212  /* also charge a cpu_operator_cost per row examined */
4213  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4214  }
4215  else
4216  {
4217  /* assume we need all tuples */
4218  sp_cost.per_tuple += plan_run_cost;
4219  }
4220 
4221  /*
4222  * Also account for subplan's startup cost. If the subplan is
4223  * uncorrelated or undirect correlated, AND its topmost node is one
4224  * that materializes its output, assume that we'll only need to pay
4225  * its startup cost once; otherwise assume we pay the startup cost
4226  * every time.
4227  */
4228  if (subplan->parParam == NIL &&
4230  sp_cost.startup += plan->startup_cost;
4231  else
4232  sp_cost.per_tuple += plan->startup_cost;
4233  }
4234 
4235  subplan->startup_cost = sp_cost.startup;
4236  subplan->per_call_cost = sp_cost.per_tuple;
4237 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:721
@ ANY_SUBLINK
Definition: primnodes.h:923
@ ALL_SUBLINK
Definition: primnodes.h:922
@ EXISTS_SUBLINK
Definition: primnodes.h:921
Cost total_cost
Definition: plannodes.h:133
Cost startup_cost
Definition: plannodes.h:132
Cardinality plan_rows
Definition: plannodes.h:138
bool useHashTable
Definition: primnodes.h:1001
Node * testexpr
Definition: primnodes.h:989
List * parParam
Definition: primnodes.h:1012
Cost startup_cost
Definition: primnodes.h:1015
Cost per_call_cost
Definition: primnodes.h:1016
SubLinkType subLinkType
Definition: primnodes.h:987

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

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

◆ cost_subqueryscan()

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

Definition at line 1422 of file costsize.c.

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

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

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

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

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

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

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

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

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,
int  numPartCols,
int  numOrderCols,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 2817 of file costsize.c.

2821 {
2822  Cost startup_cost;
2823  Cost total_cost;
2824  ListCell *lc;
2825 
2826  startup_cost = input_startup_cost;
2827  total_cost = input_total_cost;
2828 
2829  /*
2830  * Window functions are assumed to cost their stated execution cost, plus
2831  * the cost of evaluating their input expressions, per tuple. Since they
2832  * may in fact evaluate their inputs at multiple rows during each cycle,
2833  * this could be a drastic underestimate; but without a way to know how
2834  * many rows the window function will fetch, it's hard to do better. In
2835  * any case, it's a good estimate for all the built-in window functions,
2836  * so we'll just do this for now.
2837  */
2838  foreach(lc, windowFuncs)
2839  {
2840  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2841  Cost wfunccost;
2842  QualCost argcosts;
2843 
2844  argcosts.startup = argcosts.per_tuple = 0;
2845  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2846  &argcosts);
2847  startup_cost += argcosts.startup;
2848  wfunccost = argcosts.per_tuple;
2849 
2850  /* also add the input expressions' cost to per-input-row costs */
2851  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2852  startup_cost += argcosts.startup;
2853  wfunccost += argcosts.per_tuple;
2854 
2855  /*
2856  * Add the filter's cost to per-input-row costs. XXX We should reduce
2857  * input expression costs according to filter selectivity.
2858  */
2859  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2860  startup_cost += argcosts.startup;
2861  wfunccost += argcosts.per_tuple;
2862 
2863  total_cost += wfunccost * input_tuples;
2864  }
2865 
2866  /*
2867  * We also charge cpu_operator_cost per grouping column per tuple for
2868  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2869  * overhead.
2870  *
2871  * XXX this neglects costs of spooling the data to disk when it overflows
2872  * work_mem. Sooner or later that should get accounted for.
2873  */
2874  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2875  total_cost += cpu_tuple_cost * input_tuples;
2876 
2877  path->rows = input_tuples;
2878  path->startup_cost = startup_cost;
2879  path->total_cost = total_cost;
2880 }
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2041
List * args
Definition: primnodes.h:550
Expr * aggfilter
Definition: primnodes.h:552
Oid winfnoid
Definition: primnodes.h:542

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

Referenced by create_windowagg_path().

◆ final_cost_hashjoin()

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

Definition at line 3908 of file costsize.c.

3911 {
3912  Path *outer_path = path->jpath.outerjoinpath;
3913  Path *inner_path = path->jpath.innerjoinpath;
3914  double outer_path_rows = outer_path->rows;
3915  double inner_path_rows = inner_path->rows;
3916  double inner_path_rows_total = workspace->inner_rows_total;
3917  List *hashclauses = path->path_hashclauses;
3918  Cost startup_cost = workspace->startup_cost;
3919  Cost run_cost = workspace->run_cost;
3920  int numbuckets = workspace->numbuckets;
3921  int numbatches = workspace->numbatches;
3922  Cost cpu_per_tuple;
3923  QualCost hash_qual_cost;
3924  QualCost qp_qual_cost;
3925  double hashjointuples;
3926  double virtualbuckets;
3927  Selectivity innerbucketsize;
3928  Selectivity innermcvfreq;
3929  ListCell *hcl;
3930 
3931  /* Mark the path with the correct row estimate */
3932  if (path->jpath.path.param_info)
3933  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3934  else
3935  path->jpath.path.rows = path->jpath.path.parent->rows;
3936 
3937  /* For partial paths, scale row estimate. */
3938  if (path->jpath.path.parallel_workers > 0)
3939  {
3940  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3941 
3942  path->jpath.path.rows =
3943  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3944  }
3945 
3946  /*
3947  * We could include disable_cost in the preliminary estimate, but that
3948  * would amount to optimizing for the case where the join method is
3949  * disabled, which doesn't seem like the way to bet.
3950  */
3951  if (!enable_hashjoin)
3952  startup_cost += disable_cost;
3953 
3954  /* mark the path with estimated # of batches */
3955  path->num_batches = numbatches;
3956 
3957  /* store the total number of tuples (sum of partial row estimates) */
3958  path->inner_rows_total = inner_path_rows_total;
3959 
3960  /* and compute the number of "virtual" buckets in the whole join */
3961  virtualbuckets = (double) numbuckets * (double) numbatches;
3962 
3963  /*
3964  * Determine bucketsize fraction and MCV frequency for the inner relation.
3965  * We use the smallest bucketsize or MCV frequency estimated for any
3966  * individual hashclause; this is undoubtedly conservative.
3967  *
3968  * BUT: if inner relation has been unique-ified, we can assume it's good
3969  * for hashing. This is important both because it's the right answer, and
3970  * because we avoid contaminating the cache with a value that's wrong for
3971  * non-unique-ified paths.
3972  */
3973  if (IsA(inner_path, UniquePath))
3974  {
3975  innerbucketsize = 1.0 / virtualbuckets;
3976  innermcvfreq = 0.0;
3977  }
3978  else
3979  {
3980  innerbucketsize = 1.0;
3981  innermcvfreq = 1.0;
3982  foreach(hcl, hashclauses)
3983  {
3984  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3985  Selectivity thisbucketsize;
3986  Selectivity thismcvfreq;
3987 
3988  /*
3989  * First we have to figure out which side of the hashjoin clause
3990  * is the inner side.
3991  *
3992  * Since we tend to visit the same clauses over and over when
3993  * planning a large query, we cache the bucket stats estimates in
3994  * the RestrictInfo node to avoid repeated lookups of statistics.
3995  */
3996  if (bms_is_subset(restrictinfo->right_relids,
3997  inner_path->parent->relids))
3998  {
3999  /* righthand side is inner */
4000  thisbucketsize = restrictinfo->right_bucketsize;
4001  if (thisbucketsize < 0)
4002  {
4003  /* not cached yet */
4005  get_rightop(restrictinfo->clause),
4006  virtualbuckets,
4007  &restrictinfo->right_mcvfreq,
4008  &restrictinfo->right_bucketsize);
4009  thisbucketsize = restrictinfo->right_bucketsize;
4010  }
4011  thismcvfreq = restrictinfo->right_mcvfreq;
4012  }
4013  else
4014  {
4015  Assert(bms_is_subset(restrictinfo->left_relids,
4016  inner_path->parent->relids));
4017  /* lefthand side is inner */
4018  thisbucketsize = restrictinfo->left_bucketsize;
4019  if (thisbucketsize < 0)
4020  {
4021  /* not cached yet */
4023  get_leftop(restrictinfo->clause),
4024  virtualbuckets,
4025  &restrictinfo->left_mcvfreq,
4026  &restrictinfo->left_bucketsize);
4027  thisbucketsize = restrictinfo->left_bucketsize;
4028  }
4029  thismcvfreq = restrictinfo->left_mcvfreq;
4030  }
4031 
4032  if (innerbucketsize > thisbucketsize)
4033  innerbucketsize = thisbucketsize;
4034  if (innermcvfreq > thismcvfreq)
4035  innermcvfreq = thismcvfreq;
4036  }
4037  }
4038 
4039  /*
4040  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4041  * want to hash unless there is really no other alternative, so apply
4042  * disable_cost. (The executor normally copes with excessive memory usage
4043  * by splitting batches, but obviously it cannot separate equal values
4044  * that way, so it will be unable to drive the batch size below hash_mem
4045  * when this is true.)
4046  */
4047  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4048  inner_path->pathtarget->width) > get_hash_memory_limit())
4049  startup_cost += disable_cost;
4050 
4051  /*
4052  * Compute cost of the hashquals and qpquals (other restriction clauses)
4053  * separately.
4054  */
4055  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4056  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4057  qp_qual_cost.startup -= hash_qual_cost.startup;
4058  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4059 
4060  /* CPU costs */
4061 
4062  if (path->jpath.jointype == JOIN_SEMI ||
4063  path->jpath.jointype == JOIN_ANTI ||
4064  extra->inner_unique)
4065  {
4066  double outer_matched_rows;
4067  Selectivity inner_scan_frac;
4068 
4069  /*
4070  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4071  * executor will stop after the first match.
4072  *
4073  * For an outer-rel row that has at least one match, we can expect the
4074  * bucket scan to stop after a fraction 1/(match_count+1) of the
4075  * bucket's rows, if the matches are evenly distributed. Since they
4076  * probably aren't quite evenly distributed, we apply a fuzz factor of
4077  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4078  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4079  * at least 1, no such clamp is needed now.)
4080  */
4081  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4082  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4083 
4084  startup_cost += hash_qual_cost.startup;
4085  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4086  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4087 
4088  /*
4089  * For unmatched outer-rel rows, the picture is quite a lot different.
4090  * In the first place, there is no reason to assume that these rows
4091  * preferentially hit heavily-populated buckets; instead assume they
4092  * are uncorrelated with the inner distribution and so they see an
4093  * average bucket size of inner_path_rows / virtualbuckets. In the
4094  * second place, it seems likely that they will have few if any exact
4095  * hash-code matches and so very few of the tuples in the bucket will
4096  * actually require eval of the hash quals. We don't have any good
4097  * way to estimate how many will, but for the moment assume that the
4098  * effective cost per bucket entry is one-tenth what it is for
4099  * matchable tuples.
4100  */
4101  run_cost += hash_qual_cost.per_tuple *
4102  (outer_path_rows - outer_matched_rows) *
4103  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4104 
4105  /* Get # of tuples that will pass the basic join */
4106  if (path->jpath.jointype == JOIN_ANTI)
4107  hashjointuples = outer_path_rows - outer_matched_rows;
4108  else
4109  hashjointuples = outer_matched_rows;
4110  }
4111  else
4112  {
4113  /*
4114  * The number of tuple comparisons needed is the number of outer
4115  * tuples times the typical number of tuples in a hash bucket, which
4116  * is the inner relation size times its bucketsize fraction. At each
4117  * one, we need to evaluate the hashjoin quals. But actually,
4118  * charging the full qual eval cost at each tuple is pessimistic,
4119  * since we don't evaluate the quals unless the hash values match
4120  * exactly. For lack of a better idea, halve the cost estimate to
4121  * allow for that.
4122  */
4123  startup_cost += hash_qual_cost.startup;
4124  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4125  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4126 
4127  /*
4128  * Get approx # tuples passing the hashquals. We use
4129  * approx_tuple_count here because we need an estimate done with
4130  * JOIN_INNER semantics.
4131  */
4132  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4133  }
4134 
4135  /*
4136  * For each tuple that gets through the hashjoin proper, we charge
4137  * cpu_tuple_cost plus the cost of evaluating additional restriction
4138  * clauses that are to be applied at the join. (This is pessimistic since
4139  * not all of the quals may get evaluated at each tuple.)
4140  */
4141  startup_cost += qp_qual_cost.startup;
4142  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4143  run_cost += cpu_per_tuple * hashjointuples;
4144 
4145  /* tlist eval costs are paid per output row, not per tuple scanned */
4146  startup_cost += path->jpath.path.pathtarget->cost.startup;
4147  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4148 
4149  path->jpath.path.startup_cost = startup_cost;
4150  path->jpath.path.total_cost = startup_cost + run_cost;
4151 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:316
bool enable_hashjoin
Definition: costsize.c:147
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4934
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:3390
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:2117
Cardinality inner_rows_total
Definition: pathnodes.h:2119
int num_batches
Definition: pathnodes.h:2118
JoinPath jpath
Definition: pathnodes.h:2116
Cardinality inner_rows_total
Definition: pathnodes.h:3289
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3168
Path * outerjoinpath
Definition: pathnodes.h:2039
Path * innerjoinpath
Definition: pathnodes.h:2040
JoinType jointype
Definition: pathnodes.h:2034
List * joinrestrictinfo
Definition: pathnodes.h:2042

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

3475 {
3476  Path *outer_path = path->jpath.outerjoinpath;
3477  Path *inner_path = path->jpath.innerjoinpath;
3478  double inner_path_rows = inner_path->rows;
3479  List *mergeclauses = path->path_mergeclauses;
3480  List *innersortkeys = path->innersortkeys;
3481  Cost startup_cost = workspace->startup_cost;
3482  Cost run_cost = workspace->run_cost;
3483  Cost inner_run_cost = workspace->inner_run_cost;
3484  double outer_rows = workspace->outer_rows;
3485  double inner_rows = workspace->inner_rows;
3486  double outer_skip_rows = workspace->outer_skip_rows;
3487  double inner_skip_rows = workspace->inner_skip_rows;
3488  Cost cpu_per_tuple,
3489  bare_inner_cost,
3490  mat_inner_cost;
3491  QualCost merge_qual_cost;
3492  QualCost qp_qual_cost;
3493  double mergejointuples,
3494  rescannedtuples;
3495  double rescanratio;
3496 
3497  /* Protect some assumptions below that rowcounts aren't zero */
3498  if (inner_path_rows <= 0)
3499  inner_path_rows = 1;
3500 
3501  /* Mark the path with the correct row estimate */
3502  if (path->jpath.path.param_info)
3503  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3504  else
3505  path->jpath.path.rows = path->jpath.path.parent->rows;
3506 
3507  /* For partial paths, scale row estimate. */
3508  if (path->jpath.path.parallel_workers > 0)
3509  {
3510  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3511 
3512  path->jpath.path.rows =
3513  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3514  }
3515 
3516  /*
3517  * We could include disable_cost in the preliminary estimate, but that
3518  * would amount to optimizing for the case where the join method is
3519  * disabled, which doesn't seem like the way to bet.
3520  */
3521  if (!enable_mergejoin)
3522  startup_cost += disable_cost;
3523 
3524  /*
3525  * Compute cost of the mergequals and qpquals (other restriction clauses)
3526  * separately.
3527  */
3528  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3529  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3530  qp_qual_cost.startup -= merge_qual_cost.startup;
3531  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3532 
3533  /*
3534  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3535  * executor will stop scanning for matches after the first match. When
3536  * all the joinclauses are merge clauses, this means we don't ever need to
3537  * back up the merge, and so we can skip mark/restore overhead.
3538  */
3539  if ((path->jpath.jointype == JOIN_SEMI ||
3540  path->jpath.jointype == JOIN_ANTI ||
3541  extra->inner_unique) &&
3544  path->skip_mark_restore = true;
3545  else
3546  path->skip_mark_restore = false;
3547 
3548  /*
3549  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3550  * here because we need an estimate done with JOIN_INNER semantics.
3551  */
3552  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3553 
3554  /*
3555  * When there are equal merge keys in the outer relation, the mergejoin
3556  * must rescan any matching tuples in the inner relation. This means
3557  * re-fetching inner tuples; we have to estimate how often that happens.
3558  *
3559  * For regular inner and outer joins, the number of re-fetches can be
3560  * estimated approximately as size of merge join output minus size of
3561  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3562  * denote the number of values of each key in the outer relation as m1,
3563  * m2, ...; in the inner relation, n1, n2, ... Then we have
3564  *
3565  * size of join = m1 * n1 + m2 * n2 + ...
3566  *
3567  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3568  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3569  * relation
3570  *
3571  * This equation works correctly for outer tuples having no inner match
3572  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3573  * are effectively subtracting those from the number of rescanned tuples,
3574  * when we should not. Can we do better without expensive selectivity
3575  * computations?
3576  *
3577  * The whole issue is moot if we are working from a unique-ified outer
3578  * input, or if we know we don't need to mark/restore at all.
3579  */
3580  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3581  rescannedtuples = 0;
3582  else
3583  {
3584  rescannedtuples = mergejointuples - inner_path_rows;
3585  /* Must clamp because of possible underestimate */
3586  if (rescannedtuples < 0)
3587  rescannedtuples = 0;
3588  }
3589 
3590  /*
3591  * We'll inflate various costs this much to account for rescanning. Note
3592  * that this is to be multiplied by something involving inner_rows, or
3593  * another number related to the portion of the inner rel we'll scan.
3594  */
3595  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3596 
3597  /*
3598  * Decide whether we want to materialize the inner input to shield it from
3599  * mark/restore and performing re-fetches. Our cost model for regular
3600  * re-fetches is that a re-fetch costs the same as an original fetch,
3601  * which is probably an overestimate; but on the other hand we ignore the
3602  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3603  * a more refined model. So we just need to inflate the inner run cost by
3604  * rescanratio.
3605  */
3606  bare_inner_cost = inner_run_cost * rescanratio;
3607 
3608  /*
3609  * When we interpose a Material node the re-fetch cost is assumed to be
3610  * just cpu_operator_cost per tuple, independently of the underlying
3611  * plan's cost; and we charge an extra cpu_operator_cost per original
3612  * fetch as well. Note that we're assuming the materialize node will
3613  * never spill to disk, since it only has to remember tuples back to the
3614  * last mark. (If there are a huge number of duplicates, our other cost
3615  * factors will make the path so expensive that it probably won't get
3616  * chosen anyway.) So we don't use cost_rescan here.
3617  *
3618  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3619  * of the generated Material node.
3620  */
3621  mat_inner_cost = inner_run_cost +
3622  cpu_operator_cost * inner_rows * rescanratio;
3623 
3624  /*
3625  * If we don't need mark/restore at all, we don't need materialization.
3626  */
3627  if (path->skip_mark_restore)
3628  path->materialize_inner = false;
3629 
3630  /*
3631  * Prefer materializing if it looks cheaper, unless the user has asked to
3632  * suppress materialization.
3633  */
3634  else if (enable_material && mat_inner_cost < bare_inner_cost)
3635  path->materialize_inner = true;
3636 
3637  /*
3638  * Even if materializing doesn't look cheaper, we *must* do it if the
3639  * inner path is to be used directly (without sorting) and it doesn't
3640  * support mark/restore.
3641  *
3642  * Since the inner side must be ordered, and only Sorts and IndexScans can
3643  * create order to begin with, and they both support mark/restore, you
3644  * might think there's no problem --- but you'd be wrong. Nestloop and
3645  * merge joins can *preserve* the order of their inputs, so they can be
3646  * selected as the input of a mergejoin, and they don't support
3647  * mark/restore at present.
3648  *
3649  * We don't test the value of enable_material here, because
3650  * materialization is required for correctness in this case, and turning
3651  * it off does not entitle us to deliver an invalid plan.
3652  */
3653  else if (innersortkeys == NIL &&
3654  !ExecSupportsMarkRestore(inner_path))
3655  path->materialize_inner = true;
3656 
3657  /*
3658  * Also, force materializing if the inner path is to be sorted and the
3659  * sort is expected to spill to disk. This is because the final merge
3660  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3661  * We don't try to adjust the cost estimates for this consideration,
3662  * though.
3663  *
3664  * Since materialization is a performance optimization in this case,
3665  * rather than necessary for correctness, we skip it if enable_material is
3666  * off.
3667  */
3668  else if (enable_material && innersortkeys != NIL &&
3669  relation_byte_size(inner_path_rows,
3670  inner_path->pathtarget->width) >
3671  (work_mem * 1024L))
3672  path->materialize_inner = true;
3673  else
3674  path->materialize_inner = false;
3675 
3676  /* Charge the right incremental cost for the chosen case */
3677  if (path->materialize_inner)
3678  run_cost += mat_inner_cost;
3679  else
3680  run_cost += bare_inner_cost;
3681 
3682  /* CPU costs */
3683 
3684  /*
3685  * The number of tuple comparisons needed is approximately number of outer
3686  * rows plus number of inner rows plus number of rescanned tuples (can we
3687  * refine this?). At each one, we need to evaluate the mergejoin quals.
3688  */
3689  startup_cost += merge_qual_cost.startup;
3690  startup_cost += merge_qual_cost.per_tuple *
3691  (outer_skip_rows + inner_skip_rows * rescanratio);
3692  run_cost += merge_qual_cost.per_tuple *
3693  ((outer_rows - outer_skip_rows) +
3694  (inner_rows - inner_skip_rows) * rescanratio);
3695 
3696  /*
3697  * For each tuple that gets through the mergejoin proper, we charge
3698  * cpu_tuple_cost plus the cost of evaluating additional restriction
3699  * clauses that are to be applied at the join. (This is pessimistic since
3700  * not all of the quals may get evaluated at each tuple.)
3701  *
3702  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3703  * evaluations here, but it's probably not worth the trouble.
3704  */
3705  startup_cost += qp_qual_cost.startup;
3706  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3707  run_cost += cpu_per_tuple * mergejointuples;
3708 
3709  /* tlist eval costs are paid per output row, not per tuple scanned */
3710  startup_cost += path->jpath.path.pathtarget->cost.startup;
3711  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3712 
3713  path->jpath.path.startup_cost = startup_cost;
3714  path->jpath.path.total_cost = startup_cost + run_cost;
3715 }
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:3282
Cardinality outer_rows
Definition: pathnodes.h:3281
Cardinality inner_skip_rows
Definition: pathnodes.h:3284
Cardinality outer_skip_rows
Definition: pathnodes.h:3283
bool skip_mark_restore
Definition: pathnodes.h:2101
List * innersortkeys
Definition: pathnodes.h:2100
JoinPath jpath
Definition: pathnodes.h:2097
bool materialize_inner
Definition: pathnodes.h:2102
List * path_mergeclauses
Definition: pathnodes.h:2098

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

3039 {
3040  Path *outer_path = path->jpath.outerjoinpath;
3041  Path *inner_path = path->jpath.innerjoinpath;
3042  double outer_path_rows = outer_path->rows;
3043  double inner_path_rows = inner_path->rows;
3044  Cost startup_cost = workspace->startup_cost;
3045  Cost run_cost = workspace->run_cost;
3046  Cost cpu_per_tuple;
3047  QualCost restrict_qual_cost;
3048  double ntuples;
3049 
3050  /* Protect some assumptions below that rowcounts aren't zero */
3051  if (outer_path_rows <= 0)
3052  outer_path_rows = 1;
3053  if (inner_path_rows <= 0)
3054  inner_path_rows = 1;
3055  /* Mark the path with the correct row estimate */
3056  if (path->jpath.path.param_info)
3057  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3058  else
3059  path->jpath.path.rows = path->jpath.path.parent->rows;
3060 
3061  /* For partial paths, scale row estimate. */
3062  if (path->jpath.path.parallel_workers > 0)
3063  {
3064  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3065 
3066  path->jpath.path.rows =
3067  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3068  }
3069 
3070  /*
3071  * We could include disable_cost in the preliminary estimate, but that
3072  * would amount to optimizing for the case where the join method is
3073  * disabled, which doesn't seem like the way to bet.
3074  */
3075  if (!enable_nestloop)
3076  startup_cost += disable_cost;
3077 
3078  /* cost of inner-relation source data (we already dealt with outer rel) */
3079 
3080  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3081  extra->inner_unique)
3082  {
3083  /*
3084  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3085  * executor will stop after the first match.
3086  */
3087  Cost inner_run_cost = workspace->inner_run_cost;
3088  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3089  double outer_matched_rows;
3090  double outer_unmatched_rows;
3091  Selectivity inner_scan_frac;
3092 
3093  /*
3094  * For an outer-rel row that has at least one match, we can expect the
3095  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3096  * rows, if the matches are evenly distributed. Since they probably
3097  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3098  * that fraction. (If we used a larger fuzz factor, we'd have to
3099  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3100  * least 1, no such clamp is needed now.)
3101  */
3102  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3103  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3104  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3105 
3106  /*
3107  * Compute number of tuples processed (not number emitted!). First,
3108  * account for successfully-matched outer rows.
3109  */
3110  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3111 
3112  /*
3113  * Now we need to estimate the actual costs of scanning the inner
3114  * relation, which may be quite a bit less than N times inner_run_cost
3115  * due to early scan stops. We consider two cases. If the inner path
3116  * is an indexscan using all the joinquals as indexquals, then an
3117  * unmatched outer row results in an indexscan returning no rows,
3118  * which is probably quite cheap. Otherwise, the executor will have
3119  * to scan the whole inner rel for an unmatched row; not so cheap.
3120  */
3121  if (has_indexed_join_quals(path))
3122  {
3123  /*
3124  * Successfully-matched outer rows will only require scanning
3125  * inner_scan_frac of the inner relation. In this case, we don't
3126  * need to charge the full inner_run_cost even when that's more
3127  * than inner_rescan_run_cost, because we can assume that none of
3128  * the inner scans ever scan the whole inner relation. So it's
3129  * okay to assume that all the inner scan executions can be
3130  * fractions of the full cost, even if materialization is reducing
3131  * the rescan cost. At this writing, it's impossible to get here
3132  * for a materialized inner scan, so inner_run_cost and
3133  * inner_rescan_run_cost will be the same anyway; but just in
3134  * case, use inner_run_cost for the first matched tuple and
3135  * inner_rescan_run_cost for additional ones.
3136  */
3137  run_cost += inner_run_cost * inner_scan_frac;
3138  if (outer_matched_rows > 1)
3139  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3140 
3141  /*
3142  * Add the cost of inner-scan executions for unmatched outer rows.
3143  * We estimate this as the same cost as returning the first tuple
3144  * of a nonempty scan. We consider that these are all rescans,
3145  * since we used inner_run_cost once already.
3146  */
3147  run_cost += outer_unmatched_rows *
3148  inner_rescan_run_cost / inner_path_rows;
3149 
3150  /*
3151  * We won't be evaluating any quals at all for unmatched rows, so
3152  * don't add them to ntuples.
3153  */
3154  }
3155  else
3156  {
3157  /*
3158  * Here, a complicating factor is that rescans may be cheaper than
3159  * first scans. If we never scan all the way to the end of the
3160  * inner rel, it might be (depending on the plan type) that we'd
3161  * never pay the whole inner first-scan run cost. However it is
3162  * difficult to estimate whether that will happen (and it could
3163  * not happen if there are any unmatched outer rows!), so be
3164  * conservative and always charge the whole first-scan cost once.
3165  * We consider this charge to correspond to the first unmatched
3166  * outer row, unless there isn't one in our estimate, in which
3167  * case blame it on the first matched row.
3168  */
3169 
3170  /* First, count all unmatched join tuples as being processed */
3171  ntuples += outer_unmatched_rows * inner_path_rows;
3172 
3173  /* Now add the forced full scan, and decrement appropriate count */
3174  run_cost += inner_run_cost;
3175  if (outer_unmatched_rows >= 1)
3176  outer_unmatched_rows -= 1;
3177  else
3178  outer_matched_rows -= 1;
3179 
3180  /* Add inner run cost for additional outer tuples having matches */
3181  if (outer_matched_rows > 0)
3182  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3183 
3184  /* Add inner run cost for additional unmatched outer tuples */
3185  if (outer_unmatched_rows > 0)
3186  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3187  }
3188  }
3189  else
3190  {
3191  /* Normal-case source costs were included in preliminary estimate */
3192 
3193  /* Compute number of tuples processed (not number emitted!) */
3194  ntuples = outer_path_rows * inner_path_rows;
3195  }
3196 
3197  /* CPU costs */
3198  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3199  startup_cost += restrict_qual_cost.startup;
3200  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3201  run_cost += cpu_per_tuple * ntuples;
3202 
3203  /* tlist eval costs are paid per output row, not per tuple scanned */
3204  startup_cost += path->jpath.path.pathtarget->cost.startup;
3205  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3206 
3207  path->jpath.path.startup_cost = startup_cost;
3208  path->jpath.path.total_cost = startup_cost + run_cost;
3209 }
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:4841
bool enable_nestloop
Definition: costsize.c:143
Cost inner_rescan_run_cost
Definition: pathnodes.h:3278
JoinPath jpath
Definition: pathnodes.h:2057

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

5025 {
5026  List *allclauses;
5027  double nrows;
5028 
5029  /*
5030  * Estimate the number of rows returned by the parameterized scan, knowing
5031  * that it will apply all the extra join clauses as well as the rel's own
5032  * restriction clauses. Note that we force the clauses to be treated as
5033  * non-join clauses during selectivity estimation.
5034  */
5035  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5036  nrows = rel->tuples *
5038  allclauses,
5039  rel->relid, /* do not use 0! */
5040  JOIN_INNER,
5041  NULL);
5042  nrows = clamp_row_est(nrows);
5043  /* For safety, make sure result is not more than the base estimate */
5044  if (nrows > rel->rows)
5045  nrows = rel->rows;
5046  return nrows;
5047 }

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

5109 {
5110  double nrows;
5111 
5112  /*
5113  * Estimate the number of rows returned by the parameterized join as the
5114  * sizes of the input paths times the selectivity of the clauses that have
5115  * ended up at this join node.
5116  *
5117  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5118  * on the pair of input paths provided, though ideally we'd get the same
5119  * estimate for any pair with the same parameterization.
5120  */
5121  nrows = calc_joinrel_size_estimate(root,
5122  rel,
5123  outer_path->parent,
5124  inner_path->parent,
5125  outer_path->rows,
5126  inner_path->rows,
5127  sjinfo,
5128  restrict_clauses);
5129  /* For safety, make sure result is not more than the base estimate */
5130  if (nrows > rel->rows)
5131  nrows = rel->rows;
5132  return nrows;
5133 }
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:5145

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

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

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

3806 {
3807  Cost startup_cost = 0;
3808  Cost run_cost = 0;
3809  double outer_path_rows = outer_path->rows;
3810  double inner_path_rows = inner_path->rows;
3811  double inner_path_rows_total = inner_path_rows;
3812  int num_hashclauses = list_length(hashclauses);
3813  int numbuckets;
3814  int numbatches;
3815  int num_skew_mcvs;
3816  size_t space_allowed; /* unused */
3817 
3818  /* cost of source data */
3819  startup_cost += outer_path->startup_cost;
3820  run_cost += outer_path->total_cost - outer_path->startup_cost;
3821  startup_cost += inner_path->total_cost;
3822 
3823  /*
3824  * Cost of computing hash function: must do it once per input tuple. We
3825  * charge one cpu_operator_cost for each column's hash function. Also,
3826  * tack on one cpu_tuple_cost per inner row, to model the costs of
3827  * inserting the row into the hashtable.
3828  *
3829  * XXX when a hashclause is more complex than a single operator, we really
3830  * should charge the extra eval costs of the left or right side, as
3831  * appropriate, here. This seems more work than it's worth at the moment.
3832  */
3833  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3834  * inner_path_rows;
3835  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3836 
3837  /*
3838  * If this is a parallel hash build, then the value we have for
3839  * inner_rows_total currently refers only to the rows returned by each
3840  * participant. For shared hash table size estimation, we need the total
3841  * number, so we need to undo the division.
3842  */
3843  if (parallel_hash)
3844  inner_path_rows_total *= get_parallel_divisor(inner_path);
3845 
3846  /*
3847  * Get hash table size that executor would use for inner relation.
3848  *
3849  * XXX for the moment, always assume that skew optimization will be
3850  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
3851  * trying to determine that for sure.
3852  *
3853  * XXX at some point it might be interesting to try to account for skew
3854  * optimization in the cost estimate, but for now, we don't.
3855  */
3856  ExecChooseHashTableSize(inner_path_rows_total,
3857  inner_path->pathtarget->width,
3858  true, /* useskew */
3859  parallel_hash, /* try_combined_hash_mem */
3860  outer_path->parallel_workers,
3861  &space_allowed,
3862  &numbuckets,
3863  &numbatches,
3864  &num_skew_mcvs);
3865 
3866  /*
3867  * If inner relation is too big then we will need to "batch" the join,
3868  * which implies writing and reading most of the tuples to disk an extra
3869  * time. Charge seq_page_cost per page, since the I/O should be nice and
3870  * sequential. Writing the inner rel counts as startup cost, all the rest
3871  * as run cost.
3872  */
3873  if (numbatches > 1)
3874  {
3875  double outerpages = page_size(outer_path_rows,
3876  outer_path->pathtarget->width);
3877  double innerpages = page_size(inner_path_rows,
3878  inner_path->pathtarget->width);
3879 
3880  startup_cost += seq_page_cost * innerpages;
3881  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3882  }
3883 
3884  /* CPU costs left for later */
3885 
3886  /* Public result fields */
3887  workspace->startup_cost = startup_cost;
3888  workspace->total_cost = startup_cost + run_cost;
3889  /* Save private data for final_cost_hashjoin */
3890  workspace->run_cost = run_cost;
3891  workspace->numbuckets = numbuckets;
3892  workspace->numbatches = numbatches;
3893  workspace->inner_rows_total = inner_path_rows_total;
3894 }
static double page_size(double tuples, int width)
Definition: costsize.c:6101
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:663

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

3248 {
3249  Cost startup_cost = 0;
3250  Cost run_cost = 0;
3251  double outer_path_rows = outer_path->rows;
3252  double inner_path_rows = inner_path->rows;
3253  Cost inner_run_cost;
3254  double outer_rows,
3255  inner_rows,
3256  outer_skip_rows,
3257  inner_skip_rows;
3258  Selectivity outerstartsel,
3259  outerendsel,
3260  innerstartsel,
3261  innerendsel;
3262  Path sort_path; /* dummy for result of cost_sort */
3263 
3264  /* Protect some assumptions below that rowcounts aren't zero */
3265  if (outer_path_rows <= 0)
3266  outer_path_rows = 1;
3267  if (inner_path_rows <= 0)
3268  inner_path_rows = 1;
3269 
3270  /*
3271  * A merge join will stop as soon as it exhausts either input stream
3272  * (unless it's an outer join, in which case the outer side has to be
3273  * scanned all the way anyway). Estimate fraction of the left and right
3274  * inputs that will actually need to be scanned. Likewise, we can
3275  * estimate the number of rows that will be skipped before the first join
3276  * pair is found, which should be factored into startup cost. We use only
3277  * the first (most significant) merge clause for this purpose. Since
3278  * mergejoinscansel() is a fairly expensive computation, we cache the
3279  * results in the merge clause RestrictInfo.
3280  */
3281  if (mergeclauses && jointype != JOIN_FULL)
3282  {
3283  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3284  List *opathkeys;
3285  List *ipathkeys;
3286  PathKey *opathkey;
3287  PathKey *ipathkey;
3288  MergeScanSelCache *cache;
3289 
3290  /* Get the input pathkeys to determine the sort-order details */
3291  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3292  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3293  Assert(opathkeys);
3294  Assert(ipathkeys);
3295  opathkey = (PathKey *) linitial(opathkeys);
3296  ipathkey = (PathKey *) linitial(ipathkeys);
3297  /* debugging check */
3298  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3299  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3300  opathkey->pk_strategy != ipathkey->pk_strategy ||
3301  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3302  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3303 
3304  /* Get the selectivity with caching */
3305  cache = cached_scansel(root, firstclause, opathkey);
3306 
3307  if (bms_is_subset(firstclause->left_relids,
3308  outer_path->parent->relids))
3309  {
3310  /* left side of clause is outer */
3311  outerstartsel = cache->leftstartsel;
3312  outerendsel = cache->leftendsel;
3313  innerstartsel = cache->rightstartsel;
3314  innerendsel = cache->rightendsel;
3315  }
3316  else
3317  {
3318  /* left side of clause is inner */
3319  outerstartsel = cache->rightstartsel;
3320  outerendsel = cache->rightendsel;
3321  innerstartsel = cache->leftstartsel;
3322  innerendsel = cache->leftendsel;
3323  }
3324  if (jointype == JOIN_LEFT ||
3325  jointype == JOIN_ANTI)
3326  {
3327  outerstartsel = 0.0;
3328  outerendsel = 1.0;
3329  }
3330  else if (jointype == JOIN_RIGHT)
3331  {
3332  innerstartsel = 0.0;
3333  innerendsel = 1.0;
3334  }
3335  }
3336  else
3337  {
3338  /* cope with clauseless or full mergejoin */
3339  outerstartsel = innerstartsel = 0.0;
3340  outerendsel = innerendsel = 1.0;
3341  }
3342 
3343  /*
3344  * Convert selectivities to row counts. We force outer_rows and
3345  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3346  */
3347  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3348  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3349  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3350  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3351 
3352  Assert(outer_skip_rows <= outer_rows);
3353  Assert(inner_skip_rows <= inner_rows);
3354 
3355  /*
3356  * Readjust scan selectivities to account for above rounding. This is
3357  * normally an insignificant effect, but when there are only a few rows in
3358  * the inputs, failing to do this makes for a large percentage error.
3359  */
3360  outerstartsel = outer_skip_rows / outer_path_rows;
3361  innerstartsel = inner_skip_rows / inner_path_rows;
3362  outerendsel = outer_rows / outer_path_rows;
3363  innerendsel = inner_rows / inner_path_rows;
3364 
3365  Assert(outerstartsel <= outerendsel);
3366  Assert(innerstartsel <= innerendsel);
3367 
3368  /* cost of source data */
3369 
3370  if (outersortkeys) /* do we need to sort outer? */
3371  {
3372  cost_sort(&sort_path,
3373  root,
3374  outersortkeys,
3375  outer_path->total_cost,
3376  outer_path_rows,
3377  outer_path->pathtarget->width,
3378  0.0,
3379  work_mem,
3380  -1.0);
3381  startup_cost += sort_path.startup_cost;
3382  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3383  * outerstartsel;
3384  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3385  * (outerendsel - outerstartsel);
3386  }
3387  else
3388  {
3389  startup_cost += outer_path->startup_cost;
3390  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3391  * outerstartsel;
3392  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3393  * (outerendsel - outerstartsel);
3394  }
3395 
3396  if (innersortkeys) /* do we need to sort inner? */
3397  {
3398  cost_sort(&sort_path,
3399  root,
3400  innersortkeys,
3401  inner_path->total_cost,
3402  inner_path_rows,
3403  inner_path->pathtarget->width,
3404  0.0,
3405  work_mem,
3406  -1.0);
3407  startup_cost += sort_path.startup_cost;
3408  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3409  * innerstartsel;
3410  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3411  * (innerendsel - innerstartsel);
3412  }
3413  else
3414  {
3415  startup_cost += inner_path->startup_cost;
3416  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3417  * innerstartsel;
3418  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3419  * (innerendsel - innerstartsel);
3420  }
3421 
3422  /*
3423  * We can't yet determine whether rescanning occurs, or whether
3424  * materialization of the inner input should be done. The minimum
3425  * possible inner input cost, regardless of rescan and materialization
3426  * considerations, is inner_run_cost. We include that in
3427  * workspace->total_cost, but not yet in run_cost.
3428  */
3429 
3430  /* CPU costs left for later */
3431 
3432  /* Public result fields */
3433  workspace->startup_cost = startup_cost;
3434  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3435  /* Save private data for final_cost_mergejoin */
3436  workspace->run_cost = run_cost;
3437  workspace->inner_run_cost = inner_run_cost;
3438  workspace->outer_rows = outer_rows;
3439  workspace->inner_rows = inner_rows;
3440  workspace->outer_skip_rows = outer_skip_rows;
3441  workspace->inner_skip_rows = inner_skip_rows;
3442 }
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3721
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_RIGHT
Definition: nodes.h:307
@ JOIN_LEFT
Definition: nodes.h:305
Selectivity leftstartsel
Definition: pathnodes.h:2687
Selectivity leftendsel
Definition: pathnodes.h:2688
Selectivity rightendsel
Definition: pathnodes.h:2690
Selectivity rightstartsel
Definition: pathnodes.h:2689
bool pk_nulls_first
Definition: pathnodes.h:1466
int pk_strategy
Definition: pathnodes.h:1465
Oid pk_opfamily
Definition: pathnodes.h:1464

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

2965 {
2966  Cost startup_cost = 0;
2967  Cost run_cost = 0;
2968  double outer_path_rows = outer_path->rows;
2969  Cost inner_rescan_start_cost;
2970  Cost inner_rescan_total_cost;
2971  Cost inner_run_cost;
2972  Cost inner_rescan_run_cost;
2973 
2974  /* estimate costs to rescan the inner relation */
2975  cost_rescan(root, inner_path,
2976  &inner_rescan_start_cost,
2977  &inner_rescan_total_cost);
2978 
2979  /* cost of source data */
2980 
2981  /*
2982  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2983  * before we can start returning tuples, so the join's startup cost is
2984  * their sum. We'll also pay the inner path's rescan startup cost
2985  * multiple times.
2986  */
2987  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2988  run_cost += outer_path->total_cost - outer_path->startup_cost;
2989  if (outer_path_rows > 1)
2990  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
2991 
2992  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
2993  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
2994 
2995  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
2996  extra->inner_unique)
2997  {
2998  /*
2999  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3000  * executor will stop after the first match.
3001  *
3002  * Getting decent estimates requires inspection of the join quals,
3003  * which we choose to postpone to final_cost_nestloop.
3004  */
3005 
3006  /* Save private data for final_cost_nestloop */
3007  workspace->inner_run_cost = inner_run_cost;
3008  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3009  }
3010  else
3011  {
3012  /* Normal case; we'll scan whole input rel for each outer row */
3013  run_cost += inner_run_cost;
3014  if (outer_path_rows > 1)
3015  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3016  }
3017 
3018  /* CPU costs left for later */
3019 
3020  /* Public result fields */
3021  workspace->startup_cost = startup_cost;
3022  workspace->total_cost = startup_cost + run_cost;
3023  /* Save private data for final_cost_nestloop */
3024  workspace->run_cost = run_cost;
3025 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:4255

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

4994 {
4995  double nrows;
4996 
4997  /* Should only be applied to base relations */
4998  Assert(rel->relid > 0);
4999 
5000  nrows = rel->tuples *
5002  rel->baserestrictinfo,
5003  0,
5004  JOIN_INNER,
5005  NULL);
5006 
5007  rel->rows = clamp_row_est(nrows);
5008 
5010 
5011  set_rel_width(root, rel);
5012 }
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5853

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

5719 {
5720  RangeTblEntry *rte;
5721 
5722  /* Should only be applied to base relations that are CTE references */
5723  Assert(rel->relid > 0);
5724  rte = planner_rt_fetch(rel->relid, root);
5725  Assert(rte->rtekind == RTE_CTE);
5726 
5727  if (rte->self_reference)
5728  {
5729  /*
5730  * In a self-reference, we assume the average worktable size is a
5731  * multiple of the nonrecursive term's size. The best multiplier will
5732  * vary depending on query "fan-out", so make its value adjustable.
5733  */
5734  rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
5735  }
5736  else
5737  {
5738  /* Otherwise just believe the CTE's rowcount estimate */
5739  rel->tuples = cte_rows;
5740  }
5741 
5742  /* Now estimate number of output rows, etc */
5743  set_baserel_size_estimates(root, rel);
5744 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4993
double recursive_worktable_factor
Definition: costsize.c:127
bool self_reference
Definition: parsenodes.h:1165

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

5819 {
5820  /* Should only be applied to base relations */
5821  Assert(rel->relid > 0);
5822 
5823  rel->rows = 1000; /* entirely bogus default estimate */
5824 
5826 
5827  set_rel_width(root, rel);
5828 }

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

5627 {
5628  RangeTblEntry *rte;
5629  ListCell *lc;
5630 
5631  /* Should only be applied to base relations that are functions */
5632  Assert(rel->relid > 0);
5633  rte = planner_rt_fetch(rel->relid, root);
5634  Assert(rte->rtekind == RTE_FUNCTION);
5635 
5636  /*
5637  * Estimate number of rows the functions will return. The rowcount of the
5638  * node is that of the largest function result.
5639  */
5640  rel->tuples = 0;
5641  foreach(lc, rte->functions)
5642  {
5643  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5644  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5645 
5646  if (ntup > rel->tuples)
5647  rel->tuples = ntup;
5648  }
5649 
5650  /* Now estimate number of output rows, etc */
5651  set_baserel_size_estimates(root, rel);
5652 }
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:289

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

5077 {
5078  rel->rows = calc_joinrel_size_estimate(root,
5079  rel,
5080  outer_rel,
5081  inner_rel,
5082  outer_rel->rows,
5083  inner_rel->rows,
5084  sjinfo,
5085  restrictlist);
5086 }

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

5757 {
5758  RangeTblEntry *rte;
5759 
5760  /* Should only be applied to base relations that are tuplestore references */
5761  Assert(rel->relid > 0);
5762  rte = planner_rt_fetch(rel->relid, root);
5764 
5765  /*
5766  * Use the estimate provided by the code which is generating the named
5767  * tuplestore. In some cases, the actual number might be available; in
5768  * others the same plan will be re-used, so a "typical" value might be
5769  * estimated and used.
5770  */
5771  rel->tuples = rte->enrtuples;
5772  if (rel->tuples < 0)
5773  rel->tuples = 1000;
5774 
5775  /* Now estimate number of output rows, etc */
5776  set_baserel_size_estimates(root, rel);
5777 }
Cardinality enrtuples
Definition: parsenodes.h:1193

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

6012 {
6013  int32 tuple_width = 0;
6014  ListCell *lc;
6015 
6016  /* Vars are assumed to have cost zero, but other exprs do not */
6017  target->cost.startup = 0;
6018  target->cost.per_tuple = 0;
6019 
6020  foreach(lc, target->exprs)
6021  {
6022  Node *node = (Node *) lfirst(lc);
6023 
6024  if (IsA(node, Var))
6025  {
6026  Var *var = (Var *) node;
6027  int32 item_width;
6028 
6029  /* We should not see any upper-level Vars here */
6030  Assert(var->varlevelsup == 0);
6031 
6032  /* Try to get data from RelOptInfo cache */
6033  if (!IS_SPECIAL_VARNO(var->varno) &&
6034  var->varno < root->simple_rel_array_size)
6035  {
6036  RelOptInfo *rel = root->simple_rel_array[var->varno];
6037 
6038  if (rel != NULL &&
6039  var->varattno >= rel->min_attr &&
6040  var->varattno <= rel->max_attr)
6041  {
6042  int ndx = var->varattno - rel->min_attr;
6043 
6044  if (rel->attr_widths[ndx] > 0)
6045  {
6046  tuple_width += rel->attr_widths[ndx];
6047  continue;
6048  }
6049  }
6050  }
6051 
6052  /*
6053  * No cached data available, so estimate using just the type info.
6054  */
6055  item_width = get_typavgwidth(var->vartype, var->vartypmod);
6056  Assert(item_width > 0);
6057  tuple_width += item_width;
6058  }
6059  else
6060  {
6061  /*
6062  * Handle general expressions using type info.
6063  */
6064  int32 item_width;
6065  QualCost cost;
6066 
6067  item_width = get_typavgwidth(exprType(node), exprTypmod(node));
6068  Assert(item_width > 0);
6069  tuple_width += item_width;
6070 
6071  /* Account for cost, too */
6072  cost_qual_eval_node(&cost, node, root);
6073  target->cost.startup += cost.startup;
6074  target->cost.per_tuple += cost.per_tuple;
6075  }
6076  }
6077 
6078  Assert(tuple_width >= 0);
6079  target->width = tuple_width;
6080 
6081  return target;
6082 }
signed int int32
Definition: c.h:478
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2536
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:266
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:216
List * exprs
Definition: pathnodes.h:1511
QualCost cost
Definition: pathnodes.h:1517
int simple_rel_array_size
Definition: pathnodes.h:232
AttrNumber max_attr
Definition: pathnodes.h:921
AttrNumber min_attr
Definition: pathnodes.h:919
Definition: primnodes.h:223
AttrNumber varattno
Definition: primnodes.h:235
int varno
Definition: primnodes.h:230
Index varlevelsup
Definition: primnodes.h:255

References Assert(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, exprType(), exprTypmod(), get_typavgwidth(), IS_SPECIAL_VARNO, IsA, lfirst, RelOptInfo::max_attr, RelOptInfo::min_attr, QualCost::per_tuple, PlannerInfo::simple_rel_array_size, QualCost::startup, Var::varattno, Var::varlevelsup, Var::varno, 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 5789 of file costsize.c.

5790 {
5791  /* Should only be applied to RTE_RESULT base relations */
5792  Assert(rel->relid > 0);
5793  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
5794 
5795  /* RTE_RESULT always generates a single row, natively */
5796  rel->tuples = 1;
5797 
5798  /* Now estimate number of output rows, etc */
5799  set_baserel_size_estimates(root, rel);
5800 }

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

5547 {
5548  PlannerInfo *subroot = rel->subroot;
5549  RelOptInfo *sub_final_rel;
5550  ListCell *lc;
5551 
5552  /* Should only be applied to base relations that are subqueries */
5553  Assert(rel->relid > 0);
5554  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5555 
5556  /*
5557  * Copy raw number of output rows from subquery. All of its paths should
5558  * have the same output rowcount, so just look at cheapest-total.
5559  */
5560  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5561  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5562 
5563  /*
5564  * Compute per-output-column width estimates by examining the subquery's
5565  * targetlist. For any output that is a plain Var, get the width estimate
5566  * that was made while planning the subquery. Otherwise, we leave it to
5567  * set_rel_width to fill in a datatype-based default estimate.
5568  */
5569  foreach(lc, subroot->parse->targetList)
5570  {
5571  TargetEntry *te = lfirst_node(TargetEntry, lc);
5572  Node *texpr = (Node *) te->expr;
5573  int32 item_width = 0;
5574 
5575  /* junk columns aren't visible to upper query */
5576  if (te->resjunk)
5577  continue;
5578 
5579  /*
5580  * The subquery could be an expansion of a view that's had columns
5581  * added to it since the current query was parsed, so that there are
5582  * non-junk tlist columns in it that don't correspond to any column
5583  * visible at our query level. Ignore such columns.
5584  */
5585  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5586  continue;
5587 
5588  /*
5589  * XXX This currently doesn't work for subqueries containing set
5590  * operations, because the Vars in their tlists are bogus references
5591  * to the first leaf subquery, which wouldn't give the right answer
5592  * even if we could still get to its PlannerInfo.
5593  *
5594  * Also, the subquery could be an appendrel for which all branches are
5595  * known empty due to constraint exclusion, in which case
5596  * set_append_rel_pathlist will have left the attr_widths set to zero.
5597  *
5598  * In either case, we just leave the width estimate zero until
5599  * set_rel_width fixes it.
5600  */
5601  if (IsA(texpr, Var) &&
5602  subroot->parse->setOperations == NULL)
5603  {
5604  Var *var = (Var *) texpr;
5605  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5606 
5607  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5608  }
5609  rel->attr_widths[te->resno - rel->min_attr] = item_width;
5610  }
5611 
5612  /* Now estimate number of output rows, etc */
5613  set_baserel_size_estimates(root, rel);
5614 }
@ UPPERREL_FINAL
Definition: pathnodes.h:79
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:393
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1395
Query * parse
Definition: pathnodes.h:202
Node * setOperations
Definition: parsenodes.h:217
List * targetList
Definition: parsenodes.h:189
struct Path * cheapest_total_path
Definition: pathnodes.h:897
PlannerInfo * subroot
Definition: pathnodes.h:942
Expr * expr
Definition: primnodes.h:1722
AttrNumber resno
Definition: primnodes.h:1724

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

5665 {
5666  /* Should only be applied to base relations that are functions */
5667  Assert(rel->relid > 0);
5668  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
5669 
5670  rel->tuples = 100;
5671 
5672  /* Now estimate number of output rows, etc */
5673  set_baserel_size_estimates(root, rel);
5674 }

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

5687 {
5688  RangeTblEntry *rte;
5689 
5690  /* Should only be applied to base relations that are values lists */
5691  Assert(rel->relid > 0);
5692  rte = planner_rt_fetch(rel->relid, root);
5693  Assert(rte->rtekind == RTE_VALUES);
5694 
5695  /*
5696  * Estimate number of rows the values list will return. We know this
5697  * precisely based on the list length (well, barring set-returning
5698  * functions in list items, but that's a refinement not catered for
5699  * anywhere else either).
5700  */
5701  rel->tuples = list_length(rte->values_lists);
5702 
5703  /* Now estimate number of output rows, etc */
5704  set_baserel_size_estimates(root, rel);
5705 }
List * values_lists
Definition: parsenodes.h:1158

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