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
 
#define MAXIMUM_ROWCOUNT   1e100
 

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

◆ MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

Definition at line 116 of file costsize.c.

Referenced by clamp_row_est().

Function Documentation

◆ append_nonpartial_cost()

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

Definition at line 1968 of file costsize.c.

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

Referenced by cost_append().

1969 {
1970  Cost *costarr;
1971  int arrlen;
1972  ListCell *l;
1973  ListCell *cell;
1974  int i;
1975  int path_index;
1976  int min_index;
1977  int max_index;
1978 
1979  if (numpaths == 0)
1980  return 0;
1981 
1982  /*
1983  * Array length is number of workers or number of relevant paths,
1984  * whichever is less.
1985  */
1986  arrlen = Min(parallel_workers, numpaths);
1987  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
1988 
1989  /* The first few paths will each be claimed by a different worker. */
1990  path_index = 0;
1991  foreach(cell, subpaths)
1992  {
1993  Path *subpath = (Path *) lfirst(cell);
1994 
1995  if (path_index == arrlen)
1996  break;
1997  costarr[path_index++] = subpath->total_cost;
1998  }
1999 
2000  /*
2001  * Since subpaths are sorted by decreasing cost, the last one will have
2002  * the minimum cost.
2003  */
2004  min_index = arrlen - 1;
2005 
2006  /*
2007  * For each of the remaining subpaths, add its cost to the array element
2008  * with minimum cost.
2009  */
2010  for_each_cell(l, subpaths, cell)
2011  {
2012  Path *subpath = (Path *) lfirst(l);
2013  int i;
2014 
2015  /* Consider only the non-partial paths */
2016  if (path_index++ == numpaths)
2017  break;
2018 
2019  costarr[min_index] += subpath->total_cost;
2020 
2021  /* Update the new min cost array index */
2022  for (min_index = i = 0; i < arrlen; i++)
2023  {
2024  if (costarr[i] < costarr[min_index])
2025  min_index = i;
2026  }
2027  }
2028 
2029  /* Return the highest cost from the array */
2030  for (max_index = i = 0; i < arrlen; i++)
2031  {
2032  if (costarr[i] > costarr[max_index])
2033  max_index = i;
2034  }
2035 
2036  return costarr[max_index];
2037 }
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417
#define Min(x, y)
Definition: c.h:974
Cost total_cost
Definition: pathnodes.h:1160
#define lfirst(lc)
Definition: pg_list.h:169
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 4595 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().

4596 {
4597  double tuples;
4598  double outer_tuples = path->outerjoinpath->rows;
4599  double inner_tuples = path->innerjoinpath->rows;
4600  SpecialJoinInfo sjinfo;
4601  Selectivity selec = 1.0;
4602  ListCell *l;
4603 
4604  /*
4605  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4606  */
4607  sjinfo.type = T_SpecialJoinInfo;
4608  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4609  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4610  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4611  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4612  sjinfo.jointype = JOIN_INNER;
4613  /* we don't bother trying to make the remaining fields valid */
4614  sjinfo.lhs_strict = false;
4615  sjinfo.delay_upper_joins = false;
4616  sjinfo.semi_can_btree = false;
4617  sjinfo.semi_can_hash = false;
4618  sjinfo.semi_operators = NIL;
4619  sjinfo.semi_rhs_exprs = NIL;
4620 
4621  /* Get the approximate selectivity */
4622  foreach(l, quals)
4623  {
4624  Node *qual = (Node *) lfirst(l);
4625 
4626  /* Note that clause_selectivity will be able to cache its result */
4627  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4628  }
4629 
4630  /* Apply it to the input relation sizes */
4631  tuples = selec * outer_tuples * inner_tuples;
4632 
4633  return clamp_row_est(tuples);
4634 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2185
Path * innerjoinpath
Definition: pathnodes.h:1532
Definition: nodes.h:528
double Selectivity
Definition: nodes.h:661
Relids syn_lefthand
Definition: pathnodes.h:2186
Relids syn_righthand
Definition: pathnodes.h:2187
List * semi_rhs_exprs
Definition: pathnodes.h:2195
RelOptInfo * parent
Definition: pathnodes.h:1148
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:690
Relids relids
Definition: pathnodes.h:666
Path * outerjoinpath
Definition: pathnodes.h:1531
bool delay_upper_joins
Definition: pathnodes.h:2190
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
JoinType jointype
Definition: pathnodes.h:2188
List * semi_operators
Definition: pathnodes.h:2194
double clamp_row_est(double nrows)
Definition: costsize.c:196
Relids min_lefthand
Definition: pathnodes.h:2184

◆ cached_scansel()

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

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

3423 {
3424  MergeScanSelCache *cache;
3425  ListCell *lc;
3426  Selectivity leftstartsel,
3427  leftendsel,
3428  rightstartsel,
3429  rightendsel;
3430  MemoryContext oldcontext;
3431 
3432  /* Do we have this result already? */
3433  foreach(lc, rinfo->scansel_cache)
3434  {
3435  cache = (MergeScanSelCache *) lfirst(lc);
3436  if (cache->opfamily == pathkey->pk_opfamily &&
3437  cache->collation == pathkey->pk_eclass->ec_collation &&
3438  cache->strategy == pathkey->pk_strategy &&
3439  cache->nulls_first == pathkey->pk_nulls_first)
3440  return cache;
3441  }
3442 
3443  /* Nope, do the computation */
3444  mergejoinscansel(root,
3445  (Node *) rinfo->clause,
3446  pathkey->pk_opfamily,
3447  pathkey->pk_strategy,
3448  pathkey->pk_nulls_first,
3449  &leftstartsel,
3450  &leftendsel,
3451  &rightstartsel,
3452  &rightendsel);
3453 
3454  /* Cache the result in suitably long-lived workspace */
3455  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3456 
3457  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3458  cache->opfamily = pathkey->pk_opfamily;
3459  cache->collation = pathkey->pk_eclass->ec_collation;
3460  cache->strategy = pathkey->pk_strategy;
3461  cache->nulls_first = pathkey->pk_nulls_first;
3462  cache->leftstartsel = leftstartsel;
3463  cache->leftendsel = leftendsel;
3464  cache->rightstartsel = rightstartsel;
3465  cache->rightendsel = rightendsel;
3466 
3467  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3468 
3469  MemoryContextSwitchTo(oldcontext);
3470 
3471  return cache;
3472 }
Selectivity leftendsel
Definition: pathnodes.h:2091
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:1047
bool pk_nulls_first
Definition: pathnodes.h:1048
Selectivity rightstartsel
Definition: pathnodes.h:2092
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:1994
#define lfirst(lc)
Definition: pg_list.h:169
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1045
Oid pk_opfamily
Definition: pathnodes.h:1046
void * palloc(Size size)
Definition: mcxt.c:950
MemoryContext planner_cxt
Definition: pathnodes.h:325
Selectivity rightendsel
Definition: pathnodes.h:2093
List * scansel_cache
Definition: pathnodes.h:2046
Selectivity leftstartsel
Definition: pathnodes.h:2090

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

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

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 196 of file costsize.c.

References MAXIMUM_ROWCOUNT.

Referenced by adjust_limit_rows_costs(), approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), cost_agg(), cost_append(), cost_bitmap_heap_scan(), cost_group(), cost_index(), cost_seqscan(), cost_subplan(), create_bitmap_subplan(), estimate_hash_bucket_stats(), estimate_num_groups(), estimate_path_cost_size(), estimate_size(), expression_returns_set_rows(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_parameterized_baserel_size(), get_variable_numdistinct(), initial_cost_mergejoin(), set_baserel_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

197 {
198  /*
199  * Avoid infinite and NaN row estimates. Costs derived from such values
200  * are going to be useless. Also force the estimate to be at least one
201  * row, to make explain output look better and to avoid possible
202  * divide-by-zero when interpolating costs. Make it an integer, too.
203  */
204  if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
205  nrows = MAXIMUM_ROWCOUNT;
206  else if (nrows <= 1.0)
207  nrows = 1.0;
208  else
209  nrows = rint(nrows);
210 
211  return nrows;
212 }
#define MAXIMUM_ROWCOUNT
Definition: costsize.c:116

◆ compute_bitmap_pages()

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

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

5804 {
5805  Cost indexTotalCost;
5806  Selectivity indexSelectivity;
5807  double T;
5808  double pages_fetched;
5809  double tuples_fetched;
5810  double heap_pages;
5811  long maxentries;
5812 
5813  /*
5814  * Fetch total cost of obtaining the bitmap, as well as its total
5815  * selectivity.
5816  */
5817  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5818 
5819  /*
5820  * Estimate number of main-table pages fetched.
5821  */
5822  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5823 
5824  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5825 
5826  /*
5827  * For a single scan, the number of heap pages that need to be fetched is
5828  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
5829  * re-reads needed).
5830  */
5831  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5832 
5833  /*
5834  * Calculate the number of pages fetched from the heap. Then based on
5835  * current work_mem estimate get the estimated maxentries in the bitmap.
5836  * (Note that we always do this calculation based on the number of pages
5837  * that would be fetched in a single iteration, even if loop_count > 1.
5838  * That's correct, because only that number of entries will be stored in
5839  * the bitmap at one time.)
5840  */
5841  heap_pages = Min(pages_fetched, baserel->pages);
5842  maxentries = tbm_calculate_entries(work_mem * 1024L);
5843 
5844  if (loop_count > 1)
5845  {
5846  /*
5847  * For repeated bitmap scans, scale up the number of tuples fetched in
5848  * the Mackert and Lohman formula by the number of scans, so that we
5849  * estimate the number of pages fetched by all the scans. Then
5850  * pro-rate for one scan.
5851  */
5852  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5853  baserel->pages,
5854  get_indexpath_pages(bitmapqual),
5855  root);
5856  pages_fetched /= loop_count;
5857  }
5858 
5859  if (pages_fetched >= T)
5860  pages_fetched = T;
5861  else
5862  pages_fetched = ceil(pages_fetched);
5863 
5864  if (maxentries < heap_pages)
5865  {
5866  double exact_pages;
5867  double lossy_pages;
5868 
5869  /*
5870  * Crude approximation of the number of lossy pages. Because of the
5871  * way tbm_lossify() is coded, the number of lossy pages increases
5872  * very sharply as soon as we run short of memory; this formula has
5873  * that property and seems to perform adequately in testing, but it's
5874  * possible we could do better somehow.
5875  */
5876  lossy_pages = Max(0, heap_pages - maxentries / 2);
5877  exact_pages = heap_pages - lossy_pages;
5878 
5879  /*
5880  * If there are lossy pages then recompute the number of tuples
5881  * processed by the bitmap heap node. We assume here that the chance
5882  * of a given tuple coming from an exact page is the same as the
5883  * chance that a given page is exact. This might not be true, but
5884  * it's not clear how we can do any better.
5885  */
5886  if (lossy_pages > 0)
5887  tuples_fetched =
5888  clamp_row_est(indexSelectivity *
5889  (exact_pages / heap_pages) * baserel->tuples +
5890  (lossy_pages / heap_pages) * baserel->tuples);
5891  }
5892 
5893  if (cost)
5894  *cost = indexTotalCost;
5895  if (tuple)
5896  *tuple = tuples_fetched;
5897 
5898  return pages_fetched;
5899 }
double tuples
Definition: pathnodes.h:706
#define Min(x, y)
Definition: c.h:974
double Selectivity
Definition: nodes.h:661
int work_mem
Definition: globals.c:122
#define Max(x, y)
Definition: c.h:968
static const uint32 T[65]
Definition: md5.c:119
BlockNumber pages
Definition: pathnodes.h:705
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:902
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:196
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:837
double Cost
Definition: nodes.h:662
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1053

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

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

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

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

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

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

◆ cost_append()

void cost_append ( AppendPath apath)

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

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

1097 {
1098  Cost totalCost;
1099  Selectivity selec;
1100  ListCell *l;
1101 
1102  /*
1103  * We estimate AND selectivity on the assumption that the inputs are
1104  * independent. This is probably often wrong, but we don't have the info
1105  * to do better.
1106  *
1107  * The runtime cost of the BitmapAnd itself is estimated at 100x
1108  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1109  * definitely too simplistic?
1110  */
1111  totalCost = 0.0;
1112  selec = 1.0;
1113  foreach(l, path->bitmapquals)
1114  {
1115  Path *subpath = (Path *) lfirst(l);
1116  Cost subCost;
1117  Selectivity subselec;
1118 
1119  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1120 
1121  selec *= subselec;
1122 
1123  totalCost += subCost;
1124  if (l != list_head(path->bitmapquals))
1125  totalCost += 100.0 * cpu_operator_cost;
1126  }
1127  path->bitmapselectivity = selec;
1128  path->path.rows = 0; /* per above, not used */
1129  path->path.startup_cost = totalCost;
1130  path->path.total_cost = totalCost;
1131 }
double Selectivity
Definition: nodes.h:661
Selectivity bitmapselectivity
Definition: pathnodes.h:1297
List * bitmapquals
Definition: pathnodes.h:1296
Cost startup_cost
Definition: pathnodes.h:1159
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1160
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
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:1053

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

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

1141 {
1142  Cost totalCost;
1143  Selectivity selec;
1144  ListCell *l;
1145 
1146  /*
1147  * We estimate OR selectivity on the assumption that the inputs are
1148  * non-overlapping, since that's often the case in "x IN (list)" type
1149  * situations. Of course, we clamp to 1.0 at the end.
1150  *
1151  * The runtime cost of the BitmapOr itself is estimated at 100x
1152  * cpu_operator_cost for each tbm_union needed. Probably too small,
1153  * definitely too simplistic? We are aware that the tbm_unions are
1154  * optimized out when the inputs are BitmapIndexScans.
1155  */
1156  totalCost = 0.0;
1157  selec = 0.0;
1158  foreach(l, path->bitmapquals)
1159  {
1160  Path *subpath = (Path *) lfirst(l);
1161  Cost subCost;
1162  Selectivity subselec;
1163 
1164  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1165 
1166  selec += subselec;
1167 
1168  totalCost += subCost;
1169  if (l != list_head(path->bitmapquals) &&
1170  !IsA(subpath, IndexPath))
1171  totalCost += 100.0 * cpu_operator_cost;
1172  }
1173  path->bitmapselectivity = Min(selec, 1.0);
1174  path->path.rows = 0; /* per above, not used */
1175  path->path.startup_cost = totalCost;
1176  path->path.total_cost = totalCost;
1177 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define Min(x, y)
Definition: c.h:974
double Selectivity
Definition: nodes.h:661
List * bitmapquals
Definition: pathnodes.h:1309
Cost startup_cost
Definition: pathnodes.h:1159
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
double cpu_operator_cost
Definition: costsize.c:122
Selectivity bitmapselectivity
Definition: pathnodes.h:1310
Cost total_cost
Definition: pathnodes.h:1160
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1158
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:1053

◆ cost_bitmap_tree_node()

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

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

1054 {
1055  if (IsA(path, IndexPath))
1056  {
1057  *cost = ((IndexPath *) path)->indextotalcost;
1058  *selec = ((IndexPath *) path)->indexselectivity;
1059 
1060  /*
1061  * Charge a small amount per retrieved tuple to reflect the costs of
1062  * manipulating the bitmap. This is mostly to make sure that a bitmap
1063  * scan doesn't look to be the same cost as an indexscan to retrieve a
1064  * single tuple.
1065  */
1066  *cost += 0.1 * cpu_operator_cost * path->rows;
1067  }
1068  else if (IsA(path, BitmapAndPath))
1069  {
1070  *cost = path->total_cost;
1071  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1072  }
1073  else if (IsA(path, BitmapOrPath))
1074  {
1075  *cost = path->total_cost;
1076  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1077  }
1078  else
1079  {
1080  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1081  *cost = *selec = 0; /* keep compiler quiet */
1082  }
1083 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define ERROR
Definition: elog.h:45
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1160
double rows
Definition: pathnodes.h:1158
#define nodeTag(nodeptr)
Definition: nodes.h:533
#define elog(elevel,...)
Definition: elog.h:228

◆ cost_ctescan()

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

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

1512 {
1513  Cost startup_cost = 0;
1514  Cost run_cost = 0;
1515  QualCost qpqual_cost;
1516  Cost cpu_per_tuple;
1517 
1518  /* Should only be applied to base relations that are CTEs */
1519  Assert(baserel->relid > 0);
1520  Assert(baserel->rtekind == RTE_CTE);
1521 
1522  /* Mark the path with the correct row estimate */
1523  if (param_info)
1524  path->rows = param_info->ppi_rows;
1525  else
1526  path->rows = baserel->rows;
1527 
1528  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1529  cpu_per_tuple = cpu_tuple_cost;
1530 
1531  /* Add scanning CPU costs */
1532  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1533 
1534  startup_cost += qpqual_cost.startup;
1535  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1536  run_cost += cpu_per_tuple * baserel->tuples;
1537 
1538  /* tlist eval costs are paid per output row, not per tuple scanned */
1539  startup_cost += path->pathtarget->cost.startup;
1540  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1541 
1542  path->startup_cost = startup_cost;
1543  path->total_cost = startup_cost + run_cost;
1544 }
PathTarget * pathtarget
Definition: pathnodes.h:1149
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:1159
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
double Cost
Definition: nodes.h:662

◆ cost_functionscan()

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

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

1345 {
1346  Cost startup_cost = 0;
1347  Cost run_cost = 0;
1348  QualCost qpqual_cost;
1349  Cost cpu_per_tuple;
1350  RangeTblEntry *rte;
1351  QualCost exprcost;
1352 
1353  /* Should only be applied to base relations that are functions */
1354  Assert(baserel->relid > 0);
1355  rte = planner_rt_fetch(baserel->relid, root);
1356  Assert(rte->rtekind == RTE_FUNCTION);
1357 
1358  /* Mark the path with the correct row estimate */
1359  if (param_info)
1360  path->rows = param_info->ppi_rows;
1361  else
1362  path->rows = baserel->rows;
1363 
1364  /*
1365  * Estimate costs of executing the function expression(s).
1366  *
1367  * Currently, nodeFunctionscan.c always executes the functions to
1368  * completion before returning any rows, and caches the results in a
1369  * tuplestore. So the function eval cost is all startup cost, and per-row
1370  * costs are minimal.
1371  *
1372  * XXX in principle we ought to charge tuplestore spill costs if the
1373  * number of rows is large. However, given how phony our rowcount
1374  * estimates for functions tend to be, there's not a lot of point in that
1375  * refinement right now.
1376  */
1377  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1378 
1379  startup_cost += exprcost.startup + exprcost.per_tuple;
1380 
1381  /* Add scanning CPU costs */
1382  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1383 
1384  startup_cost += qpqual_cost.startup;
1385  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1386  run_cost += cpu_per_tuple * baserel->tuples;
1387 
1388  /* tlist eval costs are paid per output row, not per tuple scanned */
1389  startup_cost += path->pathtarget->cost.startup;
1390  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1391 
1392  path->startup_cost = startup_cost;
1393  path->total_cost = startup_cost + run_cost;
1394 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4092
PathTarget * pathtarget
Definition: pathnodes.h:1149
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:1159
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
Index relid
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
List * functions
Definition: parsenodes.h:1068
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
RTEKind rtekind
Definition: parsenodes.h:981
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 375 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().

378 {
379  Cost startup_cost = 0;
380  Cost run_cost = 0;
381 
382  /* Mark the path with the correct row estimate */
383  if (rows)
384  path->path.rows = *rows;
385  else if (param_info)
386  path->path.rows = param_info->ppi_rows;
387  else
388  path->path.rows = rel->rows;
389 
390  startup_cost = path->subpath->startup_cost;
391 
392  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
393 
394  /* Parallel setup and communication cost. */
395  startup_cost += parallel_setup_cost;
396  run_cost += parallel_tuple_cost * path->path.rows;
397 
398  path->path.startup_cost = startup_cost;
399  path->path.total_cost = (startup_cost + run_cost);
400 }
double parallel_setup_cost
Definition: costsize.c:124
Cost startup_cost
Definition: pathnodes.h:1159
Path * subpath
Definition: pathnodes.h:1501
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
double rows
Definition: pathnodes.h:1158
double ppi_rows
Definition: pathnodes.h:1108
double Cost
Definition: nodes.h:662
double parallel_tuple_cost
Definition: costsize.c:123

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

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

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

2597 {
2598  double output_tuples;
2599  Cost startup_cost;
2600  Cost total_cost;
2601 
2602  output_tuples = numGroups;
2603  startup_cost = input_startup_cost;
2604  total_cost = input_total_cost;
2605 
2606  /*
2607  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2608  * all columns get compared at most of the tuples.
2609  */
2610  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2611 
2612  /*
2613  * If there are quals (HAVING quals), account for their cost and
2614  * selectivity.
2615  */
2616  if (quals)
2617  {
2618  QualCost qual_cost;
2619 
2620  cost_qual_eval(&qual_cost, quals, root);
2621  startup_cost += qual_cost.startup;
2622  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2623 
2624  output_tuples = clamp_row_est(output_tuples *
2626  quals,
2627  0,
2628  JOIN_INNER,
2629  NULL));
2630  }
2631 
2632  path->rows = output_tuples;
2633  path->startup_cost = startup_cost;
2634  path->total_cost = total_cost;
2635 }
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:4066
Cost startup_cost
Definition: pathnodes.h:1159
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1160
double rows
Definition: pathnodes.h:1158
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:196
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 1798 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().

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

◆ cost_index()

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

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

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

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

2221 {
2222  Cost startup_cost = 0;
2223  Cost run_cost = 0;
2224  Cost comparison_cost;
2225  double N;
2226  double logN;
2227 
2228  /*
2229  * Avoid log(0)...
2230  */
2231  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2232  logN = LOG2(N);
2233 
2234  /* Assumed cost per tuple comparison */
2235  comparison_cost = 2.0 * cpu_operator_cost;
2236 
2237  /* Heap creation cost */
2238  startup_cost += comparison_cost * N * logN;
2239 
2240  /* Per-tuple heap maintenance cost */
2241  run_cost += tuples * comparison_cost * logN;
2242 
2243  /*
2244  * Although MergeAppend does not do any selection or projection, it's not
2245  * free; add a small per-tuple overhead.
2246  */
2247  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2248 
2249  path->startup_cost = startup_cost + input_startup_cost;
2250  path->total_cost = startup_cost + run_cost + input_total_cost;
2251 }
Cost startup_cost
Definition: pathnodes.h:1159
double cpu_operator_cost
Definition: costsize.c:122
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
Cost total_cost
Definition: pathnodes.h:1160
#define LOG2(x)
Definition: costsize.c:101
double cpu_tuple_cost
Definition: costsize.c:120
double Cost
Definition: nodes.h:662

◆ cost_namedtuplestorescan()

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

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

1553 {
1554  Cost startup_cost = 0;
1555  Cost run_cost = 0;
1556  QualCost qpqual_cost;
1557  Cost cpu_per_tuple;
1558 
1559  /* Should only be applied to base relations that are Tuplestores */
1560  Assert(baserel->relid > 0);
1561  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1562 
1563  /* Mark the path with the correct row estimate */
1564  if (param_info)
1565  path->rows = param_info->ppi_rows;
1566  else
1567  path->rows = baserel->rows;
1568 
1569  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1570  cpu_per_tuple = cpu_tuple_cost;
1571 
1572  /* Add scanning CPU costs */
1573  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1574 
1575  startup_cost += qpqual_cost.startup;
1576  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1577  run_cost += cpu_per_tuple * baserel->tuples;
1578 
1579  path->startup_cost = startup_cost;
1580  path->total_cost = startup_cost + run_cost;
1581 }
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:1159
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
double Cost
Definition: nodes.h:662

◆ cost_qual_eval()

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

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

4067 {
4068  cost_qual_eval_context context;
4069  ListCell *l;
4070 
4071  context.root = root;
4072  context.total.startup = 0;
4073  context.total.per_tuple = 0;
4074 
4075  /* We don't charge any cost for the implicit ANDing at top level ... */
4076 
4077  foreach(l, quals)
4078  {
4079  Node *qual = (Node *) lfirst(l);
4080 
4081  cost_qual_eval_walker(qual, &context);
4082  }
4083 
4084  *cost = context.total;
4085 }
PlannerInfo * root
Definition: costsize.c:153
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:4106
#define lfirst(lc)
Definition: pg_list.h:169

◆ cost_qual_eval_node()

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

Definition at line 4092 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(), index_other_operands_eval_cost(), make_sort_input_target(), order_qual_clauses(), set_pathtarget_cost_width(), and set_rel_width().

4093 {
4094  cost_qual_eval_context context;
4095 
4096  context.root = root;
4097  context.total.startup = 0;
4098  context.total.per_tuple = 0;
4099 
4100  cost_qual_eval_walker(qual, &context);
4101 
4102  *cost = context.total;
4103 }
PlannerInfo * root
Definition: costsize.c:153
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:4106

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

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

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

◆ cost_recursive_union()

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

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

1626 {
1627  Cost startup_cost;
1628  Cost total_cost;
1629  double total_rows;
1630 
1631  /* We probably have decent estimates for the non-recursive term */
1632  startup_cost = nrterm->startup_cost;
1633  total_cost = nrterm->total_cost;
1634  total_rows = nrterm->rows;
1635 
1636  /*
1637  * We arbitrarily assume that about 10 recursive iterations will be
1638  * needed, and that we've managed to get a good fix on the cost and output
1639  * size of each one of them. These are mighty shaky assumptions but it's
1640  * hard to see how to do better.
1641  */
1642  total_cost += 10 * rterm->total_cost;
1643  total_rows += 10 * rterm->rows;
1644 
1645  /*
1646  * Also charge cpu_tuple_cost per row to account for the costs of
1647  * manipulating the tuplestores. (We don't worry about possible
1648  * spill-to-disk costs.)
1649  */
1650  total_cost += cpu_tuple_cost * total_rows;
1651 
1652  runion->startup_cost = startup_cost;
1653  runion->total_cost = total_cost;
1654  runion->rows = total_rows;
1655  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1656  rterm->pathtarget->width);
1657 }
PathTarget * pathtarget
Definition: pathnodes.h:1149
Cost startup_cost
Definition: pathnodes.h:1159
Cost total_cost
Definition: pathnodes.h:1160
#define Max(x, y)
Definition: c.h:968
double rows
Definition: pathnodes.h:1158
double cpu_tuple_cost
Definition: costsize.c:120
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 3959 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().

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

◆ cost_resultscan()

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

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

1590 {
1591  Cost startup_cost = 0;
1592  Cost run_cost = 0;
1593  QualCost qpqual_cost;
1594  Cost cpu_per_tuple;
1595 
1596  /* Should only be applied to RTE_RESULT base relations */
1597  Assert(baserel->relid > 0);
1598  Assert(baserel->rtekind == RTE_RESULT);
1599 
1600  /* Mark the path with the correct row estimate */
1601  if (param_info)
1602  path->rows = param_info->ppi_rows;
1603  else
1604  path->rows = baserel->rows;
1605 
1606  /* We charge qual cost plus cpu_tuple_cost */
1607  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1608 
1609  startup_cost += qpqual_cost.startup;
1610  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1611  run_cost += cpu_per_tuple * baserel->tuples;
1612 
1613  path->startup_cost = startup_cost;
1614  path->total_cost = startup_cost + run_cost;
1615 }
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:1159
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
double Cost
Definition: nodes.h:662

◆ cost_samplescan()

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

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

302 {
303  Cost startup_cost = 0;
304  Cost run_cost = 0;
305  RangeTblEntry *rte;
306  TableSampleClause *tsc;
307  TsmRoutine *tsm;
308  double spc_seq_page_cost,
309  spc_random_page_cost,
310  spc_page_cost;
311  QualCost qpqual_cost;
312  Cost cpu_per_tuple;
313 
314  /* Should only be applied to base relations with tablesample clauses */
315  Assert(baserel->relid > 0);
316  rte = planner_rt_fetch(baserel->relid, root);
317  Assert(rte->rtekind == RTE_RELATION);
318  tsc = rte->tablesample;
319  Assert(tsc != NULL);
320  tsm = GetTsmRoutine(tsc->tsmhandler);
321 
322  /* Mark the path with the correct row estimate */
323  if (param_info)
324  path->rows = param_info->ppi_rows;
325  else
326  path->rows = baserel->rows;
327 
328  /* fetch estimated page cost for tablespace containing table */
330  &spc_random_page_cost,
331  &spc_seq_page_cost);
332 
333  /* if NextSampleBlock is used, assume random access, else sequential */
334  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
335  spc_random_page_cost : spc_seq_page_cost;
336 
337  /*
338  * disk costs (recall that baserel->pages has already been set to the
339  * number of pages the sampling method will visit)
340  */
341  run_cost += spc_page_cost * baserel->pages;
342 
343  /*
344  * CPU costs (recall that baserel->tuples has already been set to the
345  * number of tuples the sampling method will select). Note that we ignore
346  * execution cost of the TABLESAMPLE parameter expressions; they will be
347  * evaluated only once per scan, and in most usages they'll likely be
348  * simple constants anyway. We also don't charge anything for the
349  * calculations the sampling method might do internally.
350  */
351  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
352 
353  startup_cost += qpqual_cost.startup;
354  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
355  run_cost += cpu_per_tuple * baserel->tuples;
356  /* tlist eval costs are paid per output row, not per tuple scanned */
357  startup_cost += path->pathtarget->cost.startup;
358  run_cost += path->pathtarget->cost.per_tuple * path->rows;
359 
360  path->startup_cost = startup_cost;
361  path->total_cost = startup_cost + run_cost;
362 }
PathTarget * pathtarget
Definition: pathnodes.h:1149
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:1159
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
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:181
Index relid
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: pathnodes.h:705
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
RTEKind rtekind
Definition: parsenodes.h:981
struct TableSampleClause * tablesample
Definition: parsenodes.h:1011
double Cost
Definition: nodes.h:662

◆ cost_seqscan()

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

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

225 {
226  Cost startup_cost = 0;
227  Cost cpu_run_cost;
228  Cost disk_run_cost;
229  double spc_seq_page_cost;
230  QualCost qpqual_cost;
231  Cost cpu_per_tuple;
232 
233  /* Should only be applied to base relations */
234  Assert(baserel->relid > 0);
235  Assert(baserel->rtekind == RTE_RELATION);
236 
237  /* Mark the path with the correct row estimate */
238  if (param_info)
239  path->rows = param_info->ppi_rows;
240  else
241  path->rows = baserel->rows;
242 
243  if (!enable_seqscan)
244  startup_cost += disable_cost;
245 
246  /* fetch estimated page cost for tablespace containing table */
248  NULL,
249  &spc_seq_page_cost);
250 
251  /*
252  * disk costs
253  */
254  disk_run_cost = spc_seq_page_cost * baserel->pages;
255 
256  /* CPU costs */
257  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
258 
259  startup_cost += qpqual_cost.startup;
260  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
261  cpu_run_cost = cpu_per_tuple * baserel->tuples;
262  /* tlist eval costs are paid per output row, not per tuple scanned */
263  startup_cost += path->pathtarget->cost.startup;
264  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
265 
266  /* Adjust costing for parallelism, if used. */
267  if (path->parallel_workers > 0)
268  {
269  double parallel_divisor = get_parallel_divisor(path);
270 
271  /* The CPU cost is divided among all the workers. */
272  cpu_run_cost /= parallel_divisor;
273 
274  /*
275  * It may be possible to amortize some of the I/O cost, but probably
276  * not very much, because most operating systems already do aggressive
277  * prefetching. For now, we assume that the disk run cost can't be
278  * amortized at all.
279  */
280 
281  /*
282  * In the case of a parallel plan, the row count needs to represent
283  * the number of tuples processed per worker.
284  */
285  path->rows = clamp_row_est(path->rows / parallel_divisor);
286  }
287 
288  path->startup_cost = startup_cost;
289  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
290 }
PathTarget * pathtarget
Definition: pathnodes.h:1149
double tuples
Definition: pathnodes.h:706
Oid reltablespace
Definition: pathnodes.h:695
int parallel_workers
Definition: pathnodes.h:1155
bool enable_seqscan
Definition: costsize.c:132
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1159
Cost disable_cost
Definition: costsize.c:128
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5769
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
BlockNumber pages
Definition: pathnodes.h:705
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
double clamp_row_est(double nrows)
Definition: costsize.c:196
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 1937 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().

1942 {
1943  Cost startup_cost;
1944  Cost run_cost;
1945 
1946  cost_tuplesort(&startup_cost, &run_cost,
1947  tuples, width,
1948  comparison_cost, sort_mem,
1949  limit_tuples);
1950 
1951  if (!enable_sort)
1952  startup_cost += disable_cost;
1953 
1954  startup_cost += input_cost;
1955 
1956  path->rows = tuples;
1957  path->startup_cost = startup_cost;
1958  path->total_cost = startup_cost + run_cost;
1959 }
bool enable_sort
Definition: costsize.c:137
Cost startup_cost
Definition: pathnodes.h:1159
Cost disable_cost
Definition: costsize.c:128
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:1696
Cost total_cost
Definition: pathnodes.h:1160
double rows
Definition: pathnodes.h:1158
double Cost
Definition: nodes.h:662

◆ cost_subplan()

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

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

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

◆ cost_subqueryscan()

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

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

1296 {
1297  Cost startup_cost;
1298  Cost run_cost;
1299  QualCost qpqual_cost;
1300  Cost cpu_per_tuple;
1301 
1302  /* Should only be applied to base relations that are subqueries */
1303  Assert(baserel->relid > 0);
1304  Assert(baserel->rtekind == RTE_SUBQUERY);
1305 
1306  /* Mark the path with the correct row estimate */
1307  if (param_info)
1308  path->path.rows = param_info->ppi_rows;
1309  else
1310  path->path.rows = baserel->rows;
1311 
1312  /*
1313  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1314  * any restriction clauses and tlist that will be attached to the
1315  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1316  * projection overhead.
1317  */
1318  path->path.startup_cost = path->subpath->startup_cost;
1319  path->path.total_cost = path->subpath->total_cost;
1320 
1321  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1322 
1323  startup_cost = qpqual_cost.startup;
1324  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1325  run_cost = cpu_per_tuple * baserel->tuples;
1326 
1327  /* tlist eval costs are paid per output row, not per tuple scanned */
1328  startup_cost += path->path.pathtarget->cost.startup;
1329  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1330 
1331  path->path.startup_cost += startup_cost;
1332  path->path.total_cost += startup_cost + run_cost;
1333 }
PathTarget * pathtarget
Definition: pathnodes.h:1149
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:1159
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
double Cost
Definition: nodes.h:662

◆ cost_tablefuncscan()

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

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

1406 {
1407  Cost startup_cost = 0;
1408  Cost run_cost = 0;
1409  QualCost qpqual_cost;
1410  Cost cpu_per_tuple;
1411  RangeTblEntry *rte;
1412  QualCost exprcost;
1413 
1414  /* Should only be applied to base relations that are functions */
1415  Assert(baserel->relid > 0);
1416  rte = planner_rt_fetch(baserel->relid, root);
1417  Assert(rte->rtekind == RTE_TABLEFUNC);
1418 
1419  /* Mark the path with the correct row estimate */
1420  if (param_info)
1421  path->rows = param_info->ppi_rows;
1422  else
1423  path->rows = baserel->rows;
1424 
1425  /*
1426  * Estimate costs of executing the table func expression(s).
1427  *
1428  * XXX in principle we ought to charge tuplestore spill costs if the
1429  * number of rows is large. However, given how phony our rowcount
1430  * estimates for tablefuncs tend to be, there's not a lot of point in that
1431  * refinement right now.
1432  */
1433  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1434 
1435  startup_cost += exprcost.startup + exprcost.per_tuple;
1436 
1437  /* Add scanning CPU costs */
1438  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1439 
1440  startup_cost += qpqual_cost.startup;
1441  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1442  run_cost += cpu_per_tuple * baserel->tuples;
1443 
1444  /* tlist eval costs are paid per output row, not per tuple scanned */
1445  startup_cost += path->pathtarget->cost.startup;
1446  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1447 
1448  path->startup_cost = startup_cost;
1449  path->total_cost = startup_cost + run_cost;
1450 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4092
PathTarget * pathtarget
Definition: pathnodes.h:1149
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:1074
Cost startup_cost
Definition: pathnodes.h:1159
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
Index relid
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
RTEKind rtekind
Definition: parsenodes.h:981
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 1188 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().

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

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

◆ cost_valuesscan()

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

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

1462 {
1463  Cost startup_cost = 0;
1464  Cost run_cost = 0;
1465  QualCost qpqual_cost;
1466  Cost cpu_per_tuple;
1467 
1468  /* Should only be applied to base relations that are values lists */
1469  Assert(baserel->relid > 0);
1470  Assert(baserel->rtekind == RTE_VALUES);
1471 
1472  /* Mark the path with the correct row estimate */
1473  if (param_info)
1474  path->rows = param_info->ppi_rows;
1475  else
1476  path->rows = baserel->rows;
1477 
1478  /*
1479  * For now, estimate list evaluation cost at one operator eval per list
1480  * (probably pretty bogus, but is it worth being smarter?)
1481  */
1482  cpu_per_tuple = cpu_operator_cost;
1483 
1484  /* Add scanning CPU costs */
1485  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1486 
1487  startup_cost += qpqual_cost.startup;
1488  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1489  run_cost += cpu_per_tuple * baserel->tuples;
1490 
1491  /* tlist eval costs are paid per output row, not per tuple scanned */
1492  startup_cost += path->pathtarget->cost.startup;
1493  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1494 
1495  path->startup_cost = startup_cost;
1496  path->total_cost = startup_cost + run_cost;
1497 }
PathTarget * pathtarget
Definition: pathnodes.h:1149
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:1159
double cpu_operator_cost
Definition: costsize.c:122
Index relid
Definition: pathnodes.h:694
RTEKind rtekind
Definition: pathnodes.h:696
double rows
Definition: pathnodes.h:669
Cost total_cost
Definition: pathnodes.h:1160
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4352
#define Assert(condition)
Definition: c.h:792
double rows
Definition: pathnodes.h:1158
QualCost cost
Definition: pathnodes.h:1080
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1108
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 2518 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().

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

◆ extract_nonindex_conditions()

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

Definition at line 779 of file costsize.c.

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

Referenced by cost_index().

780 {
781  List *result = NIL;
782  ListCell *lc;
783 
784  foreach(lc, qual_clauses)
785  {
786  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
787 
788  if (rinfo->pseudoconstant)
789  continue; /* we may drop pseudoconstants here */
790  if (is_redundant_with_indexclauses(rinfo, indexclauses))
791  continue; /* dup or derived from same EquivalenceClass */
792  /* ... skip the predicate proof attempt createplan.c will try ... */
793  result = lappend(result, rinfo);
794  }
795  return result;
796 }
#define NIL
Definition: pg_list.h:65
bool pseudoconstant
Definition: pathnodes.h:2002
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:2999
#define lfirst_node(type, lc)
Definition: pg_list.h:172
List * lappend(List *list, void *datum)
Definition: list.c:336
Definition: pg_list.h:50

◆ final_cost_hashjoin()

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

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

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

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