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/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
#include "utils/spccache.h"
#include "utils/tuplesort.h"
Include dependency graph for costsize.c:

Go to the source code of this file.

Data Structures

struct  cost_qual_eval_context
 

Macros

#define LOG2(x)   (log(x) / 0.693147180559945)
 
#define APPEND_CPU_COST_MULTIPLIER   0.5
 
#define MAXIMUM_ROWCOUNT   1e100
 

Functions

static Listextract_nonindex_conditions (List *qual_clauses, List *indexclauses)
 
static MergeScanSelCachecached_scansel (PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
 
static void cost_rescan (PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
static bool cost_qual_eval_walker (Node *node, cost_qual_eval_context *context)
 
static void get_restriction_qual_cost (PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
 
static bool has_indexed_join_quals (NestPath *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 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)
 
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)
 
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 bool is_fake_var (Expr *expr)
 
static double get_width_cost_multiplier (PlannerInfo *root, Expr *expr)
 
static Cost compute_cpu_sort_cost (PlannerInfo *root, List *pathkeys, int nPresortedKeys, Cost comparison_cost, double tuples, double output_tuples, bool heapSort)
 
Cost cost_sort_estimate (PlannerInfo *root, List *pathkeys, int nPresortedKeys, double tuples)
 
static void cost_tuplesort (PlannerInfo *root, List *pathkeys, Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
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, PlannerInfo *root)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
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)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
 

Variables

double seq_page_cost = DEFAULT_SEQ_PAGE_COST
 
double random_page_cost = DEFAULT_RANDOM_PAGE_COST
 
double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST
 
double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST
 
double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST
 
double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST
 
double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST
 
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_async_append = true
 

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 110 of file costsize.c.

◆ LOG2

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

Definition at line 103 of file costsize.c.

◆ MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

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

2427 {
2428  Cost *costarr;
2429  int arrlen;
2430  ListCell *l;
2431  ListCell *cell;
2432  int i;
2433  int path_index;
2434  int min_index;
2435  int max_index;
2436 
2437  if (numpaths == 0)
2438  return 0;
2439 
2440  /*
2441  * Array length is number of workers or number of relevant paths,
2442  * whichever is less.
2443  */
2444  arrlen = Min(parallel_workers, numpaths);
2445  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2446 
2447  /* The first few paths will each be claimed by a different worker. */
2448  path_index = 0;
2449  foreach(cell, subpaths)
2450  {
2451  Path *subpath = (Path *) lfirst(cell);
2452 
2453  if (path_index == arrlen)
2454  break;
2455  costarr[path_index++] = subpath->total_cost;
2456  }
2457 
2458  /*
2459  * Since subpaths are sorted by decreasing cost, the last one will have
2460  * the minimum cost.
2461  */
2462  min_index = arrlen - 1;
2463 
2464  /*
2465  * For each of the remaining subpaths, add its cost to the array element
2466  * with minimum cost.
2467  */
2468  for_each_cell(l, subpaths, cell)
2469  {
2470  Path *subpath = (Path *) lfirst(l);
2471  int i;
2472 
2473  /* Consider only the non-partial paths */
2474  if (path_index++ == numpaths)
2475  break;
2476 
2477  costarr[min_index] += subpath->total_cost;
2478 
2479  /* Update the new min cost array index */
2480  for (min_index = i = 0; i < arrlen; i++)
2481  {
2482  if (costarr[i] < costarr[min_index])
2483  min_index = i;
2484  }
2485  }
2486 
2487  /* Return the highest cost from the array */
2488  for (max_index = i = 0; i < arrlen; i++)
2489  {
2490  if (costarr[i] > costarr[max_index])
2491  max_index = i;
2492  }
2493 
2494  return costarr[max_index];
2495 }
#define Min(x, y)
Definition: c.h:986
int i
Definition: isn.c:73
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void * palloc(Size size)
Definition: mcxt.c:1068
double Cost
Definition: nodes.h:707
#define lfirst(lc)
Definition: pg_list.h:169
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417

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

5234 {
5235  double tuples;
5236  double outer_tuples = path->outerjoinpath->rows;
5237  double inner_tuples = path->innerjoinpath->rows;
5238  SpecialJoinInfo sjinfo;
5239  Selectivity selec = 1.0;
5240  ListCell *l;
5241 
5242  /*
5243  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5244  */
5245  sjinfo.type = T_SpecialJoinInfo;
5246  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
5247  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
5248  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
5249  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
5250  sjinfo.jointype = JOIN_INNER;
5251  /* we don't bother trying to make the remaining fields valid */
5252  sjinfo.lhs_strict = false;
5253  sjinfo.delay_upper_joins = false;
5254  sjinfo.semi_can_btree = false;
5255  sjinfo.semi_can_hash = false;
5256  sjinfo.semi_operators = NIL;
5257  sjinfo.semi_rhs_exprs = NIL;
5258 
5259  /* Get the approximate selectivity */
5260  foreach(l, quals)
5261  {
5262  Node *qual = (Node *) lfirst(l);
5263 
5264  /* Note that clause_selectivity will be able to cache its result */
5265  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5266  }
5267 
5268  /* Apply it to the input relation sizes */
5269  tuples = selec * outer_tuples * inner_tuples;
5270 
5271  return clamp_row_est(tuples);
5272 }
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:690
double clamp_row_est(double nrows)
Definition: costsize.c:201
@ T_SpecialJoinInfo
Definition: nodes.h:287
double Selectivity
Definition: nodes.h:706
@ JOIN_INNER
Definition: nodes.h:749
#define NIL
Definition: pg_list.h:65
Path * outerjoinpath
Definition: pathnodes.h:1604
Path * innerjoinpath
Definition: pathnodes.h:1605
Definition: nodes.h:574
RelOptInfo * parent
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1204
Relids relids
Definition: pathnodes.h:682
Relids syn_lefthand
Definition: pathnodes.h:2274
Relids min_righthand
Definition: pathnodes.h:2273
List * semi_rhs_exprs
Definition: pathnodes.h:2283
JoinType jointype
Definition: pathnodes.h:2276
Relids min_lefthand
Definition: pathnodes.h:2272
Relids syn_righthand
Definition: pathnodes.h:2275
List * semi_operators
Definition: pathnodes.h:2282
bool delay_upper_joins
Definition: pathnodes.h:2278

References clamp_row_est(), clause_selectivity(), SpecialJoinInfo::delay_upper_joins, JoinPath::innerjoinpath, JOIN_INNER, SpecialJoinInfo::jointype, lfirst, SpecialJoinInfo::lhs_strict, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, JoinPath::outerjoinpath, Path::parent, RelOptInfo::relids, Path::rows, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, SpecialJoinInfo::syn_righthand, T_SpecialJoinInfo, and SpecialJoinInfo::type.

Referenced by final_cost_hashjoin(), and final_cost_mergejoin().

◆ cached_scansel()

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

Definition at line 4021 of file costsize.c.

4022 {
4023  MergeScanSelCache *cache;
4024  ListCell *lc;
4025  Selectivity leftstartsel,
4026  leftendsel,
4027  rightstartsel,
4028  rightendsel;
4029  MemoryContext oldcontext;
4030 
4031  /* Do we have this result already? */
4032  foreach(lc, rinfo->scansel_cache)
4033  {
4034  cache = (MergeScanSelCache *) lfirst(lc);
4035  if (cache->opfamily == pathkey->pk_opfamily &&
4036  cache->collation == pathkey->pk_eclass->ec_collation &&
4037  cache->strategy == pathkey->pk_strategy &&
4038  cache->nulls_first == pathkey->pk_nulls_first)
4039  return cache;
4040  }
4041 
4042  /* Nope, do the computation */
4043  mergejoinscansel(root,
4044  (Node *) rinfo->clause,
4045  pathkey->pk_opfamily,
4046  pathkey->pk_strategy,
4047  pathkey->pk_nulls_first,
4048  &leftstartsel,
4049  &leftendsel,
4050  &rightstartsel,
4051  &rightendsel);
4052 
4053  /* Cache the result in suitably long-lived workspace */
4054  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4055 
4056  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
4057  cache->opfamily = pathkey->pk_opfamily;
4058  cache->collation = pathkey->pk_eclass->ec_collation;
4059  cache->strategy = pathkey->pk_strategy;
4060  cache->nulls_first = pathkey->pk_nulls_first;
4061  cache->leftstartsel = leftstartsel;
4062  cache->leftendsel = leftendsel;
4063  cache->rightstartsel = rightstartsel;
4064  cache->rightendsel = rightendsel;
4065 
4066  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4067 
4068  MemoryContextSwitchTo(oldcontext);
4069 
4070  return cache;
4071 }
List * lappend(List *list, void *datum)
Definition: list.c:336
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2904
Selectivity leftstartsel
Definition: pathnodes.h:2178
Selectivity leftendsel
Definition: pathnodes.h:2179
Selectivity rightendsel
Definition: pathnodes.h:2181
Selectivity rightstartsel
Definition: pathnodes.h:2180
bool pk_nulls_first
Definition: pathnodes.h:1071
int pk_strategy
Definition: pathnodes.h:1070
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1068
Oid pk_opfamily
Definition: pathnodes.h:1069
MemoryContext planner_cxt
Definition: pathnodes.h:336
List * scansel_cache
Definition: pathnodes.h:2130
Expr * clause
Definition: pathnodes.h:2075

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

Referenced by initial_cost_mergejoin().

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

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

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

225 {
226  /*
227  * Just for paranoia's sake, ensure we do something sane with negative or
228  * NaN values.
229  */
230  if (isnan(x))
231  return LONG_MAX;
232  if (x <= 0)
233  return 0;
234 
235  /*
236  * If "long" is 64 bits, then LONG_MAX cannot be represented exactly as a
237  * double. Casting it to double and back may well result in overflow due
238  * to rounding, so avoid doing that. We trust that any double value that
239  * compares strictly less than "(double) LONG_MAX" will cast to a
240  * representable "long" value.
241  */
242  return (x < (double) LONG_MAX) ? (long) x : LONG_MAX;
243 }
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 201 of file costsize.c.

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

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_hash_bucket_stats(), estimate_num_groups_incremental(), estimate_path_cost_size(), estimate_size(), expression_returns_set_rows(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_parameterized_baserel_size(), get_variable_numdistinct(), initial_cost_mergejoin(), set_baserel_size_estimates(), set_cte_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

◆ compute_bitmap_pages()

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

Definition at line 6442 of file costsize.c.

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

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_cpu_sort_cost()

static Cost compute_cpu_sort_cost ( PlannerInfo root,
List pathkeys,
int  nPresortedKeys,
Cost  comparison_cost,
double  tuples,
double  output_tuples,
bool  heapSort 
)
static

Definition at line 1927 of file costsize.c.

1930 {
1931  Cost per_tuple_cost = 0.0;
1932  ListCell *lc;
1933  List *pathkeyExprs = NIL;
1934  double tuplesPerPrevGroup = tuples;
1935  double totalFuncCost = 1.0;
1936  bool has_fake_var = false;
1937  int i = 0;
1938  Oid prev_datatype = InvalidOid;
1939  List *cache_varinfos = NIL;
1940 
1941  /* fallback if pathkeys is unknown */
1942  if (list_length(pathkeys) == 0)
1943  {
1944  /*
1945  * If we'll use a bounded heap-sort keeping just K tuples in memory,
1946  * for a total number of tuple comparisons of N log2 K; but the
1947  * constant factor is a bit higher than for quicksort. Tweak it so
1948  * that the cost curve is continuous at the crossover point.
1949  */
1950  output_tuples = (heapSort) ? 2.0 * output_tuples : tuples;
1951  per_tuple_cost += 2.0 * cpu_operator_cost * LOG2(output_tuples);
1952 
1953  /* add cost provided by caller */
1954  per_tuple_cost += comparison_cost;
1955 
1956  return per_tuple_cost * tuples;
1957  }
1958 
1959  /*
1960  * Computing total cost of sorting takes into account the per-column
1961  * comparison function cost. We try to compute the needed number of
1962  * comparisons per column.
1963  */
1964  foreach(lc, pathkeys)
1965  {
1966  PathKey *pathkey = (PathKey *) lfirst(lc);
1967  EquivalenceMember *em;
1968  double nGroups,
1969  correctedNGroups;
1970  Cost funcCost = 1.0;
1971 
1972  /*
1973  * We believe that equivalence members aren't very different, so, to
1974  * estimate cost we consider just the first member.
1975  */
1976  em = (EquivalenceMember *) linitial(pathkey->pk_eclass->ec_members);
1977 
1978  if (em->em_datatype != InvalidOid)
1979  {
1980  /* do not lookup funcCost if the data type is the same */
1981  if (prev_datatype != em->em_datatype)
1982  {
1983  Oid sortop;
1984  QualCost cost;
1985 
1986  sortop = get_opfamily_member(pathkey->pk_opfamily,
1987  em->em_datatype, em->em_datatype,
1988  pathkey->pk_strategy);
1989 
1990  cost.startup = 0;
1991  cost.per_tuple = 0;
1992  add_function_cost(root, get_opcode(sortop), NULL, &cost);
1993 
1994  /*
1995  * add_function_cost returns the product of cpu_operator_cost
1996  * and procost, but we need just procost, co undo that.
1997  */
1998  funcCost = cost.per_tuple / cpu_operator_cost;
1999 
2000  prev_datatype = em->em_datatype;
2001  }
2002  }
2003 
2004  /* factor in the width of the values in this column */
2005  funcCost *= get_width_cost_multiplier(root, em->em_expr);
2006 
2007  /* now we have per-key cost, so add to the running total */
2008  totalFuncCost += funcCost;
2009 
2010  /* remember if we have found a fake Var in pathkeys */
2011  has_fake_var |= is_fake_var(em->em_expr);
2012  pathkeyExprs = lappend(pathkeyExprs, em->em_expr);
2013 
2014  /*
2015  * We need to calculate the number of comparisons for this column,
2016  * which requires knowing the group size. So we estimate the number of
2017  * groups by calling estimate_num_groups_incremental(), which
2018  * estimates the group size for "new" pathkeys.
2019  *
2020  * Note: estimate_num_groups_incremental does not handle fake Vars, so
2021  * use a default estimate otherwise.
2022  */
2023  if (!has_fake_var)
2024  nGroups = estimate_num_groups_incremental(root, pathkeyExprs,
2025  tuplesPerPrevGroup, NULL, NULL,
2026  &cache_varinfos,
2027  list_length(pathkeyExprs) - 1);
2028  else if (tuples > 4.0)
2029 
2030  /*
2031  * Use geometric mean as estimation if there are no stats.
2032  *
2033  * We don't use DEFAULT_NUM_DISTINCT here, because that's used for
2034  * a single column, but here we're dealing with multiple columns.
2035  */
2036  nGroups = ceil(2.0 + sqrt(tuples) * (i + 1) / list_length(pathkeys));
2037  else
2038  nGroups = tuples;
2039 
2040  /*
2041  * Presorted keys are not considered in the cost above, but we still
2042  * do have to compare them in the qsort comparator. So make sure to
2043  * factor in the cost in that case.
2044  */
2045  if (i >= nPresortedKeys)
2046  {
2047  if (heapSort)
2048  {
2049  /*
2050  * have to keep at least one group, and a multiple of group
2051  * size
2052  */
2053  correctedNGroups = ceil(output_tuples / tuplesPerPrevGroup);
2054  }
2055  else
2056  /* all groups in the input */
2057  correctedNGroups = nGroups;
2058 
2059  correctedNGroups = Max(1.0, ceil(correctedNGroups));
2060 
2061  per_tuple_cost += totalFuncCost * LOG2(correctedNGroups);
2062  }
2063 
2064  i++;
2065 
2066  /*
2067  * Uniform distributions with all groups being of the same size are
2068  * the best case, with nice smooth behavior. Real-world distributions
2069  * tend not to be uniform, though, and we don't have any reliable
2070  * easy-to-use information. As a basic defense against skewed
2071  * distributions, we use a 1.5 factor to make the expected group a bit
2072  * larger, but we need to be careful not to make the group larger than
2073  * in the preceding step.
2074  */
2075  tuplesPerPrevGroup = Min(tuplesPerPrevGroup,
2076  ceil(1.5 * tuplesPerPrevGroup / nGroups));
2077 
2078  /*
2079  * Once we get single-row group, it means tuples in the group are
2080  * unique and we can skip all remaining columns.
2081  */
2082  if (tuplesPerPrevGroup <= 1.0)
2083  break;
2084  }
2085 
2086  list_free(pathkeyExprs);
2087 
2088  /* per_tuple_cost is in cpu_operator_cost units */
2089  per_tuple_cost *= cpu_operator_cost;
2090 
2091  /*
2092  * Accordingly to "Introduction to algorithms", Thomas H. Cormen, Charles
2093  * E. Leiserson, Ronald L. Rivest, ISBN 0-07-013143-0, quicksort
2094  * estimation formula has additional term proportional to number of tuples
2095  * (see Chapter 8.2 and Theorem 4.1). That affects cases with a low number
2096  * of tuples, approximately less than 1e4. We could implement it as an
2097  * additional multiplier under the logarithm, but we use a bit more
2098  * complex formula which takes into account the number of unique tuples
2099  * and it's not clear how to combine the multiplier with the number of
2100  * groups. Estimate it as 10 cpu_operator_cost units.
2101  */
2102  per_tuple_cost += 10 * cpu_operator_cost;
2103 
2104  per_tuple_cost += comparison_cost;
2105 
2106  return tuples * per_tuple_cost;
2107 }
double cpu_operator_cost
Definition: costsize.c:124
#define LOG2(x)
Definition: costsize.c:103
static bool is_fake_var(Expr *expr)
Definition: costsize.c:1807
static double get_width_cost_multiplier(PlannerInfo *root, Expr *expr)
Definition: costsize.c:1822
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1266
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
static int list_length(const List *l)
Definition: pg_list.h:149
#define linitial(l)
Definition: pg_list.h:174
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1988
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
double estimate_num_groups_incremental(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo, List **cache_varinfos, int prevNExprs)
Definition: selfuncs.c:3382
List * ec_members
Definition: pathnodes.h:991
Cost per_tuple
Definition: pathnodes.h:46
Cost startup
Definition: pathnodes.h:45

References add_function_cost(), cpu_operator_cost, EquivalenceClass::ec_members, EquivalenceMember::em_datatype, EquivalenceMember::em_expr, estimate_num_groups_incremental(), get_opcode(), get_opfamily_member(), get_width_cost_multiplier(), i, InvalidOid, is_fake_var(), lappend(), lfirst, linitial, list_free(), list_length(), LOG2, Max, Min, NIL, QualCost::per_tuple, PathKey::pk_eclass, PathKey::pk_opfamily, PathKey::pk_strategy, and QualCost::startup.

Referenced by cost_sort_estimate(), and cost_tuplesort().

◆ compute_semi_anti_join_factors()

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

Definition at line 5031 of file costsize.c.

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

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

Referenced by add_paths_to_joinrel().

◆ cost_agg()

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

Definition at line 2919 of file costsize.c.

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

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

Definition at line 2502 of file costsize.c.

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

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

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1127 of file costsize.c.

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

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

Referenced by create_bitmap_and_path().

◆ cost_bitmap_heap_scan()

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

Definition at line 983 of file costsize.c.

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1171 of file costsize.c.

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

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

Referenced by create_bitmap_or_path().

◆ cost_bitmap_tree_node()

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

Definition at line 1084 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

Definition at line 1650 of file costsize.c.

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

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

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

Definition at line 1483 of file costsize.c.

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

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

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 406 of file costsize.c.

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

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

Referenced by create_gather_path().

◆ cost_gather_merge()

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

Definition at line 444 of file costsize.c.

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

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

Referenced by create_gather_merge_path().

◆ cost_group()

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

Definition at line 3191 of file costsize.c.

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

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

Referenced by choose_hashed_setop(), and create_group_path().

◆ cost_incremental_sort()

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

Definition at line 2255 of file costsize.c.

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

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

Referenced by create_incremental_sort_path().

◆ cost_index()

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

Definition at line 519 of file costsize.c.

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

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

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2724 of file costsize.c.

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

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

Referenced by create_material_path(), and materialize_finished_plan().

◆ cost_memoize_rescan()

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

Definition at line 2780 of file costsize.c.

2782 {
2783  EstimationInfo estinfo;
2784  Cost input_startup_cost = mpath->subpath->startup_cost;
2785  Cost input_total_cost = mpath->subpath->total_cost;
2786  double tuples = mpath->subpath->rows;
2787  double calls = mpath->calls;
2788  int width = mpath->subpath->pathtarget->width;
2789 
2790  double hash_mem_bytes;
2791  double est_entry_bytes;
2792  double est_cache_entries;
2793  double ndistinct;
2794  double evict_ratio;
2795  double hit_ratio;
2796  Cost startup_cost;
2797  Cost total_cost;
2798 
2799  /* available cache space */
2800  hash_mem_bytes = get_hash_memory_limit();
2801 
2802  /*
2803  * Set the number of bytes each cache entry should consume in the cache.
2804  * To provide us with better estimations on how many cache entries we can
2805  * store at once, we make a call to the executor here to ask it what
2806  * memory overheads there are for a single cache entry.
2807  *
2808  * XXX we also store the cache key, but that's not accounted for here.
2809  */
2810  est_entry_bytes = relation_byte_size(tuples, width) +
2812 
2813  /* estimate on the upper limit of cache entries we can hold at once */
2814  est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2815 
2816  /* estimate on the distinct number of parameter values */
2817  ndistinct = estimate_num_groups(root, mpath->param_exprs, calls, NULL,
2818  &estinfo);
2819 
2820  /*
2821  * When the estimation fell back on using a default value, it's a bit too
2822  * risky to assume that it's ok to use a Memoize node. The use of a
2823  * default could cause us to use a Memoize node when it's really
2824  * inappropriate to do so. If we see that this has been done, then we'll
2825  * assume that every call will have unique parameters, which will almost
2826  * certainly mean a MemoizePath will never survive add_path().
2827  */
2828  if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2829  ndistinct = calls;
2830 
2831  /*
2832  * Since we've already estimated the maximum number of entries we can
2833  * store at once and know the estimated number of distinct values we'll be
2834  * called with, we'll take this opportunity to set the path's est_entries.
2835  * This will ultimately determine the hash table size that the executor
2836  * will use. If we leave this at zero, the executor will just choose the
2837  * size itself. Really this is not the right place to do this, but it's
2838  * convenient since everything is already calculated.
2839  */
2840  mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2841  PG_UINT32_MAX);
2842 
2843  /*
2844  * When the number of distinct parameter values is above the amount we can
2845  * store in the cache, then we'll have to evict some entries from the
2846  * cache. This is not free. Here we estimate how often we'll incur the
2847  * cost of that eviction.
2848  */
2849  evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2850 
2851  /*
2852  * In order to estimate how costly a single scan will be, we need to
2853  * attempt to estimate what the cache hit ratio will be. To do that we
2854  * must look at how many scans are estimated in total for this node and
2855  * how many of those scans we expect to get a cache hit.
2856  */
2857  hit_ratio = 1.0 / ndistinct * Min(est_cache_entries, ndistinct) -
2858  (ndistinct / calls);
2859 
2860  /* Ensure we don't go negative */
2861  hit_ratio = Max(hit_ratio, 0.0);
2862 
2863  /*
2864  * Set the total_cost accounting for the expected cache hit ratio. We
2865  * also add on a cpu_operator_cost to account for a cache lookup. This
2866  * will happen regardless of whether it's a cache hit or not.
2867  */
2868  total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2869 
2870  /* Now adjust the total cost to account for cache evictions */
2871 
2872  /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2873  total_cost += cpu_tuple_cost * evict_ratio;
2874 
2875  /*
2876  * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2877  * The per-tuple eviction is really just a pfree, so charging a whole
2878  * cpu_operator_cost seems a little excessive.
2879  */
2880  total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2881 
2882  /*
2883  * Now adjust for storing things in the cache, since that's not free
2884  * either. Everything must go in the cache. We don't proportion this
2885  * over any ratio, just apply it once for the scan. We charge a
2886  * cpu_tuple_cost for the creation of the cache entry and also a
2887  * cpu_operator_cost for each tuple we expect to cache.
2888  */
2889  total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2890 
2891  /*
2892  * Getting the first row must be also be proportioned according to the
2893  * expected cache hit ratio.
2894  */
2895  startup_cost = input_startup_cost * (1.0 - hit_ratio);
2896 
2897  /*
2898  * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2899  * which we'll do regardless of whether it was a cache hit or not.
2900  */
2901  startup_cost += cpu_tuple_cost;
2902 
2903  *rescan_startup_cost = startup_cost;
2904  *rescan_total_cost = total_cost;
2905 }
#define PG_UINT32_MAX
Definition: c.h:525
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3401
double ExecEstimateCacheEntryOverheadBytes(double ntuples)
Definition: nodeMemoize.c:1130
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
uint32 flags
Definition: selfuncs.h:80
uint32 est_entries
Definition: pathnodes.h:1533
Cardinality calls
Definition: pathnodes.h:1532
Path * subpath
Definition: pathnodes.h:1525
List * param_exprs
Definition: pathnodes.h:1527

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

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

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

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

Referenced by create_merge_append_path().

◆ cost_namedtuplestorescan()

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

Definition at line 1691 of file costsize.c.

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

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

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

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

Definition at line 4667 of file costsize.c.

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

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

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

◆ cost_qual_eval_node()

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

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 4707 of file costsize.c.

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

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

Referenced by cost_qual_eval(), and cost_qual_eval_node().

◆ cost_recursive_union()

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

Definition at line 1765 of file costsize.c.

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

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

Referenced by create_recursiveunion_path().

◆ cost_rescan()

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

Definition at line 4555 of file costsize.c.

4558 {
4559  switch (path->pathtype)
4560  {
4561  case T_FunctionScan:
4562 
4563  /*
4564  * Currently, nodeFunctionscan.c always executes the function to
4565  * completion before returning any rows, and caches the results in
4566  * a tuplestore. So the function eval cost is all startup cost
4567  * and isn't paid over again on rescans. However, all run costs
4568  * will be paid over again.
4569  */
4570  *rescan_startup_cost = 0;
4571  *rescan_total_cost = path->total_cost - path->startup_cost;
4572  break;
4573  case T_HashJoin:
4574 
4575  /*
4576  * If it's a single-batch join, we don't need to rebuild the hash
4577  * table during a rescan.
4578  */
4579  if (((HashPath *) path)->num_batches == 1)
4580  {
4581  /* Startup cost is exactly the cost of hash table building */
4582  *rescan_startup_cost = 0;
4583  *rescan_total_cost = path->total_cost - path->startup_cost;
4584  }
4585  else
4586  {
4587  /* Otherwise, no special treatment */
4588  *rescan_startup_cost = path->startup_cost;
4589  *rescan_total_cost = path->total_cost;
4590  }
4591  break;
4592  case T_CteScan:
4593  case T_WorkTableScan:
4594  {
4595  /*
4596  * These plan types materialize their final result in a
4597  * tuplestore or tuplesort object. So the rescan cost is only
4598  * cpu_tuple_cost per tuple, unless the result is large enough
4599  * to spill to disk.
4600  */
4601  Cost run_cost = cpu_tuple_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_Material:
4618  case T_Sort:
4619  {
4620  /*
4621  * These plan types not only materialize their results, but do
4622  * not implement qual filtering or projection. So they are
4623  * even cheaper to rescan than the ones above. We charge only
4624  * cpu_operator_cost per tuple. (Note: keep that in sync with
4625  * the run_cost charge in cost_sort, and also see comments in
4626  * cost_material before you change it.)
4627  */
4628  Cost run_cost = cpu_operator_cost * path->rows;
4629  double nbytes = relation_byte_size(path->rows,
4630  path->pathtarget->width);
4631  long work_mem_bytes = work_mem * 1024L;
4632 
4633  if (nbytes > work_mem_bytes)
4634  {
4635  /* It will spill, so account for re-read cost */
4636  double npages = ceil(nbytes / BLCKSZ);
4637 
4638  run_cost += seq_page_cost * npages;
4639  }
4640  *rescan_startup_cost = 0;
4641  *rescan_total_cost = run_cost;
4642  }
4643  break;
4644  case T_Memoize:
4645  /* All the hard work is done by cost_memoize_rescan */
4646  cost_memoize_rescan(root, (MemoizePath *) path,
4647  rescan_startup_cost, rescan_total_cost);
4648  break;
4649  default:
4650  *rescan_startup_cost = path->startup_cost;
4651  *rescan_total_cost = path->total_cost;
4652  break;
4653  }
4654 }
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:2780
@ T_FunctionScan
Definition: nodes.h:65
@ T_Material
Definition: nodes.h:77
@ T_Memoize
Definition: nodes.h:78
@ T_Sort
Definition: nodes.h:79
@ T_CteScan
Definition: nodes.h:68
@ T_WorkTableScan
Definition: nodes.h:70
@ T_HashJoin
Definition: nodes.h:76

References cost_memoize_rescan(), cpu_operator_cost, cpu_tuple_cost, Path::pathtype, relation_byte_size(), seq_page_cost, Path::startup_cost, T_CteScan, T_FunctionScan, T_HashJoin, T_Material, T_Memoize, T_Sort, T_WorkTableScan, 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 1728 of file costsize.c.

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

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

Referenced by create_resultscan_path().

◆ cost_samplescan()

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

Definition at line 331 of file costsize.c.

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

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

Referenced by create_samplescan_path().

◆ cost_seqscan()

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

Definition at line 254 of file costsize.c.

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

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

Referenced by create_seqscan_path().

◆ cost_sort()

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

Definition at line 2395 of file costsize.c.

2400 {
2401  Cost startup_cost;
2402  Cost run_cost;
2403 
2404  cost_tuplesort(root, pathkeys, &startup_cost, &run_cost,
2405  tuples, width,
2406  comparison_cost, sort_mem,
2407  limit_tuples);
2408 
2409  if (!enable_sort)
2410  startup_cost += disable_cost;
2411 
2412  startup_cost += input_cost;
2413 
2414  path->rows = tuples;
2415  path->startup_cost = startup_cost;
2416  path->total_cost = startup_cost + run_cost;
2417 }
bool enable_sort
Definition: costsize.c:140

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

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

◆ cost_sort_estimate()

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

Definition at line 2113 of file costsize.c.

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

References compute_cpu_sort_cost().

Referenced by get_cheapest_group_keys_order().

◆ cost_subplan()

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

Definition at line 4462 of file costsize.c.

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

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

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

◆ cost_subqueryscan()

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

Definition at line 1420 of file costsize.c.

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

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

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

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

Definition at line 1544 of file costsize.c.

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

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

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1327 of file costsize.c.

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

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

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1219 of file costsize.c.

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

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

Referenced by create_tidscan_path().

◆ cost_tuplesort()

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

Definition at line 2159 of file costsize.c.

2163 {
2164  double input_bytes = relation_byte_size(tuples, width);
2165  double output_bytes;
2166  double output_tuples;
2167  long sort_mem_bytes = sort_mem * 1024L;
2168 
2169  /*
2170  * We want to be sure the cost of a sort is never estimated as zero, even
2171  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
2172  */
2173  if (tuples < 2.0)
2174  tuples = 2.0;
2175 
2176  /* Do we have a useful LIMIT? */
2177  if (limit_tuples > 0 && limit_tuples < tuples)
2178  {
2179  output_tuples = limit_tuples;
2180  output_bytes = relation_byte_size(output_tuples, width);
2181  }
2182  else
2183  {
2184  output_tuples = tuples;
2185  output_bytes = input_bytes;
2186  }
2187 
2188  if (output_bytes > sort_mem_bytes)
2189  {
2190  /*
2191  * We'll have to use a disk-based sort of all the tuples
2192  */
2193  double npages = ceil(input_bytes / BLCKSZ);
2194  double nruns = input_bytes / sort_mem_bytes;
2195  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
2196  double log_runs;
2197  double npageaccesses;
2198 
2199  /* CPU costs */
2200  *startup_cost = compute_cpu_sort_cost(root, pathkeys, 0,
2201  comparison_cost, tuples,
2202  tuples, false);
2203 
2204  /* Disk costs */
2205 
2206  /* Compute logM(r) as log(r) / log(M) */
2207  if (nruns > mergeorder)
2208  log_runs = ceil(log(nruns) / log(mergeorder));
2209  else
2210  log_runs = 1.0;
2211  npageaccesses = 2.0 * npages * log_runs;
2212  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
2213  *startup_cost += npageaccesses *
2214  (seq_page_cost * 0.75 + random_page_cost * 0.25);
2215  }
2216  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
2217  {
2218  /* We'll use a bounded heap-sort keeping just K tuples in memory. */
2219  *startup_cost = compute_cpu_sort_cost(root, pathkeys, 0,
2220  comparison_cost, tuples,
2221  output_tuples, true);
2222  }
2223  else
2224  {
2225  /* We'll use plain quicksort on all the input tuples */
2226  *startup_cost = compute_cpu_sort_cost(root, pathkeys, 0,
2227  comparison_cost, tuples,
2228  tuples, false);
2229  }
2230 
2231  /*
2232  * Also charge a small amount (arbitrarily set equal to operator cost) per
2233  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
2234  * doesn't do qual-checking or projection, so it has less overhead than
2235  * most plan nodes. Note it's correct to use tuples not output_tuples
2236  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
2237  * counting the LIMIT otherwise.
2238  */
2239  *run_cost = cpu_operator_cost * tuples;
2240 }
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2755

References compute_cpu_sort_cost(), cpu_operator_cost, 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 1600 of file costsize.c.

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

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

Referenced by create_valuesscan_path().

◆ cost_windowagg()

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

Definition at line 3117 of file costsize.c.

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

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

Referenced by create_windowagg_path().

◆ extract_nonindex_conditions()

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

Definition at line 810 of file costsize.c.

811 {
812  List *result = NIL;
813  ListCell *lc;
814 
815  foreach(lc, qual_clauses)
816  {
817  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
818 
819  if (rinfo->pseudoconstant)
820  continue; /* we may drop pseudoconstants here */
821  if (is_redundant_with_indexclauses(rinfo, indexclauses))
822  continue; /* dup or derived from same EquivalenceClass */
823  /* ... skip the predicate proof attempt createplan.c will try ... */
824  result = lappend(result, rinfo);
825  }
826  return result;
827 }
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:3158

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

Referenced by cost_index().

◆ final_cost_hashjoin()

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

Definition at line 4208 of file costsize.c.

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

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3772 of file costsize.c.

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

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

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3336 of file costsize.c.

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

References clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_nestloop, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOI