PostgreSQL Source Code  git master
costsize.c File Reference
#include "postgres.h"
#include <limits.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 "executor/nodeMemoize.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/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 *path)
 
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 int32 get_expr_width (PlannerInfo *root, const Node *expr)
 
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)
 
int32 clamp_width_est (int64 tuple_width)
 
long clamp_cardinality_to_long (Cardinality x)
 
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_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, bool trivial_pathtarget)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_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)
 
static void cost_memoize_rescan (PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
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)
 
static double get_windowclause_startup_tuples (PlannerInfo *root, WindowClause *wc, double input_tuples)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, WindowClause *winclause, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_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, double loop_count, Cost *cost_p, double *tuples_p)
 

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
 
double recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR
 
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_memoize = 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
 
bool enable_presorted_aggregate = true
 
bool enable_async_append = true
 

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 109 of file costsize.c.

◆ LOG2

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

Definition at line 102 of file costsize.c.

◆ MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

Definition at line 117 of file costsize.c.

Function Documentation

◆ append_nonpartial_cost()

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

Definition at line 2155 of file costsize.c.

2156 {
2157  Cost *costarr;
2158  int arrlen;
2159  ListCell *l;
2160  ListCell *cell;
2161  int path_index;
2162  int min_index;
2163  int max_index;
2164 
2165  if (numpaths == 0)
2166  return 0;
2167 
2168  /*
2169  * Array length is number of workers or number of relevant paths,
2170  * whichever is less.
2171  */
2172  arrlen = Min(parallel_workers, numpaths);
2173  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2174 
2175  /* The first few paths will each be claimed by a different worker. */
2176  path_index = 0;
2177  foreach(cell, subpaths)
2178  {
2179  Path *subpath = (Path *) lfirst(cell);
2180 
2181  if (path_index == arrlen)
2182  break;
2183  costarr[path_index++] = subpath->total_cost;
2184  }
2185 
2186  /*
2187  * Since subpaths are sorted by decreasing cost, the last one will have
2188  * the minimum cost.
2189  */
2190  min_index = arrlen - 1;
2191 
2192  /*
2193  * For each of the remaining subpaths, add its cost to the array element
2194  * with minimum cost.
2195  */
2196  for_each_cell(l, subpaths, cell)
2197  {
2198  Path *subpath = (Path *) lfirst(l);
2199 
2200  /* Consider only the non-partial paths */
2201  if (path_index++ == numpaths)
2202  break;
2203 
2204  costarr[min_index] += subpath->total_cost;
2205 
2206  /* Update the new min cost array index */
2207  min_index = 0;
2208  for (int i = 0; i < arrlen; i++)
2209  {
2210  if (costarr[i] < costarr[min_index])
2211  min_index = i;
2212  }
2213  }
2214 
2215  /* Return the highest cost from the array */
2216  max_index = 0;
2217  for (int i = 0; i < arrlen; i++)
2218  {
2219  if (costarr[i] > costarr[max_index])
2220  max_index = i;
2221  }
2222 
2223  return costarr[max_index];
2224 }
#define Min(x, y)
Definition: c.h:991
int i
Definition: isn.c:73
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void * palloc(Size size)
Definition: mcxt.c:1304
double Cost
Definition: nodes.h:241
#define lfirst(lc)
Definition: pg_list.h:172
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438

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

Referenced by cost_append().

◆ approx_tuple_count()

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

Definition at line 5209 of file costsize.c.

5210 {
5211  double tuples;
5212  double outer_tuples = path->outerjoinpath->rows;
5213  double inner_tuples = path->innerjoinpath->rows;
5214  SpecialJoinInfo sjinfo;
5215  Selectivity selec = 1.0;
5216  ListCell *l;
5217 
5218  /*
5219  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5220  */
5221  sjinfo.type = T_SpecialJoinInfo;
5222  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
5223  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
5224  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
5225  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
5226  sjinfo.jointype = JOIN_INNER;
5227  sjinfo.ojrelid = 0;
5228  sjinfo.commute_above_l = NULL;
5229  sjinfo.commute_above_r = NULL;
5230  sjinfo.commute_below_l = NULL;
5231  sjinfo.commute_below_r = NULL;
5232  /* we don't bother trying to make the remaining fields valid */
5233  sjinfo.lhs_strict = false;
5234  sjinfo.semi_can_btree = false;
5235  sjinfo.semi_can_hash = false;
5236  sjinfo.semi_operators = NIL;
5237  sjinfo.semi_rhs_exprs = NIL;
5238 
5239  /* Get the approximate selectivity */
5240  foreach(l, quals)
5241  {
5242  Node *qual = (Node *) lfirst(l);
5243 
5244  /* Note that clause_selectivity will be able to cache its result */
5245  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5246  }
5247 
5248  /* Apply it to the input relation sizes */
5249  tuples = selec * outer_tuples * inner_tuples;
5250 
5251  return clamp_row_est(tuples);
5252 }
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:667
double clamp_row_est(double nrows)
Definition: costsize.c:202
double Selectivity
Definition: nodes.h:240
@ JOIN_INNER
Definition: nodes.h:283
#define NIL
Definition: pg_list.h:68
Path * outerjoinpath
Definition: pathnodes.h:2054
Path * innerjoinpath
Definition: pathnodes.h:2055
Definition: nodes.h:129
Cardinality rows
Definition: pathnodes.h:1640
Relids commute_above_r
Definition: pathnodes.h:2875
Relids syn_lefthand
Definition: pathnodes.h:2870
Relids min_righthand
Definition: pathnodes.h:2869
List * semi_rhs_exprs
Definition: pathnodes.h:2883
Relids commute_above_l
Definition: pathnodes.h:2874
JoinType jointype
Definition: pathnodes.h:2872
Relids commute_below_l
Definition: pathnodes.h:2876
Relids min_lefthand
Definition: pathnodes.h:2868
Relids syn_righthand
Definition: pathnodes.h:2871
Relids commute_below_r
Definition: pathnodes.h:2877
List * semi_operators
Definition: pathnodes.h:2882

References clamp_row_est(), clause_selectivity(), SpecialJoinInfo::commute_above_l, SpecialJoinInfo::commute_above_r, SpecialJoinInfo::commute_below_l, SpecialJoinInfo::commute_below_r, JoinPath::innerjoinpath, JOIN_INNER, SpecialJoinInfo::jointype, lfirst, SpecialJoinInfo::lhs_strict, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, SpecialJoinInfo::ojrelid, JoinPath::outerjoinpath, Path::rows, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, and SpecialJoinInfo::syn_righthand.

Referenced by final_cost_hashjoin(), and final_cost_mergejoin().

◆ cached_scansel()

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

Definition at line 3994 of file costsize.c.

3995 {
3996  MergeScanSelCache *cache;
3997  ListCell *lc;
3998  Selectivity leftstartsel,
3999  leftendsel,
4000  rightstartsel,
4001  rightendsel;
4002  MemoryContext oldcontext;
4003 
4004  /* Do we have this result already? */
4005  foreach(lc, rinfo->scansel_cache)
4006  {
4007  cache = (MergeScanSelCache *) lfirst(lc);
4008  if (cache->opfamily == pathkey->pk_opfamily &&
4009  cache->collation == pathkey->pk_eclass->ec_collation &&
4010  cache->strategy == pathkey->pk_strategy &&
4011  cache->nulls_first == pathkey->pk_nulls_first)
4012  return cache;
4013  }
4014 
4015  /* Nope, do the computation */
4016  mergejoinscansel(root,
4017  (Node *) rinfo->clause,
4018  pathkey->pk_opfamily,
4019  pathkey->pk_strategy,
4020  pathkey->pk_nulls_first,
4021  &leftstartsel,
4022  &leftendsel,
4023  &rightstartsel,
4024  &rightendsel);
4025 
4026  /* Cache the result in suitably long-lived workspace */
4027  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4028 
4029  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
4030  cache->opfamily = pathkey->pk_opfamily;
4031  cache->collation = pathkey->pk_eclass->ec_collation;
4032  cache->strategy = pathkey->pk_strategy;
4033  cache->nulls_first = pathkey->pk_nulls_first;
4034  cache->leftstartsel = leftstartsel;
4035  cache->leftendsel = leftendsel;
4036  cache->rightstartsel = rightstartsel;
4037  cache->rightendsel = rightendsel;
4038 
4039  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4040 
4041  MemoryContextSwitchTo(oldcontext);
4042 
4043  return cache;
4044 }
List * lappend(List *list, void *datum)
Definition: list.c:339
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2952
Selectivity leftstartsel
Definition: pathnodes.h:2717
Selectivity leftendsel
Definition: pathnodes.h:2718
Selectivity rightendsel
Definition: pathnodes.h:2720
Selectivity rightstartsel
Definition: pathnodes.h:2719
bool pk_nulls_first
Definition: pathnodes.h:1458
int pk_strategy
Definition: pathnodes.h:1457
Oid pk_opfamily
Definition: pathnodes.h:1456
Expr * clause
Definition: pathnodes.h:2541

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

Referenced by initial_cost_mergejoin().

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

5429 {
5430  JoinType jointype = sjinfo->jointype;
5431  Selectivity fkselec;
5432  Selectivity jselec;
5433  Selectivity pselec;
5434  double nrows;
5435 
5436  /*
5437  * Compute joinclause selectivity. Note that we are only considering
5438  * clauses that become restriction clauses at this join level; we are not
5439  * double-counting them because they were not considered in estimating the
5440  * sizes of the component rels.
5441  *
5442  * First, see whether any of the joinclauses can be matched to known FK
5443  * constraints. If so, drop those clauses from the restrictlist, and
5444  * instead estimate their selectivity using FK semantics. (We do this
5445  * without regard to whether said clauses are local or "pushed down".
5446  * Probably, an FK-matching clause could never be seen as pushed down at
5447  * an outer join, since it would be strict and hence would be grounds for
5448  * join strength reduction.) fkselec gets the net selectivity for
5449  * FK-matching clauses, or 1.0 if there are none.
5450  */
5451  fkselec = get_foreign_key_join_selectivity(root,
5452  outer_rel->relids,
5453  inner_rel->relids,
5454  sjinfo,
5455  &restrictlist);
5456 
5457  /*
5458  * For an outer join, we have to distinguish the selectivity of the join's
5459  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5460  * down". For inner joins we just count them all as joinclauses.
5461  */
5462  if (IS_OUTER_JOIN(jointype))
5463  {
5464  List *joinquals = NIL;
5465  List *pushedquals = NIL;
5466  ListCell *l;
5467 
5468  /* Grovel through the clauses to separate into two lists */
5469  foreach(l, restrictlist)
5470  {
5471  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5472 
5473  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5474  pushedquals = lappend(pushedquals, rinfo);
5475  else
5476  joinquals = lappend(joinquals, rinfo);
5477  }
5478 
5479  /* Get the separate selectivities */
5480  jselec = clauselist_selectivity(root,
5481  joinquals,
5482  0,
5483  jointype,
5484  sjinfo);
5485  pselec = clauselist_selectivity(root,
5486  pushedquals,
5487  0,
5488  jointype,
5489  sjinfo);
5490 
5491  /* Avoid leaking a lot of ListCells */
5492  list_free(joinquals);
5493  list_free(pushedquals);
5494  }
5495  else
5496  {
5497  jselec = clauselist_selectivity(root,
5498  restrictlist,
5499  0,
5500  jointype,
5501  sjinfo);
5502  pselec = 0.0; /* not used, keep compiler quiet */
5503  }
5504 
5505  /*
5506  * Basically, we multiply size of Cartesian product by selectivity.
5507  *
5508  * If we are doing an outer join, take that into account: the joinqual
5509  * selectivity has to be clamped using the knowledge that the output must
5510  * be at least as large as the non-nullable input. However, any
5511  * pushed-down quals are applied after the outer join, so their
5512  * selectivity applies fully.
5513  *
5514  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5515  * of LHS rows that have matches, and we apply that straightforwardly.
5516  */
5517  switch (jointype)
5518  {
5519  case JOIN_INNER:
5520  nrows = outer_rows * inner_rows * fkselec * jselec;
5521  /* pselec not used */
5522  break;
5523  case JOIN_LEFT:
5524  nrows = outer_rows * inner_rows * fkselec * jselec;
5525  if (nrows < outer_rows)
5526  nrows = outer_rows;
5527  nrows *= pselec;
5528  break;
5529  case JOIN_FULL:
5530  nrows = outer_rows * inner_rows * fkselec * jselec;
5531  if (nrows < outer_rows)
5532  nrows = outer_rows;
5533  if (nrows < inner_rows)
5534  nrows = inner_rows;
5535  nrows *= pselec;
5536  break;
5537  case JOIN_SEMI:
5538  nrows = outer_rows * fkselec * jselec;
5539  /* pselec not used */
5540  break;
5541  case JOIN_ANTI:
5542  nrows = outer_rows * (1.0 - fkselec * jselec);
5543  nrows *= pselec;
5544  break;
5545  default:
5546  /* other values not expected here */
5547  elog(ERROR, "unrecognized join type: %d", (int) jointype);
5548  nrows = 0; /* keep compiler quiet */
5549  break;
5550  }
5551 
5552  return clamp_row_est(nrows);
5553 }
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:5571
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
void list_free(List *list)
Definition: list.c:1546
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:327
JoinType
Definition: nodes.h:278
@ JOIN_SEMI
Definition: nodes.h:297
@ JOIN_FULL
Definition: nodes.h:285
@ JOIN_LEFT
Definition: nodes.h:284
@ JOIN_ANTI
Definition: nodes.h:298
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2698
#define lfirst_node(type, lc)
Definition: pg_list.h:176
Definition: pg_list.h:54
Relids relids
Definition: pathnodes.h:856

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

◆ clamp_cardinality_to_long()

long clamp_cardinality_to_long ( Cardinality  x)

Definition at line 254 of file costsize.c.

255 {
256  /*
257  * Just for paranoia's sake, ensure we do something sane with negative or
258  * NaN values.
259  */
260  if (isnan(x))
261  return LONG_MAX;
262  if (x <= 0)
263  return 0;
264 
265  /*
266  * If "long" is 64 bits, then LONG_MAX cannot be represented exactly as a
267  * double. Casting it to double and back may well result in overflow due
268  * to rounding, so avoid doing that. We trust that any double value that
269  * compares strictly less than "(double) LONG_MAX" will cast to a
270  * representable "long" value.
271  */
272  return (x < (double) LONG_MAX) ? (long) x : LONG_MAX;
273 }
int x
Definition: isn.c:71

References x.

Referenced by buildSubPlanHash(), create_recursiveunion_plan(), create_setop_plan(), and make_agg().

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 202 of file costsize.c.

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

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(), cost_subqueryscan(), create_bitmap_subplan(), estimate_array_length(), 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(), get_windowclause_startup_tuples(), initial_cost_mergejoin(), set_baserel_size_estimates(), set_cte_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

◆ clamp_width_est()

int32 clamp_width_est ( int64  tuple_width)

Definition at line 231 of file costsize.c.

232 {
233  /*
234  * Anything more than MaxAllocSize is clearly bogus, since we could not
235  * create a tuple that large.
236  */
237  if (tuple_width > MaxAllocSize)
238  return (int32) MaxAllocSize;
239 
240  /*
241  * Unlike clamp_row_est, we just Assert that the value isn't negative,
242  * rather than masking such errors.
243  */
244  Assert(tuple_width >= 0);
245 
246  return (int32) tuple_width;
247 }
signed int int32
Definition: c.h:481
Assert(fmt[strlen(fmt) - 1] !='\n')
#define MaxAllocSize
Definition: memutils.h:40

References Assert(), and MaxAllocSize.

Referenced by add_placeholders_to_joinrel(), build_joinrel_tlist(), create_one_window_path(), get_rel_data_width(), set_pathtarget_cost_width(), and set_rel_width().

◆ compute_bitmap_pages()

double compute_bitmap_pages ( PlannerInfo root,
RelOptInfo baserel,
Path bitmapqual,
double  loop_count,
Cost cost_p,
double *  tuples_p 
)

Definition at line 6433 of file costsize.c.

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

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_semi_anti_join_factors()

void compute_semi_anti_join_factors ( PlannerInfo root,
RelOptInfo joinrel,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist,
SemiAntiJoinFactors semifactors 
)

Definition at line 5003 of file costsize.c.

5011 {
5012  Selectivity jselec;
5013  Selectivity nselec;
5014  Selectivity avgmatch;
5015  SpecialJoinInfo norm_sjinfo;
5016  List *joinquals;
5017  ListCell *l;
5018 
5019  /*
5020  * In an ANTI join, we must ignore clauses that are "pushed down", since
5021  * those won't affect the match logic. In a SEMI join, we do not
5022  * distinguish joinquals from "pushed down" quals, so just use the whole
5023  * restrictinfo list. For other outer join types, we should consider only
5024  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5025  */
5026  if (IS_OUTER_JOIN(jointype))
5027  {
5028  joinquals = NIL;
5029  foreach(l, restrictlist)
5030  {
5031  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5032 
5033  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5034  joinquals = lappend(joinquals, rinfo);
5035  }
5036  }
5037  else
5038  joinquals = restrictlist;
5039 
5040  /*
5041  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5042  */
5043  jselec = clauselist_selectivity(root,
5044  joinquals,
5045  0,
5046  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5047  sjinfo);
5048 
5049  /*
5050  * Also get the normal inner-join selectivity of the join clauses.
5051  */
5052  norm_sjinfo.type = T_SpecialJoinInfo;
5053  norm_sjinfo.min_lefthand = outerrel->relids;
5054  norm_sjinfo.min_righthand = innerrel->relids;
5055  norm_sjinfo.syn_lefthand = outerrel->relids;
5056  norm_sjinfo.syn_righthand = innerrel->relids;
5057  norm_sjinfo.jointype = JOIN_INNER;
5058  norm_sjinfo.ojrelid = 0;
5059  norm_sjinfo.commute_above_l = NULL;
5060  norm_sjinfo.commute_above_r = NULL;
5061  norm_sjinfo.commute_below_l = NULL;
5062  norm_sjinfo.commute_below_r = NULL;
5063  /* we don't bother trying to make the remaining fields valid */
5064  norm_sjinfo.lhs_strict = false;
5065  norm_sjinfo.semi_can_btree = false;
5066  norm_sjinfo.semi_can_hash = false;
5067  norm_sjinfo.semi_operators = NIL;
5068  norm_sjinfo.semi_rhs_exprs = NIL;
5069 
5070  nselec = clauselist_selectivity(root,
5071  joinquals,
5072  0,
5073  JOIN_INNER,
5074  &norm_sjinfo);
5075 
5076  /* Avoid leaking a lot of ListCells */
5077  if (IS_OUTER_JOIN(jointype))
5078  list_free(joinquals);
5079 
5080  /*
5081  * jselec can be interpreted as the fraction of outer-rel rows that have
5082  * any matches (this is true for both SEMI and ANTI cases). And nselec is
5083  * the fraction of the Cartesian product that matches. So, the average
5084  * number of matches for each outer-rel row that has at least one match is
5085  * nselec * inner_rows / jselec.
5086  *
5087  * Note: it is correct to use the inner rel's "rows" count here, even
5088  * though we might later be considering a parameterized inner path with
5089  * fewer rows. This is because we have included all the join clauses in
5090  * the selectivity estimate.
5091  */
5092  if (jselec > 0) /* protect against zero divide */
5093  {
5094  avgmatch = nselec * innerrel->rows / jselec;
5095  /* Clamp to sane range */
5096  avgmatch = Max(1.0, avgmatch);
5097  }
5098  else
5099  avgmatch = 1.0;
5100 
5101  semifactors->outer_match_frac = jselec;
5102  semifactors->match_count = avgmatch;
5103 }
Cardinality rows
Definition: pathnodes.h:862
Selectivity outer_match_frac
Definition: pathnodes.h:3185
Selectivity match_count
Definition: pathnodes.h:3186

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

Referenced by add_paths_to_joinrel().

◆ cost_agg()

void cost_agg ( Path path,
PlannerInfo root,
AggStrategy  aggstrategy,
const AggClauseCosts aggcosts,
int  numGroupCols,
double  numGroups,
List quals,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples,
double  input_width 
)

Definition at line 2650 of file costsize.c.

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

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

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

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2231 of file costsize.c.

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

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

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1157 of file costsize.c.

1158 {
1159  Cost totalCost;
1160  Selectivity selec;
1161  ListCell *l;
1162 
1163  /*
1164  * We estimate AND selectivity on the assumption that the inputs are
1165  * independent. This is probably often wrong, but we don't have the info
1166  * to do better.
1167  *
1168  * The runtime cost of the BitmapAnd itself is estimated at 100x
1169  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1170  * definitely too simplistic?
1171  */
1172  totalCost = 0.0;
1173  selec = 1.0;
1174  foreach(l, path->bitmapquals)
1175  {
1176  Path *subpath = (Path *) lfirst(l);
1177  Cost subCost;
1178  Selectivity subselec;
1179 
1180  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1181 
1182  selec *= subselec;
1183 
1184  totalCost += subCost;
1185  if (l != list_head(path->bitmapquals))
1186  totalCost += 100.0 * cpu_operator_cost;
1187  }
1188  path->bitmapselectivity = selec;
1189  path->path.rows = 0; /* per above, not used */
1190  path->path.startup_cost = totalCost;
1191  path->path.total_cost = totalCost;
1192 }
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
Selectivity bitmapselectivity
Definition: pathnodes.h:1778
List * bitmapquals
Definition: pathnodes.h:1777

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

Referenced by create_bitmap_and_path().

◆ cost_bitmap_heap_scan()

void cost_bitmap_heap_scan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
Path bitmapqual,
double  loop_count 
)

Definition at line 1013 of file costsize.c.

1016 {
1017  Cost startup_cost = 0;
1018  Cost run_cost = 0;
1019  Cost indexTotalCost;
1020  QualCost qpqual_cost;
1021  Cost cpu_per_tuple;
1022  Cost cost_per_page;
1023  Cost cpu_run_cost;
1024  double tuples_fetched;
1025  double pages_fetched;
1026  double spc_seq_page_cost,
1027  spc_random_page_cost;
1028  double T;
1029 
1030  /* Should only be applied to base relations */
1031  Assert(IsA(baserel, RelOptInfo));
1032  Assert(baserel->relid > 0);
1033  Assert(baserel->rtekind == RTE_RELATION);
1034 
1035  /* Mark the path with the correct row estimate */
1036  if (param_info)
1037  path->rows = param_info->ppi_rows;
1038  else
1039  path->rows = baserel->rows;
1040 
1041  if (!enable_bitmapscan)
1042  startup_cost += disable_cost;
1043 
1044  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1045  loop_count, &indexTotalCost,
1046  &tuples_fetched);
1047 
1048  startup_cost += indexTotalCost;
1049  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1050 
1051  /* Fetch estimated page costs for tablespace containing table. */
1053  &spc_random_page_cost,
1054  &spc_seq_page_cost);
1055 
1056  /*
1057  * For small numbers of pages we should charge spc_random_page_cost
1058  * apiece, while if nearly all the table's pages are being read, it's more
1059  * appropriate to charge spc_seq_page_cost apiece. The effect is
1060  * nonlinear, too. For lack of a better idea, interpolate like this to
1061  * determine the cost per page.
1062  */
1063  if (pages_fetched >= 2.0)
1064  cost_per_page = spc_random_page_cost -
1065  (spc_random_page_cost - spc_seq_page_cost)
1066  * sqrt(pages_fetched / T);
1067  else
1068  cost_per_page = spc_random_page_cost;
1069 
1070  run_cost += pages_fetched * cost_per_page;
1071 
1072  /*
1073  * Estimate CPU costs per tuple.
1074  *
1075  * Often the indexquals don't need to be rechecked at each tuple ... but
1076  * not always, especially not if there are enough tuples involved that the
1077  * bitmaps become lossy. For the moment, just assume they will be
1078  * rechecked always. This means we charge the full freight for all the
1079  * scan clauses.
1080  */
1081  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1082 
1083  startup_cost += qpqual_cost.startup;
1084  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1085  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1086 
1087  /* Adjust costing for parallelism, if used. */
1088  if (path->parallel_workers > 0)
1089  {
1090  double parallel_divisor = get_parallel_divisor(path);
1091 
1092  /* The CPU cost is divided among all the workers. */
1093  cpu_run_cost /= parallel_divisor;
1094 
1095  path->rows = clamp_row_est(path->rows / parallel_divisor);
1096  }
1097 
1098 
1099  run_cost += cpu_run_cost;
1100 
1101  /* tlist eval costs are paid per output row, not per tuple scanned */
1102  startup_cost += path->pathtarget->cost.startup;
1103  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1104 
1105  path->startup_cost = startup_cost;
1106  path->total_cost = startup_cost + run_cost;
1107 }
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4961
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition: costsize.c:6433
bool enable_bitmapscan
Definition: costsize.c:137
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
@ RTE_RELATION
Definition: parsenodes.h:1011
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Cardinality ppi_rows
Definition: pathnodes.h:1560
Index relid
Definition: pathnodes.h:903
Oid reltablespace
Definition: pathnodes.h:905
RTEKind rtekind
Definition: pathnodes.h:907

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1201 of file costsize.c.

1202 {
1203  Cost totalCost;
1204  Selectivity selec;
1205  ListCell *l;
1206 
1207  /*
1208  * We estimate OR selectivity on the assumption that the inputs are
1209  * non-overlapping, since that's often the case in "x IN (list)" type
1210  * situations. Of course, we clamp to 1.0 at the end.
1211  *
1212  * The runtime cost of the BitmapOr itself is estimated at 100x
1213  * cpu_operator_cost for each tbm_union needed. Probably too small,
1214  * definitely too simplistic? We are aware that the tbm_unions are
1215  * optimized out when the inputs are BitmapIndexScans.
1216  */
1217  totalCost = 0.0;
1218  selec = 0.0;
1219  foreach(l, path->bitmapquals)
1220  {
1221  Path *subpath = (Path *) lfirst(l);
1222  Cost subCost;
1223  Selectivity subselec;
1224 
1225  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1226 
1227  selec += subselec;
1228 
1229  totalCost += subCost;
1230  if (l != list_head(path->bitmapquals) &&
1231  !IsA(subpath, IndexPath))
1232  totalCost += 100.0 * cpu_operator_cost;
1233  }
1234  path->bitmapselectivity = Min(selec, 1.0);
1235  path->path.rows = 0; /* per above, not used */
1236  path->path.startup_cost = totalCost;
1237  path->path.total_cost = totalCost;
1238 }
Selectivity bitmapselectivity
Definition: pathnodes.h:1791
List * bitmapquals
Definition: pathnodes.h:1790

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

Referenced by create_bitmap_or_path().

◆ cost_bitmap_tree_node()

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

Definition at line 1114 of file costsize.c.

1115 {
1116  if (IsA(path, IndexPath))
1117  {
1118  *cost = ((IndexPath *) path)->indextotalcost;
1119  *selec = ((IndexPath *) path)->indexselectivity;
1120 
1121  /*
1122  * Charge a small amount per retrieved tuple to reflect the costs of
1123  * manipulating the bitmap. This is mostly to make sure that a bitmap
1124  * scan doesn't look to be the same cost as an indexscan to retrieve a
1125  * single tuple.
1126  */
1127  *cost += 0.1 * cpu_operator_cost * path->rows;
1128  }
1129  else if (IsA(path, BitmapAndPath))
1130  {
1131  *cost = path->total_cost;
1132  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1133  }
1134  else if (IsA(path, BitmapOrPath))
1135  {
1136  *cost = path->total_cost;
1137  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1138  }
1139  else
1140  {
1141  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1142  *cost = *selec = 0; /* keep compiler quiet */
1143  }
1144 }
#define nodeTag(nodeptr)
Definition: nodes.h:133

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

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

◆ cost_ctescan()

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

Definition at line 1698 of file costsize.c.

1700 {
1701  Cost startup_cost = 0;
1702  Cost run_cost = 0;
1703  QualCost qpqual_cost;
1704  Cost cpu_per_tuple;
1705 
1706  /* Should only be applied to base relations that are CTEs */
1707  Assert(baserel->relid > 0);
1708  Assert(baserel->rtekind == RTE_CTE);
1709 
1710  /* Mark the path with the correct row estimate */
1711  if (param_info)
1712  path->rows = param_info->ppi_rows;
1713  else
1714  path->rows = baserel->rows;
1715 
1716  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1717  cpu_per_tuple = cpu_tuple_cost;
1718 
1719  /* Add scanning CPU costs */
1720  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1721 
1722  startup_cost += qpqual_cost.startup;
1723  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1724  run_cost += cpu_per_tuple * baserel->tuples;
1725 
1726  /* tlist eval costs are paid per output row, not per tuple scanned */
1727  startup_cost += path->pathtarget->cost.startup;
1728  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1729 
1730  path->startup_cost = startup_cost;
1731  path->total_cost = startup_cost + run_cost;
1732 }
@ RTE_CTE
Definition: parsenodes.h:1017

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

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

Definition at line 1531 of file costsize.c.

1533 {
1534  Cost startup_cost = 0;
1535  Cost run_cost = 0;
1536  QualCost qpqual_cost;
1537  Cost cpu_per_tuple;
1538  RangeTblEntry *rte;
1539  QualCost exprcost;
1540 
1541  /* Should only be applied to base relations that are functions */
1542  Assert(baserel->relid > 0);
1543  rte = planner_rt_fetch(baserel->relid, root);
1544  Assert(rte->rtekind == RTE_FUNCTION);
1545 
1546  /* Mark the path with the correct row estimate */
1547  if (param_info)
1548  path->rows = param_info->ppi_rows;
1549  else
1550  path->rows = baserel->rows;
1551 
1552  /*
1553  * Estimate costs of executing the function expression(s).
1554  *
1555  * Currently, nodeFunctionscan.c always executes the functions to
1556  * completion before returning any rows, and caches the results in a
1557  * tuplestore. So the function eval cost is all startup cost, and per-row
1558  * costs are minimal.
1559  *
1560  * XXX in principle we ought to charge tuplestore spill costs if the
1561  * number of rows is large. However, given how phony our rowcount
1562  * estimates for functions tend to be, there's not a lot of point in that
1563  * refinement right now.
1564  */
1565  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1566 
1567  startup_cost += exprcost.startup + exprcost.per_tuple;
1568 
1569  /* Add scanning CPU costs */
1570  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1571 
1572  startup_cost += qpqual_cost.startup;
1573  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1574  run_cost += cpu_per_tuple * baserel->tuples;
1575 
1576  /* tlist eval costs are paid per output row, not per tuple scanned */
1577  startup_cost += path->pathtarget->cost.startup;
1578  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1579 
1580  path->startup_cost = startup_cost;
1581  path->total_cost = startup_cost + run_cost;
1582 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4666
@ RTE_FUNCTION
Definition: parsenodes.h:1014
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:555
List * functions
Definition: parsenodes.h:1153
RTEKind rtekind
Definition: parsenodes.h:1030

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

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 436 of file costsize.c.

439 {
440  Cost startup_cost = 0;
441  Cost run_cost = 0;
442 
443  /* Mark the path with the correct row estimate */
444  if (rows)
445  path->path.rows = *rows;
446  else if (param_info)
447  path->path.rows = param_info->ppi_rows;
448  else
449  path->path.rows = rel->rows;
450 
451  startup_cost = path->subpath->startup_cost;
452 
453  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
454 
455  /* Parallel setup and communication cost. */
456  startup_cost += parallel_setup_cost;
457  run_cost += parallel_tuple_cost * path->path.rows;
458 
459  path->path.startup_cost = startup_cost;
460  path->path.total_cost = (startup_cost + run_cost);
461 }
double parallel_setup_cost
Definition: costsize.c:125
double parallel_tuple_cost
Definition: costsize.c:124
Path * subpath
Definition: pathnodes.h:2022

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

Referenced by create_gather_path().

◆ cost_gather_merge()

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

Definition at line 474 of file costsize.c.

478 {
479  Cost startup_cost = 0;
480  Cost run_cost = 0;
481  Cost comparison_cost;
482  double N;
483  double logN;
484 
485  /* Mark the path with the correct row estimate */
486  if (rows)
487  path->path.rows = *rows;
488  else if (param_info)
489  path->path.rows = param_info->ppi_rows;
490  else
491  path->path.rows = rel->rows;
492 
493  if (!enable_gathermerge)
494  startup_cost += disable_cost;
495 
496  /*
497  * Add one to the number of workers to account for the leader. This might
498  * be overgenerous since the leader will do less work than other workers
499  * in typical cases, but we'll go with it for now.
500  */
501  Assert(path->num_workers > 0);
502  N = (double) path->num_workers + 1;
503  logN = LOG2(N);
504 
505  /* Assumed cost per tuple comparison */
506  comparison_cost = 2.0 * cpu_operator_cost;
507 
508  /* Heap creation cost */
509  startup_cost += comparison_cost * N * logN;
510 
511  /* Per-tuple heap maintenance cost */
512  run_cost += path->path.rows * comparison_cost * logN;
513 
514  /* small cost for heap management, like cost_merge_append */
515  run_cost += cpu_operator_cost * path->path.rows;
516 
517  /*
518  * Parallel setup and communication cost. Since Gather Merge, unlike
519  * Gather, requires us to block until a tuple is available from every
520  * worker, we bump the IPC cost up a little bit as compared with Gather.
521  * For lack of a better idea, charge an extra 5%.
522  */
523  startup_cost += parallel_setup_cost;
524  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
525 
526  path->path.startup_cost = startup_cost + input_startup_cost;
527  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
528 }
#define LOG2(x)
Definition: costsize.c:102
bool enable_gathermerge
Definition: costsize.c:147

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

Referenced by create_gather_merge_path().

◆ cost_group()

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

Definition at line 3163 of file costsize.c.

3168 {
3169  double output_tuples;
3170  Cost startup_cost;
3171  Cost total_cost;
3172 
3173  output_tuples = numGroups;
3174  startup_cost = input_startup_cost;
3175  total_cost = input_total_cost;
3176 
3177  /*
3178  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3179  * all columns get compared at most of the tuples.
3180  */
3181  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3182 
3183  /*
3184  * If there are quals (HAVING quals), account for their cost and
3185  * selectivity.
3186  */
3187  if (quals)
3188  {
3189  QualCost qual_cost;
3190 
3191  cost_qual_eval(&qual_cost, quals, root);
3192  startup_cost += qual_cost.startup;
3193  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3194 
3195  output_tuples = clamp_row_est(output_tuples *
3197  quals,
3198  0,
3199  JOIN_INNER,
3200  NULL));
3201  }
3202 
3203  path->rows = output_tuples;
3204  path->startup_cost = startup_cost;
3205  path->total_cost = total_cost;
3206 }

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

Referenced by choose_hashed_setop(), and create_group_path().

◆ cost_incremental_sort()

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

Definition at line 1986 of file costsize.c.

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

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

Referenced by create_incremental_sort_path().

◆ cost_index()

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

Definition at line 549 of file costsize.c.

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

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

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2453 of file costsize.c.

2456 {
2457  Cost startup_cost = input_startup_cost;
2458  Cost run_cost = input_total_cost - input_startup_cost;
2459  double nbytes = relation_byte_size(tuples, width);
2460  long work_mem_bytes = work_mem * 1024L;
2461 
2462  path->rows = tuples;
2463 
2464  /*
2465  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2466  * reflect bookkeeping overhead. (This rate must be more than what
2467  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2468  * if it is exactly the same then there will be a cost tie between
2469  * nestloop with A outer, materialized B inner and nestloop with B outer,
2470  * materialized A inner. The extra cost ensures we'll prefer
2471  * materializing the smaller rel.) Note that this is normally a good deal
2472  * less than cpu_tuple_cost; which is OK because a Material plan node
2473  * doesn't do qual-checking or projection, so it's got less overhead than
2474  * most plan nodes.
2475  */
2476  run_cost += 2 * cpu_operator_cost * tuples;
2477 
2478  /*
2479  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2480  * This cost is assumed to be evenly spread through the plan run phase,
2481  * which isn't exactly accurate but our cost model doesn't allow for
2482  * nonuniform costs within the run phase.
2483  */
2484  if (nbytes > work_mem_bytes)
2485  {
2486  double npages = ceil(nbytes / BLCKSZ);
2487 
2488  run_cost += seq_page_cost * npages;
2489  }
2490 
2491  path->startup_cost = startup_cost;
2492  path->total_cost = startup_cost + run_cost;
2493 }

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

Referenced by create_material_path(), and materialize_finished_plan().

◆ cost_memoize_rescan()

static void cost_memoize_rescan ( PlannerInfo root,
MemoizePath mpath,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 2509 of file costsize.c.

2511 {
2512  EstimationInfo estinfo;
2513  ListCell *lc;
2514  Cost input_startup_cost = mpath->subpath->startup_cost;
2515  Cost input_total_cost = mpath->subpath->total_cost;
2516  double tuples = mpath->subpath->rows;
2517  double calls = mpath->calls;
2518  int width = mpath->subpath->pathtarget->width;
2519 
2520  double hash_mem_bytes;
2521  double est_entry_bytes;
2522  double est_cache_entries;
2523  double ndistinct;
2524  double evict_ratio;
2525  double hit_ratio;
2526  Cost startup_cost;
2527  Cost total_cost;
2528 
2529  /* available cache space */
2530  hash_mem_bytes = get_hash_memory_limit();
2531 
2532  /*
2533  * Set the number of bytes each cache entry should consume in the cache.
2534  * To provide us with better estimations on how many cache entries we can
2535  * store at once, we make a call to the executor here to ask it what
2536  * memory overheads there are for a single cache entry.
2537  */
2538  est_entry_bytes = relation_byte_size(tuples, width) +
2540 
2541  /* include the estimated width for the cache keys */
2542  foreach(lc, mpath->param_exprs)
2543  est_entry_bytes += get_expr_width(root, (Node *) lfirst(lc));
2544 
2545  /* estimate on the upper limit of cache entries we can hold at once */
2546  est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2547 
2548  /* estimate on the distinct number of parameter values */
2549  ndistinct = estimate_num_groups(root, mpath->param_exprs, calls, NULL,
2550  &estinfo);
2551 
2552  /*
2553  * When the estimation fell back on using a default value, it's a bit too
2554  * risky to assume that it's ok to use a Memoize node. The use of a
2555  * default could cause us to use a Memoize node when it's really
2556  * inappropriate to do so. If we see that this has been done, then we'll
2557  * assume that every call will have unique parameters, which will almost
2558  * certainly mean a MemoizePath will never survive add_path().
2559  */
2560  if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2561  ndistinct = calls;
2562 
2563  /*
2564  * Since we've already estimated the maximum number of entries we can
2565  * store at once and know the estimated number of distinct values we'll be
2566  * called with, we'll take this opportunity to set the path's est_entries.
2567  * This will ultimately determine the hash table size that the executor
2568  * will use. If we leave this at zero, the executor will just choose the
2569  * size itself. Really this is not the right place to do this, but it's
2570  * convenient since everything is already calculated.
2571  */
2572  mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2573  PG_UINT32_MAX);
2574 
2575  /*
2576  * When the number of distinct parameter values is above the amount we can
2577  * store in the cache, then we'll have to evict some entries from the
2578  * cache. This is not free. Here we estimate how often we'll incur the
2579  * cost of that eviction.
2580  */
2581  evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2582 
2583  /*
2584  * In order to estimate how costly a single scan will be, we need to
2585  * attempt to estimate what the cache hit ratio will be. To do that we
2586  * must look at how many scans are estimated in total for this node and
2587  * how many of those scans we expect to get a cache hit.
2588  */
2589  hit_ratio = ((calls - ndistinct) / calls) *
2590  (est_cache_entries / Max(ndistinct, est_cache_entries));
2591 
2592  Assert(hit_ratio >= 0 && hit_ratio <= 1.0);
2593 
2594  /*
2595  * Set the total_cost accounting for the expected cache hit ratio. We
2596  * also add on a cpu_operator_cost to account for a cache lookup. This
2597  * will happen regardless of whether it's a cache hit or not.
2598  */
2599  total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2600 
2601  /* Now adjust the total cost to account for cache evictions */
2602 
2603  /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2604  total_cost += cpu_tuple_cost * evict_ratio;
2605 
2606  /*
2607  * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2608  * The per-tuple eviction is really just a pfree, so charging a whole
2609  * cpu_operator_cost seems a little excessive.
2610  */
2611  total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2612 
2613  /*
2614  * Now adjust for storing things in the cache, since that's not free
2615  * either. Everything must go in the cache. We don't proportion this
2616  * over any ratio, just apply it once for the scan. We charge a
2617  * cpu_tuple_cost for the creation of the cache entry and also a
2618  * cpu_operator_cost for each tuple we expect to cache.
2619  */
2620  total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2621 
2622  /*
2623  * Getting the first row must be also be proportioned according to the
2624  * expected cache hit ratio.
2625  */
2626  startup_cost = input_startup_cost * (1.0 - hit_ratio);
2627 
2628  /*
2629  * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2630  * which we'll do regardless of whether it was a cache hit or not.
2631  */
2632  startup_cost += cpu_tuple_cost;
2633 
2634  *rescan_startup_cost = startup_cost;
2635  *rescan_total_cost = total_cost;
2636 }
#define PG_UINT32_MAX
Definition: c.h:577
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition: costsize.c:6324
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3595
double ExecEstimateCacheEntryOverheadBytes(double ntuples)
Definition: nodeMemoize.c:1171
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
uint32 flags
Definition: selfuncs.h:80
uint32 est_entries
Definition: pathnodes.h:1981
Cardinality calls
Definition: pathnodes.h:1980
Path * subpath
Definition: pathnodes.h:1973
List * param_exprs
Definition: pathnodes.h:1975

References Assert(), MemoizePath::calls, cpu_operator_cost, cpu_tuple_cost, MemoizePath::est_entries, estimate_num_groups(), ExecEstimateCacheEntryOverheadBytes(), EstimationInfo::flags, get_expr_width(), get_hash_memory_limit(), lfirst, Max, Min, MemoizePath::param_exprs, PG_UINT32_MAX, relation_byte_size(), Path::rows, SELFLAG_USED_DEFAULT, Path::startup_cost, MemoizePath::subpath, and Path::total_cost.

Referenced by cost_rescan().

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

2408 {
2409  Cost startup_cost = 0;
2410  Cost run_cost = 0;
2411  Cost comparison_cost;
2412  double N;
2413  double logN;
2414 
2415  /*
2416  * Avoid log(0)...
2417  */
2418  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2419  logN = LOG2(N);
2420 
2421  /* Assumed cost per tuple comparison */
2422  comparison_cost = 2.0 * cpu_operator_cost;
2423 
2424  /* Heap creation cost */
2425  startup_cost += comparison_cost * N * logN;
2426 
2427  /* Per-tuple heap maintenance cost */
2428  run_cost += tuples * comparison_cost * logN;
2429 
2430  /*
2431  * Although MergeAppend does not do any selection or projection, it's not
2432  * free; add a small per-tuple overhead.
2433  */
2434  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2435 
2436  path->startup_cost = startup_cost + input_startup_cost;
2437  path->total_cost = startup_cost + run_cost + input_total_cost;
2438 }

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

Referenced by create_merge_append_path().

◆ cost_namedtuplestorescan()

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

Definition at line 1739 of file costsize.c.

1741 {
1742  Cost startup_cost = 0;
1743  Cost run_cost = 0;
1744  QualCost qpqual_cost;
1745  Cost cpu_per_tuple;
1746 
1747  /* Should only be applied to base relations that are Tuplestores */
1748  Assert(baserel->relid > 0);
1749  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1750 
1751  /* Mark the path with the correct row estimate */
1752  if (param_info)
1753  path->rows = param_info->ppi_rows;
1754  else
1755  path->rows = baserel->rows;
1756 
1757  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1758  cpu_per_tuple = cpu_tuple_cost;
1759 
1760  /* Add scanning CPU costs */
1761  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1762 
1763  startup_cost += qpqual_cost.startup;
1764  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1765  run_cost += cpu_per_tuple * baserel->tuples;
1766 
1767  path->startup_cost = startup_cost;
1768  path->total_cost = startup_cost + run_cost;
1769 }
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1018

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

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

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

Definition at line 4640 of file costsize.c.

4641 {
4642  cost_qual_eval_context context;
4643  ListCell *l;
4644 
4645  context.root = root;
4646  context.total.startup = 0;
4647  context.total.per_tuple = 0;
4648 
4649  /* We don't charge any cost for the implicit ANDing at top level ... */
4650 
4651  foreach(l, quals)
4652  {
4653  Node *qual = (Node *) lfirst(l);
4654 
4655  cost_qual_eval_walker(qual, &context);
4656  }
4657 
4658  *cost = context.total;
4659 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4680
PlannerInfo * root
Definition: costsize.c:158

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

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

◆ cost_qual_eval_node()

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 4680 of file costsize.c.

4681 {
4682  if (node == NULL)
4683  return false;
4684 
4685  /*
4686  * RestrictInfo nodes contain an eval_cost field reserved for this
4687  * routine's use, so that it's not necessary to evaluate the qual clause's
4688  * cost more than once. If the clause's cost hasn't been computed yet,
4689  * the field's startup value will contain -1.
4690  */
4691  if (IsA(node, RestrictInfo))
4692  {
4693  RestrictInfo *rinfo = (RestrictInfo *) node;
4694 
4695  if (rinfo->eval_cost.startup < 0)
4696  {
4697  cost_qual_eval_context locContext;
4698 
4699  locContext.root = context->root;
4700  locContext.total.startup = 0;
4701  locContext.total.per_tuple = 0;
4702 
4703  /*
4704  * For an OR clause, recurse into the marked-up tree so that we
4705  * set the eval_cost for contained RestrictInfos too.
4706  */
4707  if (rinfo->orclause)
4708  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4709  else
4710  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4711 
4712  /*
4713  * If the RestrictInfo is marked pseudoconstant, it will be tested
4714  * only once, so treat its cost as all startup cost.
4715  */
4716  if (rinfo->pseudoconstant)
4717  {
4718  /* count one execution during startup */
4719  locContext.total.startup += locContext.total.per_tuple;
4720  locContext.total.per_tuple = 0;
4721  }
4722  rinfo->eval_cost = locContext.total;
4723  }
4724  context->total.startup += rinfo->eval_cost.startup;
4725  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4726  /* do NOT recurse into children */
4727  return false;
4728  }
4729 
4730  /*
4731  * For each operator or function node in the given tree, we charge the
4732  * estimated execution cost given by pg_proc.procost (remember to multiply
4733  * this by cpu_operator_cost).
4734  *
4735  * Vars and Consts are charged zero, and so are boolean operators (AND,
4736  * OR, NOT). Simplistic, but a lot better than no model at all.
4737  *
4738  * Should we try to account for the possibility of short-circuit
4739  * evaluation of AND/OR? Probably *not*, because that would make the
4740  * results depend on the clause ordering, and we are not in any position
4741  * to expect that the current ordering of the clauses is the one that's
4742  * going to end up being used. The above per-RestrictInfo caching would
4743  * not mix well with trying to re-order clauses anyway.
4744  *
4745  * Another issue that is entirely ignored here is that if a set-returning
4746  * function is below top level in the tree, the functions/operators above
4747  * it will need to be evaluated multiple times. In practical use, such
4748  * cases arise so seldom as to not be worth the added complexity needed;
4749  * moreover, since our rowcount estimates for functions tend to be pretty
4750  * phony, the results would also be pretty phony.
4751  */
4752  if (IsA(node, FuncExpr))
4753  {
4754  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4755  &context->total);
4756  }
4757  else if (IsA(node, OpExpr) ||
4758  IsA(node, DistinctExpr) ||
4759  IsA(node, NullIfExpr))
4760  {
4761  /* rely on struct equivalence to treat these all alike */
4762  set_opfuncid((OpExpr *) node);
4763  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4764  &context->total);
4765  }
4766  else if (IsA(node, ScalarArrayOpExpr))
4767  {
4768  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4769  Node *arraynode = (Node *) lsecond(saop->args);
4770  QualCost sacosts;
4771  QualCost hcosts;
4772  double estarraylen = estimate_array_length(context->root, arraynode);
4773 
4774  set_sa_opfuncid(saop);
4775  sacosts.startup = sacosts.per_tuple = 0;
4776  add_function_cost(context->root, saop->opfuncid, NULL,
4777  &sacosts);
4778 
4779  if (OidIsValid(saop->hashfuncid))
4780  {
4781  /* Handle costs for hashed ScalarArrayOpExpr */
4782  hcosts.startup = hcosts.per_tuple = 0;
4783 
4784  add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4785  context->total.startup += sacosts.startup + hcosts.startup;
4786 
4787  /* Estimate the cost of building the hashtable. */
4788  context->total.startup += estarraylen * hcosts.per_tuple;
4789 
4790  /*
4791  * XXX should we charge a little bit for sacosts.per_tuple when
4792  * building the table, or is it ok to assume there will be zero
4793  * hash collision?
4794  */
4795 
4796  /*
4797  * Charge for hashtable lookups. Charge a single hash and a
4798  * single comparison.
4799  */
4800  context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4801  }
4802  else
4803  {
4804  /*
4805  * Estimate that the operator will be applied to about half of the
4806  * array elements before the answer is determined.
4807  */
4808  context->total.startup += sacosts.startup;
4809  context->total.per_tuple += sacosts.per_tuple *
4810  estimate_array_length(context->root, arraynode) * 0.5;
4811  }
4812  }
4813  else if (IsA(node, Aggref) ||
4814  IsA(node, WindowFunc))
4815  {
4816  /*
4817  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4818  * ie, zero execution cost in the current model, because they behave
4819  * essentially like Vars at execution. We disregard the costs of
4820  * their input expressions for the same reason. The actual execution
4821  * costs of the aggregate/window functions and their arguments have to
4822  * be factored into plan-node-specific costing of the Agg or WindowAgg
4823  * plan node.
4824  */
4825  return false; /* don't recurse into children */
4826  }
4827  else if (IsA(node, GroupingFunc))
4828  {
4829  /* Treat this as having cost 1 */
4830  context->total.per_tuple += cpu_operator_cost;
4831  return false; /* don't recurse into children */
4832  }
4833  else if (IsA(node, CoerceViaIO))
4834  {
4835  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4836  Oid iofunc;
4837  Oid typioparam;
4838  bool typisvarlena;
4839 
4840  /* check the result type's input function */
4841  getTypeInputInfo(iocoerce->resulttype,
4842  &iofunc, &typioparam);
4843  add_function_cost(context->root, iofunc, NULL,
4844  &context->total);
4845  /* check the input type's output function */
4846  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4847  &iofunc, &typisvarlena);
4848  add_function_cost(context->root, iofunc, NULL,
4849  &context->total);
4850  }
4851  else if (IsA(node, ArrayCoerceExpr))
4852  {
4853  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4854  QualCost perelemcost;
4855 
4856  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4857  context->root);
4858  context->total.startup += perelemcost.startup;
4859  if (perelemcost.per_tuple > 0)
4860  context->total.per_tuple += perelemcost.per_tuple *
4861  estimate_array_length(context->root, (Node *) acoerce->arg);
4862  }
4863  else if (IsA(node, RowCompareExpr))
4864  {
4865  /* Conservatively assume we will check all the columns */
4866  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4867  ListCell *lc;
4868 
4869  foreach(lc, rcexpr->opnos)
4870  {
4871  Oid opid = lfirst_oid(lc);
4872 
4873  add_function_cost(context->root, get_opcode(opid), NULL,
4874  &context->total);
4875  }
4876  }
4877  else if (IsA(node, MinMaxExpr) ||
4878  IsA(node, SQLValueFunction) ||
4879  IsA(node, XmlExpr) ||
4880  IsA(node, CoerceToDomain) ||
4881  IsA(node, NextValueExpr))
4882  {
4883  /* Treat all these as having cost 1 */
4884  context->total.per_tuple += cpu_operator_cost;
4885  }
4886  else if (IsA(node, CurrentOfExpr))
4887  {
4888  /* Report high cost to prevent selection of anything but TID scan */
4889  context->total.startup += disable_cost;
4890  }
4891  else if (IsA(node, SubLink))
4892  {
4893  /* This routine should not be applied to un-planned expressions */
4894  elog(ERROR, "cannot handle unplanned sub-select");
4895  }
4896  else if (IsA(node, SubPlan))
4897  {
4898  /*
4899  * A subplan node in an expression typically indicates that the
4900  * subplan will be executed on each evaluation, so charge accordingly.
4901  * (Sub-selects that can be executed as InitPlans have already been
4902  * removed from the expression.)
4903  */
4904  SubPlan *subplan = (SubPlan *) node;
4905 
4906  context->total.startup += subplan->startup_cost;
4907  context->total.per_tuple += subplan->per_call_cost;
4908 
4909  /*
4910  * We don't want to recurse into the testexpr, because it was already
4911  * counted in the SubPlan node's costs. So we're done.
4912  */
4913  return false;
4914  }
4915  else if (IsA(node, AlternativeSubPlan))
4916  {
4917  /*
4918  * Arbitrarily use the first alternative plan for costing. (We should
4919  * certainly only include one alternative, and we don't yet have
4920  * enough information to know which one the executor is most likely to
4921  * use.)
4922  */
4923  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4924 
4925  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4926  context);
4927  }
4928  else if (IsA(node, PlaceHolderVar))
4929  {
4930  /*
4931  * A PlaceHolderVar should be given cost zero when considering general
4932  * expression evaluation costs. The expense of doing the contained
4933  * expression is charged as part of the tlist eval costs of the scan
4934  * or join where the PHV is first computed (see set_rel_width and
4935  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4936  * double-counting the cost for each level of plan that the PHV
4937  * bubbles up through. Hence, return without recursing into the
4938  * phexpr.
4939  */
4940  return false;
4941  }
4942 
4943  /* recurse into children */
4945  (void *) context);
4946 }
#define OidIsValid(objectId)
Definition: c.h:762
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2863
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1263
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2830
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1801
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1790
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define lsecond(l)
Definition: pg_list.h:183
#define lfirst_oid(lc)
Definition: pg_list.h:174
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2061
unsigned int Oid
Definition: postgres_ext.h:31
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2136
Expr * arg
Definition: primnodes.h:1163
Oid resulttype
Definition: primnodes.h:1164
Cost startup_cost
Definition: primnodes.h:1049
Cost per_call_cost
Definition: primnodes.h:1050

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(), expression_tree_walker, exprType(), get_opcode(), getTypeInputInfo(), getTypeOutputInfo(), IsA, lfirst_oid, linitial, lsecond, OidIsValid, SubPlan::per_call_cost, QualCost::per_tuple, 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().

◆ cost_recursive_union()

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

Definition at line 1813 of file costsize.c.

1814 {
1815  Cost startup_cost;
1816  Cost total_cost;
1817  double total_rows;
1818 
1819  /* We probably have decent estimates for the non-recursive term */
1820  startup_cost = nrterm->startup_cost;
1821  total_cost = nrterm->total_cost;
1822  total_rows = nrterm->rows;
1823 
1824  /*
1825  * We arbitrarily assume that about 10 recursive iterations will be
1826  * needed, and that we've managed to get a good fix on the cost and output
1827  * size of each one of them. These are mighty shaky assumptions but it's
1828  * hard to see how to do better.
1829  */
1830  total_cost += 10 * rterm->total_cost;
1831  total_rows += 10 * rterm->rows;
1832 
1833  /*
1834  * Also charge cpu_tuple_cost per row to account for the costs of
1835  * manipulating the tuplestores. (We don't worry about possible
1836  * spill-to-disk costs.)
1837  */
1838  total_cost += cpu_tuple_cost * total_rows;
1839 
1840  runion->startup_cost = startup_cost;
1841  runion->total_cost = total_cost;
1842  runion->rows = total_rows;
1843  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1844  rterm->pathtarget->width);
1845 }

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

Referenced by create_recursiveunion_path().

◆ cost_rescan()

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

Definition at line 4528 of file costsize.c.

4531 {
4532  switch (path->pathtype)
4533  {
4534  case T_FunctionScan:
4535 
4536  /*
4537  * Currently, nodeFunctionscan.c always executes the function to
4538  * completion before returning any rows, and caches the results in
4539  * a tuplestore. So the function eval cost is all startup cost
4540  * and isn't paid over again on rescans. However, all run costs
4541  * will be paid over again.
4542  */
4543  *rescan_startup_cost = 0;
4544  *rescan_total_cost = path->total_cost - path->startup_cost;
4545  break;
4546  case T_HashJoin:
4547 
4548  /*
4549  * If it's a single-batch join, we don't need to rebuild the hash
4550  * table during a rescan.
4551  */
4552  if (((HashPath *) path)->num_batches == 1)
4553  {
4554  /* Startup cost is exactly the cost of hash table building */
4555  *rescan_startup_cost = 0;
4556  *rescan_total_cost = path->total_cost - path->startup_cost;
4557  }
4558  else
4559  {
4560  /* Otherwise, no special treatment */
4561  *rescan_startup_cost = path->startup_cost;
4562  *rescan_total_cost = path->total_cost;
4563  }
4564  break;
4565  case T_CteScan:
4566  case T_WorkTableScan:
4567  {
4568  /*
4569  * These plan types materialize their final result in a
4570  * tuplestore or tuplesort object. So the rescan cost is only
4571  * cpu_tuple_cost per tuple, unless the result is large enough
4572  * to spill to disk.
4573  */
4574  Cost run_cost = cpu_tuple_cost * path->rows;
4575  double nbytes = relation_byte_size(path->rows,
4576  path->pathtarget->width);
4577  long work_mem_bytes = work_mem * 1024L;
4578 
4579  if (nbytes > work_mem_bytes)
4580  {
4581  /* It will spill, so account for re-read cost */
4582  double npages = ceil(nbytes / BLCKSZ);
4583 
4584  run_cost += seq_page_cost * npages;
4585  }
4586  *rescan_startup_cost = 0;
4587  *rescan_total_cost = run_cost;
4588  }
4589  break;
4590  case T_Material:
4591  case T_Sort:
4592  {
4593  /*
4594  * These plan types not only materialize their results, but do
4595  * not implement qual filtering or projection. So they are
4596  * even cheaper to rescan than the ones above. We charge only
4597  * cpu_operator_cost per tuple. (Note: keep that in sync with
4598  * the run_cost charge in cost_sort, and also see comments in
4599  * cost_material before you change it.)
4600  */
4601  Cost run_cost = cpu_operator_cost * path->rows;
4602  double nbytes = relation_byte_size(path->rows,
4603  path->pathtarget->width);
4604  long work_mem_bytes = work_mem * 1024L;
4605 
4606  if (nbytes > work_mem_bytes)
4607  {
4608  /* It will spill, so account for re-read cost */
4609  double npages = ceil(nbytes / BLCKSZ);
4610 
4611  run_cost += seq_page_cost * npages;
4612  }
4613  *rescan_startup_cost = 0;
4614  *rescan_total_cost = run_cost;
4615  }
4616  break;
4617  case T_Memoize:
4618  /* All the hard work is done by cost_memoize_rescan */
4619  cost_memoize_rescan(root, (MemoizePath *) path,
4620  rescan_startup_cost, rescan_total_cost);
4621  break;
4622  default:
4623  *rescan_startup_cost = path->startup_cost;
4624  *rescan_total_cost = path->total_cost;
4625  break;
4626  }
4627 }
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:2509

References cost_memoize_rescan(), cpu_operator_cost, cpu_tuple_cost, Path::pathtype, relation_byte_size(), seq_page_cost, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by initial_cost_nestloop().

◆ cost_resultscan()

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

Definition at line 1776 of file costsize.c.

1778 {
1779  Cost startup_cost = 0;
1780  Cost run_cost = 0;
1781  QualCost qpqual_cost;
1782  Cost cpu_per_tuple;
1783 
1784  /* Should only be applied to RTE_RESULT base relations */
1785  Assert(baserel->relid > 0);
1786  Assert(baserel->rtekind == RTE_RESULT);
1787 
1788  /* Mark the path with the correct row estimate */
1789  if (param_info)
1790  path->rows = param_info->ppi_rows;
1791  else
1792  path->rows = baserel->rows;
1793 
1794  /* We charge qual cost plus cpu_tuple_cost */
1795  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1796 
1797  startup_cost += qpqual_cost.startup;
1798  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1799  run_cost += cpu_per_tuple * baserel->tuples;
1800 
1801  path->startup_cost = startup_cost;
1802  path->total_cost = startup_cost + run_cost;
1803 }
@ RTE_RESULT
Definition: parsenodes.h:1019

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

Referenced by create_resultscan_path().

◆ cost_samplescan()

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

Definition at line 361 of file costsize.c.

363 {
364  Cost startup_cost = 0;
365  Cost run_cost = 0;
366  RangeTblEntry *rte;
367  TableSampleClause *tsc;
368  TsmRoutine *tsm;
369  double spc_seq_page_cost,
370  spc_random_page_cost,
371  spc_page_cost;
372  QualCost qpqual_cost;
373  Cost cpu_per_tuple;
374 
375  /* Should only be applied to base relations with tablesample clauses */
376  Assert(baserel->relid > 0);
377  rte = planner_rt_fetch(baserel->relid, root);
378  Assert(rte->rtekind == RTE_RELATION);
379  tsc = rte->tablesample;
380  Assert(tsc != NULL);
381  tsm = GetTsmRoutine(tsc->tsmhandler);
382 
383  /* Mark the path with the correct row estimate */
384  if (param_info)
385  path->rows = param_info->ppi_rows;
386  else
387  path->rows = baserel->rows;
388 
389  /* fetch estimated page cost for tablespace containing table */
391  &spc_random_page_cost,
392  &spc_seq_page_cost);
393 
394  /* if NextSampleBlock is used, assume random access, else sequential */
395  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
396  spc_random_page_cost : spc_seq_page_cost;
397 
398  /*
399  * disk costs (recall that baserel->pages has already been set to the
400  * number of pages the sampling method will visit)
401  */
402  run_cost += spc_page_cost * baserel->pages;
403 
404  /*
405  * CPU costs (recall that baserel->tuples has already been set to the
406  * number of tuples the sampling method will select). Note that we ignore
407  * execution cost of the TABLESAMPLE parameter expressions; they will be
408  * evaluated only once per scan, and in most usages they'll likely be
409  * simple constants anyway. We also don't charge anything for the
410  * calculations the sampling method might do internally.
411  */
412  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
413 
414  startup_cost += qpqual_cost.startup;
415  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
416  run_cost += cpu_per_tuple * baserel->tuples;
417  /* tlist eval costs are paid per output row, not per tuple scanned */
418  startup_cost += path->pathtarget->cost.startup;
419  run_cost += path->pathtarget->cost.per_tuple * path->rows;
420 
421  path->startup_cost = startup_cost;
422  path->total_cost = startup_cost + run_cost;
423 }
struct TableSampleClause * tablesample
Definition: parsenodes.h:1081
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

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

Referenced by create_samplescan_path().

◆ cost_seqscan()

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

Definition at line 284 of file costsize.c.

286 {
287  Cost startup_cost = 0;
288  Cost cpu_run_cost;
289  Cost disk_run_cost;
290  double spc_seq_page_cost;
291  QualCost qpqual_cost;
292  Cost cpu_per_tuple;
293 
294  /* Should only be applied to base relations */
295  Assert(baserel->relid > 0);
296  Assert(baserel->rtekind == RTE_RELATION);
297 
298  /* Mark the path with the correct row estimate */
299  if (param_info)
300  path->rows = param_info->ppi_rows;
301  else
302  path->rows = baserel->rows;
303 
304  if (!enable_seqscan)
305  startup_cost += disable_cost;
306 
307  /* fetch estimated page cost for tablespace containing table */
309  NULL,
310  &spc_seq_page_cost);
311 
312  /*
313  * disk costs
314  */
315  disk_run_cost = spc_seq_page_cost * baserel->pages;
316 
317  /* CPU costs */
318  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
319 
320  startup_cost += qpqual_cost.startup;
321  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
322  cpu_run_cost = cpu_per_tuple * baserel->tuples;
323  /* tlist eval costs are paid per output row, not per tuple scanned */
324  startup_cost += path->pathtarget->cost.startup;
325  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
326 
327  /* Adjust costing for parallelism, if used. */
328  if (path->parallel_workers > 0)
329  {
330  double parallel_divisor = get_parallel_divisor(path);
331 
332  /* The CPU cost is divided among all the workers. */
333  cpu_run_cost /= parallel_divisor;
334 
335  /*
336  * It may be possible to amortize some of the I/O cost, but probably
337  * not very much, because most operating systems already do aggressive
338  * prefetching. For now, we assume that the disk run cost can't be
339  * amortized at all.
340  */
341 
342  /*
343  * In the case of a parallel plan, the row count needs to represent
344  * the number of tuples processed per worker.
345  */
346  path->rows = clamp_row_est(path->rows / parallel_divisor);
347  }
348 
349  path->startup_cost = startup_cost;
350  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
351 }
bool enable_seqscan
Definition: costsize.c:134

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

Referenced by create_seqscan_path().

◆ cost_sort()

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

Definition at line 2124 of file costsize.c.

2129 {
2130  Cost startup_cost;
2131  Cost run_cost;
2132 
2133  cost_tuplesort(&startup_cost, &run_cost,
2134  tuples, width,
2135  comparison_cost, sort_mem,
2136  limit_tuples);
2137 
2138  if (!enable_sort)
2139  startup_cost += disable_cost;
2140 
2141  startup_cost += input_cost;
2142 
2143  path->rows = tuples;
2144  path->startup_cost = startup_cost;
2145  path->total_cost = startup_cost + run_cost;
2146 }
bool enable_sort
Definition: costsize.c:139

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

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

◆ cost_subplan()

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

Definition at line 4435 of file costsize.c.

4436 {
4437  QualCost sp_cost;
4438 
4439  /* Figure any cost for evaluating the testexpr */
4440  cost_qual_eval(&sp_cost,
4441  make_ands_implicit((Expr *) subplan->testexpr),
4442  root);
4443 
4444  if (subplan->useHashTable)
4445  {
4446  /*
4447  * If we are using a hash table for the subquery outputs, then the
4448  * cost of evaluating the query is a one-time cost. We charge one
4449  * cpu_operator_cost per tuple for the work of loading the hashtable,
4450  * too.
4451  */
4452  sp_cost.startup += plan->total_cost +
4453  cpu_operator_cost * plan->plan_rows;
4454 
4455  /*
4456  * The per-tuple costs include the cost of evaluating the lefthand
4457  * expressions, plus the cost of probing the hashtable. We already
4458  * accounted for the lefthand expressions as part of the testexpr, and
4459  * will also have counted one cpu_operator_cost for each comparison
4460  * operator. That is probably too low for the probing cost, but it's
4461  * hard to make a better estimate, so live with it for now.
4462  */
4463  }
4464  else
4465  {
4466  /*
4467  * Otherwise we will be rescanning the subplan output on each
4468  * evaluation. We need to estimate how much of the output we will
4469  * actually need to scan. NOTE: this logic should agree with the
4470  * tuple_fraction estimates used by make_subplan() in
4471  * plan/subselect.c.
4472  */
4473  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4474 
4475  if (subplan->subLinkType == EXISTS_SUBLINK)
4476  {
4477  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4478  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4479  }
4480  else if (subplan->subLinkType == ALL_SUBLINK ||
4481  subplan->subLinkType == ANY_SUBLINK)
4482  {
4483  /* assume we need 50% of the tuples */
4484  sp_cost.per_tuple += 0.50 * plan_run_cost;
4485  /* also charge a cpu_operator_cost per row examined */
4486  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4487  }
4488  else
4489  {
4490  /* assume we need all tuples */
4491  sp_cost.per_tuple += plan_run_cost;
4492  }
4493 
4494  /*
4495  * Also account for subplan's startup cost. If the subplan is
4496  * uncorrelated or undirect correlated, AND its topmost node is one
4497  * that materializes its output, assume that we'll only need to pay
4498  * its startup cost once; otherwise assume we pay the startup cost
4499  * every time.
4500  */
4501  if (subplan->parParam == NIL &&
4503  sp_cost.startup += plan->startup_cost;
4504  else
4505  sp_cost.per_tuple += plan->startup_cost;
4506  }
4507 
4508  subplan->startup_cost = sp_cost.startup;
4509  subplan->per_call_cost = sp_cost.per_tuple;
4510 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:635
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:721
#define plan(x)
Definition: pg_regress.c:162
@ ANY_SUBLINK
Definition: primnodes.h:955
@ ALL_SUBLINK
Definition: primnodes.h:954
@ EXISTS_SUBLINK
Definition: primnodes.h:953
bool useHashTable
Definition: primnodes.h:1035
Node * testexpr
Definition: primnodes.h:1023
List * parParam
Definition: primnodes.h:1046
SubLinkType subLinkType
Definition: primnodes.h:1021

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

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

◆ cost_subqueryscan()

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

Definition at line 1451 of file costsize.c.

1454 {
1455  Cost startup_cost;
1456  Cost run_cost;
1457  List *qpquals;
1458  QualCost qpqual_cost;
1459  Cost cpu_per_tuple;
1460 
1461  /* Should only be applied to base relations that are subqueries */
1462  Assert(baserel->relid > 0);
1463  Assert(baserel->rtekind == RTE_SUBQUERY);
1464 
1465  /*
1466  * We compute the rowcount estimate as the subplan's estimate times the
1467  * selectivity of relevant restriction clauses. In simple cases this will
1468  * come out the same as baserel->rows; but when dealing with parallelized
1469  * paths we must do it like this to get the right answer.
1470  */
1471  if (param_info)
1472  qpquals = list_concat_copy(param_info->ppi_clauses,
1473  baserel->baserestrictinfo);
1474  else
1475  qpquals = baserel->baserestrictinfo;
1476 
1477  path->path.rows = clamp_row_est(path->subpath->rows *
1479  qpquals,
1480  0,
1481  JOIN_INNER,
1482  NULL));
1483 
1484  /*
1485  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1486  * any restriction clauses and tlist that will be attached to the
1487  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1488  * projection overhead.
1489  */
1490  path->path.startup_cost = path->subpath->startup_cost;
1491  path->path.total_cost = path->subpath->total_cost;
1492 
1493  /*
1494  * However, if there are no relevant restriction clauses and the
1495  * pathtarget is trivial, then we expect that setrefs.c will optimize away
1496  * the SubqueryScan plan node altogether, so we should just make its cost
1497  * and rowcount equal to the input path's.
1498  *
1499  * Note: there are some edge cases where createplan.c will apply a
1500  * different targetlist to the SubqueryScan node, thus falsifying our
1501  * current estimate of whether the target is trivial, and making the cost
1502  * estimate (though not the rowcount) wrong. It does not seem worth the
1503  * extra complication to try to account for that exactly, especially since
1504  * that behavior falsifies other cost estimates as well.
1505  */
1506  if (qpquals == NIL && trivial_pathtarget)
1507  return;
1508 
1509  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1510 
1511  startup_cost = qpqual_cost.startup;
1512  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1513  run_cost = cpu_per_tuple * path->subpath->rows;
1514 
1515  /* tlist eval costs are paid per output row, not per tuple scanned */
1516  startup_cost += path->path.pathtarget->cost.startup;
1517  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1518 
1519  path->path.startup_cost += startup_cost;
1520  path->path.total_cost += startup_cost + run_cost;
1521 }
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
@ RTE_SUBQUERY
Definition: parsenodes.h:1012
List * ppi_clauses
Definition: pathnodes.h:1561
List * baserestrictinfo
Definition: pathnodes.h:966

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

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

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

Definition at line 1592 of file costsize.c.

1594 {
1595  Cost startup_cost = 0;
1596  Cost run_cost = 0;
1597  QualCost qpqual_cost;
1598  Cost cpu_per_tuple;
1599  RangeTblEntry *rte;
1600  QualCost exprcost;
1601 
1602  /* Should only be applied to base relations that are functions */
1603  Assert(baserel->relid > 0);
1604  rte = planner_rt_fetch(baserel->relid, root);
1605  Assert(rte->rtekind == RTE_TABLEFUNC);
1606 
1607  /* Mark the path with the correct row estimate */
1608  if (param_info)
1609  path->rows = param_info->ppi_rows;
1610  else
1611  path->rows = baserel->rows;
1612 
1613  /*
1614  * Estimate costs of executing the table func expression(s).
1615  *
1616  * XXX in principle we ought to charge tuplestore spill costs if the
1617  * number of rows is large. However, given how phony our rowcount
1618  * estimates for tablefuncs tend to be, there's not a lot of point in that
1619  * refinement right now.
1620  */
1621  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1622 
1623  startup_cost += exprcost.startup + exprcost.per_tuple;
1624 
1625  /* Add scanning CPU costs */
1626  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1627 
1628  startup_cost += qpqual_cost.startup;
1629  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1630  run_cost += cpu_per_tuple * baserel->tuples;
1631 
1632  /* tlist eval costs are paid per output row, not per tuple scanned */
1633  startup_cost += path->pathtarget->cost.startup;
1634  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1635 
1636  path->startup_cost = startup_cost;
1637  path->total_cost = startup_cost + run_cost;
1638 }
@ RTE_TABLEFUNC
Definition: parsenodes.h:1015
TableFunc * tablefunc
Definition: parsenodes.h:1159

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

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1357 of file costsize.c.

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

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

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1249 of file costsize.c.

1251 {
1252  Cost startup_cost = 0;
1253  Cost run_cost = 0;
1254  bool isCurrentOf = false;
1255  QualCost qpqual_cost;
1256  Cost cpu_per_tuple;
1257  QualCost tid_qual_cost;
1258  double ntuples;
1259  ListCell *l;
1260  double spc_random_page_cost;
1261 
1262  /* Should only be applied to base relations */
1263  Assert(baserel->relid > 0);
1264  Assert(baserel->rtekind == RTE_RELATION);
1265 
1266  /* Mark the path with the correct row estimate */
1267  if (param_info)
1268  path->rows = param_info->ppi_rows;
1269  else
1270  path->rows = baserel->rows;
1271 
1272  /* Count how many tuples we expect to retrieve */
1273  ntuples = 0;
1274  foreach(l, tidquals)
1275  {
1276  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1277  Expr *qual = rinfo->clause;
1278 
1279  if (IsA(qual, ScalarArrayOpExpr))
1280  {
1281  /* Each element of the array yields 1 tuple */
1282  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1283  Node *arraynode = (Node *) lsecond(saop->args);
1284 
1285  ntuples += estimate_array_length(root, arraynode);
1286  }
1287  else if (IsA(qual, CurrentOfExpr))
1288  {
1289  /* CURRENT OF yields 1 tuple */
1290  isCurrentOf = true;
1291  ntuples++;
1292  }
1293  else
1294  {
1295  /* It's just CTID = something, count 1 tuple */
1296  ntuples++;
1297  }
1298  }
1299 
1300  /*
1301  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1302  * understands how to do it correctly. Therefore, honor enable_tidscan
1303  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1304  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1305  * subtract off here; that's to prevent other plan types such as seqscan
1306  * from winning.
1307  */
1308  if (isCurrentOf)
1309  {
1311  startup_cost -= disable_cost;
1312  }
1313  else if (!enable_tidscan)
1314  startup_cost += disable_cost;
1315 
1316  /*
1317  * The TID qual expressions will be computed once, any other baserestrict
1318  * quals once per retrieved tuple.
1319  */
1320  cost_qual_eval(&tid_qual_cost, tidquals, root);
1321 
1322  /* fetch estimated page cost for tablespace containing table */
1324  &spc_random_page_cost,
1325  NULL);
1326 
1327  /* disk costs --- assume each tuple on a different page */
1328  run_cost += spc_random_page_cost * ntuples;
1329 
1330  /* Add scanning CPU costs */
1331  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1332 
1333  /* XXX currently we assume TID quals are a subset of qpquals */
1334  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1335  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1336  tid_qual_cost.per_tuple;
1337  run_cost += cpu_per_tuple * ntuples;
1338 
1339  /* tlist eval costs are paid per output row, not per tuple scanned */
1340  startup_cost += path->pathtarget->cost.startup;
1341  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1342 
1343  path->startup_cost = startup_cost;
1344  path->total_cost = startup_cost + run_cost;
1345 }
QualCost baserestrictcost
Definition: pathnodes.h:968

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

Referenced by create_tidscan_path().

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

1888 {
1889  double input_bytes = relation_byte_size(tuples, width);
1890  double output_bytes;
1891  double output_tuples;
1892  long sort_mem_bytes = sort_mem * 1024L;
1893 
1894  /*
1895  * We want to be sure the cost of a sort is never estimated as zero, even
1896  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1897  */
1898  if (tuples < 2.0)
1899  tuples = 2.0;
1900 
1901  /* Include the default cost-per-comparison */
1902  comparison_cost += 2.0 * cpu_operator_cost;
1903 
1904  /* Do we have a useful LIMIT? */
1905  if (limit_tuples > 0 && limit_tuples < tuples)
1906  {
1907  output_tuples = limit_tuples;
1908  output_bytes = relation_byte_size(output_tuples, width);
1909  }
1910  else
1911  {
1912  output_tuples = tuples;
1913  output_bytes = input_bytes;
1914  }
1915 
1916  if (output_bytes > sort_mem_bytes)
1917  {
1918  /*
1919  * We'll have to use a disk-based sort of all the tuples
1920  */
1921  double npages = ceil(input_bytes / BLCKSZ);
1922  double nruns = input_bytes / sort_mem_bytes;
1923  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1924  double log_runs;
1925  double npageaccesses;
1926 
1927  /*
1928  * CPU costs
1929  *
1930  * Assume about N log2 N comparisons
1931  */
1932  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1933 
1934  /* Disk costs */
1935 
1936  /* Compute logM(r) as log(r) / log(M) */
1937  if (nruns > mergeorder)
1938  log_runs = ceil(log(nruns) / log(mergeorder));
1939  else
1940  log_runs = 1.0;
1941  npageaccesses = 2.0 * npages * log_runs;
1942  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1943  *startup_cost += npageaccesses *
1944  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1945  }
1946  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1947  {
1948  /*
1949  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1950  * a total number of tuple comparisons of N log2 K; but the constant
1951  * factor is a bit higher than for quicksort. Tweak it so that the
1952  * cost curve is continuous at the crossover point.
1953  */
1954  *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
1955  }
1956  else
1957  {
1958  /* We'll use plain quicksort on all the input tuples */
1959  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1960  }
1961 
1962  /*
1963  * Also charge a small amount (arbitrarily set equal to operator cost) per
1964  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1965  * doesn't do qual-checking or projection, so it has less overhead than
1966  * most plan nodes. Note it's correct to use tuples not output_tuples
1967  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1968  * counting the LIMIT otherwise.
1969  */
1970  *run_cost = cpu_operator_cost * tuples;
1971 }
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:1798

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

◆ cost_valuesscan()

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

Definition at line 1648 of file costsize.c.

1650 {
1651  Cost startup_cost = 0;
1652  Cost run_cost = 0;
1653  QualCost qpqual_cost;
1654  Cost cpu_per_tuple;
1655 
1656  /* Should only be applied to base relations that are values lists */
1657  Assert(baserel->relid > 0);
1658  Assert(baserel->rtekind == RTE_VALUES);
1659 
1660  /* Mark the path with the correct row estimate */
1661  if (param_info)
1662  path->rows = param_info->ppi_rows;
1663  else
1664  path->rows = baserel->rows;
1665 
1666  /*
1667  * For now, estimate list evaluation cost at one operator eval per list
1668  * (probably pretty bogus, but is it worth being smarter?)
1669  */
1670  cpu_per_tuple = cpu_operator_cost;
1671 
1672  /* Add scanning CPU costs */
1673  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1674 
1675  startup_cost += qpqual_cost.startup;
1676  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1677  run_cost += cpu_per_tuple * baserel->tuples;
1678 
1679  /* tlist eval costs are paid per output row, not per tuple scanned */
1680  startup_cost += path->pathtarget->cost.startup;
1681  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1682 
1683  path->startup_cost = startup_cost;
1684  path->total_cost = startup_cost + run_cost;
1685 }
@ RTE_VALUES
Definition: parsenodes.h:1016

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

Referenced by create_valuesscan_path().

◆ cost_windowagg()

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

Definition at line 3068 of file costsize.c.

3072 {
3073  Cost startup_cost;
3074  Cost total_cost;
3075  double startup_tuples;
3076  int numPartCols;
3077  int numOrderCols;
3078  ListCell *lc;
3079 
3080  numPartCols = list_length(winclause->partitionClause);
3081  numOrderCols = list_length(winclause->orderClause);
3082 
3083  startup_cost = input_startup_cost;
3084  total_cost = input_total_cost;
3085 
3086  /*
3087  * Window functions are assumed to cost their stated execution cost, plus
3088  * the cost of evaluating their input expressions, per tuple. Since they
3089  * may in fact evaluate their inputs at multiple rows during each cycle,
3090  * this could be a drastic underestimate; but without a way to know how
3091  * many rows the window function will fetch, it's hard to do better. In
3092  * any case, it's a good estimate for all the built-in window functions,
3093  * so we'll just do this for now.
3094  */
3095  foreach(lc, windowFuncs)
3096  {
3097  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3098  Cost wfunccost;
3099  QualCost argcosts;
3100 
3101  argcosts.startup = argcosts.per_tuple = 0;
3102  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3103  &argcosts);
3104  startup_cost += argcosts.startup;
3105  wfunccost = argcosts.per_tuple;
3106 
3107  /* also add the input expressions' cost to per-input-row costs */
3108  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3109  startup_cost += argcosts.startup;
3110  wfunccost += argcosts.per_tuple;
3111 
3112  /*
3113  * Add the filter's cost to per-input-row costs. XXX We should reduce
3114  * input expression costs according to filter selectivity.
3115  */
3116  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3117  startup_cost += argcosts.startup;
3118  wfunccost += argcosts.per_tuple;
3119 
3120  total_cost += wfunccost * input_tuples;
3121  }
3122 
3123  /*
3124  * We also charge cpu_operator_cost per grouping column per tuple for
3125  * grouping comparisons, plus cpu_tuple_cost per tuple for general
3126  * overhead.
3127  *
3128  * XXX this neglects costs of spooling the data to disk when it overflows
3129  * work_mem. Sooner or later that should get accounted for.
3130  */
3131  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3132  total_cost += cpu_tuple_cost * input_tuples;
3133 
3134  path->rows = input_tuples;
3135  path->startup_cost = startup_cost;
3136  path->total_cost = total_cost;
3137 
3138  /*
3139  * Also, take into account how many tuples we need to read from the
3140  * subnode in order to produce the first tuple from the WindowAgg. To do
3141  * this we proportion the run cost (total cost not including startup cost)
3142  * over the estimated startup tuples. We already included the startup
3143  * cost of the subnode, so we only need to do this when the estimated
3144  * startup tuples is above 1.0.
3145  */
3146  startup_tuples = get_windowclause_startup_tuples(root, winclause,
3147  input_tuples);
3148 
3149  if (startup_tuples > 1.0)
3150  path->startup_cost += (total_cost - startup_cost) / input_tuples *
3151  (startup_tuples - 1.0);
3152 }
static double get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc, double input_tuples)
Definition: costsize.c:2854
List * partitionClause
Definition: parsenodes.h:1501
List * orderClause
Definition: parsenodes.h:1503
List * args
Definition: primnodes.h:561
Expr * aggfilter
Definition: primnodes.h:563
Oid winfnoid
Definition: primnodes.h:553

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

Referenced by create_windowagg_path().

◆ extract_nonindex_conditions()

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

Definition at line 840 of file costsize.c.

841 {
842  List *result = NIL;
843  ListCell *lc;
844 
845  foreach(lc, qual_clauses)
846  {
847  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
848 
849  if (rinfo->pseudoconstant)
850  continue; /* we may drop pseudoconstants here */
851  if (is_redundant_with_indexclauses(rinfo, indexclauses))
852  continue; /* dup or derived from same EquivalenceClass */
853  /* ... skip the predicate proof attempt createplan.c will try ... */
854  result = lappend(result, rinfo);
855  }
856  return result;
857 }
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:3232

References is_redundant_with_indexclauses(), lappend(), lfirst_node, and NIL.

Referenced by cost_index().

◆ final_cost_hashjoin()

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

Definition at line 4181 of file costsize.c.

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

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3745 of file costsize.c.

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

References approx_tuple_count(), clamp_row_est(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), if(), JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, list_length(), MergePath::materialize_inner, NIL, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, JoinPath::outerjoinpath, MergePath::path_mergeclauses, QualCost::per_tuple, relation_byte_size(), Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, JoinCostWorkspace::startup_cost, and work_mem.

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3308 of file costsize.c.

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

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

Referenced by create_nestloop_path().

◆ get_expr_width()

static int32 get_expr_width ( PlannerInfo root,
const Node expr 
)
static

Definition at line 6324 of file costsize.c.

6325 {
6326  int32 width;
6327 
6328  if (IsA(expr, Var))
6329  {
6330  const Var *var = (const Var *) expr;
6331 
6332  /* We should not see any upper-level Vars here */
6333  Assert(var->varlevelsup == 0);
6334 
6335  /* Try to get data from RelOptInfo cache */
6336  if (!IS_SPECIAL_VARNO(var->varno) &&
6337  var->varno < root->simple_rel_array_size)
6338  {
6339  RelOptInfo *rel = root->simple_rel_array[var->varno];
6340 
6341  if (rel != NULL &&
6342  var->varattno >= rel->min_attr &&
6343  var->varattno <= rel->max_attr)
6344  {
6345  int ndx = var->varattno - rel->min_attr;
6346 
6347  if (rel->attr_widths[ndx] > 0)
6348  return rel->attr_widths[ndx];
6349  }
6350  }
6351 
6352  /*
6353  * No cached data available, so estimate using just the type info.
6354  */
6355  width = get_typavgwidth(var->vartype, var->vartypmod);
6356  Assert(width > 0);
6357 
6358  return width;
6359  }
6360 
6361  width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6362  Assert(width > 0);
6363  return width;
6364 }
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2534
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:284
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:227
int simple_rel_array_size
Definition: pathnodes.h:229
AttrNumber max_attr
Definition: pathnodes.h:911
AttrNumber min_attr
Definition: pathnodes.h:909
Definition: primnodes.h:234
AttrNumber varattno
Definition: primnodes.h:246
int varno
Definition: primnodes.h:241
Index varlevelsup
Definition: primnodes.h:266

References Assert(), exprType(), exprTypmod(), get_typavgwidth(), IS_SPECIAL_VARNO, IsA, RelOptInfo::max_attr, RelOptInfo::min_attr, PlannerInfo::simple_rel_array_size, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by cost_memoize_rescan(), and set_pathtarget_cost_width().

◆ get_foreign_key_join_selectivity()

static Selectivity get_foreign_key_join_selectivity ( PlannerInfo root,
Relids  outer_relids,
Relids  inner_relids,
SpecialJoinInfo sjinfo,
List **  restrictlist 
)
static

Definition at line 5571 of file costsize.c.

5576 {
5577  Selectivity fkselec = 1.0;
5578  JoinType jointype = sjinfo->jointype;
5579  List *worklist = *restrictlist;
5580  ListCell *lc;
5581 
5582  /* Consider each FK constraint that is known to match the query */
5583  foreach(lc, root->fkey_list)
5584  {
5585  ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
5586  bool ref_is_outer;
5587  List *removedlist;
5588  ListCell *cell;
5589 
5590  /*
5591  * This FK is not relevant unless it connects a baserel on one side of
5592  * this join to a baserel on the other side.
5593  */
5594  if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5595  bms_is_member(fkinfo->ref_relid, inner_relids))
5596  ref_is_outer = false;
5597  else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5598  bms_is_member(fkinfo->con_relid, inner_relids))
5599  ref_is_outer = true;
5600  else
5601  continue;
5602 
5603  /*
5604  * If we're dealing with a semi/anti join, and the FK's referenced
5605  * relation is on the outside, then knowledge of the FK doesn't help
5606  * us figure out what we need to know (which is the fraction of outer
5607  * rows that have matches). On the other hand, if the referenced rel
5608  * is on the inside, then all outer rows must have matches in the
5609  * referenced table (ignoring nulls). But any restriction or join
5610  * clauses that filter that table will reduce the fraction of matches.
5611  * We can account for restriction clauses, but it's too hard to guess
5612  * how many table rows would get through a join that's inside the RHS.
5613  * Hence, if either case applies, punt and ignore the FK.
5614  */
5615  if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5616  (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
5617  continue;
5618 
5619  /*
5620  * Modify the restrictlist by removing clauses that match the FK (and
5621  * putting them into removedlist instead). It seems unsafe to modify
5622  * the originally-passed List structure, so we make a shallow copy the
5623  * first time through.
5624  */
5625  if (worklist == *restrictlist)
5626  worklist = list_copy(worklist);
5627 
5628  removedlist = NIL;
5629  foreach(cell, worklist)
5630  {
5631  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5632  bool remove_it = false;
5633  int i;
5634 
5635  /* Drop this clause if it matches any column of the FK */
5636  for (i = 0; i < fkinfo->nkeys; i++)
5637  {
5638  if (rinfo->parent_ec)
5639  {
5640  /*
5641  * EC-derived clauses can only match by EC. It is okay to
5642  * consider any clause derived from the same EC as
5643  * matching the FK: even if equivclass.c chose to generate
5644  * a clause equating some other pair of Vars, it could
5645  * have generated one equating the FK's Vars. So for
5646  * purposes of estimation, we can act as though it did so.
5647  *
5648  * Note: checking parent_ec is a bit of a cheat because
5649  * there are EC-derived clauses that don't have parent_ec
5650  * set; but such clauses must compare expressions that
5651  * aren't just Vars, so they cannot match the FK anyway.
5652  */
5653  if (fkinfo->eclass[i] == rinfo->parent_ec)
5654  {
5655  remove_it = true;
5656  break;
5657  }
5658  }
5659  else
5660  {
5661  /*
5662  * Otherwise, see if rinfo was previously matched to FK as
5663  * a "loose" clause.
5664  */
5665  if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5666  {
5667  remove_it = true;
5668  break;
5669  }
5670  }
5671  }
5672  if (remove_it)
5673  {
5674  worklist = foreach_delete_current(worklist, cell);
5675  removedlist = lappend(removedlist, rinfo);
5676  }
5677  }
5678 
5679  /*
5680  * If we failed to remove all the matching clauses we expected to
5681  * find, chicken out and ignore this FK; applying its selectivity
5682  * might result in double-counting. Put any clauses we did manage to
5683  * remove back into the worklist.
5684  *
5685  * Since the matching clauses are known not outerjoin-delayed, they
5686  * would normally have appeared in the initial joinclause list. If we
5687  * didn't find them, there are two possibilities:
5688  *
5689  * 1. If the FK match is based on an EC that is ec_has_const, it won't
5690  * have generated any join clauses at all. We discount such ECs while
5691  * checking to see if we have "all" the clauses. (Below, we'll adjust
5692  * the selectivity estimate for this case.)
5693  *
5694  * 2. The clauses were matched to some other FK in a previous
5695  * iteration of this loop, and thus removed from worklist. (A likely
5696  * case is that two FKs are matched to the same EC; there will be only
5697  * one EC-derived clause in the initial list, so the first FK will
5698  * consume it.) Applying both FKs' selectivity independently risks
5699  * underestimating the join size; in particular, this would undo one
5700  * of the main things that ECs were invented for, namely to avoid
5701  * double-counting the selectivity of redundant equality conditions.
5702  * Later we might think of a reasonable way to combine the estimates,
5703  * but for now, just punt, since this is a fairly uncommon situation.
5704  */
5705  if (removedlist == NIL ||
5706  list_length(removedlist) !=
5707  (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5708  {
5709  worklist = list_concat(worklist, removedlist);
5710  continue;
5711  }
5712 
5713  /*
5714  * Finally we get to the payoff: estimate selectivity using the
5715  * knowledge that each referencing row will match exactly one row in
5716  * the referenced table.
5717  *
5718  * XXX that's not true in the presence of nulls in the referencing
5719  * column(s), so in principle we should derate the estimate for those.
5720  * However (1) if there are any strict restriction clauses for the
5721  * referencing column(s) elsewhere in the query, derating here would
5722  * be double-counting the null fraction, and (2) it's not very clear
5723  * how to combine null fractions for multiple referencing columns. So
5724  * we do nothing for now about correcting for nulls.
5725  *
5726  * XXX another point here is that if either side of an FK constraint
5727  * is an inheritance parent, we estimate as though the constraint
5728  * covers all its children as well. This is not an unreasonable
5729  * assumption for a referencing table, ie the user probably applied
5730  * identical constraints to all child tables (though perhaps we ought
5731  * to check that). But it's not possible to have done that for a
5732  * referenced table. Fortunately, precisely because that doesn't
5733  * work, it is uncommon in practice to have an FK referencing a parent
5734  * table. So, at least for now, disregard inheritance here.
5735  */
5736  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5737  {
5738  /*
5739  * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5740  * referenced table is exactly the inside of the join. The join
5741  * selectivity is defined as the fraction of LHS rows that have
5742  * matches. The FK implies that every LHS row has a match *in the
5743  * referenced table*; but any restriction clauses on it will
5744  * reduce the number of matches. Hence we take the join
5745  * selectivity as equal to the selectivity of the table's
5746  * restriction clauses, which is rows / tuples; but we must guard
5747  * against tuples == 0.
5748  */
5749  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5750  double ref_tuples = Max(ref_rel->tuples, 1.0);
5751 
5752  fkselec *= ref_rel->rows / ref_tuples;
5753  }
5754  else
5755  {
5756  /*
5757  * Otherwise, selectivity is exactly 1/referenced-table-size; but
5758  * guard against tuples == 0. Note we should use the raw table
5759  * tuple count, not any estimate of its filtered or joined size.
5760  */
5761  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5762  double ref_tuples = Max(ref_rel->tuples, 1.0);
5763 
5764  fkselec *= 1.0 / ref_tuples;
5765  }
5766 
5767  /*
5768  * If any of the FK columns participated in ec_has_const ECs, then
5769  * equivclass.c will have generated "var = const" restrictions for
5770  * each side of the join, thus reducing the sizes of both input
5771  * relations. Taking the fkselec at face value would amount to
5772  * double-counting the selectivity of the constant restriction for the
5773  * referencing Var. Hence, look for the restriction clause(s) that
5774  * were applied to the referencing Var(s), and divide out their
5775  * selectivity to correct for this.
5776  */
5777  if (fkinfo->nconst_ec > 0)
5778  {
5779  for (int i = 0; i < fkinfo->nkeys; i++)
5780  {
5781  EquivalenceClass *ec = fkinfo->eclass[i];
5782 
5783  if (ec && ec->ec_has_const)
5784  {
5785  EquivalenceMember *em = fkinfo->fk_eclass_member[i];
5787  em);
5788 
5789  if (rinfo)
5790  {
5791  Selectivity s0;
5792 
5793  s0 = clause_selectivity(root,
5794  (Node *) rinfo,
5795  0,
5796  jointype,
5797  sjinfo);
5798  if (s0 > 0)
5799  fkselec /= s0;
5800  }
5801  }
5802  }
5803  }
5804  }
5805 
5806  *restrictlist = worklist;
5807  CLAMP_PROBABILITY(fkselec);
5808  return fkselec;
5809 }
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
@ BMS_SINGLETON
Definition: bitmapset.h:72
RestrictInfo * find_derived_clause_for_ec_member(EquivalenceClass *ec, EquivalenceMember *em)
Definition: equivclass.c:2592
List * list_copy(const List *oldlist)
Definition: list.c:1573
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:682
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:407
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1237
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:1241
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1239
List * fkey_list
Definition: pathnodes.h:379

References bms_is_member(), bms_membership(), BMS_SINGLETON, CLAMP_PROBABILITY, clause_selectivity(), ForeignKeyOptInfo::con_relid, EquivalenceClass::ec_has_const, ForeignKeyOptInfo::eclass, find_base_rel(), find_derived_clause_for_ec_member(), ForeignKeyOptInfo::fk_eclass_member, PlannerInfo::fkey_list, foreach_delete_current, i, JOIN_ANTI, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, list_concat(), list_copy(), list_length(), list_member_ptr(), Max, ForeignKeyOptInfo::nconst_ec, NIL, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_ri, ForeignKeyOptInfo::ref_relid, ForeignKeyOptInfo::rinfos, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by calc_joinrel_size_estimate().

◆ get_indexpath_pages()

static double get_indexpath_pages ( Path bitmapqual)
static

Definition at line 963 of file costsize.c.

964 {
965  double result = 0;
966  ListCell *l;
967 
968  if (IsA(bitmapqual, BitmapAndPath))
969  {
970  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
971 
972  foreach(l, apath->bitmapquals)
973  {
974  result += get_indexpath_pages((Path *) lfirst(l));
975  }
976  }
977  else if (IsA(bitmapqual, BitmapOrPath))
978  {
979  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
980 
981  foreach(l, opath->bitmapquals)
982  {
983  result += get_indexpath_pages((Path *) lfirst(l));
984  }
985  }
986  else if (IsA(bitmapqual, IndexPath))
987  {
988  IndexPath *ipath = (IndexPath *) bitmapqual;
989 
990  result = (double) ipath->indexinfo->pages;
991  }
992  else
993  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
994 
995  return result;
996 }
BlockNumber pages
Definition: pathnodes.h:1108

References BitmapAndPath::bitmapquals, BitmapOrPath::bitmapquals, elog, ERROR, IndexPath::indexinfo, IsA, lfirst, nodeTag, and IndexOptInfo::pages.

Referenced by compute_bitmap_pages().

◆ get_parallel_divisor()

static double get_parallel_divisor ( Path path)
static

Definition at line 6393 of file costsize.c.

6394 {
6395  double parallel_divisor = path->parallel_workers;
6396 
6397  /*
6398  * Early experience with parallel query suggests that when there is only
6399  * one worker, the leader often makes a very substantial contribution to
6400  * executing the parallel portion of the plan, but as more workers are
6401  * added, it does less and less, because it's busy reading tuples from the
6402  * workers and doing whatever non-parallel post-processing is needed. By
6403  * the time we reach 4 workers, the leader no longer makes a meaningful
6404  * contribution. Thus, for now, estimate that the leader spends 30% of
6405  * its time servicing each worker, and the remainder executing the
6406  * parallel plan.
6407  */
6409  {
6410  double leader_contribution;
6411 
6412  leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6413  if (leader_contribution > 0)
6414  parallel_divisor += leader_contribution;
6415  }
6416 
6417  return parallel_divisor;
6418 }
bool parallel_leader_participation
Definition: planner.c:67

References parallel_leader_participation, and Path::parallel_workers.

Referenced by cost_append(), cost_bitmap_heap_scan(), cost_index(), cost_seqscan(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), and initial_cost_hashjoin().

◆ get_parameterized_baserel_size()

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

Definition at line 5299 of file costsize.c.

5301 {
5302  List *allclauses;
5303  double nrows;
5304 
5305  /*
5306  * Estimate the number of rows returned by the parameterized scan, knowing
5307  * that it will apply all the extra join clauses as well as the rel's own
5308  * restriction clauses. Note that we force the clauses to be treated as
5309  * non-join clauses during selectivity estimation.
5310  */
5311  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5312  nrows = rel->tuples *
5314  allclauses,
5315  rel->relid, /* do not use 0! */
5316  JOIN_INNER,
5317  NULL);
5318  nrows = clamp_row_est(nrows);
5319  /* For safety, make sure result is not more than the base estimate */
5320  if (nrows > rel->rows)
5321  nrows = rel->rows;
5322  return nrows;
5323 }

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), JOIN_INNER, list_concat_copy(), RelOptInfo::relid, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by get_baserel_parampathinfo().

◆ get_parameterized_joinrel_size()

double get_parameterized_joinrel_size ( PlannerInfo root,
RelOptInfo rel,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
List restrict_clauses 
)

Definition at line 5380 of file costsize.c.

5385 {
5386  double nrows;
5387 
5388  /*
5389  * Estimate the number of rows returned by the parameterized join as the
5390  * sizes of the input paths times the selectivity of the clauses that have
5391  * ended up at this join node.
5392  *
5393  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5394  * on the pair of input paths provided, though ideally we'd get the same
5395  * estimate for any pair with the same parameterization.
5396  */
5397  nrows = calc_joinrel_size_estimate(root,
5398  rel,
5399  outer_path->parent,
5400  inner_path->parent,
5401  outer_path->rows,
5402  inner_path->rows,
5403  sjinfo,
5404  restrict_clauses);
5405  /* For safety, make sure result is not more than the base estimate */
5406  if (nrows > rel->rows)
5407  nrows = rel->rows;
5408  return nrows;
5409 }
static double calc_joinrel_size_estimate(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
Definition: costsize.c:5421

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

Referenced by get_joinrel_parampathinfo().

◆ get_restriction_qual_cost()

static void get_restriction_qual_cost ( PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
QualCost qpqual_cost 
)
static

Definition at line 4961 of file costsize.c.

4964 {
4965  if (param_info)
4966  {
4967  /* Include costs of pushed-down clauses */
4968  cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
4969 
4970  qpqual_cost->startup += baserel->baserestrictcost.startup;
4971  qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
4972  }
4973  else
4974  *qpqual_cost = baserel->baserestrictcost;
4975 }

References RelOptInfo::baserestrictcost, cost_qual_eval(), QualCost::per_tuple, ParamPathInfo::ppi_clauses, and QualCost::startup.

Referenced by cost_bitmap_heap_scan(), cost_ctescan(), cost_functionscan(), cost_namedtuplestorescan(), cost_resultscan(), cost_samplescan(), cost_seqscan(), cost_subqueryscan(), cost_tablefuncscan(), cost_tidrangescan(), cost_tidscan(), and cost_valuesscan().

◆ get_windowclause_startup_tuples()

static double get_windowclause_startup_tuples ( PlannerInfo root,
WindowClause wc,
double  input_tuples 
)
static

Definition at line 2854 of file costsize.c.

2856 {
2857  int frameOptions = wc->frameOptions;
2858  double partition_tuples;
2859  double return_tuples;
2860  double peer_tuples;
2861 
2862  /*
2863  * First, figure out how many partitions there are likely to be and set
2864  * partition_tuples according to that estimate.
2865  */
2866  if (wc->partitionClause != NIL)
2867  {
2868  double num_partitions;
2869  List *partexprs = get_sortgrouplist_exprs(wc->partitionClause,
2870  root->parse->targetList);
2871 
2872  num_partitions = estimate_num_groups(root, partexprs, input_tuples,
2873  NULL, NULL);
2874  list_free(partexprs);
2875 
2876  partition_tuples = input_tuples / num_partitions;
2877  }
2878  else
2879  {
2880  /* all tuples belong to the same partition */
2881  partition_tuples = input_tuples;
2882  }
2883 
2884  /* estimate the number of tuples in each peer group */
2885  if (wc->orderClause != NIL)
2886  {
2887  double num_groups;
2888  List *orderexprs;
2889 
2890  orderexprs = get_sortgrouplist_exprs(wc->orderClause,
2891  root->parse->targetList);
2892 
2893  /* estimate out how many peer groups there are in the partition */
2894  num_groups = estimate_num_groups(root, orderexprs,
2895  partition_tuples, NULL,
2896  NULL);
2897  list_free(orderexprs);
2898  peer_tuples = partition_tuples / num_groups;
2899  }
2900  else
2901  {
2902  /* no ORDER BY so only 1 tuple belongs in each peer group */
2903  peer_tuples = 1.0;
2904  }
2905 
2906  if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
2907  {
2908  /* include all partition rows */
2909  return_tuples = partition_tuples;
2910  }
2911  else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
2912  {
2913  if (frameOptions & FRAMEOPTION_ROWS)
2914  {
2915  /* just count the current row */
2916  return_tuples = 1.0;
2917  }
2918  else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
2919  {
2920  /*
2921  * When in RANGE/GROUPS mode, it's more complex. If there's no
2922  * ORDER BY, then all rows in the partition are peers, otherwise
2923  * we'll need to read the first group of peers.
2924  */
2925  if (wc->orderClause == NIL)
2926  return_tuples = partition_tuples;
2927  else
2928  return_tuples = peer_tuples;
2929  }
2930  else
2931  {
2932  /*
2933  * Something new we don't support yet? This needs attention.
2934  * We'll just return 1.0 in the meantime.
2935  */
2936  Assert(false);
2937  return_tuples = 1.0;
2938  }
2939  }
2940  else if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
2941  {
2942  /*
2943  * BETWEEN ... AND N PRECEDING will only need to read the WindowAgg's
2944  * subnode after N ROWS/RANGES/GROUPS. N can be 0, but not negative,
2945  * so we'll just assume only the current row needs to be read to fetch
2946  * the first WindowAgg row.
2947  */
2948  return_tuples = 1.0;
2949  }
2950  else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
2951  {
2952  Const *endOffset = (Const *) wc->endOffset;
2953  double end_offset_value;
2954 
2955  /* try and figure out the value specified in the endOffset. */
2956  if (IsA(endOffset, Const))
2957  {
2958  if (endOffset->constisnull)
2959  {
2960  /*
2961  * NULLs are not allowed, but currently, there's no code to
2962  * error out if there's a NULL Const. We'll only discover
2963  * this during execution. For now, just pretend everything is
2964  * fine and assume that just the first row/range/group will be
2965  * needed.
2966  */
2967  end_offset_value = 1.0;
2968  }
2969  else
2970  {
2971  switch (endOffset->consttype)
2972  {
2973  case INT2OID:
2974  end_offset_value =
2975  (double) DatumGetInt16(endOffset->constvalue);
2976  break;
2977  case INT4OID:
2978  end_offset_value =
2979  (double) DatumGetInt32(endOffset->constvalue);
2980  break;
2981  case INT8OID:
2982  end_offset_value =
2983  (double) DatumGetInt64(endOffset->constvalue);
2984  break;
2985  default:
2986  end_offset_value =
2987  partition_tuples / peer_tuples *
2989  break;
2990  }
2991  }
2992  }
2993  else
2994  {
2995  /*
2996  * When the end bound is not a Const, we'll just need to guess. We
2997  * just make use of DEFAULT_INEQ_SEL.
2998  */
2999  end_offset_value =
3000  partition_tuples / peer_tuples * DEFAULT_INEQ_SEL;
3001  }
3002 
3003  if (frameOptions & FRAMEOPTION_ROWS)
3004  {
3005  /* include the N FOLLOWING and the current row */
3006  return_tuples = end_offset_value + 1.0;
3007  }
3008  else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
3009  {
3010  /* include N FOLLOWING ranges/group and the initial range/group */
3011  return_tuples = peer_tuples * (end_offset_value + 1.0);
3012  }
3013  else
3014  {
3015  /*
3016  * Something new we don't support yet? This needs attention.
3017  * We'll just return 1.0 in the meantime.
3018  */
3019  Assert(false);
3020  return_tuples = 1.0;
3021  }
3022  }
3023  else
3024  {
3025  /*
3026  * Something new we don't support yet? This needs attention. We'll
3027  * just return 1.0 in the meantime.
3028  */
3029  Assert(false);
3030  return_tuples = 1.0;
3031  }
3032 
3033  if (wc->partitionClause != NIL || wc->orderClause != NIL)
3034  {
3035  /*
3036  * Cap the return value to the estimated partition tuples and account
3037  * for the extra tuple WindowAgg will need to read to confirm the next
3038  * tuple does not belong to the same partition or peer group.
3039  */
3040  return_tuples = Min(return_tuples + 1.0, partition_tuples);
3041  }
3042  else
3043  {
3044  /*
3045  * Cap the return value so it's never higher than the expected tuples
3046  * in the partition.
3047  */
3048  return_tuples = Min(return_tuples, partition_tuples);
3049  }
3050 
3051  /*
3052  * We needn't worry about any EXCLUDE options as those only exclude rows
3053  * from being aggregated, not from being read from the WindowAgg's
3054  * subnode.
3055  */
3056 
3057  return clamp_row_est(return_tuples);
3058 }
#define FRAMEOPTION_END_CURRENT_ROW
Definition: parsenodes.h:590
#define FRAMEOPTION_END_OFFSET_PRECEDING
Definition: parsenodes.h:592
#define FRAMEOPTION_END_OFFSET_FOLLOWING
Definition: parsenodes.h:594
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:581
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:583
#define FRAMEOPTION_END_UNBOUNDED_FOLLOWING
Definition: parsenodes.h:588
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:582
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:385
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:162
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:202
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Oid consttype
Definition: primnodes.h:298
Query * parse
Definition: pathnodes.h:199
List * targetList
Definition: parsenodes.h:190
Node * endOffset
Definition: parsenodes.h:1506
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:392

References Assert(), clamp_row_est(), Const::consttype, DatumGetInt16(), DatumGetInt32(), DatumGetInt64(), DEFAULT_INEQ_SEL, WindowClause::endOffset, estimate_num_groups(), FRAMEOPTION_END_CURRENT_ROW, FRAMEOPTION_END_OFFSET_FOLLOWING, FRAMEOPTION_END_OFFSET_PRECEDING, FRAMEOPTION_END_UNBOUNDED_FOLLOWING, FRAMEOPTION_GROUPS, FRAMEOPTION_RANGE, FRAMEOPTION_ROWS, WindowClause::frameOptions, get_sortgrouplist_exprs(), if(), IsA, list_free(), Min, NIL, WindowClause::orderClause, PlannerInfo::parse, WindowClause::partitionClause, and Query::targetList.

Referenced by cost_windowagg().

◆ has_indexed_join_quals()

static bool has_indexed_join_quals ( NestPath path)
static

Definition at line 5116 of file costsize.c.

5117 {
5118  JoinPath *joinpath = &path->jpath;
5119  Relids joinrelids = joinpath->path.parent->relids;
5120  Path *innerpath = joinpath->innerjoinpath;
5121  List *indexclauses;
5122  bool found_one;
5123  ListCell *lc;
5124 
5125  /* If join still has quals to evaluate, it's not fast */
5126  if (joinpath->joinrestrictinfo != NIL)
5127  return false;
5128  /* Nor if the inner path isn't parameterized at all */
5129  if (innerpath->param_info == NULL)
5130  return false;
5131 
5132  /* Find the indexclauses list for the inner scan */
5133  switch (innerpath->pathtype)
5134  {
5135  case T_IndexScan:
5136  case T_IndexOnlyScan:
5137  indexclauses = ((IndexPath *) innerpath)->indexclauses;
5138  break;
5139  case T_BitmapHeapScan:
5140  {
5141  /* Accept only a simple bitmap scan, not AND/OR cases */
5142  Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5143 
5144  if (IsA(bmqual, IndexPath))
5145  indexclauses = ((IndexPath *) bmqual)->indexclauses;
5146  else
5147  return false;
5148  break;
5149  }
5150  default:
5151 
5152  /*
5153  * If it's not a simple indexscan, it probably doesn't run quickly
5154  * for zero rows out, even if it's a parameterized path using all
5155  * the joinquals.
5156  */
5157  return false;
5158  }
5159 
5160  /*
5161  * Examine the inner path's param clauses. Any that are from the outer
5162  * path must be found in the indexclauses list, either exactly or in an
5163  * equivalent form generated by equivclass.c. Also, we must find at least
5164  * one such clause, else it's a clauseless join which isn't fast.
5165  */
5166  found_one = false;
5167  foreach(lc, innerpath->param_info->ppi_clauses)
5168  {
5169  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5170 
5171  if (join_clause_is_movable_into(rinfo,
5172  innerpath->parent->relids,
5173  joinrelids))
5174  {
5175  if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5176  return false;
5177  found_one = true;
5178  }
5179  }
5180  return found_one;
5181 }
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)
Definition: restrictinfo.c:670

References JoinPath::innerjoinpath, is_redundant_with_indexclauses(), IsA, join_clause_is_movable_into(), JoinPath::joinrestrictinfo, NestPath::jpath, lfirst, NIL, and Path::pathtype.

Referenced by final_cost_nestloop().

◆ index_pages_fetched()

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

Definition at line 898 of file costsize.c.

900 {
901  double pages_fetched;
902  double total_pages;
903  double T,
904  b;
905 
906  /* T is # pages in table, but don't allow it to be zero */
907  T = (pages > 1) ? (double) pages : 1.0;
908 
909  /* Compute number of pages assumed to be competing for cache space */
910  total_pages = root->total_table_pages + index_pages;
911  total_pages = Max(total_pages, 1.0);
912  Assert(T <= total_pages);
913 
914  /* b is pro-rated share of effective_cache_size */
915  b = (double) effective_cache_size * T / total_pages;
916 
917  /* force it positive and integral */
918  if (b <= 1.0)
919  b = 1.0;
920  else
921  b = ceil(b);
922 
923  /* This part is the Mackert and Lohman formula */
924  if (T <= b)
925  {
926  pages_fetched =
927  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
928  if (pages_fetched >= T)
929  pages_fetched = T;
930  else
931  pages_fetched = ceil(pages_fetched);
932  }
933  else
934  {
935  double lim;
936 
937  lim = (2.0 * T * b) / (2.0 * T - b);
938  if (tuples_fetched <= lim)
939  {
940  pages_fetched =
941  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
942  }
943  else
944  {
945  pages_fetched =
946  b + (tuples_fetched - lim) * (T - b) / T;
947  }
948  pages_fetched = ceil(pages_fetched);
949  }
950  return pages_fetched;
951 }
int effective_cache_size
Definition: costsize.c:128
int b
Definition: isn.c:70
Cardinality total_table_pages
Definition: pathnodes.h:475

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

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

◆ initial_cost_hashjoin()

void initial_cost_hashjoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List hashclauses,
Path outer_path,
Path inner_path,
JoinPathExtraData extra,
bool  parallel_hash 
)

Definition at line 4073 of file costsize.c.

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

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

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

◆ initial_cost_mergejoin()

void initial_cost_mergejoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List mergeclauses,
Path outer_path,
Path inner_path,
List outersortkeys,
List innersortkeys,
JoinPathExtraData extra 
)

Definition at line 3514 of file costsize.c.

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

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

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

◆ initial_cost_nestloop()

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

Definition at line 3233 of file costsize.c.

3237 {
3238  Cost startup_cost = 0;
3239  Cost run_cost = 0;
3240  double outer_path_rows = outer_path->rows;
3241  Cost inner_rescan_start_cost;
3242  Cost inner_rescan_total_cost;
3243  Cost inner_run_cost;
3244  Cost inner_rescan_run_cost;
3245 
3246  /* estimate costs to rescan the inner relation */
3247  cost_rescan(root, inner_path,
3248  &inner_rescan_start_cost,
3249  &inner_rescan_total_cost);
3250 
3251  /* cost of source data */
3252 
3253  /*
3254  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3255  * before we can start returning tuples, so the join's startup cost is
3256  * their sum. We'll also pay the inner path's rescan startup cost
3257  * multiple times.
3258  */
3259  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3260  run_cost += outer_path->total_cost - outer_path->startup_cost;
3261  if (outer_path_rows > 1)
3262  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3263 
3264  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3265  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3266 
3267  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3268  extra->inner_unique)
3269  {
3270  /*
3271  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3272  * executor will stop after the first match.
3273  *
3274  * Getting decent estimates requires inspection of the join quals,
3275  * which we choose to postpone to final_cost_nestloop.
3276  */
3277 
3278  /* Save private data for final_cost_nestloop */
3279  workspace->inner_run_cost = inner_run_cost;
3280  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3281  }
3282  else
3283  {
3284  /* Normal case; we'll scan whole input rel for each outer row */
3285  run_cost += inner_run_cost;
3286  if (outer_path_rows > 1)
3287  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3288  }
3289 
3290  /* CPU costs left for later */
3291 
3292  /* Public result fields */
3293  workspace->startup_cost = startup_cost;
3294  workspace->total_cost = startup_cost + run_cost;
3295  /* Save private data for final_cost_nestloop */
3296  workspace->run_cost = run_cost;
3297 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:4528

References cost_rescan(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JOIN_ANTI, JOIN_SEMI, Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, and JoinCostWorkspace::total_cost.

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

◆ page_size()

static double page_size ( double  tuples,
int  width 
)
static

Definition at line 6383 of file costsize.c.

6384 {
6385  return ceil(relation_byte_size(tuples, width) / BLCKSZ);
6386 }

References relation_byte_size().

Referenced by initial_cost_hashjoin().

◆ relation_byte_size()

static double relation_byte_size ( double  tuples,
int  width 
)
static

Definition at line 6372 of file costsize.c.

6373 {
6374  return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
6375 }
#define MAXALIGN(LEN)
Definition: c.h:798
#define SizeofHeapTupleHeader
Definition: htup_details.h:185

References MAXALIGN, and SizeofHeapTupleHeader.

Referenced by cost_agg(), cost_material(), cost_memoize_rescan(), cost_rescan(), cost_tuplesort(), final_cost_hashjoin(), final_cost_mergejoin(), and page_size().

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5269 of file costsize.c.

5270 {
5271  double nrows;
5272 
5273  /* Should only be applied to base relations */
5274  Assert(rel->relid > 0);
5275 
5276  nrows = rel->tuples *
5278  rel->baserestrictinfo,
5279  0,
5280  JOIN_INNER,
5281  NULL);
5282 
5283  rel->rows = clamp_row_est(nrows);
5284 
5286 
5287  set_rel_width(root, rel);
5288 }
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6129

References Assert(), RelOptInfo::baserestrictcost, RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), JOIN_INNER, RelOptInfo::relid, RelOptInfo::rows, set_rel_width(), and RelOptInfo::tuples.

Referenced by postgresGetForeignRelSize(), set_cte_size_estimates(), set_function_size_estimates(), set_namedtuplestore_size_estimates(), set_plain_rel_size(), set_result_size_estimates(), set_subquery_size_estimates(), set_tablefunc_size_estimates(), set_tablesample_rel_size(), and set_values_size_estimates().

◆ set_cte_size_estimates()

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

Definition at line 5994 of file costsize.c.

5995 {
5996  RangeTblEntry *rte;
5997 
5998  /* Should only be applied to base relations that are CTE references */
5999  Assert(rel->relid > 0);
6000  rte = planner_rt_fetch(rel->relid, root);
6001  Assert(rte->rtekind == RTE_CTE);
6002 
6003  if (rte->self_reference)
6004  {
6005  /*
6006  * In a self-reference, we assume the average worktable size is a
6007  * multiple of the nonrecursive term's size. The best multiplier will
6008  * vary depending on query "fan-out", so make its value adjustable.
6009  */
6010  rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
6011  }
6012  else
6013  {
6014  /* Otherwise just believe the CTE's rowcount estimate */
6015  rel->tuples = cte_rows;
6016  }
6017 
6018  /* Now estimate number of output rows, etc */
6019  set_baserel_size_estimates(root, rel);
6020 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5269
double recursive_worktable_factor
Definition: costsize.c:126
bool self_reference
Definition: parsenodes.h:1171

References Assert(), clamp_row_est(), planner_rt_fetch, recursive_worktable_factor, RelOptInfo::relid, RTE_CTE, RangeTblEntry::rtekind, RangeTblEntry::self_reference, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

◆ set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6094 of file costsize.c.

6095 {
6096  /* Should only be applied to base relations */
6097  Assert(rel->relid > 0);
6098 
6099  rel->rows = 1000; /* entirely bogus default estimate */
6100 
6102 
6103  set_rel_width(root, rel);
6104 }

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

Referenced by set_foreign_size().

◆ set_function_size_estimates()

void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5902 of file costsize.c.

5903 {
5904  RangeTblEntry *rte;
5905  ListCell *lc;
5906 
5907  /* Should only be applied to base relations that are functions */
5908  Assert(rel->relid > 0);
5909  rte = planner_rt_fetch(rel->relid, root);
5910  Assert(rte->rtekind == RTE_FUNCTION);
5911 
5912  /*
5913  * Estimate number of rows the functions will return. The rowcount of the
5914  * node is that of the largest function result.
5915  */
5916  rel->tuples = 0;
5917  foreach(lc, rte->functions)
5918  {
5919  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5920  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5921 
5922  if (ntup > rel->tuples)
5923  rel->tuples = ntup;
5924  }
5925 
5926  /* Now estimate number of output rows, etc */
5927  set_baserel_size_estimates(root, rel);
5928 }
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:288

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

Referenced by set_rel_size().

◆ set_joinrel_size_estimates()

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

Definition at line 5348 of file costsize.c.

5353 {
5354  rel->rows = calc_joinrel_size_estimate(root,
5355  rel,
5356  outer_rel,
5357  inner_rel,
5358  outer_rel->rows,
5359  inner_rel->rows,
5360  sjinfo,
5361  restrictlist);
5362 }

References calc_joinrel_size_estimate(), and RelOptInfo::rows.

Referenced by build_child_join_rel(), and build_join_rel().

◆ set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6032 of file costsize.c.

6033 {
6034  RangeTblEntry *rte;
6035 
6036  /* Should only be applied to base relations that are tuplestore references */
6037  Assert(rel->relid > 0);
6038  rte = planner_rt_fetch(rel->relid, root);
6040 
6041  /*
6042  * Use the estimate provided by the code which is generating the named
6043  * tuplestore. In some cases, the actual number might be available; in
6044  * others the same plan will be re-used, so a "typical" value might be
6045  * estimated and used.
6046  */
6047  rel->tuples = rte->enrtuples;
6048  if (rel->tuples < 0)
6049  rel->tuples = 1000;
6050 
6051  /* Now estimate number of output rows, etc */
6052  set_baserel_size_estimates(root, rel);
6053 }
Cardinality enrtuples
Definition: parsenodes.h:1199

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

Referenced by set_namedtuplestore_pathlist().

◆ set_pathtarget_cost_width()

PathTarget* set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)

Definition at line 6286 of file costsize.c.

6287 {
6288  int64 tuple_width = 0;
6289  ListCell *lc;
6290 
6291  /* Vars are assumed to have cost zero, but other exprs do not */
6292  target->cost.startup = 0;
6293  target->cost.per_tuple = 0;
6294 
6295  foreach(lc, target->exprs)
6296  {
6297  Node *node = (Node *) lfirst(lc);
6298 
6299  tuple_width += get_expr_width(root, node);
6300 
6301  /* For non-Vars, account for evaluation cost */
6302  if (!IsA(node, Var))
6303  {
6304  QualCost cost;
6305 
6306  cost_qual_eval_node(&cost, node, root);
6307  target->cost.startup += cost.startup;
6308  target->cost.per_tuple += cost.per_tuple;
6309  }
6310  }
6311 
6312  target->width = clamp_width_est(tuple_width);
6313 
6314  return target;
6315 }
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:231
List * exprs
Definition: pathnodes.h:1513
QualCost cost
Definition: pathnodes.h:1519

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

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

◆ set_rel_width()

static void set_rel_width ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 6129 of file costsize.c.

6130 {
6131  Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
6132  int64 tuple_width = 0;
6133  bool have_wholerow_var = false;
6134  ListCell *lc;
6135 
6136  /* Vars are assumed to have cost zero, but other exprs do not */
6137  rel->reltarget->cost.startup = 0;
6138  rel->reltarget->cost.per_tuple = 0;
6139 
6140  foreach(lc, rel->reltarget->exprs)
6141  {
6142  Node *node = (Node *) lfirst(lc);
6143 
6144  /*
6145  * Ordinarily, a Var in a rel's targetlist must belong to that rel;
6146  * but there are corner cases involving LATERAL references where that
6147  * isn't so. If the Var has the wrong varno, fall through to the
6148  * generic case (it doesn't seem worth the trouble to be any smarter).
6149  */
6150  if (IsA(node, Var) &&
6151  ((Var *) node)->varno == rel->relid)
6152  {
6153  Var *var = (Var *) node;
6154  int ndx;
6155  int32 item_width;
6156 
6157  Assert(var->varattno >= rel->min_attr);
6158  Assert(var->varattno <= rel->max_attr);
6159 
6160  ndx = var->varattno - rel->min_attr;
6161 
6162  /*
6163  * If it's a whole-row Var, we'll deal with it below after we have
6164  * already cached as many attr widths as possible.
6165  */
6166  if (var->varattno == 0)
6167  {
6168  have_wholerow_var = true;
6169  continue;
6170  }
6171 
6172  /*
6173  * The width may have been cached already (especially if it's a
6174  * subquery), so don't duplicate effort.
6175  */
6176  if (rel->attr_widths[ndx] > 0)
6177  {
6178  tuple_width += rel->attr_widths[ndx];
6179  continue;
6180  }
6181 
6182  /* Try to get column width from statistics */
6183  if (reloid != InvalidOid && var->varattno > 0)
6184  {
6185  item_width = get_attavgwidth(reloid, var->varattno);
6186  if (item_width > 0)
6187  {
6188  rel->attr_widths[ndx] = item_width;
6189  tuple_width += item_width;
6190  continue;
6191  }
6192  }
6193 
6194  /*
6195  * Not a plain relation, or can't find statistics for it. Estimate
6196  * using just the type info.
6197  */
6198  item_width = get_typavgwidth(var->vartype, var->vartypmod);
6199  Assert(item_width > 0);
6200  rel->attr_widths[ndx] = item_width;
6201  tuple_width += item_width;
6202  }
6203  else if (IsA(node, PlaceHolderVar))
6204  {
6205  /*
6206  * We will need to evaluate the PHV's contained expression while
6207  * scanning this rel, so be sure to include it in reltarget->cost.
6208  */
6209  PlaceHolderVar *phv = (PlaceHolderVar *) node;
6210  PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
6211  QualCost cost;
6212 
6213  tuple_width += phinfo->ph_width;
6214  cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
6215  rel->reltarget->cost.startup += cost.startup;
6216  rel->reltarget->cost.per_tuple += cost.per_tuple;
6217  }
6218  else
6219  {
6220  /*
6221  * We could be looking at an expression pulled up from a subquery,
6222  * or a ROW() representing a whole-row child Var, etc. Do what we
6223  * can using the expression type information.
6224  */
6225  int32 item_width;
6226  QualCost cost;
6227 
6228  item_width = get_typavgwidth(exprType(node), exprTypmod(node));
6229  Assert(item_width > 0);
6230  tuple_width += item_width;
6231  /* Not entirely clear if we need to account for cost, but do so */
6232  cost_qual_eval_node(&cost, node, root);
6233  rel->reltarget->cost.startup += cost.startup;
6234  rel->reltarget->cost.per_tuple += cost.per_tuple;
6235  }
6236  }
6237 
6238  /*
6239  * If we have a whole-row reference, estimate its width as the sum of
6240  * per-column widths plus heap tuple header overhead.
6241  */
6242  if (have_wholerow_var)
6243  {
6244  int64 wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
6245 
6246  if (reloid != InvalidOid)
6247  {
6248  /* Real relation, so estimate true tuple width */
6249  wholerow_width += get_relation_data_width(reloid,
6250  rel->attr_widths - rel->min_attr);
6251  }
6252  else
6253  {
6254  /* Do what we can with info for a phony rel */
6255  AttrNumber i;
6256 
6257  for (i = 1; i <= rel->max_attr; i++)
6258  wholerow_width += rel->attr_widths[i - rel->min_attr];
6259  }
6260 
6261  rel->attr_widths[0 - rel->min_attr] = clamp_width_est(wholerow_width);
6262 
6263  /*
6264  * Include the whole-row Var as part of the output tuple. Yes, that
6265  * really is what happens at runtime.
6266  */
6267  tuple_width += wholerow_width;
6268  }
6269 
6270  rel->reltarget->width = clamp_width_est(tuple_width);
6271 }
int16 AttrNumber
Definition: attnum.h:21
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3114
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv)
Definition: placeholder.c:83
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1197
#define InvalidOid
Definition: postgres_ext.h:36
struct PathTarget * reltarget
Definition: pathnodes.h:878

References Assert(), clamp_width_est(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, exprType(), exprTypmod(), find_placeholder_info(), get_attavgwidth(), get_relation_data_width(), get_typavgwidth(), i, InvalidOid, IsA, lfirst, RelOptInfo::max_attr, MAXALIGN, RelOptInfo::min_attr, QualCost::per_tuple, PlaceHolderInfo::ph_width, planner_rt_fetch, RelOptInfo::relid, RelOptInfo::reltarget, SizeofHeapTupleHeader, QualCost::startup, Var::varattno, and PathTarget::width.

Referenced by set_baserel_size_estimates(), and set_foreign_size_estimates().

◆ set_result_size_estimates()

void set_result_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6065 of file costsize.c.

6066 {
6067  /* Should only be applied to RTE_RESULT base relations */
6068  Assert(rel->relid > 0);
6069  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6070 
6071  /* RTE_RESULT always generates a single row, natively */
6072  rel->tuples = 1;
6073 
6074  /* Now estimate number of output rows, etc */
6075  set_baserel_size_estimates(root, rel);
6076 }

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

Referenced by set_result_pathlist().

◆ set_subquery_size_estimates()

void set_subquery_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5822 of file costsize.c.

5823 {
5824  PlannerInfo *subroot = rel->subroot;
5825  RelOptInfo *sub_final_rel;
5826  ListCell *lc;
5827 
5828  /* Should only be applied to base relations that are subqueries */
5829  Assert(rel->relid > 0);
5830  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5831 
5832  /*
5833  * Copy raw number of output rows from subquery. All of its paths should
5834  * have the same output rowcount, so just look at cheapest-total.
5835  */
5836  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5837  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5838 
5839  /*
5840  * Compute per-output-column width estimates by examining the subquery's
5841  * targetlist. For any output that is a plain Var, get the width estimate
5842  * that was made while planning the subquery. Otherwise, we leave it to
5843  * set_rel_width to fill in a datatype-based default estimate.
5844  */
5845  foreach(lc, subroot->parse->targetList)
5846  {
5847  TargetEntry *te = lfirst_node(TargetEntry, lc);
5848  Node *texpr = (Node *) te->expr;
5849  int32 item_width = 0;
5850 
5851  /* junk columns aren't visible to upper query */
5852  if (te->resjunk)
5853  continue;
5854 
5855  /*
5856  * The subquery could be an expansion of a view that's had columns
5857  * added to it since the current query was parsed, so that there are
5858  * non-junk tlist columns in it that don't correspond to any column
5859  * visible at our query level. Ignore such columns.
5860  */
5861  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5862  continue;
5863 
5864  /*
5865  * XXX This currently doesn't work for subqueries containing set
5866  * operations, because the Vars in their tlists are bogus references
5867  * to the first leaf subquery, which wouldn't give the right answer
5868  * even if we could still get to its PlannerInfo.
5869  *
5870  * Also, the subquery could be an appendrel for which all branches are
5871  * known empty due to constraint exclusion, in which case
5872  * set_append_rel_pathlist will have left the attr_widths set to zero.
5873  *
5874  * In either case, we just leave the width estimate zero until
5875  * set_rel_width fixes it.
5876  */
5877  if (IsA(texpr, Var) &&
5878  subroot->parse->setOperations == NULL)
5879  {
5880  Var *var = (Var *) texpr;
5881  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5882 
5883  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5884  }
5885  rel->attr_widths[te->resno - rel->min_attr] = item_width;
5886  }
5887 
5888  /* Now estimate number of output rows, etc */
5889  set_baserel_size_estimates(root, rel);
5890 }
@ UPPERREL_FINAL
Definition: pathnodes.h:79
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1463
Node * setOperations
Definition: parsenodes.h:218
struct Path * cheapest_total_path
Definition: pathnodes.h:887
PlannerInfo * subroot
Definition: pathnodes.h:934
Expr * expr
Definition: primnodes.h:1943
AttrNumber resno
Definition: primnodes.h:1945

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

Referenced by recurse_set_operations(), and set_subquery_pathlist().

◆ set_tablefunc_size_estimates()

void set_tablefunc_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5940 of file costsize.c.

5941 {
5942  /* Should only be applied to base relations that are functions */
5943  Assert(rel->relid > 0);
5944  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
5945 
5946  rel->tuples = 100;
5947 
5948  /* Now estimate number of output rows, etc */
5949  set_baserel_size_estimates(root, rel);
5950 }

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

Referenced by set_rel_size().

◆ set_values_size_estimates()

void set_values_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5962 of file costsize.c.

5963 {
5964  RangeTblEntry *rte;
5965 
5966  /* Should only be applied to base relations that are values lists */
5967  Assert(rel->relid > 0);
5968  rte = planner_rt_fetch(rel->relid, root);
5969  Assert(rte->rtekind == RTE_VALUES);
5970 
5971  /*
5972  * Estimate number of rows the values list will return. We know this
5973  * precisely based on the list length (well, barring set-returning
5974  * functions in list items, but that's a refinement not catered for
5975  * anywhere else either).
5976  */
5977  rel->tuples = list_length(rte->values_lists);
5978 
5979  /* Now estimate number of output rows, etc */
5980  set_baserel_size_estimates(root, rel);
5981 }
List * values_lists
Definition: parsenodes.h:1164

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

Referenced by set_rel_size().

Variable Documentation

◆ cpu_index_tuple_cost

double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST

Definition at line 122 of file costsize.c.

Referenced by genericcostestimate(), and gincostestimate().

◆ cpu_operator_cost

◆ cpu_tuple_cost

◆ disable_cost

◆ effective_cache_size

int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE

Definition at line 128 of file costsize.c.

Referenced by gistBuildCallback(), gistInitBuffering(), and index_pages_fetched().

◆ enable_async_append

bool enable_async_append = true

Definition at line 154 of file costsize.c.

Referenced by create_append_plan().

◆ enable_bitmapscan

bool enable_bitmapscan = true

Definition at line 137 of file costsize.c.

Referenced by cost_bitmap_heap_scan().

◆ enable_gathermerge

bool enable_gathermerge = true

Definition at line 147 of file costsize.c.

Referenced by cost_gather_merge().

◆ enable_hashagg

◆ enable_hashjoin

bool enable_hashjoin = true

Definition at line 146 of file costsize.c.

Referenced by add_paths_to_joinrel(), and final_cost_hashjoin().

◆ enable_incremental_sort

◆ enable_indexonlyscan

bool enable_indexonlyscan = true

Definition at line 136 of file costsize.c.

Referenced by check_index_only().

◆ enable_indexscan

bool enable_indexscan = true

Definition at line 135 of file costsize.c.

Referenced by cost_index(), and plan_cluster_use_sort().

◆ enable_material

bool enable_material = true

Definition at line 143 of file costsize.c.

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

◆ enable_memoize

bool enable_memoize = true

Definition at line 144 of file costsize.c.

Referenced by get_memoize_path().

◆ enable_mergejoin

bool enable_mergejoin = true

Definition at line 145 of file costsize.c.

Referenced by add_paths_to_joinrel(), and final_cost_mergejoin().

◆ enable_nestloop

bool enable_nestloop = true

Definition at line 142 of file costsize.c.

Referenced by final_cost_nestloop().

◆ enable_parallel_append

bool enable_parallel_append = true

Definition at line 150 of file costsize.c.

Referenced by add_paths_to_append_rel(), and generate_union_paths().

◆ enable_parallel_hash

bool enable_parallel_hash = true

Definition at line 151 of file costsize.c.

Referenced by hash_inner_and_outer().

◆ enable_partition_pruning

bool enable_partition_pruning = true

◆ enable_partitionwise_aggregate

bool enable_partitionwise_aggregate = false

Definition at line 149 of file costsize.c.

Referenced by create_grouping_paths().

◆ enable_partitionwise_join

bool enable_partitionwise_join = false

Definition at line 148 of file costsize.c.

Referenced by build_joinrel_partition_info(), and set_append_rel_size().

◆ enable_presorted_aggregate

bool enable_presorted_aggregate = true

Definition at line 153 of file costsize.c.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ enable_seqscan

bool enable_seqscan = true

Definition at line 134 of file costsize.c.

Referenced by cost_seqscan().

◆ enable_sort

bool enable_sort = true

Definition at line 139 of file costsize.c.

Referenced by cost_sort().

◆ enable_tidscan

bool enable_tidscan = true

Definition at line 138 of file costsize.c.

Referenced by cost_tidrangescan(), and cost_tidscan().

◆ max_parallel_workers_per_gather

int max_parallel_workers_per_gather = 2

◆ parallel_setup_cost

double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST

Definition at line 125 of file costsize.c.

Referenced by cost_gather(), cost_gather_merge(), and standard_planner().

◆ parallel_tuple_cost

double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST

Definition at line 124 of file costsize.c.

Referenced by cost_gather(), cost_gather_merge(), and standard_planner().

◆ random_page_cost

double random_page_cost = DEFAULT_RANDOM_PAGE_COST

◆ recursive_worktable_factor

double recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR

Definition at line 126 of file costsize.c.

Referenced by set_cte_size_estimates().

◆ seq_page_cost