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)
 
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)
 
Cost cost_sort_estimate (PlannerInfo *root, List *pathkeys, int nPresortedKeys, double tuples)
 
void cost_append (AppendPath *path, PlannerInfo *root)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
 

Variables

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

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 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 6442 of file costsize.c.

6444 {
6445  Cost indexTotalCost;
6446  Selectivity indexSelectivity;
6447  double T;
6448  double pages_fetched;
6449  double tuples_fetched;
6450  double heap_pages;
6451  long maxentries;
6452 
6453  /*
6454  * Fetch total cost of obtaining the bitmap, as well as its total
6455  * selectivity.
6456  */
6457  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6458 
6459  /*
6460  * Estimate number of main-table pages fetched.
6461  */
6462  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6463 
6464  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6465 
6466  /*
6467  * For a single scan, the number of heap pages that need to be fetched is
6468  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6469  * re-reads needed).
6470  */
6471  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6472 
6473  /*
6474  * Calculate the number of pages fetched from the heap. Then based on
6475  * current work_mem estimate get the estimated maxentries in the bitmap.
6476  * (Note that we always do this calculation based on the number of pages
6477  * that would be fetched in a single iteration, even if loop_count > 1.
6478  * That's correct, because only that number of entries will be stored in
6479  * the bitmap at one time.)
6480  */
6481  heap_pages = Min(pages_fetched, baserel->pages);
6482  maxentries = tbm_calculate_entries(work_mem * 1024L);
6483 
6484  if (loop_count > 1)
6485  {
6486  /*
6487  * For repeated bitmap scans, scale up the number of tuples fetched in
6488  * the Mackert and Lohman formula by the number of scans, so that we
6489  * estimate the number of pages fetched by all the scans. Then
6490  * pro-rate for one scan.
6491  */
6492  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6493  baserel->pages,
6494  get_indexpath_pages(bitmapqual),
6495  root);
6496  pages_fetched /= loop_count;
6497  }
6498 
6499  if (pages_fetched >= T)
6500  pages_fetched = T;
6501  else
6502  pages_fetched = ceil(pages_fetched);
6503 
6504  if (maxentries < heap_pages)
6505  {
6506  double exact_pages;
6507  double lossy_pages;
6508 
6509  /*
6510  * Crude approximation of the number of lossy pages. Because of the
6511  * way tbm_lossify() is coded, the number of lossy pages increases
6512  * very sharply as soon as we run short of memory; this formula has
6513  * that property and seems to perform adequately in testing, but it's
6514  * possible we could do better somehow.
6515  */
6516  lossy_pages = Max(0, heap_pages - maxentries / 2);
6517  exact_pages = heap_pages - lossy_pages;
6518 
6519  /*
6520  * If there are lossy pages then recompute the number of tuples
6521  * processed by the bitmap heap node. We assume here that the chance
6522  * of a given tuple coming from an exact page is the same as the
6523  * chance that a given page is exact. This might not be true, but
6524  * it's not clear how we can do any better.
6525  */
6526  if (lossy_pages > 0)
6527  tuples_fetched =
6528  clamp_row_est(indexSelectivity *
6529  (exact_pages / heap_pages) * baserel->tuples +
6530  (lossy_pages / heap_pages) * baserel->tuples);
6531  }
6532 
6533  if (cost)
6534  *cost = indexTotalCost;
6535  if (tuple)
6536  *tuple = tuples_fetched;
6537 
6538  return pages_fetched;
6539 }
#define Min(x, y)
Definition: c.h:986
#define Max(x, y)
Definition: c.h:980
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:868
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1084
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:933
double clamp_row_est(double nrows)
Definition: costsize.c:201
int work_mem
Definition: globals.c:125
static const uint32 T[65]
Definition: md5.c:119
double Cost
Definition: nodes.h:707
double Selectivity
Definition: nodes.h:706
Cardinality tuples
Definition: pathnodes.h:722
BlockNumber pages
Definition: pathnodes.h:721
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 5031 of file costsize.c.

5039 {
5040  Selectivity jselec;
5041  Selectivity nselec;
5042  Selectivity avgmatch;
5043  SpecialJoinInfo norm_sjinfo;
5044  List *joinquals;
5045  ListCell *l;
5046 
5047  /*
5048  * In an ANTI join, we must ignore clauses that are "pushed down", since
5049  * those won't affect the match logic. In a SEMI join, we do not
5050  * distinguish joinquals from "pushed down" quals, so just use the whole
5051  * restrictinfo list. For other outer join types, we should consider only
5052  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5053  */
5054  if (IS_OUTER_JOIN(jointype))
5055  {
5056  joinquals = NIL;
5057  foreach(l, restrictlist)
5058  {
5059  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5060 
5061  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5062  joinquals = lappend(joinquals, rinfo);
5063  }
5064  }
5065  else
5066  joinquals = restrictlist;
5067 
5068  /*
5069  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5070  */
5071  jselec = clauselist_selectivity(root,
5072  joinquals,
5073  0,
5074  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5075  sjinfo);
5076 
5077  /*
5078  * Also get the normal inner-join selectivity of the join clauses.
5079  */
5080  norm_sjinfo.type = T_SpecialJoinInfo;
5081  norm_sjinfo.min_lefthand = outerrel->relids;
5082  norm_sjinfo.min_righthand = innerrel->relids;
5083  norm_sjinfo.syn_lefthand = outerrel->relids;
5084  norm_sjinfo.syn_righthand = innerrel->relids;
5085  norm_sjinfo.jointype = JOIN_INNER;
5086  /* we don't bother trying to make the remaining fields valid */
5087  norm_sjinfo.lhs_strict = false;
5088  norm_sjinfo.delay_upper_joins = false;
5089  norm_sjinfo.semi_can_btree = false;
5090  norm_sjinfo.semi_can_hash = false;
5091  norm_sjinfo.semi_operators = NIL;
5092  norm_sjinfo.semi_rhs_exprs = NIL;
5093 
5094  nselec = clauselist_selectivity(root,
5095  joinquals,
5096  0,
5097  JOIN_INNER,
5098  &norm_sjinfo);
5099 
5100  /* Avoid leaking a lot of ListCells */
5101  if (IS_OUTER_JOIN(jointype))
5102  list_free(joinquals);
5103 
5104  /*
5105  * jselec can be interpreted as the fraction of outer-rel rows that have
5106  * any matches (this is true for both SEMI and ANTI cases). And nselec is
5107  * the fraction of the Cartesian product that matches. So, the average
5108  * number of matches for each outer-rel row that has at least one match is
5109  * nselec * inner_rows / jselec.
5110  *
5111  * Note: it is correct to use the inner rel's "rows" count here, even
5112  * though we might later be considering a parameterized inner path with
5113  * fewer rows. This is because we have included all the join clauses in
5114  * the selectivity estimate.
5115  */
5116  if (jselec > 0) /* protect against zero divide */
5117  {
5118  avgmatch = nselec * innerrel->rows / jselec;
5119  /* Clamp to sane range */
5120  avgmatch = Max(1.0, avgmatch);
5121  }
5122  else
5123  avgmatch = 1.0;
5124 
5125  semifactors->outer_match_frac = jselec;
5126  semifactors->match_count = avgmatch;
5127 }
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:336
void list_free(List *list)
Definition: list.c:1505
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:792
@ T_SpecialJoinInfo
Definition: nodes.h:287
@ JOIN_SEMI
Definition: nodes.h:763
@ JOIN_INNER
Definition: nodes.h:749
@ JOIN_ANTI
Definition: nodes.h:764
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2159
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:65
Definition: pg_list.h:51
Relids relids
Definition: pathnodes.h:682
Cardinality rows
Definition: pathnodes.h:685
Selectivity outer_match_frac
Definition: pathnodes.h:2530
Selectivity match_count
Definition: pathnodes.h:2531
Relids syn_lefthand
Definition: pathnodes.h:2274
Relids min_righthand
Definition: pathnodes.h:2273
List * semi_rhs_exprs
Definition: pathnodes.h:2283
JoinType jointype
Definition: pathnodes.h:2276
Relids min_lefthand
Definition: pathnodes.h:2272
Relids syn_righthand
Definition: pathnodes.h:2275
List * semi_operators
Definition: pathnodes.h:2282
bool delay_upper_joins
Definition: pathnodes.h:2278

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

Referenced by add_paths_to_joinrel().

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

2925 {
2926  double output_tuples;
2927  Cost startup_cost;
2928  Cost total_cost;
2929  AggClauseCosts dummy_aggcosts;
2930 
2931  /* Use all-zero per-aggregate costs if NULL is passed */
2932  if (aggcosts == NULL)
2933  {
2934  Assert(aggstrategy == AGG_HASHED);
2935  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2936  aggcosts = &dummy_aggcosts;
2937  }
2938 
2939  /*
2940  * The transCost.per_tuple component of aggcosts should be charged once
2941  * per input tuple, corresponding to the costs of evaluating the aggregate
2942  * transfns and their input expressions. The finalCost.per_tuple component
2943  * is charged once per output tuple, corresponding to the costs of
2944  * evaluating the finalfns. Startup costs are of course charged but once.
2945  *
2946  * If we are grouping, we charge an additional cpu_operator_cost per
2947  * grouping column per input tuple for grouping comparisons.
2948  *
2949  * We will produce a single output tuple if not grouping, and a tuple per
2950  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2951  *
2952  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2953  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2954  * input path is already sorted appropriately, AGG_SORTED should be
2955  * preferred (since it has no risk of memory overflow). This will happen
2956  * as long as the computed total costs are indeed exactly equal --- but if
2957  * there's roundoff error we might do the wrong thing. So be sure that
2958  * the computations below form the same intermediate values in the same
2959  * order.
2960  */
2961  if (aggstrategy == AGG_PLAIN)
2962  {
2963  startup_cost = input_total_cost;
2964  startup_cost += aggcosts->transCost.startup;
2965  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2966  startup_cost += aggcosts->finalCost.startup;
2967  startup_cost += aggcosts->finalCost.per_tuple;
2968  /* we aren't grouping */
2969  total_cost = startup_cost + cpu_tuple_cost;
2970  output_tuples = 1;
2971  }
2972  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2973  {
2974  /* Here we are able to deliver output on-the-fly */
2975  startup_cost = input_startup_cost;
2976  total_cost = input_total_cost;
2977  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2978  {
2979  startup_cost += disable_cost;
2980  total_cost += disable_cost;
2981  }
2982  /* calcs phrased this way to match HASHED case, see note above */
2983  total_cost += aggcosts->transCost.startup;
2984  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2985  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2986  total_cost += aggcosts->finalCost.startup;
2987  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2988  total_cost += cpu_tuple_cost * numGroups;
2989  output_tuples = numGroups;
2990  }
2991  else
2992  {
2993  /* must be AGG_HASHED */
2994  startup_cost = input_total_cost;
2995  if (!enable_hashagg)
2996  startup_cost += disable_cost;
2997  startup_cost += aggcosts->transCost.startup;
2998  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2999  /* cost of computing hash value */
3000  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
3001  startup_cost += aggcosts->finalCost.startup;
3002 
3003  total_cost = startup_cost;
3004  total_cost += aggcosts->finalCost.per_tuple * numGroups;
3005  /* cost of retrieving from hash table */
3006  total_cost += cpu_tuple_cost * numGroups;
3007  output_tuples = numGroups;
3008  }
3009 
3010  /*
3011  * Add the disk costs of hash aggregation that spills to disk.
3012  *
3013  * Groups that go into the hash table stay in memory until finalized, so
3014  * spilling and reprocessing tuples doesn't incur additional invocations
3015  * of transCost or finalCost. Furthermore, the computed hash value is
3016  * stored with the spilled tuples, so we don't incur extra invocations of
3017  * the hash function.
3018  *
3019  * Hash Agg begins returning tuples after the first batch is complete.
3020  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
3021  * accrue reads only to total_cost.
3022  */
3023  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
3024  {
3025  double pages;
3026  double pages_written = 0.0;
3027  double pages_read = 0.0;
3028  double spill_cost;
3029  double hashentrysize;
3030  double nbatches;
3031  Size mem_limit;
3032  uint64 ngroups_limit;
3033  int num_partitions;
3034  int depth;
3035 
3036  /*
3037  * Estimate number of batches based on the computed limits. If less
3038  * than or equal to one, all groups are expected to fit in memory;
3039  * otherwise we expect to spill.
3040  */
3041  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3042  input_width,
3043  aggcosts->transitionSpace);
3044  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
3045  &ngroups_limit, &num_partitions);
3046 
3047  nbatches = Max((numGroups * hashentrysize) / mem_limit,
3048  numGroups / ngroups_limit);
3049 
3050  nbatches = Max(ceil(nbatches), 1.0);
3051  num_partitions = Max(num_partitions, 2);
3052 
3053  /*
3054  * The number of partitions can change at different levels of
3055  * recursion; but for the purposes of this calculation assume it stays
3056  * constant.
3057  */
3058  depth = ceil(log(nbatches) / log(num_partitions));
3059 
3060  /*
3061  * Estimate number of pages read and written. For each level of
3062  * recursion, a tuple must be written and then later read.
3063  */
3064  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
3065  pages_written = pages_read = pages * depth;
3066 
3067  /*
3068  * HashAgg has somewhat worse IO behavior than Sort on typical
3069  * hardware/OS combinations. Account for this with a generic penalty.
3070  */
3071  pages_read *= 2.0;
3072  pages_written *= 2.0;
3073 
3074  startup_cost += pages_written * random_page_cost;
3075  total_cost += pages_written * random_page_cost;
3076  total_cost += pages_read * seq_page_cost;
3077 
3078  /* account for CPU cost of spilling a tuple and reading it back */
3079  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
3080  startup_cost += spill_cost;
3081  total_cost += spill_cost;
3082  }
3083 
3084  /*
3085  * If there are quals (HAVING quals), account for their cost and
3086  * selectivity.
3087  */
3088  if (quals)
3089  {
3090  QualCost qual_cost;
3091 
3092  cost_qual_eval(&qual_cost, quals, root);
3093  startup_cost += qual_cost.startup;
3094  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3095 
3096  output_tuples = clamp_row_est(output_tuples *
3098  quals,
3099  0,
3100  JOIN_INNER,
3101  NULL));
3102  }
3103 
3104  path->rows = output_tuples;
3105  path->startup_cost = startup_cost;
3106  path->total_cost = total_cost;
3107 }
#define MemSet(start, val, len)
Definition: c.h:1008
size_t Size
Definition: c.h:540
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:6388
double cpu_tuple_cost
Definition: costsize.c:122
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4667
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:1676
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1780
@ AGG_SORTED
Definition: nodes.h:808
@ AGG_HASHED
Definition: nodes.h:809
@ AGG_MIXED
Definition: nodes.h:810
@ AGG_PLAIN
Definition: nodes.h:807
static int list_length(const List *l)
Definition: pg_list.h:149
QualCost finalCost
Definition: pathnodes.h:59
Size transitionSpace
Definition: pathnodes.h:60
QualCost transCost
Definition: pathnodes.h:58
Cardinality rows
Definition: pathnodes.h:1204
Cost startup_cost
Definition: pathnodes.h:1205
Cost total_cost
Definition: pathnodes.h:1206
List * aggtransinfos
Definition: pathnodes.h:359
Cost per_tuple
Definition: pathnodes.h:46
Cost startup
Definition: pathnodes.h:45

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 path,
PlannerInfo root 
)

Definition at line 2502 of file costsize.c.

2503 {
2504  ListCell *l;
2505 
2506  apath->path.startup_cost = 0;
2507  apath->path.total_cost = 0;
2508  apath->path.rows = 0;
2509 
2510  if (apath->subpaths == NIL)
2511  return;
2512 
2513  if (!apath->path.parallel_aware)
2514  {
2515  List *pathkeys = apath->path.pathkeys;
2516 
2517  if (pathkeys == NIL)
2518  {
2519  Path *subpath = (Path *) linitial(apath->subpaths);
2520 
2521  /*
2522  * For an unordered, non-parallel-aware Append we take the startup
2523  * cost as the startup cost of the first subpath.
2524  */
2525  apath->path.startup_cost = subpath->startup_cost;
2526 
2527  /* Compute rows and costs as sums of subplan rows and costs. */
2528  foreach(l, apath->subpaths)
2529  {
2530  Path *subpath = (Path *) lfirst(l);
2531 
2532  apath->path.rows += subpath->rows;
2533  apath->path.total_cost += subpath->total_cost;
2534  }
2535  }
2536  else
2537  {
2538  /*
2539  * For an ordered, non-parallel-aware Append we take the startup
2540  * cost as the sum of the subpath startup costs. This ensures
2541  * that we don't underestimate the startup cost when a query's
2542  * LIMIT is such that several of the children have to be run to
2543  * satisfy it. This might be overkill --- another plausible hack
2544  * would be to take the Append's startup cost as the maximum of
2545  * the child startup costs. But we don't want to risk believing
2546  * that an ORDER BY LIMIT query can be satisfied at small cost
2547  * when the first child has small startup cost but later ones
2548  * don't. (If we had the ability to deal with nonlinear cost
2549  * interpolation for partial retrievals, we would not need to be
2550  * so conservative about this.)
2551  *
2552  * This case is also different from the above in that we have to
2553  * account for possibly injecting sorts into subpaths that aren't
2554  * natively ordered.
2555  */
2556  foreach(l, apath->subpaths)
2557  {
2558  Path *subpath = (Path *) lfirst(l);
2559  Path sort_path; /* dummy for result of cost_sort */
2560 
2561  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2562  {
2563  /*
2564  * We'll need to insert a Sort node, so include costs for
2565  * that. We can use the parent's LIMIT if any, since we
2566  * certainly won't pull more than that many tuples from
2567  * any child.
2568  */
2569  cost_sort(&sort_path,
2570  root,
2571  pathkeys,
2572  subpath->total_cost,
2573  subpath->rows,
2574  subpath->pathtarget->width,
2575  0.0,
2576  work_mem,
2577  apath->limit_tuples);
2578  subpath = &sort_path;
2579  }
2580 
2581  apath->path.rows += subpath->rows;
2582  apath->path.startup_cost += subpath->startup_cost;
2583  apath->path.total_cost += subpath->total_cost;
2584  }
2585  }
2586  }
2587  else /* parallel-aware */
2588  {
2589  int i = 0;
2590  double parallel_divisor = get_parallel_divisor(&apath->path);
2591 
2592  /* Parallel-aware Append never produces ordered output. */
2593  Assert(apath->path.pathkeys == NIL);
2594 
2595  /* Calculate startup cost. */
2596  foreach(l, apath->subpaths)
2597  {
2598  Path *subpath = (Path *) lfirst(l);
2599 
2600  /*
2601  * Append will start returning tuples when the child node having
2602  * lowest startup cost is done setting up. We consider only the
2603  * first few subplans that immediately get a worker assigned.
2604  */
2605  if (i == 0)
2606  apath->path.startup_cost = subpath->startup_cost;
2607  else if (i < apath->path.parallel_workers)
2608  apath->path.startup_cost = Min(apath->path.startup_cost,
2609  subpath->startup_cost);
2610 
2611  /*
2612  * Apply parallel divisor to subpaths. Scale the number of rows
2613  * for each partial subpath based on the ratio of the parallel
2614  * divisor originally used for the subpath to the one we adopted.
2615  * Also add the cost of partial paths to the total cost, but
2616  * ignore non-partial paths for now.
2617  */
2618  if (i < apath->first_partial_path)
2619  apath->path.rows += subpath->rows / parallel_divisor;
2620  else
2621  {
2622  double subpath_parallel_divisor;
2623 
2624  subpath_parallel_divisor = get_parallel_divisor(subpath);
2625  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2626  parallel_divisor);
2627  apath->path.total_cost += subpath->total_cost;
2628  }
2629 
2630  apath->path.rows = clamp_row_est(apath->path.rows);
2631 
2632  i++;
2633  }
2634 
2635  /* Add cost for non-partial subpaths. */
2636  apath->path.total_cost +=
2637  append_nonpartial_cost(apath->subpaths,
2638  apath->first_partial_path,
2639  apath->path.parallel_workers);
2640  }
2641 
2642  /*
2643  * Although Append does not do any selection or projection, it's not free;
2644  * add a small per-tuple overhead.
2645  */
2646  apath->path.total_cost +=
2647  cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
2648 }
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:110
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2426
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6409
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:2395
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:329
#define lfirst(lc)
Definition: pg_list.h:169
#define linitial(l)
Definition: pg_list.h:174

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

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

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

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1171 of file costsize.c.

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

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

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

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

1652 {
1653  Cost startup_cost = 0;
1654  Cost run_cost = 0;
1655  QualCost qpqual_cost;
1656  Cost cpu_per_tuple;
1657 
1658  /* Should only be applied to base relations that are CTEs */
1659  Assert(baserel->relid > 0);
1660  Assert(baserel->rtekind == RTE_CTE);
1661 
1662  /* Mark the path with the correct row estimate */
1663  if (param_info)
1664  path->rows = param_info->ppi_rows;
1665  else
1666  path->rows = baserel->rows;
1667 
1668  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1669  cpu_per_tuple = cpu_tuple_cost;
1670 
1671  /* Add scanning CPU costs */
1672  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1673 
1674  startup_cost += qpqual_cost.startup;
1675  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1676  run_cost += cpu_per_tuple * baserel->tuples;
1677 
1678  /* tlist eval costs are paid per output row, not per tuple scanned */
1679  startup_cost += path->pathtarget->cost.startup;
1680  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1681 
1682  path->startup_cost = startup_cost;
1683  path->total_cost = startup_cost + run_cost;
1684 }
@ RTE_CTE
Definition: parsenodes.h:1004

References Assert(), PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_CTE, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

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

Definition at line 1483 of file costsize.c.

1485 {
1486  Cost startup_cost = 0;
1487  Cost run_cost = 0;
1488  QualCost qpqual_cost;
1489  Cost cpu_per_tuple;
1490  RangeTblEntry *rte;
1491  QualCost exprcost;
1492 
1493  /* Should only be applied to base relations that are functions */
1494  Assert(baserel->relid > 0);
1495  rte = planner_rt_fetch(baserel->relid, root);
1496  Assert(rte->rtekind == RTE_FUNCTION);
1497 
1498  /* Mark the path with the correct row estimate */
1499  if (param_info)
1500  path->rows = param_info->ppi_rows;
1501  else
1502  path->rows = baserel->rows;
1503 
1504  /*
1505  * Estimate costs of executing the function expression(s).
1506  *
1507  * Currently, nodeFunctionscan.c always executes the functions to
1508  * completion before returning any rows, and caches the results in a
1509  * tuplestore. So the function eval cost is all startup cost, and per-row
1510  * costs are minimal.
1511  *
1512  * XXX in principle we ought to charge tuplestore spill costs if the
1513  * number of rows is large. However, given how phony our rowcount
1514  * estimates for functions tend to be, there's not a lot of point in that
1515  * refinement right now.
1516  */
1517  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1518 
1519  startup_cost += exprcost.startup + exprcost.per_tuple;
1520 
1521  /* Add scanning CPU costs */
1522  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1523 
1524  startup_cost += qpqual_cost.startup;
1525  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1526  run_cost += cpu_per_tuple * baserel->tuples;
1527 
1528  /* tlist eval costs are paid per output row, not per tuple scanned */
1529  startup_cost += path->pathtarget->cost.startup;
1530  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1531 
1532  path->startup_cost = startup_cost;
1533  path->total_cost = startup_cost + run_cost;
1534 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4693
@ RTE_FUNCTION
Definition: parsenodes.h:1001
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:389
Definition: nodes.h:574
List * functions
Definition: parsenodes.h:1109
RTEKind rtekind
Definition: parsenodes.h:1015

References Assert(), PathTarget::cost, cost_qual_eval_node(), cpu_tuple_cost, RangeTblEntry::functions, get_restriction_qual_cost(), Path::pathtarget, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_FUNCTION, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 406 of file costsize.c.

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

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

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

3196 {
3197  double output_tuples;
3198  Cost startup_cost;
3199  Cost total_cost;
3200 
3201  output_tuples = numGroups;
3202  startup_cost = input_startup_cost;
3203  total_cost = input_total_cost;
3204 
3205  /*
3206  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3207  * all columns get compared at most of the tuples.
3208  */
3209  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3210 
3211  /*
3212  * If there are quals (HAVING quals), account for their cost and
3213  * selectivity.
3214  */
3215  if (quals)
3216  {
3217  QualCost qual_cost;
3218 
3219  cost_qual_eval(&qual_cost, quals, root);
3220  startup_cost += qual_cost.startup;
3221  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3222 
3223  output_tuples = clamp_row_est(output_tuples *
3225  quals,
3226  0,
3227  JOIN_INNER,
3228  NULL));
3229  }
3230 
3231  path->rows = output_tuples;
3232  path->startup_cost = startup_cost;
3233  path->total_cost = total_cost;
3234 }

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

2260 {
2261  Cost startup_cost,
2262  run_cost,
2263  input_run_cost = input_total_cost - input_startup_cost;
2264  double group_tuples,
2265  input_groups;
2266  Cost group_startup_cost,
2267  group_run_cost,
2268  group_input_run_cost;
2269  List *presortedExprs = NIL;
2270  ListCell *l;
2271  int i = 0;
2272  bool unknown_varno = false;
2273 
2274  Assert(presorted_keys != 0);
2275 
2276  /*
2277  * We want to be sure the cost of a sort is never estimated as zero, even
2278  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
2279  */
2280  if (input_tuples < 2.0)
2281  input_tuples = 2.0;
2282 
2283  /* Default estimate of number of groups, capped to one group per row. */
2284  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
2285 
2286  /*
2287  * Extract presorted keys as list of expressions.
2288  *
2289  * We need to be careful about Vars containing "varno 0" which might have
2290  * been introduced by generate_append_tlist, which would confuse
2291  * estimate_num_groups (in fact it'd fail for such expressions). See
2292  * recurse_set_operations which has to deal with the same issue.
2293  *
2294  * Unlike recurse_set_operations we can't access the original target list
2295  * here, and even if we could it's not very clear how useful would that be
2296  * for a set operation combining multiple tables. So we simply detect if
2297  * there are any expressions with "varno 0" and use the default
2298  * DEFAULT_NUM_DISTINCT in that case.
2299  *
2300  * We might also use either 1.0 (a single group) or input_tuples (each row
2301  * being a separate group), pretty much the worst and best case for
2302  * incremental sort. But those are extreme cases and using something in
2303  * between seems reasonable. Furthermore, generate_append_tlist is used
2304  * for set operations, which are likely to produce mostly unique output
2305  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2306  * while maintaining lower startup cost.
2307  */
2308  foreach(l, pathkeys)
2309  {
2310  PathKey *key = (PathKey *) lfirst(l);
2311  EquivalenceMember *member = (EquivalenceMember *)
2312  linitial(key->pk_eclass->ec_members);
2313 
2314  /*
2315  * Check if the expression contains Var with "varno 0" so that we
2316  * don't call estimate_num_groups in that case.
2317  */
2318  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2319  {
2320  unknown_varno = true;
2321  break;
2322  }
2323 
2324  /* expression not containing any Vars with "varno 0" */
2325  presortedExprs = lappend(presortedExprs, member->em_expr);
2326 
2327  i++;
2328  if (i >= presorted_keys)
2329  break;
2330  }
2331 
2332  /* Estimate number of groups with equal presorted keys. */
2333  if (!unknown_varno)
2334  input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2335  NULL, NULL);
2336 
2337  group_tuples = input_tuples / input_groups;
2338  group_input_run_cost = input_run_cost / input_groups;
2339 
2340  /*
2341  * Estimate average cost of sorting of one group where presorted keys are
2342  * equal. Incremental sort is sensitive to distribution of tuples to the
2343  * groups, where we're relying on quite rough assumptions. Thus, we're
2344  * pessimistic about incremental sort performance and increase its average
2345  * group size by half.
2346  */
2347  cost_tuplesort(root, pathkeys, &group_startup_cost, &group_run_cost,
2348  1.5 * group_tuples, width, comparison_cost, sort_mem,
2349  limit_tuples);
2350 
2351  /*
2352  * Startup cost of incremental sort is the startup cost of its first group
2353  * plus the cost of its input.
2354  */
2355  startup_cost = group_startup_cost
2356  + input_startup_cost + group_input_run_cost;
2357 
2358  /*
2359  * After we started producing tuples from the first group, the cost of
2360  * producing all the tuples is given by the cost to finish processing this
2361  * group, plus the total cost to process the remaining groups, plus the
2362  * remaining cost of input.
2363  */
2364  run_cost = group_run_cost
2365  + (group_run_cost + group_startup_cost) * (input_groups - 1)
2366  + group_input_run_cost * (input_groups - 1);
2367 
2368  /*
2369  * Incremental sort adds some overhead by itself. Firstly, it has to
2370  * detect the sort groups. This is roughly equal to one extra copy and
2371  * comparison per tuple. Secondly, it has to reset the tuplesort context
2372  * for every group.
2373  */
2374  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2375  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2376 
2377  path->rows = input_tuples;
2378  path->startup_cost = startup_cost;
2379  path->total_cost = startup_cost + run_cost;
2380 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
static void cost_tuplesort(PlannerInfo *root, List *pathkeys, Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:2159
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:100

References Assert(), bms_is_member(), cost_tuplesort(), cpu_tuple_cost, DEFAULT_NUM_DISTINCT, EquivalenceMember::em_expr, estimate_num_groups(), i, sort-test::key, lappend(), lfirst, linitial, 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 519 of file costsize.c.

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

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

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2724 of file costsize.c.

2727 {
2728  Cost startup_cost = input_startup_cost;
2729  Cost run_cost = input_total_cost - input_startup_cost;
2730  double nbytes = relation_byte_size(tuples, width);
2731  long work_mem_bytes = work_mem * 1024L;
2732 
2733  path->rows = tuples;
2734 
2735  /*
2736  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2737  * reflect bookkeeping overhead. (This rate must be more than what
2738  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2739  * if it is exactly the same then there will be a cost tie between
2740  * nestloop with A outer, materialized B inner and nestloop with B outer,
2741  * materialized A inner. The extra cost ensures we'll prefer
2742  * materializing the smaller rel.) Note that this is normally a good deal
2743  * less than cpu_tuple_cost; which is OK because a Material plan node
2744  * doesn't do qual-checking or projection, so it's got less overhead than
2745  * most plan nodes.
2746  */
2747  run_cost += 2 * cpu_operator_cost * tuples;
2748 
2749  /*
2750  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2751  * This cost is assumed to be evenly spread through the plan run phase,
2752  * which isn't exactly accurate but our cost model doesn't allow for
2753  * nonuniform costs within the run phase.
2754  */
2755  if (nbytes > work_mem_bytes)
2756  {
2757  double npages = ceil(nbytes / BLCKSZ);
2758 
2759  run_cost += seq_page_cost * npages;
2760  }
2761 
2762  path->startup_cost = startup_cost;
2763  path->total_cost = startup_cost + run_cost;
2764 }

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

2679 {
2680  Cost startup_cost = 0;
2681  Cost run_cost = 0;
2682  Cost comparison_cost;
2683  double N;
2684  double logN;
2685 
2686  /*
2687  * Avoid log(0)...
2688  */
2689  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2690  logN = LOG2(N);
2691 
2692  /* Assumed cost per tuple comparison */
2693  comparison_cost = 2.0 * cpu_operator_cost;
2694 
2695  /* Heap creation cost */
2696  startup_cost += comparison_cost * N * logN;
2697 
2698  /* Per-tuple heap maintenance cost */
2699  run_cost += tuples * comparison_cost * logN;
2700 
2701  /*
2702  * Although MergeAppend does not do any selection or projection, it's not
2703  * free; add a small per-tuple overhead.
2704  */
2705  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2706 
2707  path->startup_cost = startup_cost + input_startup_cost;
2708  path->total_cost = startup_cost + run_cost + input_total_cost;
2709 }

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

1693 {
1694  Cost startup_cost = 0;
1695  Cost run_cost = 0;
1696  QualCost qpqual_cost;
1697  Cost cpu_per_tuple;
1698 
1699  /* Should only be applied to base relations that are Tuplestores */
1700  Assert(baserel->relid > 0);
1701  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1702 
1703  /* Mark the path with the correct row estimate */
1704  if (param_info)
1705  path->rows = param_info->ppi_rows;
1706  else
1707  path->rows = baserel->rows;
1708 
1709  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1710  cpu_per_tuple = cpu_tuple_cost;
1711 
1712  /* Add scanning CPU costs */
1713  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1714 
1715  startup_cost += qpqual_cost.startup;
1716  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1717  run_cost += cpu_per_tuple * baserel->tuples;
1718 
1719  path->startup_cost = startup_cost;
1720  path->total_cost = startup_cost + run_cost;
1721 }
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1005

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

4668 {
4669  cost_qual_eval_context context;
4670  ListCell *l;
4671 
4672  context.root = root;
4673  context.total.startup = 0;
4674  context.total.per_tuple = 0;
4675 
4676  /* We don't charge any cost for the implicit ANDing at top level ... */
4677 
4678  foreach(l, quals)
4679  {
4680  Node *qual = (Node *) lfirst(l);
4681 
4682  cost_qual_eval_walker(qual, &context);
4683  }
4684 
4685  *cost = context.total;
4686 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4707
PlannerInfo * root
Definition: costsize.c:158

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

1766 {
1767  Cost startup_cost;
1768  Cost total_cost;
1769  double total_rows;
1770 
1771  /* We probably have decent estimates for the non-recursive term */
1772  startup_cost = nrterm->startup_cost;
1773  total_cost = nrterm->total_cost;
1774  total_rows = nrterm->rows;
1775 
1776  /*
1777  * We arbitrarily assume that about 10 recursive iterations will be
1778  * needed, and that we've managed to get a good fix on the cost and output
1779  * size of each one of them. These are mighty shaky assumptions but it's
1780  * hard to see how to do better.
1781  */
1782  total_cost += 10 * rterm->total_cost;
1783  total_rows += 10 * rterm->rows;
1784 
1785  /*
1786  * Also charge cpu_tuple_cost per row to account for the costs of
1787  * manipulating the tuplestores. (We don't worry about possible
1788  * spill-to-disk costs.)
1789  */
1790  total_cost += cpu_tuple_cost * total_rows;
1791 
1792  runion->startup_cost = startup_cost;
1793  runion->total_cost = total_cost;
1794  runion->rows = total_rows;
1795  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1796  rterm->pathtarget->width);
1797 }

References cpu_tuple_cost, Max, Path::pathtarget, Path::rows, Path::startup_cost, Path::total_cost, and PathTarget::width.

Referenced by create_recursiveunion_path().

◆ cost_resultscan()

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

Definition at line 1728 of file costsize.c.

1730 {
1731  Cost startup_cost = 0;
1732  Cost run_cost = 0;
1733  QualCost qpqual_cost;
1734  Cost cpu_per_tuple;
1735 
1736  /* Should only be applied to RTE_RESULT base relations */
1737  Assert(baserel->relid > 0);
1738  Assert(baserel->rtekind == RTE_RESULT);
1739 
1740  /* Mark the path with the correct row estimate */
1741  if (param_info)
1742  path->rows = param_info->ppi_rows;
1743  else
1744  path->rows = baserel->rows;
1745 
1746  /* We charge qual cost plus cpu_tuple_cost */
1747  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1748 
1749  startup_cost += qpqual_cost.startup;
1750  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1751  run_cost += cpu_per_tuple * baserel->tuples;
1752 
1753  path->startup_cost = startup_cost;
1754  path->total_cost = startup_cost + run_cost;
1755 }
@ RTE_RESULT
Definition: parsenodes.h:1006

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

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

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

Referenced by create_samplescan_path().

◆ cost_seqscan()

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

Definition at line 254 of file costsize.c.

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

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

Referenced by create_seqscan_path().

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

2400 {
2401  Cost startup_cost;
2402  Cost run_cost;
2403 
2404  cost_tuplesort(root, pathkeys, &startup_cost, &run_cost,
2405  tuples, width,
2406  comparison_cost, sort_mem,
2407  limit_tuples);
2408 
2409  if (!enable_sort)
2410  startup_cost += disable_cost;
2411 
2412  startup_cost += input_cost;
2413 
2414  path->rows = tuples;
2415  path->startup_cost = startup_cost;
2416  path->total_cost = startup_cost + run_cost;
2417 }
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_sort_estimate()

Cost cost_sort_estimate ( PlannerInfo root,
List pathkeys,
int  nPresortedKeys,
double  tuples 
)

Definition at line 2113 of file costsize.c.

2115 {
2116  return compute_cpu_sort_cost(root, pathkeys, nPresortedKeys,
2117  0, tuples, tuples, false);
2118 }
static Cost compute_cpu_sort_cost(PlannerInfo *root, List *pathkeys, int nPresortedKeys, Cost comparison_cost, double tuples, double output_tuples, bool heapSort)
Definition: costsize.c:1927

References compute_cpu_sort_cost().

Referenced by get_cheapest_group_keys_order().

◆ cost_subplan()

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

Definition at line 4462 of file costsize.c.

4463 {
4464  QualCost sp_cost;
4465 
4466  /* Figure any cost for evaluating the testexpr */
4467  cost_qual_eval(&sp_cost,
4468  make_ands_implicit((Expr *) subplan->testexpr),
4469  root);
4470 
4471  if (subplan->useHashTable)
4472  {
4473  /*
4474  * If we are using a hash table for the subquery outputs, then the
4475  * cost of evaluating the query is a one-time cost. We charge one
4476  * cpu_operator_cost per tuple for the work of loading the hashtable,
4477  * too.
4478  */
4479  sp_cost.startup += plan->total_cost +
4480  cpu_operator_cost * plan->plan_rows;
4481 
4482  /*
4483  * The per-tuple costs include the cost of evaluating the lefthand
4484  * expressions, plus the cost of probing the hashtable. We already
4485  * accounted for the lefthand expressions as part of the testexpr, and
4486  * will also have counted one cpu_operator_cost for each comparison
4487  * operator. That is probably too low for the probing cost, but it's
4488  * hard to make a better estimate, so live with it for now.
4489  */
4490  }
4491  else
4492  {
4493  /*
4494  * Otherwise we will be rescanning the subplan output on each
4495  * evaluation. We need to estimate how much of the output we will
4496  * actually need to scan. NOTE: this logic should agree with the
4497  * tuple_fraction estimates used by make_subplan() in
4498  * plan/subselect.c.
4499  */
4500  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4501 
4502  if (subplan->subLinkType == EXISTS_SUBLINK)
4503  {
4504  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4505  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4506  }
4507  else if (subplan->subLinkType == ALL_SUBLINK ||
4508  subplan->subLinkType == ANY_SUBLINK)
4509  {
4510  /* assume we need 50% of the tuples */
4511  sp_cost.per_tuple += 0.50 * plan_run_cost;
4512  /* also charge a cpu_operator_cost per row examined */
4513  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4514  }
4515  else
4516  {
4517  /* assume we need all tuples */
4518  sp_cost.per_tuple += plan_run_cost;
4519  }
4520 
4521  /*
4522  * Also account for subplan's startup cost. If the subplan is
4523  * uncorrelated or undirect correlated, AND its topmost node is one
4524  * that materializes its output, assume that we'll only need to pay
4525  * its startup cost once; otherwise assume we pay the startup cost
4526  * every time.
4527  */
4528  if (subplan->parParam == NIL &&
4530  sp_cost.startup += plan->startup_cost;
4531  else
4532  sp_cost.per_tuple += plan->startup_cost;
4533  }
4534 
4535  subplan->startup_cost = sp_cost.startup;
4536  subplan->per_call_cost = sp_cost.per_tuple;
4537 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:720
@ ANY_SUBLINK
Definition: primnodes.h:694
@ ALL_SUBLINK
Definition: primnodes.h:693
@ EXISTS_SUBLINK
Definition: primnodes.h:692
Cost total_cost
Definition: plannodes.h:119
Cost startup_cost
Definition: plannodes.h:118
Cardinality plan_rows
Definition: plannodes.h:124
bool useHashTable
Definition: primnodes.h:770
Node * testexpr
Definition: primnodes.h:758
List * parParam
Definition: primnodes.h:781
Cost startup_cost
Definition: primnodes.h:784
Cost per_call_cost
Definition: primnodes.h:785
SubLinkType subLinkType
Definition: primnodes.h:756

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 
)

Definition at line 1420 of file costsize.c.

1422 {
1423  Cost startup_cost;
1424  Cost run_cost;
1425  List *qpquals;
1426  QualCost qpqual_cost;
1427  Cost cpu_per_tuple;
1428 
1429  /* Should only be applied to base relations that are subqueries */
1430  Assert(baserel->relid > 0);
1431  Assert(baserel->rtekind == RTE_SUBQUERY);
1432 
1433  /*
1434  * We compute the rowcount estimate as the subplan's estimate times the
1435  * selectivity of relevant restriction clauses. In simple cases this will
1436  * come out the same as baserel->rows; but when dealing with parallelized
1437  * paths we must do it like this to get the right answer.
1438  */
1439  if (param_info)
1440  qpquals = list_concat_copy(param_info->ppi_clauses,
1441  baserel->baserestrictinfo);
1442  else
1443  qpquals = baserel->baserestrictinfo;
1444 
1445  path->path.rows = clamp_row_est(path->subpath->rows *
1447  qpquals,
1448  0,
1449  JOIN_INNER,
1450  NULL));
1451 
1452  /*
1453  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1454  * any restriction clauses and tlist that will be attached to the
1455  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1456  * projection overhead.
1457  */
1458  path->path.startup_cost = path->subpath->startup_cost;
1459  path->path.total_cost = path->subpath->total_cost;
1460 
1461  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1462 
1463  startup_cost = qpqual_cost.startup;
1464  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1465  run_cost = cpu_per_tuple * path->subpath->rows;
1466 
1467  /* tlist eval costs are paid per output row, not per tuple scanned */
1468  startup_cost += path->path.pathtarget->cost.startup;
1469  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1470 
1471  path->path.startup_cost += startup_cost;
1472  path->path.total_cost += startup_cost + run_cost;
1473 }
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:577
@ RTE_SUBQUERY
Definition: parsenodes.h:999
List * baserestrictinfo
Definition: pathnodes.h:746

References Assert(), RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), SubqueryScanPath::path, Path::pathtarget, 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 1544 of file costsize.c.

1546 {
1547  Cost startup_cost = 0;
1548  Cost run_cost = 0;
1549  QualCost qpqual_cost;
1550  Cost cpu_per_tuple;
1551  RangeTblEntry *rte;
1552  QualCost exprcost;
1553 
1554  /* Should only be applied to base relations that are functions */
1555  Assert(baserel->relid > 0);
1556  rte = planner_rt_fetch(baserel->relid, root);
1557  Assert(rte->rtekind == RTE_TABLEFUNC);
1558 
1559  /* Mark the path with the correct row estimate */
1560  if (param_info)
1561  path->rows = param_info->ppi_rows;
1562  else
1563  path->rows = baserel->rows;
1564 
1565  /*
1566  * Estimate costs of executing the table func expression(s).
1567  *
1568  * XXX in principle we ought to charge tuplestore spill costs if the
1569  * number of rows is large. However, given how phony our rowcount
1570  * estimates for tablefuncs tend to be, there's not a lot of point in that
1571  * refinement right now.
1572  */
1573  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1574 
1575  startup_cost += exprcost.startup + exprcost.per_tuple;
1576 
1577  /* Add scanning CPU costs */
1578  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1579 
1580  startup_cost += qpqual_cost.startup;
1581  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1582  run_cost += cpu_per_tuple * baserel->tuples;
1583 
1584  /* tlist eval costs are paid per output row, not per tuple scanned */
1585  startup_cost += path->pathtarget->cost.startup;
1586  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1587 
1588  path->startup_cost = startup_cost;
1589  path->total_cost = startup_cost + run_cost;
1590 }
@ RTE_TABLEFUNC
Definition: parsenodes.h:1002
TableFunc * tablefunc
Definition: parsenodes.h:1115

References Assert(), PathTarget::cost, cost_qual_eval_node(), cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_TABLEFUNC, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, RangeTblEntry::tablefunc, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1327 of file costsize.c.

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

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

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1219 of file costsize.c.

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

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

Referenced by create_tidscan_path().

◆ cost_valuesscan()

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

Definition at line 1600 of file costsize.c.

1602 {
1603  Cost startup_cost = 0;
1604  Cost run_cost = 0;
1605  QualCost qpqual_cost;
1606  Cost cpu_per_tuple;
1607 
1608  /* Should only be applied to base relations that are values lists */
1609  Assert(baserel->relid > 0);
1610  Assert(baserel->rtekind == RTE_VALUES);
1611 
1612  /* Mark the path with the correct row estimate */
1613  if (param_info)
1614  path->rows = param_info->ppi_rows;
1615  else
1616  path->rows = baserel->rows;
1617 
1618  /*
1619  * For now, estimate list evaluation cost at one operator eval per list
1620  * (probably pretty bogus, but is it worth being smarter?)
1621  */
1622  cpu_per_tuple = cpu_operator_cost;
1623 
1624  /* Add scanning CPU costs */
1625  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1626 
1627  startup_cost += qpqual_cost.startup;
1628  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1629  run_cost += cpu_per_tuple * baserel->tuples;
1630 
1631  /* tlist eval costs are paid per output row, not per tuple scanned */
1632  startup_cost += path->pathtarget->cost.startup;
1633  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1634 
1635  path->startup_cost = startup_cost;
1636  path->total_cost = startup_cost + run_cost;
1637 }
@ RTE_VALUES
Definition: parsenodes.h:1003

References Assert(), PathTarget::cost, cpu_operator_cost, cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_VALUES, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_valuesscan_path().

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

3121 {
3122  Cost startup_cost;
3123  Cost total_cost;
3124  ListCell *lc;
3125 
3126  startup_cost = input_startup_cost;
3127  total_cost = input_total_cost;
3128 
3129  /*
3130  * Window functions are assumed to cost their stated execution cost, plus
3131  * the cost of evaluating their input expressions, per tuple. Since they
3132  * may in fact evaluate their inputs at multiple rows during each cycle,
3133  * this could be a drastic underestimate; but without a way to know how
3134  * many rows the window function will fetch, it's hard to do better. In
3135  * any case, it's a good estimate for all the built-in window functions,
3136  * so we'll just do this for now.
3137  */
3138  foreach(lc, windowFuncs)
3139  {
3140  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3141  Cost wfunccost;
3142  QualCost argcosts;
3143 
3144  argcosts.startup = argcosts.per_tuple = 0;
3145  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3146  &argcosts);
3147  startup_cost += argcosts.startup;
3148  wfunccost = argcosts.per_tuple;
3149 
3150  /* also add the input expressions' cost to per-input-row costs */
3151  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3152  startup_cost += argcosts.startup;
3153  wfunccost += argcosts.per_tuple;
3154 
3155  /*
3156  * Add the filter's cost to per-input-row costs. XXX We should reduce
3157  * input expression costs according to filter selectivity.
3158  */
3159  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3160  startup_cost += argcosts.startup;
3161  wfunccost += argcosts.per_tuple;
3162 
3163  total_cost += wfunccost * input_tuples;
3164  }
3165 
3166  /*
3167  * We also charge cpu_operator_cost per grouping column per tuple for
3168  * grouping comparisons, plus cpu_tuple_cost per tuple for general
3169  * overhead.
3170  *
3171  * XXX this neglects costs of spooling the data to disk when it overflows
3172  * work_mem. Sooner or later that should get accounted for.
3173  */
3174  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3175  total_cost += cpu_tuple_cost * input_tuples;
3176 
3177  path->rows = input_tuples;
3178  path->startup_cost = startup_cost;
3179  path->total_cost = total_cost;
3180 }
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1988
List * args
Definition: primnodes.h:399
Expr * aggfilter
Definition: primnodes.h:400
Oid winfnoid
Definition: primnodes.h:395

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

4211 {
4212  Path *outer_path = path->jpath.outerjoinpath;
4213  Path *inner_path = path->jpath.innerjoinpath;
4214  double outer_path_rows = outer_path->rows;
4215  double inner_path_rows = inner_path->rows;
4216  double inner_path_rows_total = workspace->inner_rows_total;
4217  List *hashclauses = path->path_hashclauses;
4218  Cost startup_cost = workspace->startup_cost;
4219  Cost run_cost = workspace->run_cost;
4220  int numbuckets = workspace->numbuckets;
4221  int numbatches = workspace->numbatches;
4222  Cost cpu_per_tuple;
4223  QualCost hash_qual_cost;
4224  QualCost qp_qual_cost;
4225  double hashjointuples;
4226  double virtualbuckets;
4227  Selectivity innerbucketsize;
4228  Selectivity innermcvfreq;
4229  ListCell *hcl;
4230 
4231  /* Mark the path with the correct row estimate */
4232  if (path->jpath.path.param_info)
4233  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4234  else
4235  path->jpath.path.rows = path->jpath.path.parent->rows;
4236 
4237  /* For partial paths, scale row estimate. */
4238  if (path->jpath.path.parallel_workers > 0)
4239  {
4240  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4241 
4242  path->jpath.path.rows =
4243  clamp_row_est(path->jpath.path.rows / parallel_divisor);
4244  }
4245 
4246  /*
4247  * We could include disable_cost in the preliminary estimate, but that
4248  * would amount to optimizing for the case where the join method is
4249  * disabled, which doesn't seem like the way to bet.
4250  */
4251  if (!enable_hashjoin)
4252  startup_cost += disable_cost;
4253 
4254  /* mark the path with estimated # of batches */
4255  path->num_batches = numbatches;
4256 
4257  /* store the total number of tuples (sum of partial row estimates) */
4258  path->inner_rows_total = inner_path_rows_total;
4259 
4260  /* and compute the number of "virtual" buckets in the whole join */
4261  virtualbuckets = (double) numbuckets * (double) numbatches;
4262 
4263  /*
4264  * Determine bucketsize fraction and MCV frequency for the inner relation.
4265  * We use the smallest bucketsize or MCV frequency estimated for any
4266  * individual hashclause; this is undoubtedly conservative.
4267  *
4268  * BUT: if inner relation has been unique-ified, we can assume it's good
4269  * for hashing. This is important both because it's the right answer, and
4270  * because we avoid contaminating the cache with a value that's wrong for
4271  * non-unique-ified paths.
4272  */
4273  if (IsA(inner_path, UniquePath))
4274  {
4275  innerbucketsize = 1.0 / virtualbuckets;
4276  innermcvfreq = 0.0;
4277  }
4278  else
4279  {
4280  innerbucketsize = 1.0;
4281  innermcvfreq = 1.0;
4282  foreach(hcl, hashclauses)
4283  {
4284  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4285  Selectivity thisbucketsize;
4286  Selectivity thismcvfreq;
4287 
4288  /*
4289  * First we have to figure out which side of the hashjoin clause
4290  * is the inner side.
4291  *
4292  * Since we tend to visit the same clauses over and over when
4293  * planning a large query, we cache the bucket stats estimates in
4294  * the RestrictInfo node to avoid repeated lookups of statistics.
4295  */
4296  if (bms_is_subset(restrictinfo->right_relids,
4297  inner_path->parent->relids))
4298  {
4299  /* righthand side is inner */
4300  thisbucketsize = restrictinfo->right_bucketsize;
4301  if (thisbucketsize < 0)
4302  {
4303  /* not cached yet */
4305  get_rightop(restrictinfo->clause),
4306  virtualbuckets,
4307  &restrictinfo->right_mcvfreq,
4308  &restrictinfo->right_bucketsize);
4309  thisbucketsize = restrictinfo->right_bucketsize;
4310  }
4311  thismcvfreq = restrictinfo->right_mcvfreq;
4312  }
4313  else
4314  {
4315  Assert(bms_is_subset(restrictinfo->left_relids,
4316  inner_path->parent->relids));
4317  /* lefthand side is inner */
4318  thisbucketsize = restrictinfo->left_bucketsize;
4319  if (thisbucketsize < 0)
4320  {
4321  /* not cached yet */
4323  get_leftop(restrictinfo->clause),
4324  virtualbuckets,
4325  &restrictinfo->left_mcvfreq,
4326  &restrictinfo->left_bucketsize);
4327  thisbucketsize = restrictinfo->left_bucketsize;
4328  }
4329  thismcvfreq = restrictinfo->left_mcvfreq;
4330  }
4331 
4332  if (innerbucketsize > thisbucketsize)
4333  innerbucketsize = thisbucketsize;
4334  if (innermcvfreq > thismcvfreq)
4335  innermcvfreq = thismcvfreq;
4336  }
4337  }
4338 
4339  /*
4340  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4341  * want to hash unless there is really no other alternative, so apply
4342  * disable_cost. (The executor normally copes with excessive memory usage
4343  * by splitting batches, but obviously it cannot separate equal values
4344  * that way, so it will be unable to drive the batch size below hash_mem
4345  * when this is true.)
4346  */
4347  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4348  inner_path->pathtarget->width) > get_hash_memory_limit())
4349  startup_cost += disable_cost;
4350 
4351  /*
4352  * Compute cost of the hashquals and qpquals (other restriction clauses)
4353  * separately.
4354  */
4355  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4356  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4357  qp_qual_cost.startup -= hash_qual_cost.startup;
4358  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4359 
4360  /* CPU costs */
4361 
4362  if (path->jpath.jointype == JOIN_SEMI ||
4363  path->jpath.jointype == JOIN_ANTI ||
4364  extra->inner_unique)
4365  {
4366  double outer_matched_rows;
4367  Selectivity inner_scan_frac;
4368 
4369  /*
4370  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4371  * executor will stop after the first match.
4372  *
4373  * For an outer-rel row that has at least one match, we can expect the
4374  * bucket scan to stop after a fraction 1/(match_count+1) of the
4375  * bucket's rows, if the matches are evenly distributed. Since they
4376  * probably aren't quite evenly distributed, we apply a fuzz factor of
4377  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4378  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4379  * at least 1, no such clamp is needed now.)
4380  */
4381  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4382  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4383 
4384  startup_cost += hash_qual_cost.startup;
4385  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4386  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4387 
4388  /*
4389  * For unmatched outer-rel rows, the picture is quite a lot different.
4390  * In the first place, there is no reason to assume that these rows
4391  * preferentially hit heavily-populated buckets; instead assume they
4392  * are uncorrelated with the inner distribution and so they see an
4393  * average bucket size of inner_path_rows / virtualbuckets. In the
4394  * second place, it seems likely that they will have few if any exact
4395  * hash-code matches and so very few of the tuples in the bucket will
4396  * actually require eval of the hash quals. We don't have any good
4397  * way to estimate how many will, but for the moment assume that the
4398  * effective cost per bucket entry is one-tenth what it is for
4399  * matchable tuples.
4400  */
4401  run_cost += hash_qual_cost.per_tuple *
4402  (outer_path_rows - outer_matched_rows) *
4403  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4404 
4405  /* Get # of tuples that will pass the basic join */
4406  if (path->jpath.jointype == JOIN_ANTI)
4407  hashjointuples = outer_path_rows - outer_matched_rows;
4408  else
4409  hashjointuples = outer_matched_rows;
4410  }
4411  else
4412  {
4413  /*
4414  * The number of tuple comparisons needed is the number of outer
4415  * tuples times the typical number of tuples in a hash bucket, which
4416  * is the inner relation size times its bucketsize fraction. At each
4417  * one, we need to evaluate the hashjoin quals. But actually,
4418  * charging the full qual eval cost at each tuple is pessimistic,
4419  * since we don't evaluate the quals unless the hash values match
4420  * exactly. For lack of a better idea, halve the cost estimate to
4421  * allow for that.
4422  */
4423  startup_cost += hash_qual_cost.startup;
4424  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4425  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4426 
4427  /*
4428  * Get approx # tuples passing the hashquals. We use
4429  * approx_tuple_count here because we need an estimate done with
4430  * JOIN_INNER semantics.
4431  */
4432  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4433  }
4434 
4435  /*
4436  * For each tuple that gets through the hashjoin proper, we charge
4437  * cpu_tuple_cost plus the cost of evaluating additional restriction
4438  * clauses that are to be applied at the join. (This is pessimistic since
4439  * not all of the quals may get evaluated at each tuple.)
4440  */
4441  startup_cost += qp_qual_cost.startup;
4442  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4443  run_cost += cpu_per_tuple * hashjointuples;
4444 
4445  /* tlist eval costs are paid per output row, not per tuple scanned */
4446  startup_cost += path->jpath.path.pathtarget->cost.startup;
4447  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4448 
4449  path->jpath.path.startup_cost = startup_cost;
4450  path->jpath.path.total_cost = startup_cost + run_cost;
4451 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
bool enable_hashjoin
Definition: costsize.c:147
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:5233
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:83
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:71
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3401
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3782
List * path_hashclauses
Definition: pathnodes.h:1682
Cardinality inner_rows_total
Definition: pathnodes.h:1684
int num_batches
Definition: pathnodes.h:1683
JoinPath jpath
Definition: pathnodes.h:1681
Cardinality inner_rows_total
Definition: pathnodes.h:2674
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2553
Path * outerjoinpath
Definition: pathnodes.h:1604
Path path
Definition: pathnodes.h:1597
Path * innerjoinpath
Definition: pathnodes.h:1605
JoinType jointype
Definition: pathnodes.h:1599
List * joinrestrictinfo
Definition: pathnodes.h:1607
RelOptInfo * parent
Definition: pathnodes.h:1194
Selectivity left_mcvfreq
Definition: pathnodes.h:2141
Selectivity right_bucketsize
Definition: pathnodes.h:2140
Relids right_relids
Definition: pathnodes.h:2106
Selectivity left_bucketsize
Definition: pathnodes.h:2139
Relids left_relids
Definition: pathnodes.h:2105
Selectivity right_mcvfreq
Definition: pathnodes.h:2142

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3772 of file costsize.c.

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

References approx_tuple_count(), clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), 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, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, MergePath::path_mergeclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3336 of file costsize.c.

3339 {
3340  Path *outer_path = path->jpath.outerjoinpath;
3341  Path *inner_path = path->jpath.innerjoinpath;
3342  double outer_path_rows = outer_path->rows;
3343  double inner_path_rows = inner_path->rows;
3344  Cost startup_cost = workspace->startup_cost;
3345  Cost run_cost = workspace->run_cost;
3346  Cost cpu_per_tuple;
3347  QualCost restrict_qual_cost;
3348  double ntuples;
3349 
3350  /* Protect some assumptions below that rowcounts aren't zero */
3351  if (outer_path_rows <= 0)
3352  outer_path_rows = 1;
3353  if (inner_path_rows <= 0)
3354  inner_path_rows = 1;
3355  /* Mark the path with the correct row estimate */
3356  if (path->jpath.path.param_info)
3357  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3358  else
3359  path->jpath.path.rows = path->jpath.path.parent->rows;
3360 
3361  /* For partial paths, scale row estimate. */
3362  if (path->jpath.path.parallel_workers > 0)
3363  {
3364  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3365 
3366  path->jpath.path.rows =
3367  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3368  }
3369 
3370  /*
3371  * We could include disable_cost in the preliminary estimate, but that
3372  * would amount to optimizing for the case where the join method is
3373  * disabled, which doesn't seem like the way to bet.
3374  */
3375  if (!enable_nestloop)
3376  startup_cost += disable_cost;
3377 
3378  /* cost of inner-relation source data (we already dealt with outer rel) */
3379 
3380  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3381  extra->inner_unique)
3382  {
3383  /*
3384  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3385  * executor will stop after the first match.
3386  */
3387  Cost inner_run_cost = workspace->inner_run_cost;
3388  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3389  double outer_matched_rows;
3390  double outer_unmatched_rows;
3391  Selectivity inner_scan_frac;
3392 
3393  /*
3394  * For an outer-rel row that has at least one match, we can expect the
3395  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3396  * rows, if the matches are evenly distributed. Since they probably
3397  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3398  * that fraction. (If we used a larger fuzz factor, we'd have to
3399  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3400  * least 1, no such clamp is needed now.)
3401  */
3402  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3403  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3404  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3405 
3406  /*
3407  * Compute number of tuples processed (not number emitted!). First,
3408  * account for successfully-matched outer rows.
3409  */
3410  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3411 
3412  /*
3413  * Now we need to estimate the actual costs of scanning the inner
3414  * relation, which may be quite a bit less than N times inner_run_cost
3415  * due to early scan stops. We consider two cases. If the inner path
3416  * is an indexscan using all the joinquals as indexquals, then an
3417  * unmatched outer row results in an indexscan returning no rows,
3418  * which is probably quite cheap. Otherwise, the executor will have
3419  * to scan the whole inner rel for an unmatched row; not so cheap.
3420  */
3421  if (has_indexed_join_quals(path))
3422  {
3423  /*
3424  * Successfully-matched outer rows will only require scanning
3425  * inner_scan_frac of the inner relation. In this case, we don't
3426  * need to charge the full inner_run_cost even when that's more
3427  * than inner_rescan_run_cost, because we can assume that none of
3428  * the inner scans ever scan the whole inner relation. So it's
3429  * okay to assume that all the inner scan executions can be
3430  * fractions of the full cost, even if materialization is reducing
3431  * the rescan cost. At this writing, it's impossible to get here
3432  * for a materialized inner scan, so inner_run_cost and
3433  * inner_rescan_run_cost will be the same anyway; but just in
3434  * case, use inner_run_cost for the first matched tuple and
3435  * inner_rescan_run_cost for additional ones.
3436  */
3437  run_cost += inner_run_cost * inner_scan_frac;
3438  if (outer_matched_rows > 1)
3439  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3440 
3441  /*
3442  * Add the cost of inner-scan executions for unmatched outer rows.
3443  * We estimate this as the same cost as returning the first tuple
3444  * of a nonempty scan. We consider that these are all rescans,
3445  * since we used inner_run_cost once already.
3446  */
3447  run_cost += outer_unmatched_rows *
3448  inner_rescan_run_cost / inner_path_rows;
3449 
3450  /*
3451  * We won't be evaluating any quals at all for unmatched rows, so
3452  * don't add them to ntuples.
3453  */
3454  }
3455  else
3456  {
3457  /*
3458  * Here, a complicating factor is that rescans may be cheaper than
3459  * first scans. If we never scan all the way to the end of the
3460  * inner rel, it might be (depending on the plan type) that we'd
3461  * never pay the whole inner first-scan run cost. However it is
3462  * difficult to estimate whether that will happen (and it could
3463  * not happen if there are any unmatched outer rows!), so be
3464  * conservative and always charge the whole first-scan cost once.
3465  * We consider this charge to correspond to the first unmatched
3466  * outer row, unless there isn't one in our estimate, in which
3467  * case blame it on the first matched row.
3468  */
3469 
3470  /* First, count all unmatched join tuples as being processed */
3471  ntuples += outer_unmatched_rows * inner_path_rows;
3472 
3473  /* Now add the forced full scan, and decrement appropriate count */
3474  run_cost += inner_run_cost;
3475  if (outer_unmatched_rows >= 1)
3476  outer_unmatched_rows -= 1;
3477  else
3478  outer_matched_rows -= 1;
3479 
3480  /* Add inner run cost for additional outer tuples having matches */
3481  if (outer_matched_rows > 0)
3482  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3483 
3484  /* Add inner run cost for additional unmatched outer tuples */
3485  if (outer_unmatched_rows > 0)
3486  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3487  }
3488  }
3489  else
3490  {
3491  /* Normal-case source costs were included in preliminary estimate */
3492 
3493  /* Compute number of tuples processed (not number emitted!) */
3494  ntuples = outer_path_rows * inner_path_rows;
3495  }
3496 
3497  /* CPU costs */
3498  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3499  startup_cost += restrict_qual_cost.startup;
3500  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3501  run_cost += cpu_per_tuple * ntuples;
3502 
3503  /* tlist eval costs are paid per output row, not per tuple scanned */
3504  startup_cost += path->jpath.path.pathtarget->cost.startup;
3505  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3506 
3507  path->jpath.path.startup_cost = startup_cost;
3508  path->jpath.path.total_cost = startup_cost + run_cost;
3509 }
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:5140
bool enable_nestloop
Definition: costsize.c:143
Cost inner_rescan_run_cost
Definition: pathnodes.h:2663
JoinPath jpath
Definition: pathnodes.h:1622

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

Referenced by create_nestloop_path().

◆ get_parameterized_baserel_size()

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

Definition at line 5319 of file costsize.c.

5321 {
5322  List *allclauses;
5323  double nrows;
5324 
5325  /*
5326  * Estimate the number of rows returned by the parameterized scan, knowing
5327  * that it will apply all the extra join clauses as well as the rel's own
5328  * restriction clauses. Note that we force the clauses to be treated as
5329  * non-join clauses during selectivity estimation.
5330  */
5331  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5332  nrows = rel->tuples *
5334  allclauses,
5335  rel->relid, /* do not use 0! */
5336  JOIN_INNER,
5337  NULL);
5338  nrows = clamp_row_est(nrows);
5339  /* For safety, make sure result is not more than the base estimate */
5340  if (nrows > rel->rows)
5341  nrows = rel->rows;
5342  return nrows;
5343 }

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

5405 {
5406  double nrows;
5407 
5408  /*
5409  * Estimate the number of rows returned by the parameterized join as the
5410  * sizes of the input paths times the selectivity of the clauses that have
5411  * ended up at this join node.
5412  *
5413  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5414  * on the pair of input paths provided, though ideally we'd get the same
5415  * estimate for any pair with the same parameterization.
5416  */
5417  nrows = calc_joinrel_size_estimate(root,
5418  rel,
5419  outer_path->parent,
5420  inner_path->parent,
5421  outer_path->rows,
5422  inner_path->rows,
5423  sjinfo,
5424  restrict_clauses);
5425  /* For safety, make sure result is not more than the base estimate */
5426  if (nrows > rel->rows)
5427  nrows = rel->rows;
5428  return nrows;
5429 }
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:5441

References calc_joinrel_size_estimate(), Path::parent, 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 868 of file costsize.c.

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

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

4106 {
4107  Cost startup_cost = 0;
4108  Cost run_cost = 0;
4109  double outer_path_rows = outer_path->rows;
4110  double inner_path_rows = inner_path->rows;
4111  double inner_path_rows_total = inner_path_rows;
4112  int num_hashclauses = list_length(hashclauses);
4113  int numbuckets;
4114  int numbatches;
4115  int num_skew_mcvs;
4116  size_t space_allowed; /* unused */
4117 
4118  /* cost of source data */
4119  startup_cost += outer_path->startup_cost;
4120  run_cost += outer_path->total_cost - outer_path->startup_cost;
4121  startup_cost += inner_path->total_cost;
4122 
4123  /*
4124  * Cost of computing hash function: must do it once per input tuple. We
4125  * charge one cpu_operator_cost for each column's hash function. Also,
4126  * tack on one cpu_tuple_cost per inner row, to model the costs of
4127  * inserting the row into the hashtable.
4128  *
4129  * XXX when a hashclause is more complex than a single operator, we really
4130  * should charge the extra eval costs of the left or right side, as
4131  * appropriate, here. This seems more work than it's worth at the moment.
4132  */
4133  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4134  * inner_path_rows;
4135  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
4136 
4137  /*
4138  * If this is a parallel hash build, then the value we have for
4139  * inner_rows_total currently refers only to the rows returned by each
4140  * participant. For shared hash table size estimation, we need the total
4141  * number, so we need to undo the division.
4142  */
4143  if (parallel_hash)
4144  inner_path_rows_total *= get_parallel_divisor(inner_path);
4145 
4146  /*
4147  * Get hash table size that executor would use for inner relation.
4148  *
4149  * XXX for the moment, always assume that skew optimization will be
4150  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4151  * trying to determine that for sure.
4152  *
4153  * XXX at some point it might be interesting to try to account for skew
4154  * optimization in the cost estimate, but for now, we don't.
4155  */
4156  ExecChooseHashTableSize(inner_path_rows_total,
4157  inner_path->pathtarget->width,
4158  true, /* useskew */
4159  parallel_hash, /* try_combined_hash_mem */
4160  outer_path->parallel_workers,
4161  &space_allowed,
4162  &numbuckets,
4163  &numbatches,
4164  &num_skew_mcvs);
4165 
4166  /*
4167  * If inner relation is too big then we will need to "batch" the join,
4168  * which implies writing and reading most of the tuples to disk an extra
4169  * time. Charge seq_page_cost per page, since the I/O should be nice and
4170  * sequential. Writing the inner rel counts as startup cost, all the rest
4171  * as run cost.
4172  */
4173  if (numbatches > 1)
4174  {
4175  double outerpages = page_size(outer_path_rows,
4176  outer_path->pathtarget->width);
4177  double innerpages = page_size(inner_path_rows,
4178  inner_path->pathtarget->width);
4179 
4180  startup_cost += seq_page_cost * innerpages;
4181  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4182  }
4183 
4184  /* CPU costs left for later */
4185 
4186  /* Public result fields */
4187  workspace->startup_cost = startup_cost;
4188  workspace->total_cost = startup_cost + run_cost;
4189  /* Save private data for final_cost_hashjoin */
4190  workspace->run_cost = run_cost;
4191  workspace->numbuckets = numbuckets;
4192  workspace->numbatches = numbatches;
4193  workspace->inner_rows_total = inner_path_rows_total;
4194 }
static double page_size(double tuples, int width)
Definition: costsize.c:6399
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_hash_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:668

References cpu_operator_cost, cpu_tuple_cost, ExecChooseHashTableSize(), get_parallel_divisor(), JoinCostWorkspace::inner_rows_total, list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), Path::parallel_workers, Path::pathtarget, Path::rows, JoinCostWorkspace::run_cost, seq_page_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, and PathTarget::width.

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

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

3548 {
3549  Cost startup_cost = 0;
3550  Cost run_cost = 0;
3551  double outer_path_rows = outer_path->rows;
3552  double inner_path_rows = inner_path->rows;
3553  Cost inner_run_cost;
3554  double outer_rows,
3555  inner_rows,
3556  outer_skip_rows,
3557  inner_skip_rows;
3558  Selectivity outerstartsel,
3559  outerendsel,
3560  innerstartsel,
3561  innerendsel;
3562  Path sort_path; /* dummy for result of cost_sort */
3563 
3564  /* Protect some assumptions below that rowcounts aren't zero */
3565  if (outer_path_rows <= 0)
3566  outer_path_rows = 1;
3567  if (inner_path_rows <= 0)
3568  inner_path_rows = 1;
3569 
3570  /*
3571  * A merge join will stop as soon as it exhausts either input stream
3572  * (unless it's an outer join, in which case the outer side has to be
3573  * scanned all the way anyway). Estimate fraction of the left and right
3574  * inputs that will actually need to be scanned. Likewise, we can
3575  * estimate the number of rows that will be skipped before the first join
3576  * pair is found, which should be factored into startup cost. We use only
3577  * the first (most significant) merge clause for this purpose. Since
3578  * mergejoinscansel() is a fairly expensive computation, we cache the
3579  * results in the merge clause RestrictInfo.
3580  */
3581  if (mergeclauses && jointype != JOIN_FULL)
3582  {
3583  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3584  List *opathkeys;
3585  List *ipathkeys;
3586  PathKey *opathkey;
3587  PathKey *ipathkey;
3588  MergeScanSelCache *cache;
3589 
3590  /* Get the input pathkeys to determine the sort-order details */
3591  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3592  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3593  Assert(opathkeys);
3594  Assert(ipathkeys);
3595  opathkey = (PathKey *) linitial(opathkeys);
3596  ipathkey = (PathKey *) linitial(ipathkeys);
3597  /* debugging check */
3598  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3599  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3600  opathkey->pk_strategy != ipathkey->pk_strategy ||
3601  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3602  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3603 
3604  /* Get the selectivity with caching */
3605  cache = cached_scansel(root, firstclause, opathkey);
3606 
3607  if (bms_is_subset(firstclause->left_relids,
3608  outer_path->parent->relids))
3609  {
3610  /* left side of clause is outer */
3611  outerstartsel = cache->leftstartsel;
3612  outerendsel = cache->leftendsel;
3613  innerstartsel = cache->rightstartsel;
3614  innerendsel = cache->rightendsel;
3615  }
3616  else
3617  {
3618  /* left side of clause is inner */
3619  outerstartsel = cache->rightstartsel;
3620  outerendsel = cache->rightendsel;
3621  innerstartsel = cache->leftstartsel;
3622  innerendsel = cache->leftendsel;
3623  }
3624  if (jointype == JOIN_LEFT ||
3625  jointype == JOIN_ANTI)
3626  {
3627  outerstartsel = 0.0;
3628  outerendsel = 1.0;
3629  }
3630  else if (jointype == JOIN_RIGHT)
3631  {
3632  innerstartsel = 0.0;
3633  innerendsel = 1.0;
3634  }
3635  }
3636  else
3637  {
3638  /* cope with clauseless or full mergejoin */
3639  outerstartsel = innerstartsel = 0.0;
3640  outerendsel = innerendsel = 1.0;
3641  }
3642 
3643  /*
3644  * Convert selectivities to row counts. We force outer_rows and
3645  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3646  */
3647  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3648  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3649  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3650  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3651 
3652  Assert(outer_skip_rows <= outer_rows);
3653  Assert(inner_skip_rows <= inner_rows);
3654 
3655  /*
3656  * Readjust scan selectivities to account for above rounding. This is
3657  * normally an insignificant effect, but when there are only a few rows in
3658  * the inputs, failing to do this makes for a large percentage error.
3659  */
3660  outerstartsel = outer_skip_rows / outer_path_rows;
3661  innerstartsel = inner_skip_rows / inner_path_rows;
3662  outerendsel = outer_rows / outer_path_rows;
3663  innerendsel = inner_rows / inner_path_rows;
3664 
3665  Assert(outerstartsel <= outerendsel);
3666  Assert(innerstartsel <= innerendsel);
3667 
3668  /* cost of source data */
3669 
3670  if (outersortkeys) /* do we need to sort outer? */
3671  {
3672  cost_sort(&sort_path,
3673  root,
3674  outersortkeys,
3675  outer_path->total_cost,
3676  outer_path_rows,
3677  outer_path->pathtarget->width,
3678  0.0,
3679  work_mem,
3680  -1.0);
3681  startup_cost += sort_path.startup_cost;
3682  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3683  * outerstartsel;
3684  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3685  * (outerendsel - outerstartsel);
3686  }
3687  else
3688  {
3689  startup_cost += outer_path->startup_cost;
3690  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3691  * outerstartsel;
3692  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3693  * (outerendsel - outerstartsel);
3694  }
3695 
3696  if (innersortkeys) /* do we need to sort inner? */
3697  {
3698  cost_sort(&sort_path,
3699  root,
3700  innersortkeys,
3701  inner_path->total_cost,
3702  inner_path_rows,
3703  inner_path->pathtarget->width,
3704  0.0,
3705  work_mem,
3706  -1.0);
3707  startup_cost += sort_path.startup_cost;
3708  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3709  * innerstartsel;
3710  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3711  * (innerendsel - innerstartsel);
3712  }
3713  else
3714  {
3715  startup_cost += inner_path->startup_cost;
3716  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3717  * innerstartsel;
3718  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3719  * (innerendsel - innerstartsel);
3720  }
3721 
3722  /*
3723  * We can't yet determine whether rescanning occurs, or whether
3724  * materialization of the inner input should be done. The minimum
3725  * possible inner input cost, regardless of rescan and materialization
3726  * considerations, is inner_run_cost. We include that in
3727  * workspace->total_cost, but not yet in run_cost.
3728  */
3729 
3730  /* CPU costs left for later */
3731 
3732  /* Public result fields */
3733  workspace->startup_cost = startup_cost;
3734  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3735  /* Save private data for final_cost_mergejoin */
3736  workspace->run_cost = run_cost;
3737  workspace->inner_run_cost = inner_run_cost;
3738  workspace->outer_rows = outer_rows;
3739  workspace->inner_rows = inner_rows;
3740  workspace->outer_skip_rows = outer_skip_rows;
3741  workspace->inner_skip_rows = inner_skip_rows;
3742 }
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:4021
@ JOIN_FULL
Definition: nodes.h:751
@ JOIN_RIGHT
Definition: nodes.h:752
@ JOIN_LEFT
Definition: nodes.h:750
Selectivity leftstartsel
Definition: pathnodes.h:2178
Selectivity leftendsel
Definition: pathnodes.h:2179
Selectivity rightendsel
Definition: pathnodes.h:2181
Selectivity rightstartsel
Definition: pathnodes.h:2180
bool pk_nulls_first
Definition: pathnodes.h:1071
int pk_strategy
Definition: pathnodes.h:1070
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1068
Oid pk_opfamily
Definition: pathnodes.h:1069
List * pathkeys
Definition: pathnodes.h:1208

References Assert(), bms_is_subset(), cached_scansel(), clamp_row_est(), cost_sort(), EquivalenceClass::ec_collation, elog, ERROR, JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JOIN_ANTI, JOIN_FULL, JOIN_LEFT, JOIN_RIGHT, RestrictInfo::left_relids, MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, linitial, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, Path::parent, Path::pathkeys, Path::pathtarget, PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, RelOptInfo::relids, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, PathTarget::width, and work_mem.

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

◆ initial_cost_nestloop()

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

Definition at line 3261 of file costsize.c.

3265 {
3266  Cost startup_cost = 0;
3267  Cost run_cost = 0;
3268  double outer_path_rows = outer_path->rows;
3269  Cost inner_rescan_start_cost;
3270  Cost inner_rescan_total_cost;
3271  Cost inner_run_cost;
3272  Cost inner_rescan_run_cost;
3273 
3274  /* estimate costs to rescan the inner relation */
3275  cost_rescan(root, inner_path,
3276  &inner_rescan_start_cost,
3277  &inner_rescan_total_cost);
3278 
3279  /* cost of source data */
3280 
3281  /*
3282  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3283  * before we can start returning tuples, so the join's startup cost is
3284  * their sum. We'll also pay the inner path's rescan startup cost
3285  * multiple times.
3286  */
3287  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3288  run_cost += outer_path->total_cost - outer_path->startup_cost;
3289  if (outer_path_rows > 1)
3290  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3291 
3292  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3293  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3294 
3295  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3296  extra->inner_unique)
3297  {
3298  /*
3299  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3300  * executor will stop after the first match.
3301  *
3302  * Getting decent estimates requires inspection of the join quals,
3303  * which we choose to postpone to final_cost_nestloop.
3304  */
3305 
3306  /* Save private data for final_cost_nestloop */
3307  workspace->inner_run_cost = inner_run_cost;
3308  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3309  }
3310  else
3311  {
3312  /* Normal case; we'll scan whole input rel for each outer row */
3313  run_cost += inner_run_cost;
3314  if (outer_path_rows > 1)
3315  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3316  }
3317 
3318  /* CPU costs left for later */
3319 
3320  /* Public result fields */
3321  workspace->startup_cost = startup_cost;
3322  workspace->total_cost = startup_cost + run_cost;
3323  /* Save private data for final_cost_nestloop */
3324  workspace->run_cost = run_cost;
3325 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:4555

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

5290 {
5291  double nrows;
5292 
5293  /* Should only be applied to base relations */
5294  Assert(rel->relid > 0);
5295 
5296  nrows = rel->tuples *
5298  rel->baserestrictinfo,
5299  0,
5300  JOIN_INNER,
5301  NULL);
5302 
5303  rel->rows = clamp_row_est(nrows);
5304 
5306 
5307  set_rel_width(root, rel);
5308 }
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6151

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

6017 {
6018  RangeTblEntry *rte;
6019 
6020  /* Should only be applied to base relations that are CTE references */
6021  Assert(rel->relid > 0);
6022  rte = planner_rt_fetch(rel->relid, root);
6023  Assert(rte->rtekind == RTE_CTE);
6024 
6025  if (rte->self_reference)
6026  {
6027  /*
6028  * In a self-reference, we assume the average worktable size is a
6029  * multiple of the nonrecursive term's size. The best multiplier will
6030  * vary depending on query "fan-out", so make its value adjustable.
6031  */
6032  rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
6033  }
6034  else
6035  {
6036  /* Otherwise just believe the CTE's rowcount estimate */
6037  rel->tuples = cte_rows;
6038  }
6039 
6040  /* Now estimate number of output rows, etc */
6041  set_baserel_size_estimates(root, rel);
6042 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5289
double recursive_worktable_factor
Definition: costsize.c:127
bool self_reference
Definition: parsenodes.h:1127

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

6117 {
6118  /* Should only be applied to base relations */
6119  Assert(rel->relid > 0);
6120 
6121  rel->rows = 1000; /* entirely bogus default estimate */
6122 
6124 
6125  set_rel_width(root, rel);
6126 }

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

5925 {
5926  RangeTblEntry *rte;
5927  ListCell *lc;
5928 
5929  /* Should only be applied to base relations that are functions */
5930  Assert(rel->relid > 0);
5931  rte = planner_rt_fetch(rel->relid, root);
5932  Assert(rte->rtekind == RTE_FUNCTION);
5933 
5934  /*
5935  * Estimate number of rows the functions will return. The rowcount of the
5936  * node is that of the largest function result.
5937  */
5938  rel->tuples = 0;
5939  foreach(lc, rte->functions)
5940  {
5941  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5942  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5943 
5944  if (ntup > rel->tuples)
5945  rel->tuples = ntup;
5946  }
5947 
5948  /* Now estimate number of output rows, etc */
5949  set_baserel_size_estimates(root, rel);
5950 }
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:292

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

5373 {
5374  rel->rows = calc_joinrel_size_estimate(root,
5375  rel,
5376  outer_rel,
5377  inner_rel,
5378  outer_rel->rows,
5379  inner_rel->rows,
5380  sjinfo,
5381  restrictlist);
5382 }

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

6055 {
6056  RangeTblEntry *rte;
6057 
6058  /* Should only be applied to base relations that are tuplestore references */
6059  Assert(rel->relid > 0);
6060  rte = planner_rt_fetch(rel->relid, root);
6062 
6063  /*
6064  * Use the estimate provided by the code which is generating the named
6065  * tuplestore. In some cases, the actual number might be available; in
6066  * others the same plan will be re-used, so a "typical" value might be
6067  * estimated and used.
6068  */
6069  rel->tuples = rte->enrtuples;
6070  if (rel->tuples < 0)
6071  rel->tuples = 1000;
6072 
6073  /* Now estimate number of output rows, etc */
6074  set_baserel_size_estimates(root, rel);
6075 }
Cardinality enrtuples
Definition: parsenodes.h:1155

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

6310 {
6311  int32 tuple_width = 0;
6312  ListCell *lc;
6313 
6314  /* Vars are assumed to have cost zero, but other exprs do not */
6315  target->cost.startup = 0;
6316  target->cost.per_tuple = 0;
6317 
6318  foreach(lc, target->exprs)
6319  {
6320  Node *node = (Node *) lfirst(lc);
6321 
6322  if (IsA(node, Var))
6323  {
6324  Var *var = (Var *) node;
6325  int32 item_width;
6326 
6327  /* We should not see any upper-level Vars here */
6328  Assert(var->varlevelsup == 0);
6329 
6330  /* Try to get data from RelOptInfo cache */
6331  if (!IS_SPECIAL_VARNO(var->varno) &&
6332  var->varno < root->simple_rel_array_size)
6333  {
6334  RelOptInfo *rel = root->simple_rel_array[var->varno];
6335 
6336  if (rel != NULL &&
6337  var->varattno >= rel->min_attr &&
6338  var->varattno <= rel->max_attr)
6339  {
6340  int ndx = var->varattno - rel->min_attr;
6341 
6342  if (rel->attr_widths[ndx] > 0)
6343  {
6344  tuple_width += rel->attr_widths[ndx];
6345  continue;
6346  }
6347  }
6348  }
6349 
6350  /*
6351  * No cached data available, so estimate using just the type info.
6352  */
6353  item_width = get_typavgwidth(var->vartype, var->vartypmod);
6354  Assert(item_width > 0);
6355  tuple_width += item_width;
6356  }
6357  else
6358  {
6359  /*
6360  * Handle general expressions using type info.
6361  */
6362  int32 item_width;
6363  QualCost cost;
6364 
6365  item_width = get_typavgwidth(exprType(node), exprTypmod(node));
6366  Assert(item_width > 0);
6367  tuple_width += item_width;
6368 
6369  /* Account for cost, too */
6370  cost_qual_eval_node(&cost, node, root);
6371  target->cost.startup += cost.startup;
6372  target->cost.per_tuple += cost.per_tuple;
6373  }
6374  }
6375 
6376  Assert(tuple_width >= 0);
6377  target->width = tuple_width;
6378 
6379  return target;
6380 }
signed int int32
Definition: c.h:429
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2535
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:286
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:189
List * exprs
Definition: pathnodes.h:1122
int simple_rel_array_size
Definition: pathnodes.h:187
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:186
int32 * attr_widths
Definition: pathnodes.h:716
AttrNumber max_attr
Definition: pathnodes.h:714
AttrNumber min_attr
Definition: pathnodes.h:713
Definition: primnodes.h:196
Oid vartype
Definition: primnodes.h:202
AttrNumber varattno
Definition: primnodes.h:200
int varno
Definition: primnodes.h:198
int32 vartypmod
Definition: primnodes.h:203
Index varlevelsup
Definition: primnodes.h:205

References Assert(), RelOptInfo::attr_widths, 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, PlannerInfo::simple_rel_array_size, QualCost::startup, Var::varattno, Var::varlevelsup, Var::varno, Var::vartype, Var::vartypmod, 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 6087 of file costsize.c.

6088 {
6089  /* Should only be applied to RTE_RESULT base relations */
6090  Assert(rel->relid > 0);
6091  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6092 
6093  /* RTE_RESULT always generates a single row, natively */
6094  rel->tuples = 1;
6095 
6096  /* Now estimate number of output rows, etc */
6097  set_baserel_size_estimates(root, rel);
6098 }

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

5845 {
5846  PlannerInfo *subroot = rel->subroot;
5847  RelOptInfo *sub_final_rel;
5848  ListCell *lc;
5849 
5850  /* Should only be applied to base relations that are subqueries */
5851  Assert(rel->relid > 0);
5852  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5853 
5854  /*
5855  * Copy raw number of output rows from subquery. All of its paths should
5856  * have the same output rowcount, so just look at cheapest-total.
5857  */
5858  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5859  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5860 
5861  /*
5862  * Compute per-output-column width estimates by examining the subquery's
5863  * targetlist. For any output that is a plain Var, get the width estimate
5864  * that was made while planning the subquery. Otherwise, we leave it to
5865  * set_rel_width to fill in a datatype-based default estimate.
5866  */
5867  foreach(lc, subroot->parse->targetList)
5868  {
5869  TargetEntry *te = lfirst_node(TargetEntry, lc);
5870  Node *texpr = (Node *) te->expr;
5871  int32 item_width = 0;
5872 
5873  /* junk columns aren't visible to upper query */
5874  if (te->resjunk)
5875  continue;
5876 
5877  /*
5878  * The subquery could be an expansion of a view that's had columns
5879  * added to it since the current query was parsed, so that there are
5880  * non-junk tlist columns in it that don't correspond to any column
5881  * visible at our query level. Ignore such columns.
5882  */
5883  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5884  continue;
5885 
5886  /*
5887  * XXX This currently doesn't work for subqueries containing set
5888  * operations, because the Vars in their tlists are bogus references
5889  * to the first leaf subquery, which wouldn't give the right answer
5890  * even if we could still get to its PlannerInfo.
5891  *
5892  * Also, the subquery could be an appendrel for which all branches are
5893  * known empty due to constraint exclusion, in which case
5894  * set_append_rel_pathlist will have left the attr_widths set to zero.
5895  *
5896  * In either case, we just leave the width estimate zero until
5897  * set_rel_width fixes it.
5898  */
5899  if (IsA(texpr, Var) &&
5900  subroot->parse->setOperations == NULL)
5901  {
5902  Var *var = (Var *) texpr;
5903  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5904 
5905  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5906  }
5907  rel->attr_widths[te->resno - rel->min_attr] = item_width;
5908  }
5909 
5910  /* Now estimate number of output rows, etc */
5911  set_baserel_size_estimates(root, rel);
5912 }
@ UPPERREL_FINAL
Definition: pathnodes.h:77
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:375
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
Query * parse
Definition: pathnodes.h:162
Node * setOperations
Definition: parsenodes.h:182
List * targetList
Definition: parsenodes.h:155
struct Path * cheapest_total_path
Definition: pathnodes.h:700
PlannerInfo * subroot
Definition: pathnodes.h:726
Expr * expr
Definition: primnodes.h:1716
AttrNumber resno
Definition: primnodes.h:1717
bool resjunk
Definition: primnodes.h:1723

References Assert(), RelOptInfo::attr_widths, 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::resjunk, 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 5962 of file costsize.c.

5963 {
5964  /* Should only be applied to base relations that are functions */
5965  Assert(rel->relid > 0);
5966  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
5967 
5968  rel->tuples = 100;
5969 
5970  /* Now estimate number of output rows, etc */
5971  set_baserel_size_estimates(root, rel);
5972 }

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

5985 {
5986  RangeTblEntry *rte;
5987 
5988  /* Should only be applied to base relations that are values lists */
5989  Assert(rel->relid > 0);
5990  rte = planner_rt_fetch(rel->relid, root);
5991  Assert(rte->rtekind == RTE_VALUES);
5992 
5993  /*
5994  * Estimate number of rows the values list will return. We know this
5995  * precisely based on the list length (well, barring set-returning
5996  * functions in list items, but that's a refinement not catered for
5997  * anywhere else either).
5998  */
5999  rel->tuples = list_length(rte->values_lists);
6000 
6001  /* Now estimate number of output rows, etc */
6002  set_baserel_size_estimates(root, rel);
6003 }
List * values_lists
Definition: parsenodes.h:1120

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 154 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_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