PostgreSQL Source Code  git master
costsize.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/tsmapi.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "executor/nodeHash.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/placeholder.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
#include "utils/spccache.h"
#include "utils/tuplesort.h"
Include dependency graph for costsize.c:

Go to the source code of this file.

Data Structures

struct  cost_qual_eval_context
 

Macros

#define LOG2(x)   (log(x) / 0.693147180559945)
 
#define APPEND_CPU_COST_MULTIPLIER   0.5
 

Functions

static Listextract_nonindex_conditions (List *qual_clauses, List *indexclauses)
 
static MergeScanSelCachecached_scansel (PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
 
static void cost_rescan (PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
static bool cost_qual_eval_walker (Node *node, cost_qual_eval_context *context)
 
static void get_restriction_qual_cost (PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
 
static bool has_indexed_join_quals (NestPath *joinpath)
 
static double approx_tuple_count (PlannerInfo *root, JoinPath *path, List *quals)
 
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)
 
static Selectivity get_foreign_key_join_selectivity (PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
 
static Cost append_nonpartial_cost (List *subpaths, int numpaths, int parallel_workers)
 
static void set_rel_width (PlannerInfo *root, RelOptInfo *rel)
 
static double relation_byte_size (double tuples, int width)
 
static double page_size (double tuples, int width)
 
static double get_parallel_divisor (Path *path)
 
double clamp_row_est (double nrows)
 
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_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
static double get_indexpath_pages (Path *bitmapqual)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (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)
 
static void cost_tuplesort (Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_incremental_sort (Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_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_append (AppendPath *apath)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_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)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_tablefunc_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_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

double seq_page_cost = DEFAULT_SEQ_PAGE_COST
 
double random_page_cost = DEFAULT_RANDOM_PAGE_COST
 
double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST
 
double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST
 
double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST
 
double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST
 
double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST
 
int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE
 
Cost disable_cost = 1.0e10
 
int max_parallel_workers_per_gather = 2
 
bool enable_seqscan = true
 
bool enable_indexscan = true
 
bool enable_indexonlyscan = true
 
bool enable_bitmapscan = true
 
bool enable_tidscan = true
 
bool enable_sort = true
 
bool enable_incremental_sort = true
 
bool enable_hashagg = true
 
bool enable_nestloop = true
 
bool enable_material = true
 
bool enable_mergejoin = true
 
bool enable_hashjoin = true
 
bool enable_gathermerge = true
 
bool enable_partitionwise_join = false
 
bool enable_partitionwise_aggregate = false
 
bool enable_parallel_append = true
 
bool enable_parallel_hash = true
 
bool enable_partition_pruning = true
 

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 108 of file costsize.c.

Referenced by cost_append(), and cost_merge_append().

◆ LOG2

#define LOG2 (   x)    (log(x) / 0.693147180559945)

Definition at line 101 of file costsize.c.

Referenced by cost_gather_merge(), cost_merge_append(), and cost_tuplesort().

Function Documentation

◆ append_nonpartial_cost()

static Cost append_nonpartial_cost ( List subpaths,
int  numpaths,
int  parallel_workers 
)
static

Definition at line 1958 of file costsize.c.

References for_each_cell, i, lfirst, Min, palloc(), subpath(), and Path::total_cost.

Referenced by cost_append().

1959 {
1960  Cost *costarr;
1961  int arrlen;
1962  ListCell *l;
1963  ListCell *cell;
1964  int i;
1965  int path_index;
1966  int min_index;
1967  int max_index;
1968 
1969  if (numpaths == 0)
1970  return 0;
1971 
1972  /*
1973  * Array length is number of workers or number of relevant paths,
1974  * whichever is less.
1975  */
1976  arrlen = Min(parallel_workers, numpaths);
1977  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
1978 
1979  /* The first few paths will each be claimed by a different worker. */
1980  path_index = 0;
1981  foreach(cell, subpaths)
1982  {
1983  Path *subpath = (Path *) lfirst(cell);
1984 
1985  if (path_index == arrlen)
1986  break;
1987  costarr[path_index++] = subpath->total_cost;
1988  }
1989 
1990  /*
1991  * Since subpaths are sorted by decreasing cost, the last one will have
1992  * the minimum cost.
1993  */
1994  min_index = arrlen - 1;
1995 
1996  /*
1997  * For each of the remaining subpaths, add its cost to the array element
1998  * with minimum cost.
1999  */
2000  for_each_cell(l, subpaths, cell)
2001  {
2002  Path *subpath = (Path *) lfirst(l);
2003  int i;
2004 
2005  /* Consider only the non-partial paths */
2006  if (path_index++ == numpaths)
2007  break;
2008 
2009  costarr[min_index] += subpath->total_cost;
2010 
2011  /* Update the new min cost array index */
2012  for (min_index = i = 0; i < arrlen; i++)
2013  {
2014  if (costarr[i] < costarr[min_index])
2015  min_index = i;
2016  }
2017  }
2018 
2019  /* Return the highest cost from the array */
2020  for (max_index = i = 0; i < arrlen; i++)
2021  {
2022  if (costarr[i] > costarr[max_index])
2023  max_index = i;
2024  }
2025 
2026  return costarr[max_index];
2027 }
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:399
#define Min(x, y)
Definition: c.h:927
Cost total_cost
Definition: pathnodes.h:1157
#define lfirst(lc)
Definition: pg_list.h:189
void * palloc(Size size)
Definition: mcxt.c:950
int i
double Cost
Definition: nodes.h:662
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ approx_tuple_count()

static double approx_tuple_count ( PlannerInfo root,
JoinPath path,
List quals 
)
static

Definition at line 4585 of file costsize.c.

References clamp_row_est(), clause_selectivity(), SpecialJoinInfo::delay_upper_joins, JoinPath::innerjoinpath, JOIN_INNER, SpecialJoinInfo::jointype, lfirst, SpecialJoinInfo::lhs_strict, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, JoinPath::outerjoinpath, Path::parent, RelOptInfo::relids, Path::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 final_cost_hashjoin(), and final_cost_mergejoin().

4586 {
4587  double tuples;
4588  double outer_tuples = path->outerjoinpath->rows;
4589  double inner_tuples = path->innerjoinpath->rows;
4590  SpecialJoinInfo sjinfo;
4591  Selectivity selec = 1.0;
4592  ListCell *l;
4593 
4594  /*
4595  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4596  */
4597  sjinfo.type = T_SpecialJoinInfo;
4598  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4599  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4600  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4601  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4602  sjinfo.jointype = JOIN_INNER;
4603  /* we don't bother trying to make the remaining fields valid */
4604  sjinfo.lhs_strict = false;
4605  sjinfo.delay_upper_joins = false;
4606  sjinfo.semi_can_btree = false;
4607  sjinfo.semi_can_hash = false;
4608  sjinfo.semi_operators = NIL;
4609  sjinfo.semi_rhs_exprs = NIL;
4610 
4611  /* Get the approximate selectivity */
4612  foreach(l, quals)
4613  {
4614  Node *qual = (Node *) lfirst(l);
4615 
4616  /* Note that clause_selectivity will be able to cache its result */
4617  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4618  }
4619 
4620  /* Apply it to the input relation sizes */
4621  tuples = selec * outer_tuples * inner_tuples;
4622 
4623  return clamp_row_est(tuples);
4624 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2177
Path * innerjoinpath
Definition: pathnodes.h:1527
Definition: nodes.h:528
double Selectivity
Definition: nodes.h:661
Relids syn_lefthand
Definition: pathnodes.h:2178
Relids syn_righthand
Definition: pathnodes.h:2179
List * semi_rhs_exprs
Definition: pathnodes.h:2187
RelOptInfo * parent
Definition: pathnodes.h:1145
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:599
Relids relids
Definition: pathnodes.h:666
Path * outerjoinpath
Definition: pathnodes.h:1526
bool delay_upper_joins
Definition: pathnodes.h:2182
#define lfirst(lc)
Definition: pg_list.h:189
double rows
Definition: pathnodes.h:1155
JoinType jointype
Definition: pathnodes.h:2180
List * semi_operators
Definition: pathnodes.h:2186
double clamp_row_est(double nrows)
Definition: costsize.c:189
Relids min_lefthand
Definition: pathnodes.h:2176

◆ cached_scansel()

static MergeScanSelCache * cached_scansel ( PlannerInfo root,
RestrictInfo rinfo,
PathKey pathkey 
)
static

Definition at line 3412 of file costsize.c.

References RestrictInfo::clause, MergeScanSelCache::collation, EquivalenceClass::ec_collation, lappend(), MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, lfirst, MemoryContextSwitchTo(), mergejoinscansel(), MergeScanSelCache::nulls_first, MergeScanSelCache::opfamily, palloc(), PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, PlannerInfo::planner_cxt, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, RestrictInfo::scansel_cache, and MergeScanSelCache::strategy.

Referenced by initial_cost_mergejoin().

3413 {
3414  MergeScanSelCache *cache;
3415  ListCell *lc;
3416  Selectivity leftstartsel,
3417  leftendsel,
3418  rightstartsel,
3419  rightendsel;
3420  MemoryContext oldcontext;
3421 
3422  /* Do we have this result already? */
3423  foreach(lc, rinfo->scansel_cache)
3424  {
3425  cache = (MergeScanSelCache *) lfirst(lc);
3426  if (cache->opfamily == pathkey->pk_opfamily &&
3427  cache->collation == pathkey->pk_eclass->ec_collation &&
3428  cache->strategy == pathkey->pk_strategy &&
3429  cache->nulls_first == pathkey->pk_nulls_first)
3430  return cache;
3431  }
3432 
3433  /* Nope, do the computation */
3434  mergejoinscansel(root,
3435  (Node *) rinfo->clause,
3436  pathkey->pk_opfamily,
3437  pathkey->pk_strategy,
3438  pathkey->pk_nulls_first,
3439  &leftstartsel,
3440  &leftendsel,
3441  &rightstartsel,
3442  &rightendsel);
3443 
3444  /* Cache the result in suitably long-lived workspace */
3445  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3446 
3447  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3448  cache->opfamily = pathkey->pk_opfamily;
3449  cache->collation = pathkey->pk_eclass->ec_collation;
3450  cache->strategy = pathkey->pk_strategy;
3451  cache->nulls_first = pathkey->pk_nulls_first;
3452  cache->leftstartsel = leftstartsel;
3453  cache->leftendsel = leftendsel;
3454  cache->rightstartsel = rightstartsel;
3455  cache->rightendsel = rightendsel;
3456 
3457  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3458 
3459  MemoryContextSwitchTo(oldcontext);
3460 
3461  return cache;
3462 }
Selectivity leftendsel
Definition: pathnodes.h:2083
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2904
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:528
double Selectivity
Definition: nodes.h:661
int pk_strategy
Definition: pathnodes.h:1044
bool pk_nulls_first
Definition: pathnodes.h:1045
Selectivity rightstartsel
Definition: pathnodes.h:2084
List * lappend(List *list, void *datum)
Definition: list.c:321
Expr * clause
Definition: pathnodes.h:1986
#define lfirst(lc)
Definition: pg_list.h:189
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1042
Oid pk_opfamily
Definition: pathnodes.h:1043
void * palloc(Size size)
Definition: mcxt.c:950
MemoryContext planner_cxt
Definition: pathnodes.h:331
Selectivity rightendsel
Definition: pathnodes.h:2085
List * scansel_cache
Definition: pathnodes.h:2038
Selectivity leftstartsel
Definition: pathnodes.h:2082

◆ calc_joinrel_size_estimate()

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 
)
static

Definition at line 4793 of file costsize.c.

References clamp_row_est(), clauselist_selectivity(), elog, ERROR, get_foreign_key_join_selectivity(), IS_OUTER_JOIN, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst_node, list_free(), NIL, RelOptInfo::relids, and RINFO_IS_PUSHED_DOWN.

Referenced by get_parameterized_joinrel_size(), and set_joinrel_size_estimates().

4801 {
4802  /* This apparently-useless variable dodges a compiler bug in VS2013: */
4803  List *restrictlist = restrictlist_in;
4804  JoinType jointype = sjinfo->jointype;
4805  Selectivity fkselec;
4806  Selectivity jselec;
4807  Selectivity pselec;
4808  double nrows;
4809 
4810  /*
4811  * Compute joinclause selectivity. Note that we are only considering
4812  * clauses that become restriction clauses at this join level; we are not
4813  * double-counting them because they were not considered in estimating the
4814  * sizes of the component rels.
4815  *
4816  * First, see whether any of the joinclauses can be matched to known FK
4817  * constraints. If so, drop those clauses from the restrictlist, and
4818  * instead estimate their selectivity using FK semantics. (We do this
4819  * without regard to whether said clauses are local or "pushed down".
4820  * Probably, an FK-matching clause could never be seen as pushed down at
4821  * an outer join, since it would be strict and hence would be grounds for
4822  * join strength reduction.) fkselec gets the net selectivity for
4823  * FK-matching clauses, or 1.0 if there are none.
4824  */
4825  fkselec = get_foreign_key_join_selectivity(root,
4826  outer_rel->relids,
4827  inner_rel->relids,
4828  sjinfo,
4829  &restrictlist);
4830 
4831  /*
4832  * For an outer join, we have to distinguish the selectivity of the join's
4833  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
4834  * down". For inner joins we just count them all as joinclauses.
4835  */
4836  if (IS_OUTER_JOIN(jointype))
4837  {
4838  List *joinquals = NIL;
4839  List *pushedquals = NIL;
4840  ListCell *l;
4841 
4842  /* Grovel through the clauses to separate into two lists */
4843  foreach(l, restrictlist)
4844  {
4845  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4846 
4847  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4848  pushedquals = lappend(pushedquals, rinfo);
4849  else
4850  joinquals = lappend(joinquals, rinfo);
4851  }
4852 
4853  /* Get the separate selectivities */
4854  jselec = clauselist_selectivity(root,
4855  joinquals,
4856  0,
4857  jointype,
4858  sjinfo);
4859  pselec = clauselist_selectivity(root,
4860  pushedquals,
4861  0,
4862  jointype,
4863  sjinfo);
4864 
4865  /* Avoid leaking a lot of ListCells */
4866  list_free(joinquals);
4867  list_free(pushedquals);
4868  }
4869  else
4870  {
4871  jselec = clauselist_selectivity(root,
4872  restrictlist,
4873  0,
4874  jointype,
4875  sjinfo);
4876  pselec = 0.0; /* not used, keep compiler quiet */
4877  }
4878 
4879  /*
4880  * Basically, we multiply size of Cartesian product by selectivity.
4881  *
4882  * If we are doing an outer join, take that into account: the joinqual
4883  * selectivity has to be clamped using the knowledge that the output must
4884  * be at least as large as the non-nullable input. However, any
4885  * pushed-down quals are applied after the outer join, so their
4886  * selectivity applies fully.
4887  *
4888  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
4889  * of LHS rows that have matches, and we apply that straightforwardly.
4890  */
4891  switch (jointype)
4892  {
4893  case JOIN_INNER:
4894  nrows = outer_rows * inner_rows * fkselec * jselec;
4895  /* pselec not used */
4896  break;
4897  case JOIN_LEFT:
4898  nrows = outer_rows * inner_rows * fkselec * jselec;
4899  if (nrows < outer_rows)
4900  nrows = outer_rows;
4901  nrows *= pselec;
4902  break;
4903  case JOIN_FULL:
4904  nrows = outer_rows * inner_rows * fkselec * jselec;
4905  if (nrows < outer_rows)
4906  nrows = outer_rows;
4907  if (nrows < inner_rows)
4908  nrows = inner_rows;
4909  nrows *= pselec;
4910  break;
4911  case JOIN_SEMI:
4912  nrows = outer_rows * fkselec * jselec;
4913  /* pselec not used */
4914  break;
4915  case JOIN_ANTI:
4916  nrows = outer_rows * (1.0 - fkselec * jselec);
4917  nrows *= pselec;
4918  break;
4919  default:
4920  /* other values not expected here */
4921  elog(ERROR, "unrecognized join type: %d", (int) jointype);
4922  nrows = 0; /* keep compiler quiet */
4923  break;
4924  }
4925 
4926  return clamp_row_est(nrows);
4927 }
#define NIL
Definition: pg_list.h:65
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:744
double Selectivity
Definition: nodes.h:661
JoinType
Definition: nodes.h:695
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:4945
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:192
Relids relids
Definition: pathnodes.h:666
List * lappend(List *list, void *datum)
Definition: list.c:321
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2063
JoinType jointype
Definition: pathnodes.h:2180
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:214
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:189
Definition: pg_list.h:50

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

◆ compute_bitmap_pages()

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

Definition at line 5745 of file costsize.c.

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

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

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

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

Referenced by add_paths_to_joinrel().

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

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

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

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

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

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2034 of file costsize.c.

References APPEND_CPU_COST_MULTIPLIER, append_nonpartial_cost(), Assert, clamp_row_est(), cost_sort(), cpu_tuple_cost, AppendPath::first_partial_path, get_parallel_divisor(), i, lfirst, AppendPath::limit_tuples, linitial, Min, NIL, Path::parallel_aware, Path::parallel_workers, AppendPath::path, Path::pathkeys, pathkeys_contained_in(), Path::pathtarget, Path::rows, Path::startup_cost, subpath(), AppendPath::subpaths, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_append_path().

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

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1086 of file costsize.c.

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

Referenced by create_bitmap_and_path().

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

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1130 of file costsize.c.

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

Referenced by create_bitmap_or_path().

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

◆ cost_bitmap_tree_node()

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

Definition at line 1043 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

Definition at line 1500 of file costsize.c.

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

1502 {
1503  Cost startup_cost = 0;
1504  Cost run_cost = 0;
1505  QualCost qpqual_cost;
1506  Cost cpu_per_tuple;
1507 
1508  /* Should only be applied to base relations that are CTEs */
1509  Assert(baserel->relid > 0);
1510  Assert(baserel->rtekind == RTE_CTE);
1511 
1512  /* Mark the path with the correct row estimate */
1513  if (param_info)
1514  path->rows = param_info->ppi_rows;
1515  else
1516  path->rows = baserel->rows;
1517 
1518  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1519  cpu_per_tuple = cpu_tuple_cost;
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 }
PathTarget * pathtarget
Definition: pathnodes.h:1146
double tuples
Definition: pathnodes.h:706
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1156
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1157
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4342
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1155
QualCost cost
Definition: pathnodes.h:1077
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1105
double Cost
Definition: nodes.h:662

◆ cost_functionscan()

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

Definition at line 1333 of file costsize.c.

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

Referenced by create_functionscan_path().

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

◆ cost_gather()

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

Definition at line 365 of file costsize.c.

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

Referenced by create_gather_path().

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

◆ cost_gather_merge()

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

Definition at line 403 of file costsize.c.

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

Referenced by create_gather_merge_path().

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

◆ cost_group()

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

Definition at line 2581 of file costsize.c.

References clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, JOIN_INNER, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, and Path::total_cost.

Referenced by choose_hashed_setop(), and create_group_path().

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

◆ cost_incremental_sort()

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

Definition at line 1788 of file costsize.c.

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

Referenced by create_incremental_sort_path().

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

◆ cost_index()

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

Definition at line 478 of file costsize.c.

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

Referenced by create_index_path(), and reparameterize_path().

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

◆ cost_material()

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

Definition at line 2256 of file costsize.c.

References cpu_operator_cost, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by create_material_path(), and materialize_finished_plan().

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

◆ cost_merge_append()

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

Definition at line 2207 of file costsize.c.

References APPEND_CPU_COST_MULTIPLIER, cpu_operator_cost, cpu_tuple_cost, LOG2, Path::startup_cost, and Path::total_cost.

Referenced by create_merge_append_path().

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

◆ cost_namedtuplestorescan()

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

Definition at line 1541 of file costsize.c.

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

Referenced by create_namedtuplestorescan_path().

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

◆ cost_qual_eval()

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

Definition at line 4056 of file costsize.c.

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

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

4057 {
4058  cost_qual_eval_context context;
4059  ListCell *l;
4060 
4061  context.root = root;
4062  context.total.startup = 0;
4063  context.total.per_tuple = 0;
4064 
4065  /* We don't charge any cost for the implicit ANDing at top level ... */
4066 
4067  foreach(l, quals)
4068  {
4069  Node *qual = (Node *) lfirst(l);
4070 
4071  cost_qual_eval_walker(qual, &context);
4072  }
4073 
4074  *cost = context.total;
4075 }
PlannerInfo * root
Definition: costsize.c:146
Definition: nodes.h:528
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4096
#define lfirst(lc)
Definition: pg_list.h:189

◆ cost_qual_eval_node()

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

Definition at line 4082 of file costsize.c.

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

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

4083 {
4084  cost_qual_eval_context context;
4085 
4086  context.root = root;
4087  context.total.startup = 0;
4088  context.total.per_tuple = 0;
4089 
4090  cost_qual_eval_walker(qual, &context);
4091 
4092  *cost = context.total;
4093 }
PlannerInfo * root
Definition: costsize.c:146
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4096

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 4096 of file costsize.c.

References add_function_cost(), CoerceViaIO::arg, ArrayCoerceExpr::arg, ScalarArrayOpExpr::args, RestrictInfo::clause, cost_qual_eval_node(), cpu_operator_cost, disable_cost, ArrayCoerceExpr::elemexpr, elog, ERROR, estimate_array_length(), RestrictInfo::eval_cost, expression_tree_walker(), exprType(), get_opcode(), getTypeInputInfo(), getTypeOutputInfo(), IsA, lfirst_oid, linitial, lsecond, ScalarArrayOpExpr::opfuncid, RowCompareExpr::opnos, RestrictInfo::orclause, SubPlan::per_call_cost, QualCost::per_tuple, RestrictInfo::pseudoconstant, CoerceViaIO::resulttype, cost_qual_eval_context::root, set_opfuncid(), set_sa_opfuncid(), QualCost::startup, SubPlan::startup_cost, AlternativeSubPlan::subplans, and cost_qual_eval_context::total.

Referenced by cost_qual_eval(), and cost_qual_eval_node().

4097 {
4098  if (node == NULL)
4099  return false;
4100 
4101  /*
4102  * RestrictInfo nodes contain an eval_cost field reserved for this
4103  * routine's use, so that it's not necessary to evaluate the qual clause's
4104  * cost more than once. If the clause's cost hasn't been computed yet,
4105  * the field's startup value will contain -1.
4106  */
4107  if (IsA(node, RestrictInfo))
4108  {
4109  RestrictInfo *rinfo = (RestrictInfo *) node;
4110 
4111  if (rinfo->eval_cost.startup < 0)
4112  {
4113  cost_qual_eval_context locContext;
4114 
4115  locContext.root = context->root;
4116  locContext.total.startup = 0;
4117  locContext.total.per_tuple = 0;
4118 
4119  /*
4120  * For an OR clause, recurse into the marked-up tree so that we
4121  * set the eval_cost for contained RestrictInfos too.
4122  */
4123  if (rinfo->orclause)
4124  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4125  else
4126  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4127 
4128  /*
4129  * If the RestrictInfo is marked pseudoconstant, it will be tested
4130  * only once, so treat its cost as all startup cost.
4131  */
4132  if (rinfo->pseudoconstant)
4133  {
4134  /* count one execution during startup */
4135  locContext.total.startup += locContext.total.per_tuple;
4136  locContext.total.per_tuple = 0;
4137  }
4138  rinfo->eval_cost = locContext.total;
4139  }
4140  context->total.startup += rinfo->eval_cost.startup;
4141  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4142  /* do NOT recurse into children */
4143  return false;
4144  }
4145 
4146  /*
4147  * For each operator or function node in the given tree, we charge the
4148  * estimated execution cost given by pg_proc.procost (remember to multiply
4149  * this by cpu_operator_cost).
4150  *
4151  * Vars and Consts are charged zero, and so are boolean operators (AND,
4152  * OR, NOT). Simplistic, but a lot better than no model at all.
4153  *
4154  * Should we try to account for the possibility of short-circuit
4155  * evaluation of AND/OR? Probably *not*, because that would make the
4156  * results depend on the clause ordering, and we are not in any position
4157  * to expect that the current ordering of the clauses is the one that's
4158  * going to end up being used. The above per-RestrictInfo caching would
4159  * not mix well with trying to re-order clauses anyway.
4160  *
4161  * Another issue that is entirely ignored here is that if a set-returning
4162  * function is below top level in the tree, the functions/operators above
4163  * it will need to be evaluated multiple times. In practical use, such
4164  * cases arise so seldom as to not be worth the added complexity needed;
4165  * moreover, since our rowcount estimates for functions tend to be pretty
4166  * phony, the results would also be pretty phony.
4167  */
4168  if (IsA(node, FuncExpr))
4169  {
4170  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4171  &context->total);
4172  }
4173  else if (IsA(node, OpExpr) ||
4174  IsA(node, DistinctExpr) ||
4175  IsA(node, NullIfExpr))
4176  {
4177  /* rely on struct equivalence to treat these all alike */
4178  set_opfuncid((OpExpr *) node);
4179  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4180  &context->total);
4181  }
4182  else if (IsA(node, ScalarArrayOpExpr))
4183  {
4184  /*
4185  * Estimate that the operator will be applied to about half of the
4186  * array elements before the answer is determined.
4187  */
4188  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4189  Node *arraynode = (Node *) lsecond(saop->args);
4190  QualCost sacosts;
4191 
4192  set_sa_opfuncid(saop);
4193  sacosts.startup = sacosts.per_tuple = 0;
4194  add_function_cost(context->root, saop->opfuncid, NULL,
4195  &sacosts);
4196  context->total.startup += sacosts.startup;
4197  context->total.per_tuple += sacosts.per_tuple *
4198  estimate_array_length(arraynode) * 0.5;
4199  }
4200  else if (IsA(node, Aggref) ||
4201  IsA(node, WindowFunc))
4202  {
4203  /*
4204  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4205  * ie, zero execution cost in the current model, because they behave
4206  * essentially like Vars at execution. We disregard the costs of
4207  * their input expressions for the same reason. The actual execution
4208  * costs of the aggregate/window functions and their arguments have to
4209  * be factored into plan-node-specific costing of the Agg or WindowAgg
4210  * plan node.
4211  */
4212  return false; /* don't recurse into children */
4213  }
4214  else if (IsA(node, CoerceViaIO))
4215  {
4216  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4217  Oid iofunc;
4218  Oid typioparam;
4219  bool typisvarlena;
4220 
4221  /* check the result type's input function */
4222  getTypeInputInfo(iocoerce->resulttype,
4223  &iofunc, &typioparam);
4224  add_function_cost(context->root, iofunc, NULL,
4225  &context->total);
4226  /* check the input type's output function */
4227  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4228  &iofunc, &typisvarlena);
4229  add_function_cost(context->root, iofunc, NULL,
4230  &context->total);
4231  }
4232  else if (IsA(node, ArrayCoerceExpr))
4233  {
4234  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4235  QualCost perelemcost;
4236 
4237  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4238  context->root);
4239  context->total.startup += perelemcost.startup;
4240  if (perelemcost.per_tuple > 0)
4241  context->total.per_tuple += perelemcost.per_tuple *
4242  estimate_array_length((Node *) acoerce->arg);
4243  }
4244  else if (IsA(node, RowCompareExpr))
4245  {
4246  /* Conservatively assume we will check all the columns */
4247  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4248  ListCell *lc;
4249 
4250  foreach(lc, rcexpr->opnos)
4251  {
4252  Oid opid = lfirst_oid(lc);
4253 
4254  add_function_cost(context->root, get_opcode(opid), NULL,
4255  &context->total);
4256  }
4257  }
4258  else if (IsA(node, MinMaxExpr) ||
4259  IsA(node, SQLValueFunction) ||
4260  IsA(node, XmlExpr) ||
4261  IsA(node, CoerceToDomain) ||
4262  IsA(node, NextValueExpr))
4263  {
4264  /* Treat all these as having cost 1 */
4265  context->total.per_tuple += cpu_operator_cost;
4266  }
4267  else if (IsA(node, CurrentOfExpr))
4268  {
4269  /* Report high cost to prevent selection of anything but TID scan */
4270  context->total.startup += disable_cost;
4271  }
4272  else if (IsA(node, SubLink))
4273  {
4274  /* This routine should not be applied to un-planned expressions */
4275  elog(ERROR, "cannot handle unplanned sub-select");
4276  }
4277  else if (IsA(node, SubPlan))
4278  {
4279  /*
4280  * A subplan node in an expression typically indicates that the
4281  * subplan will be executed on each evaluation, so charge accordingly.
4282  * (Sub-selects that can be executed as InitPlans have already been
4283  * removed from the expression.)
4284  */
4285  SubPlan *subplan = (SubPlan *) node;
4286 
4287  context->total.startup += subplan->startup_cost;
4288  context->total.per_tuple += subplan->per_call_cost;
4289 
4290  /*
4291  * We don't want to recurse into the testexpr, because it was already
4292  * counted in the SubPlan node's costs. So we're done.
4293  */
4294  return false;
4295  }
4296  else if (IsA(node, AlternativeSubPlan))
4297  {
4298  /*
4299  * Arbitrarily use the first alternative plan for costing. (We should
4300  * certainly only include one alternative, and we don't yet have
4301  * enough information to know which one the executor is most likely to
4302  * use.)
4303  */
4304  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4305 
4306  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4307  context);
4308  }
4309  else if (IsA(node, PlaceHolderVar))
4310  {
4311  /*
4312  * A PlaceHolderVar should be given cost zero when considering general
4313  * expression evaluation costs. The expense of doing the contained
4314  * expression is charged as part of the tlist eval costs of the scan
4315  * or join where the PHV is first computed (see set_rel_width and
4316  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4317  * double-counting the cost for each level of plan that the PHV
4318  * bubbles up through. Hence, return without recursing into the
4319  * phexpr.
4320  */
4321  return false;
4322  }
4323 
4324  /* recurse into children */
4326  (void *) context);
4327 }
QualCost eval_cost
Definition: pathnodes.h:2023
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4082
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
PlannerInfo * root
Definition: costsize.c:146
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2784
Expr * orclause
Definition: pathnodes.h:2017
Oid resulttype
Definition: primnodes.h:838
bool pseudoconstant
Definition: pathnodes.h:1994
Definition: nodes.h:528
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1905
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:199
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
#define linitial(l)
Definition: pg_list.h:194
#define ERROR
Definition: elog.h:43
Cost disable_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:115
Expr * arg
Definition: primnodes.h:837
Expr * elemexpr
Definition: primnodes.h:862
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2751
Expr * clause
Definition: pathnodes.h:1986
Cost per_call_cost
Definition: primnodes.h:733
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4096
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1888
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1667
#define elog(elevel,...)
Definition: elog.h:214
Cost startup_cost
Definition: primnodes.h:732
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1678
#define lfirst_oid(lc)
Definition: pg_list.h:191

◆ cost_recursive_union()

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

Definition at line 1615 of file costsize.c.

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

Referenced by create_recursiveunion_path().

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

◆ cost_rescan()

static void cost_rescan ( PlannerInfo root,
Path path,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 3949 of file costsize.c.

References cpu_operator_cost, cpu_tuple_cost, Path::pathtype, relation_byte_size(), seq_page_cost, Path::startup_cost, T_CteScan, T_FunctionScan, T_HashJoin, T_Material, T_Sort, T_WorkTableScan, Path::total_cost, and work_mem.

Referenced by initial_cost_nestloop().

3952 {
3953  switch (path->pathtype)
3954  {
3955  case T_FunctionScan:
3956 
3957  /*
3958  * Currently, nodeFunctionscan.c always executes the function to
3959  * completion before returning any rows, and caches the results in
3960  * a tuplestore. So the function eval cost is all startup cost
3961  * and isn't paid over again on rescans. However, all run costs
3962  * will be paid over again.
3963  */
3964  *rescan_startup_cost = 0;
3965  *rescan_total_cost = path->total_cost - path->startup_cost;
3966  break;
3967  case T_HashJoin:
3968 
3969  /*
3970  * If it's a single-batch join, we don't need to rebuild the hash
3971  * table during a rescan.
3972  */
3973  if (((HashPath *) path)->num_batches == 1)
3974  {
3975  /* Startup cost is exactly the cost of hash table building */
3976  *rescan_startup_cost = 0;
3977  *rescan_total_cost = path->total_cost - path->startup_cost;
3978  }
3979  else
3980  {
3981  /* Otherwise, no special treatment */
3982  *rescan_startup_cost = path->startup_cost;
3983  *rescan_total_cost = path->total_cost;
3984  }
3985  break;
3986  case T_CteScan:
3987  case T_WorkTableScan:
3988  {
3989  /*
3990  * These plan types materialize their final result in a
3991  * tuplestore or tuplesort object. So the rescan cost is only
3992  * cpu_tuple_cost per tuple, unless the result is large enough
3993  * to spill to disk.
3994  */
3995  Cost run_cost = cpu_tuple_cost * path->rows;
3996  double nbytes = relation_byte_size(path->rows,
3997  path->pathtarget->width);
3998  long work_mem_bytes = work_mem * 1024L;
3999 
4000  if (nbytes > work_mem_bytes)
4001  {
4002  /* It will spill, so account for re-read cost */
4003  double npages = ceil(nbytes / BLCKSZ);
4004 
4005  run_cost += seq_page_cost * npages;
4006  }
4007  *rescan_startup_cost = 0;
4008  *rescan_total_cost = run_cost;
4009  }
4010  break;
4011  case T_Material:
4012  case T_Sort:
4013  {
4014  /*
4015  * These plan types not only materialize their results, but do
4016  * not implement qual filtering or projection. So they are
4017  * even cheaper to rescan than the ones above. We charge only
4018  * cpu_operator_cost per tuple. (Note: keep that in sync with
4019  * the run_cost charge in cost_sort, and also see comments in
4020  * cost_material before you change it.)
4021  */
4022  Cost run_cost = cpu_operator_cost * path->rows;
4023  double nbytes = relation_byte_size(path->rows,
4024  path->pathtarget->width);
4025  long work_mem_bytes = work_mem * 1024L;
4026 
4027  if (nbytes > work_mem_bytes)
4028  {
4029  /* It will spill, so account for re-read cost */
4030  double npages = ceil(nbytes / BLCKSZ);
4031 
4032  run_cost += seq_page_cost * npages;
4033  }
4034  *rescan_startup_cost = 0;
4035  *rescan_total_cost = run_cost;
4036  }
4037  break;
4038  default:
4039  *rescan_startup_cost = path->startup_cost;
4040  *rescan_total_cost = path->total_cost;
4041  break;
4042  }
4043 }
Definition: nodes.h:76
NodeTag pathtype
Definition: pathnodes.h:1143
Cost startup_cost
Definition: pathnodes.h:1156
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5691
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1157
double cpu_tuple_cost
Definition: costsize.c:113
double seq_page_cost
Definition: costsize.c:111
double Cost
Definition: nodes.h:662

◆ cost_resultscan()

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

Definition at line 1578 of file costsize.c.

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

Referenced by create_resultscan_path().

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

◆ cost_samplescan()

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

Definition at line 290 of file costsize.c.

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

Referenced by create_samplescan_path().

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

◆ cost_seqscan()

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

Definition at line 213 of file costsize.c.

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

Referenced by create_seqscan_path().

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

◆ cost_sort()

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

Definition at line 1927 of file costsize.c.

References cost_tuplesort(), disable_cost, enable_sort, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by adjust_foreign_grouping_path_cost(), choose_hashed_setop(), cost_append(), create_gather_merge_path(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), initial_cost_mergejoin(), label_sort_with_costsize(), and plan_cluster_use_sort().

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

◆ cost_subplan()

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

Definition at line 3856 of file costsize.c.

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

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

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

◆ cost_subqueryscan()

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

Definition at line 1284 of file costsize.c.

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

Referenced by create_subqueryscan_path().

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

◆ cost_tablefuncscan()

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

Definition at line 1394 of file costsize.c.

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

Referenced by create_tablefuncscan_path().

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

◆ cost_tidscan()

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

Definition at line 1178 of file costsize.c.

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

Referenced by create_tidscan_path().

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

◆ cost_tuplesort()

static void cost_tuplesort ( Cost startup_cost,
Cost run_cost,
double  tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)
static

Definition at line 1686 of file costsize.c.

References cpu_operator_cost, LOG2, random_page_cost, relation_byte_size(), seq_page_cost, and tuplesort_merge_order().

Referenced by cost_incremental_sort(), and cost_sort().

1690 {
1691  double input_bytes = relation_byte_size(tuples, width);
1692  double output_bytes;
1693  double output_tuples;
1694  long sort_mem_bytes = sort_mem * 1024L;
1695 
1696  /*
1697  * We want to be sure the cost of a sort is never estimated as zero, even
1698  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1699  */
1700  if (tuples < 2.0)
1701  tuples = 2.0;
1702 
1703  /* Include the default cost-per-comparison */
1704  comparison_cost += 2.0 * cpu_operator_cost;
1705 
1706  /* Do we have a useful LIMIT? */
1707  if (limit_tuples > 0 && limit_tuples < tuples)
1708  {
1709  output_tuples = limit_tuples;
1710  output_bytes = relation_byte_size(output_tuples, width);
1711  }
1712  else
1713  {
1714  output_tuples = tuples;
1715  output_bytes = input_bytes;
1716  }
1717 
1718  if (output_bytes > sort_mem_bytes)
1719  {
1720  /*
1721  * We'll have to use a disk-based sort of all the tuples
1722  */
1723  double npages = ceil(input_bytes / BLCKSZ);
1724  double nruns = input_bytes / sort_mem_bytes;
1725  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1726  double log_runs;
1727  double npageaccesses;
1728 
1729  /*
1730  * CPU costs
1731  *
1732  * Assume about N log2 N comparisons
1733  */
1734  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1735 
1736  /* Disk costs */
1737 
1738  /* Compute logM(r) as log(r) / log(M) */
1739  if (nruns > mergeorder)
1740  log_runs = ceil(log(nruns) / log(mergeorder));
1741  else
1742  log_runs = 1.0;
1743  npageaccesses = 2.0 * npages * log_runs;
1744  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1745  *startup_cost += npageaccesses *
1746  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1747  }
1748  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1749  {
1750  /*
1751  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1752  * a total number of tuple comparisons of N log2 K; but the constant
1753  * factor is a bit higher than for quicksort. Tweak it so that the
1754  * cost curve is continuous at the crossover point.
1755  */
1756  *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
1757  }
1758  else
1759  {
1760  /* We'll use plain quicksort on all the input tuples */
1761  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1762  }
1763 
1764  /*
1765  * Also charge a small amount (arbitrarily set equal to operator cost) per
1766  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1767  * doesn't do qual-checking or projection, so it has less overhead than
1768  * most plan nodes. Note it's correct to use tuples not output_tuples
1769  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1770  * counting the LIMIT otherwise.
1771  */
1772  *run_cost = cpu_operator_cost * tuples;
1773 }
double random_page_cost
Definition: costsize.c:112
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5691
#define LOG2(x)
Definition: costsize.c:101
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2583
double seq_page_cost
Definition: costsize.c:111

◆ cost_valuesscan()

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

Definition at line 1450 of file costsize.c.

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

Referenced by create_valuesscan_path().

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

◆ cost_windowagg()

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

Definition at line 2507 of file costsize.c.

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

Referenced by create_windowagg_path().

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

◆ extract_nonindex_conditions()

static List * extract_nonindex_conditions ( List qual_clauses,
List indexclauses 
)
static

Definition at line 769 of file costsize.c.

References is_redundant_with_indexclauses(), lappend(), lfirst_node, NIL, and RestrictInfo::pseudoconstant.

Referenced by cost_index().

770 {
771  List *result = NIL;
772  ListCell *lc;
773 
774  foreach(lc, qual_clauses)
775  {
776  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
777 
778  if (rinfo->pseudoconstant)
779  continue; /* we may drop pseudoconstants here */
780  if (is_redundant_with_indexclauses(rinfo, indexclauses))
781  continue; /* dup or derived from same EquivalenceClass */
782  /* ... skip the predicate proof attempt createplan.c will try ... */
783  result = lappend(result, rinfo);
784  }
785  return result;
786 }
#define NIL
Definition: pg_list.h:65
bool pseudoconstant
Definition: pathnodes.h:1994
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:2842
#define lfirst_node(type, lc)
Definition: pg_list.h:192
List * lappend(List *list, void *datum)
Definition: list.c:321
Definition: pg_list.h:50

◆ final_cost_hashjoin()

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

Definition at line 3599 of file costsize.c.

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

Referenced by create_hashjoin_path().

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

◆ final_cost_mergejoin()

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

Definition at line 3163 of file costsize.c.

References approx_tuple_count(), clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, list_length(), MergePath::materialize_inner, NIL, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, MergePath::path_mergeclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_mergejoin_path().

3166 {
3167  Path *outer_path = path->jpath.outerjoinpath;
3168  Path *inner_path = path->jpath.innerjoinpath;
3169  double inner_path_rows = inner_path->rows;
3170  List *mergeclauses = path->path_mergeclauses;
3171  List *innersortkeys = path->innersortkeys;
3172  Cost startup_cost = workspace->startup_cost;
3173  Cost run_cost = workspace->run_cost;
3174  Cost inner_run_cost = workspace->inner_run_cost;
3175  double outer_rows = workspace->outer_rows;
3176  double inner_rows = workspace->inner_rows;
3177  double outer_skip_rows = workspace->outer_skip_rows;
3178  double inner_skip_rows = workspace->inner_skip_rows;
3179  Cost cpu_per_tuple,
3180  bare_inner_cost,
3181  mat_inner_cost;
3182  QualCost merge_qual_cost;
3183  QualCost qp_qual_cost;
3184  double mergejointuples,
3185  rescannedtuples;
3186  double rescanratio;
3187 
3188  /* Protect some assumptions below that rowcounts aren't zero or NaN */
3189  if (inner_path_rows <= 0 || isnan(inner_path_rows))
3190  inner_path_rows = 1;
3191 
3192  /* Mark the path with the correct row estimate */
3193  if (path->jpath.path.param_info)
3194  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3195  else
3196  path->jpath.path.rows = path->jpath.path.parent->rows;
3197 
3198  /* For partial paths, scale row estimate. */
3199  if (path->jpath.path.parallel_workers > 0)
3200  {
3201  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3202 
3203  path->jpath.path.rows =
3204  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3205  }
3206 
3207  /*
3208  * We could include disable_cost in the preliminary estimate, but that
3209  * would amount to optimizing for the case where the join method is
3210  * disabled, which doesn't seem like the way to bet.
3211  */
3212  if (!enable_mergejoin)
3213  startup_cost += disable_cost;
3214 
3215  /*
3216  * Compute cost of the mergequals and qpquals (other restriction clauses)
3217  * separately.
3218  */
3219  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3220  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3221  qp_qual_cost.startup -= merge_qual_cost.startup;
3222  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3223 
3224  /*
3225  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3226  * executor will stop scanning for matches after the first match. When
3227  * all the joinclauses are merge clauses, this means we don't ever need to
3228  * back up the merge, and so we can skip mark/restore overhead.
3229  */
3230  if ((path->jpath.jointype == JOIN_SEMI ||
3231  path->jpath.jointype == JOIN_ANTI ||
3232  extra->inner_unique) &&
3235  path->skip_mark_restore = true;
3236  else
3237  path->skip_mark_restore = false;
3238 
3239  /*
3240  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3241  * here because we need an estimate done with JOIN_INNER semantics.
3242  */
3243  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3244 
3245  /*
3246  * When there are equal merge keys in the outer relation, the mergejoin
3247  * must rescan any matching tuples in the inner relation. This means
3248  * re-fetching inner tuples; we have to estimate how often that happens.
3249  *
3250  * For regular inner and outer joins, the number of re-fetches can be
3251  * estimated approximately as size of merge join output minus size of
3252  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3253  * denote the number of values of each key in the outer relation as m1,
3254  * m2, ...; in the inner relation, n1, n2, ... Then we have
3255  *
3256  * size of join = m1 * n1 + m2 * n2 + ...
3257  *
3258  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3259  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3260  * relation
3261  *
3262  * This equation works correctly for outer tuples having no inner match
3263  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3264  * are effectively subtracting those from the number of rescanned tuples,
3265  * when we should not. Can we do better without expensive selectivity
3266  * computations?
3267  *
3268  * The whole issue is moot if we are working from a unique-ified outer
3269  * input, or if we know we don't need to mark/restore at all.
3270  */
3271  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3272  rescannedtuples = 0;
3273  else
3274  {
3275  rescannedtuples = mergejointuples - inner_path_rows;
3276  /* Must clamp because of possible underestimate */
3277  if (rescannedtuples < 0)
3278  rescannedtuples = 0;
3279  }
3280 
3281  /*
3282  * We'll inflate various costs this much to account for rescanning. Note
3283  * that this is to be multiplied by something involving inner_rows, or
3284  * another number related to the portion of the inner rel we'll scan.
3285  */
3286  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3287 
3288  /*
3289  * Decide whether we want to materialize the inner input to shield it from
3290  * mark/restore and performing re-fetches. Our cost model for regular
3291  * re-fetches is that a re-fetch costs the same as an original fetch,
3292  * which is probably an overestimate; but on the other hand we ignore the
3293  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3294  * a more refined model. So we just need to inflate the inner run cost by
3295  * rescanratio.
3296  */
3297  bare_inner_cost = inner_run_cost * rescanratio;
3298 
3299  /*
3300  * When we interpose a Material node the re-fetch cost is assumed to be
3301  * just cpu_operator_cost per tuple, independently of the underlying
3302  * plan's cost; and we charge an extra cpu_operator_cost per original
3303  * fetch as well. Note that we're assuming the materialize node will
3304  * never spill to disk, since it only has to remember tuples back to the
3305  * last mark. (If there are a huge number of duplicates, our other cost
3306  * factors will make the path so expensive that it probably won't get
3307  * chosen anyway.) So we don't use cost_rescan here.
3308  *
3309  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3310</