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

Go to the source code of this file.

Data Structures

struct  cost_qual_eval_context
 

Macros

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

Functions

static Listextract_nonindex_conditions (List *qual_clauses, List *indexclauses)
 
static MergeScanSelCachecached_scansel (PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
 
static void cost_rescan (PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
static bool cost_qual_eval_walker (Node *node, cost_qual_eval_context *context)
 
static void get_restriction_qual_cost (PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
 
static bool has_indexed_join_quals (NestPath *path)
 
static double approx_tuple_count (PlannerInfo *root, JoinPath *path, List *quals)
 
static double calc_joinrel_size_estimate (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
 
static Selectivity get_foreign_key_join_selectivity (PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
 
static Cost append_nonpartial_cost (List *subpaths, int numpaths, int parallel_workers)
 
static void set_rel_width (PlannerInfo *root, RelOptInfo *rel)
 
static int32 get_expr_width (PlannerInfo *root, const Node *expr)
 
static double relation_byte_size (double tuples, int width)
 
static double page_size (double tuples, int width)
 
static double get_parallel_divisor (Path *path)
 
double clamp_row_est (double nrows)
 
int32 clamp_width_est (int64 tuple_width)
 
long clamp_cardinality_to_long (Cardinality x)
 
void cost_seqscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_samplescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
static double get_indexpath_pages (Path *bitmapqual)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, bool trivial_pathtarget)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_ctescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_namedtuplestorescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_resultscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
static void cost_tuplesort (Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_incremental_sort (Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, int input_disabled_nodes, 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, int input_disabled_nodes, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *apath)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, int input_disabled_nodes, 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, int disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
static double get_windowclause_startup_tuples (PlannerInfo *root, WindowClause *wc, double input_tuples)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, WindowClause *winclause, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
 
double compute_gather_rows (Path *path)
 

Variables

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

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 120 of file costsize.c.

◆ LOG2

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

Definition at line 113 of file costsize.c.

◆ MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

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

2175 {
2176  Cost *costarr;
2177  int arrlen;
2178  ListCell *l;
2179  ListCell *cell;
2180  int path_index;
2181  int min_index;
2182  int max_index;
2183 
2184  if (numpaths == 0)
2185  return 0;
2186 
2187  /*
2188  * Array length is number of workers or number of relevant paths,
2189  * whichever is less.
2190  */
2191  arrlen = Min(parallel_workers, numpaths);
2192  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2193 
2194  /* The first few paths will each be claimed by a different worker. */
2195  path_index = 0;
2196  foreach(cell, subpaths)
2197  {
2198  Path *subpath = (Path *) lfirst(cell);
2199 
2200  if (path_index == arrlen)
2201  break;
2202  costarr[path_index++] = subpath->total_cost;
2203  }
2204 
2205  /*
2206  * Since subpaths are sorted by decreasing cost, the last one will have
2207  * the minimum cost.
2208  */
2209  min_index = arrlen - 1;
2210 
2211  /*
2212  * For each of the remaining subpaths, add its cost to the array element
2213  * with minimum cost.
2214  */
2215  for_each_cell(l, subpaths, cell)
2216  {
2217  Path *subpath = (Path *) lfirst(l);
2218 
2219  /* Consider only the non-partial paths */
2220  if (path_index++ == numpaths)
2221  break;
2222 
2223  costarr[min_index] += subpath->total_cost;
2224 
2225  /* Update the new min cost array index */
2226  min_index = 0;
2227  for (int i = 0; i < arrlen; i++)
2228  {
2229  if (costarr[i] < costarr[min_index])
2230  min_index = i;
2231  }
2232  }
2233 
2234  /* Return the highest cost from the array */
2235  max_index = 0;
2236  for (int i = 0; i < arrlen; i++)
2237  {
2238  if (costarr[i] > costarr[max_index])
2239  max_index = i;
2240  }
2241 
2242  return costarr[max_index];
2243 }
#define Min(x, y)
Definition: c.h:958
int i
Definition: isn.c:72
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:308
void * palloc(Size size)
Definition: mcxt.c:1317
double Cost
Definition: nodes.h:251
#define lfirst(lc)
Definition: pg_list.h:172
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438

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

Referenced by cost_append().

◆ approx_tuple_count()

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

Definition at line 5280 of file costsize.c.

5281 {
5282  double tuples;
5283  double outer_tuples = path->outerjoinpath->rows;
5284  double inner_tuples = path->innerjoinpath->rows;
5285  SpecialJoinInfo sjinfo;
5286  Selectivity selec = 1.0;
5287  ListCell *l;
5288 
5289  /*
5290  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5291  */
5292  init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
5293  path->innerjoinpath->parent->relids);
5294 
5295  /* Get the approximate selectivity */
5296  foreach(l, quals)
5297  {
5298  Node *qual = (Node *) lfirst(l);
5299 
5300  /* Note that clause_selectivity will be able to cache its result */
5301  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5302  }
5303 
5304  /* Apply it to the input relation sizes */
5305  tuples = selec * outer_tuples * inner_tuples;
5306 
5307  return clamp_row_est(tuples);
5308 }
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:667
double clamp_row_est(double nrows)
Definition: costsize.c:213
void init_dummy_sjinfo(SpecialJoinInfo *sjinfo, Relids left_relids, Relids right_relids)
Definition: joinrels.c:669
double Selectivity
Definition: nodes.h:250
@ JOIN_INNER
Definition: nodes.h:293
tree ctl root
Definition: radixtree.h:1886
Path * outerjoinpath
Definition: pathnodes.h:2084
Path * innerjoinpath
Definition: pathnodes.h:2085
Definition: nodes.h:129
Cardinality rows
Definition: pathnodes.h:1669

References clamp_row_est(), clause_selectivity(), init_dummy_sjinfo(), JoinPath::innerjoinpath, JOIN_INNER, lfirst, JoinPath::outerjoinpath, root, and Path::rows.

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

4082 {
4083  MergeScanSelCache *cache;
4084  ListCell *lc;
4085  Selectivity leftstartsel,
4086  leftendsel,
4087  rightstartsel,
4088  rightendsel;
4089  MemoryContext oldcontext;
4090 
4091  /* Do we have this result already? */
4092  foreach(lc, rinfo->scansel_cache)
4093  {
4094  cache = (MergeScanSelCache *) lfirst(lc);
4095  if (cache->opfamily == pathkey->pk_opfamily &&
4096  cache->collation == pathkey->pk_eclass->ec_collation &&
4097  cache->strategy == pathkey->pk_strategy &&
4098  cache->nulls_first == pathkey->pk_nulls_first)
4099  return cache;
4100  }
4101 
4102  /* Nope, do the computation */
4104  (Node *) rinfo->clause,
4105  pathkey->pk_opfamily,
4106  pathkey->pk_strategy,
4107  pathkey->pk_nulls_first,
4108  &leftstartsel,
4109  &leftendsel,
4110  &rightstartsel,
4111  &rightendsel);
4112 
4113  /* Cache the result in suitably long-lived workspace */
4114  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4115 
4116  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
4117  cache->opfamily = pathkey->pk_opfamily;
4118  cache->collation = pathkey->pk_eclass->ec_collation;
4119  cache->strategy = pathkey->pk_strategy;
4120  cache->nulls_first = pathkey->pk_nulls_first;
4121  cache->leftstartsel = leftstartsel;
4122  cache->leftendsel = leftendsel;
4123  cache->rightstartsel = rightstartsel;
4124  cache->rightendsel = rightendsel;
4125 
4126  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4127 
4128  MemoryContextSwitchTo(oldcontext);
4129 
4130  return cache;
4131 }
List * lappend(List *list, void *datum)
Definition: list.c:339
MemoryContextSwitchTo(old_ctx)
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2955
Selectivity leftstartsel
Definition: pathnodes.h:2750
Selectivity leftendsel
Definition: pathnodes.h:2751
Selectivity rightendsel
Definition: pathnodes.h:2753
Selectivity rightstartsel
Definition: pathnodes.h:2752
bool pk_nulls_first
Definition: pathnodes.h:1480
int pk_strategy
Definition: pathnodes.h:1479
Oid pk_opfamily
Definition: pathnodes.h:1478
Expr * clause
Definition: pathnodes.h:2574

References RestrictInfo::clause, MergeScanSelCache::collation, lappend(), MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, lfirst, MemoryContextSwitchTo(), mergejoinscansel(), MergeScanSelCache::nulls_first, MergeScanSelCache::opfamily, palloc(), PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, root, 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 5477 of file costsize.c.

5485 {
5486  JoinType jointype = sjinfo->jointype;
5487  Selectivity fkselec;
5488  Selectivity jselec;
5489  Selectivity pselec;
5490  double nrows;
5491 
5492  /*
5493  * Compute joinclause selectivity. Note that we are only considering
5494  * clauses that become restriction clauses at this join level; we are not
5495  * double-counting them because they were not considered in estimating the
5496  * sizes of the component rels.
5497  *
5498  * First, see whether any of the joinclauses can be matched to known FK
5499  * constraints. If so, drop those clauses from the restrictlist, and
5500  * instead estimate their selectivity using FK semantics. (We do this
5501  * without regard to whether said clauses are local or "pushed down".
5502  * Probably, an FK-matching clause could never be seen as pushed down at
5503  * an outer join, since it would be strict and hence would be grounds for
5504  * join strength reduction.) fkselec gets the net selectivity for
5505  * FK-matching clauses, or 1.0 if there are none.
5506  */
5508  outer_rel->relids,
5509  inner_rel->relids,
5510  sjinfo,
5511  &restrictlist);
5512 
5513  /*
5514  * For an outer join, we have to distinguish the selectivity of the join's
5515  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5516  * down". For inner joins we just count them all as joinclauses.
5517  */
5518  if (IS_OUTER_JOIN(jointype))
5519  {
5520  List *joinquals = NIL;
5521  List *pushedquals = NIL;
5522  ListCell *l;
5523 
5524  /* Grovel through the clauses to separate into two lists */
5525  foreach(l, restrictlist)
5526  {
5527  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5528 
5529  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5530  pushedquals = lappend(pushedquals, rinfo);
5531  else
5532  joinquals = lappend(joinquals, rinfo);
5533  }
5534 
5535  /* Get the separate selectivities */
5536  jselec = clauselist_selectivity(root,
5537  joinquals,
5538  0,
5539  jointype,
5540  sjinfo);
5541  pselec = clauselist_selectivity(root,
5542  pushedquals,
5543  0,
5544  jointype,
5545  sjinfo);
5546 
5547  /* Avoid leaking a lot of ListCells */
5548  list_free(joinquals);
5549  list_free(pushedquals);
5550  }
5551  else
5552  {
5553  jselec = clauselist_selectivity(root,
5554  restrictlist,
5555  0,
5556  jointype,
5557  sjinfo);
5558  pselec = 0.0; /* not used, keep compiler quiet */
5559  }
5560 
5561  /*
5562  * Basically, we multiply size of Cartesian product by selectivity.
5563  *
5564  * If we are doing an outer join, take that into account: the joinqual
5565  * selectivity has to be clamped using the knowledge that the output must
5566  * be at least as large as the non-nullable input. However, any
5567  * pushed-down quals are applied after the outer join, so their
5568  * selectivity applies fully.
5569  *
5570  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5571  * of LHS rows that have matches, and we apply that straightforwardly.
5572  */
5573  switch (jointype)
5574  {
5575  case JOIN_INNER:
5576  nrows = outer_rows * inner_rows * fkselec * jselec;
5577  /* pselec not used */
5578  break;
5579  case JOIN_LEFT:
5580  nrows = outer_rows * inner_rows * fkselec * jselec;
5581  if (nrows < outer_rows)
5582  nrows = outer_rows;
5583  nrows *= pselec;
5584  break;
5585  case JOIN_FULL:
5586  nrows = outer_rows * inner_rows * fkselec * jselec;
5587  if (nrows < outer_rows)
5588  nrows = outer_rows;
5589  if (nrows < inner_rows)
5590  nrows = inner_rows;
5591  nrows *= pselec;
5592  break;
5593  case JOIN_SEMI:
5594  nrows = outer_rows * fkselec * jselec;
5595  /* pselec not used */
5596  break;
5597  case JOIN_ANTI:
5598  nrows = outer_rows * (1.0 - fkselec * jselec);
5599  nrows *= pselec;
5600  break;
5601  default:
5602  /* other values not expected here */
5603  elog(ERROR, "unrecognized join type: %d", (int) jointype);
5604  nrows = 0; /* keep compiler quiet */
5605  break;
5606  }
5607 
5608  return clamp_row_est(nrows);
5609 }
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:5627
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
void list_free(List *list)
Definition: list.c:1546
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:338
JoinType
Definition: nodes.h:288
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_LEFT
Definition: nodes.h:294
@ JOIN_ANTI
Definition: nodes.h:308
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2731
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
Definition: pg_list.h:54
Relids relids
Definition: pathnodes.h:871
JoinType jointype
Definition: pathnodes.h:2908

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, RINFO_IS_PUSHED_DOWN, and root.

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

266 {
267  /*
268  * Just for paranoia's sake, ensure we do something sane with negative or
269  * NaN values.
270  */
271  if (isnan(x))
272  return LONG_MAX;
273  if (x <= 0)
274  return 0;
275 
276  /*
277  * If "long" is 64 bits, then LONG_MAX cannot be represented exactly as a
278  * double. Casting it to double and back may well result in overflow due
279  * to rounding, so avoid doing that. We trust that any double value that
280  * compares strictly less than "(double) LONG_MAX" will cast to a
281  * representable "long" value.
282  */
283  return (x < (double) LONG_MAX) ? (long) x : LONG_MAX;
284 }
int x
Definition: isn.c:70

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

214 {
215  /*
216  * Avoid infinite and NaN row estimates. Costs derived from such values
217  * are going to be useless. Also force the estimate to be at least one
218  * row, to make explain output look better and to avoid possible
219  * divide-by-zero when interpolating costs. Make it an integer, too.
220  */
221  if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
222  nrows = MAXIMUM_ROWCOUNT;
223  else if (nrows <= 1.0)
224  nrows = 1.0;
225  else
226  nrows = rint(nrows);
227 
228  return nrows;
229 }
#define MAXIMUM_ROWCOUNT
Definition: costsize.c:128

References MAXIMUM_ROWCOUNT.

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

◆ clamp_width_est()

int32 clamp_width_est ( int64  tuple_width)

Definition at line 242 of file costsize.c.

243 {
244  /*
245  * Anything more than MaxAllocSize is clearly bogus, since we could not
246  * create a tuple that large.
247  */
248  if (tuple_width > MaxAllocSize)
249  return (int32) MaxAllocSize;
250 
251  /*
252  * Unlike clamp_row_est, we just Assert that the value isn't negative,
253  * rather than masking such errors.
254  */
255  Assert(tuple_width >= 0);
256 
257  return (int32) tuple_width;
258 }
#define Assert(condition)
Definition: c.h:812
int32_t int32
Definition: c.h:481
#define MaxAllocSize
Definition: fe_memutils.h:22

References Assert, and MaxAllocSize.

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

◆ compute_bitmap_pages()

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

Definition at line 6489 of file costsize.c.

6492 {
6493  Cost indexTotalCost;
6494  Selectivity indexSelectivity;
6495  double T;
6496  double pages_fetched;
6497  double tuples_fetched;
6498  double heap_pages;
6499  long maxentries;
6500 
6501  /*
6502  * Fetch total cost of obtaining the bitmap, as well as its total
6503  * selectivity.
6504  */
6505  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6506 
6507  /*
6508  * Estimate number of main-table pages fetched.
6509  */
6510  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6511 
6512  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6513 
6514  /*
6515  * For a single scan, the number of heap pages that need to be fetched is
6516  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6517  * re-reads needed).
6518  */
6519  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6520 
6521  /*
6522  * Calculate the number of pages fetched from the heap. Then based on
6523  * current work_mem estimate get the estimated maxentries in the bitmap.
6524  * (Note that we always do this calculation based on the number of pages
6525  * that would be fetched in a single iteration, even if loop_count > 1.
6526  * That's correct, because only that number of entries will be stored in
6527  * the bitmap at one time.)
6528  */
6529  heap_pages = Min(pages_fetched, baserel->pages);
6530  maxentries = tbm_calculate_entries(work_mem * 1024L);
6531 
6532  if (loop_count > 1)
6533  {
6534  /*
6535  * For repeated bitmap scans, scale up the number of tuples fetched in
6536  * the Mackert and Lohman formula by the number of scans, so that we
6537  * estimate the number of pages fetched by all the scans. Then
6538  * pro-rate for one scan.
6539  */
6540  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6541  baserel->pages,
6542  get_indexpath_pages(bitmapqual),
6543  root);
6544  pages_fetched /= loop_count;
6545  }
6546 
6547  if (pages_fetched >= T)
6548  pages_fetched = T;
6549  else
6550  pages_fetched = ceil(pages_fetched);
6551 
6552  if (maxentries < heap_pages)
6553  {
6554  double exact_pages;
6555  double lossy_pages;
6556 
6557  /*
6558  * Crude approximation of the number of lossy pages. Because of the
6559  * way tbm_lossify() is coded, the number of lossy pages increases
6560  * very sharply as soon as we run short of memory; this formula has
6561  * that property and seems to perform adequately in testing, but it's
6562  * possible we could do better somehow.
6563  */
6564  lossy_pages = Max(0, heap_pages - maxentries / 2);
6565  exact_pages = heap_pages - lossy_pages;
6566 
6567  /*
6568  * If there are lossy pages then recompute the number of tuples
6569  * processed by the bitmap heap node. We assume here that the chance
6570  * of a given tuple coming from an exact page is the same as the
6571  * chance that a given page is exact. This might not be true, but
6572  * it's not clear how we can do any better.
6573  */
6574  if (lossy_pages > 0)
6575  tuples_fetched =
6576  clamp_row_est(indexSelectivity *
6577  (exact_pages / heap_pages) * baserel->tuples +
6578  (lossy_pages / heap_pages) * baserel->tuples);
6579  }
6580 
6581  if (cost_p)
6582  *cost_p = indexTotalCost;
6583  if (tuples_p)
6584  *tuples_p = tuples_fetched;
6585 
6586  return pages_fetched;
6587 }
#define Max(x, y)
Definition: c.h:952
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:908
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1122
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:973
int work_mem
Definition: globals.c:130
static const uint32 T[65]
Definition: md5.c:119
Cardinality tuples
Definition: pathnodes.h:949
BlockNumber pages
Definition: pathnodes.h:948
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1542

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_gather_rows()

double compute_gather_rows ( Path path)

Definition at line 6600 of file costsize.c.

6601 {
6602  Assert(path->parallel_workers > 0);
6603 
6604  return clamp_row_est(path->rows * get_parallel_divisor(path));
6605 }
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6449
int parallel_workers
Definition: pathnodes.h:1666

References Assert, clamp_row_est(), get_parallel_divisor(), Path::parallel_workers, and Path::rows.

Referenced by create_ordered_paths(), gather_grouping_paths(), generate_gather_paths(), and generate_useful_gather_paths().

◆ compute_semi_anti_join_factors()

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

Definition at line 5090 of file costsize.c.

5098 {
5099  Selectivity jselec;
5100  Selectivity nselec;
5101  Selectivity avgmatch;
5102  SpecialJoinInfo norm_sjinfo;
5103  List *joinquals;
5104  ListCell *l;
5105 
5106  /*
5107  * In an ANTI join, we must ignore clauses that are "pushed down", since
5108  * those won't affect the match logic. In a SEMI join, we do not
5109  * distinguish joinquals from "pushed down" quals, so just use the whole
5110  * restrictinfo list. For other outer join types, we should consider only
5111  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5112  */
5113  if (IS_OUTER_JOIN(jointype))
5114  {
5115  joinquals = NIL;
5116  foreach(l, restrictlist)
5117  {
5118  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5119 
5120  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5121  joinquals = lappend(joinquals, rinfo);
5122  }
5123  }
5124  else
5125  joinquals = restrictlist;
5126 
5127  /*
5128  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5129  */
5130  jselec = clauselist_selectivity(root,
5131  joinquals,
5132  0,
5133  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5134  sjinfo);
5135 
5136  /*
5137  * Also get the normal inner-join selectivity of the join clauses.
5138  */
5139  init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5140 
5141  nselec = clauselist_selectivity(root,
5142  joinquals,
5143  0,
5144  JOIN_INNER,
5145  &norm_sjinfo);
5146 
5147  /* Avoid leaking a lot of ListCells */
5148  if (IS_OUTER_JOIN(jointype))
5149  list_free(joinquals);
5150 
5151  /*
5152  * jselec can be interpreted as the fraction of outer-rel rows that have
5153  * any matches (this is true for both SEMI and ANTI cases). And nselec is
5154  * the fraction of the Cartesian product that matches. So, the average
5155  * number of matches for each outer-rel row that has at least one match is
5156  * nselec * inner_rows / jselec.
5157  *
5158  * Note: it is correct to use the inner rel's "rows" count here, even
5159  * though we might later be considering a parameterized inner path with
5160  * fewer rows. This is because we have included all the join clauses in
5161  * the selectivity estimate.
5162  */
5163  if (jselec > 0) /* protect against zero divide */
5164  {
5165  avgmatch = nselec * innerrel->rows / jselec;
5166  /* Clamp to sane range */
5167  avgmatch = Max(1.0, avgmatch);
5168  }
5169  else
5170  avgmatch = 1.0;
5171 
5172  semifactors->outer_match_frac = jselec;
5173  semifactors->match_count = avgmatch;
5174 }
Cardinality rows
Definition: pathnodes.h:877
Selectivity outer_match_frac
Definition: pathnodes.h:3221
Selectivity match_count
Definition: pathnodes.h:3222

References clauselist_selectivity(), init_dummy_sjinfo(), IS_OUTER_JOIN, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, lappend(), lfirst_node, list_free(), SemiAntiJoinFactors::match_count, Max, NIL, SemiAntiJoinFactors::outer_match_frac, RelOptInfo::relids, RINFO_IS_PUSHED_DOWN, root, and RelOptInfo::rows.

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,
int  disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples,
double  input_width 
)

Definition at line 2682 of file costsize.c.

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

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Assert, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, 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(), root, Path::rows, seq_page_cost, QualCost::startup, Path::startup_cost, Path::total_cost, AggClauseCosts::transCost, and AggClauseCosts::transitionSpace.

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

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2250 of file costsize.c.

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

References APPEND_CPU_COST_MULTIPLIER, append_nonpartial_cost(), Assert, clamp_row_est(), cost_sort(), cpu_tuple_cost, Path::disabled_nodes, 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 1165 of file costsize.c.

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

References BitmapAndPath::bitmapquals, BitmapAndPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, Path::disabled_nodes, 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 1023 of file costsize.c.

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

References Assert, clamp_row_est(), compute_bitmap_pages(), cpu_tuple_cost, Path::disabled_nodes, enable_bitmapscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, RelOptInfo::pages, Path::parallel_workers, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, 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 1210 of file costsize.c.

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

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

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

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

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

◆ cost_ctescan()

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

Definition at line 1708 of file costsize.c.

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

References Assert, cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, 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 1538 of file costsize.c.

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

References Assert, cost_qual_eval_node(), cpu_tuple_cost, Path::disabled_nodes, RangeTblEntry::functions, get_restriction_qual_cost(), QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, 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 446 of file costsize.c.

449 {
450  Cost startup_cost = 0;
451  Cost run_cost = 0;
452 
453  /* Mark the path with the correct row estimate */
454  if (rows)
455  path->path.rows = *rows;
456  else if (param_info)
457  path->path.rows = param_info->ppi_rows;
458  else
459  path->path.rows = rel->rows;
460 
461  startup_cost = path->subpath->startup_cost;
462 
463  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
464 
465  /* Parallel setup and communication cost. */
466  startup_cost += parallel_setup_cost;
467  run_cost += parallel_tuple_cost * path->path.rows;
468 
469  path->path.disabled_nodes = path->subpath->disabled_nodes;
470  path->path.startup_cost = startup_cost;
471  path->path.total_cost = (startup_cost + run_cost);
472 }
double parallel_setup_cost
Definition: costsize.c:136
double parallel_tuple_cost
Definition: costsize.c:135
Path * subpath
Definition: pathnodes.h:2052

References Path::disabled_nodes, 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,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double *  rows 
)

Definition at line 485 of file costsize.c.

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

References Assert, cpu_operator_cost, Path::disabled_nodes, 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,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 3196 of file costsize.c.

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

References clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, Path::disabled_nodes, JOIN_INNER, QualCost::per_tuple, root, 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,
int  input_disabled_nodes,
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 2000 of file costsize.c.

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

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

Referenced by create_incremental_sort_path(), initial_cost_mergejoin(), and label_incrementalsort_with_costsize().

◆ cost_index()

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

Definition at line 560 of file costsize.c.

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

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

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2483 of file costsize.c.

2487 {
2488  Cost startup_cost = input_startup_cost;
2489  Cost run_cost = input_total_cost - input_startup_cost;
2490  double nbytes = relation_byte_size(tuples, width);
2491  long work_mem_bytes = work_mem * 1024L;
2492 
2493  path->rows = tuples;
2494 
2495  /*
2496  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2497  * reflect bookkeeping overhead. (This rate must be more than what
2498  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2499  * if it is exactly the same then there will be a cost tie between
2500  * nestloop with A outer, materialized B inner and nestloop with B outer,
2501  * materialized A inner. The extra cost ensures we'll prefer
2502  * materializing the smaller rel.) Note that this is normally a good deal
2503  * less than cpu_tuple_cost; which is OK because a Material plan node
2504  * doesn't do qual-checking or projection, so it's got less overhead than
2505  * most plan nodes.
2506  */
2507  run_cost += 2 * cpu_operator_cost * tuples;
2508 
2509  /*
2510  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2511  * This cost is assumed to be evenly spread through the plan run phase,
2512  * which isn't exactly accurate but our cost model doesn't allow for
2513  * nonuniform costs within the run phase.
2514  */
2515  if (nbytes > work_mem_bytes)
2516  {
2517  double npages = ceil(nbytes / BLCKSZ);
2518 
2519  run_cost += seq_page_cost * npages;
2520  }
2521 
2522  path->disabled_nodes = input_disabled_nodes + (enable_material ? 0 : 1);
2523  path->startup_cost = startup_cost;
2524  path->total_cost = startup_cost + run_cost;
2525 }
bool enable_material
Definition: costsize.c:154

References cpu_operator_cost, Path::disabled_nodes, enable_material, 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 2541 of file costsize.c.

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

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

Referenced by cost_rescan().

◆ cost_merge_append()

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

Definition at line 2432 of file costsize.c.

2437 {
2438  Cost startup_cost = 0;
2439  Cost run_cost = 0;
2440  Cost comparison_cost;
2441  double N;
2442  double logN;
2443 
2444  /*
2445  * Avoid log(0)...
2446  */
2447  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2448  logN = LOG2(N);
2449 
2450  /* Assumed cost per tuple comparison */
2451  comparison_cost = 2.0 * cpu_operator_cost;
2452 
2453  /* Heap creation cost */
2454  startup_cost += comparison_cost * N * logN;
2455 
2456  /* Per-tuple heap maintenance cost */
2457  run_cost += tuples * comparison_cost * logN;
2458 
2459  /*
2460  * Although MergeAppend does not do any selection or projection, it's not
2461  * free; add a small per-tuple overhead.
2462  */
2463  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2464 
2465  path->disabled_nodes = input_disabled_nodes;
2466  path->startup_cost = startup_cost + input_startup_cost;
2467  path->total_cost = startup_cost + run_cost + input_total_cost;
2468 }

References APPEND_CPU_COST_MULTIPLIER, cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, 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 1750 of file costsize.c.

1752 {
1753  Cost startup_cost = 0;
1754  Cost run_cost = 0;
1755  QualCost qpqual_cost;
1756  Cost cpu_per_tuple;
1757 
1758  /* Should only be applied to base relations that are Tuplestores */
1759  Assert(baserel->relid > 0);
1760  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1761 
1762  /* Mark the path with the correct row estimate */
1763  if (param_info)
1764  path->rows = param_info->ppi_rows;
1765  else
1766  path->rows = baserel->rows;
1767 
1768  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1769  cpu_per_tuple = cpu_tuple_cost;
1770 
1771  /* Add scanning CPU costs */
1772  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1773 
1774  startup_cost += qpqual_cost.startup;
1775  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1776  run_cost += cpu_per_tuple * baserel->tuples;
1777 
1778  path->disabled_nodes = 0;
1779  path->startup_cost = startup_cost;
1780  path->total_cost = startup_cost + run_cost;
1781 }
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1024

References Assert, cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, 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 4732 of file costsize.c.

4733 {
4735  ListCell *l;
4736 
4737  context.root = root;
4738  context.total.startup = 0;
4739  context.total.per_tuple = 0;
4740 
4741  /* We don't charge any cost for the implicit ANDing at top level ... */
4742 
4743  foreach(l, quals)
4744  {
4745  Node *qual = (Node *) lfirst(l);
4746 
4748  }
4749 
4750  *cost = context.total;
4751 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4772
tree context
Definition: radixtree.h:1835

References context, cost_qual_eval_walker(), lfirst, and root.

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

4773 {
4774  if (node == NULL)
4775  return false;
4776 
4777  /*
4778  * RestrictInfo nodes contain an eval_cost field reserved for this
4779  * routine's use, so that it's not necessary to evaluate the qual clause's
4780  * cost more than once. If the clause's cost hasn't been computed yet,
4781  * the field's startup value will contain -1.
4782  */
4783  if (IsA(node, RestrictInfo))
4784  {
4785  RestrictInfo *rinfo = (RestrictInfo *) node;
4786 
4787  if (rinfo->eval_cost.startup < 0)
4788  {
4789  cost_qual_eval_context locContext;
4790 
4791  locContext.root = context->root;
4792  locContext.total.startup = 0;
4793  locContext.total.per_tuple = 0;
4794 
4795  /*
4796  * For an OR clause, recurse into the marked-up tree so that we
4797  * set the eval_cost for contained RestrictInfos too.
4798  */
4799  if (rinfo->orclause)
4800  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4801  else
4802  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4803 
4804  /*
4805  * If the RestrictInfo is marked pseudoconstant, it will be tested
4806  * only once, so treat its cost as all startup cost.
4807  */
4808  if (rinfo->pseudoconstant)
4809  {
4810  /* count one execution during startup */
4811  locContext.total.startup += locContext.total.per_tuple;
4812  locContext.total.per_tuple = 0;
4813  }
4814  rinfo->eval_cost = locContext.total;
4815  }
4816  context->total.startup += rinfo->eval_cost.startup;
4817  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4818  /* do NOT recurse into children */
4819  return false;
4820  }
4821 
4822  /*
4823  * For each operator or function node in the given tree, we charge the
4824  * estimated execution cost given by pg_proc.procost (remember to multiply
4825  * this by cpu_operator_cost).
4826  *
4827  * Vars and Consts are charged zero, and so are boolean operators (AND,
4828  * OR, NOT). Simplistic, but a lot better than no model at all.
4829  *
4830  * Should we try to account for the possibility of short-circuit
4831  * evaluation of AND/OR? Probably *not*, because that would make the
4832  * results depend on the clause ordering, and we are not in any position
4833  * to expect that the current ordering of the clauses is the one that's
4834  * going to end up being used. The above per-RestrictInfo caching would
4835  * not mix well with trying to re-order clauses anyway.
4836  *
4837  * Another issue that is entirely ignored here is that if a set-returning
4838  * function is below top level in the tree, the functions/operators above
4839  * it will need to be evaluated multiple times. In practical use, such
4840  * cases arise so seldom as to not be worth the added complexity needed;
4841  * moreover, since our rowcount estimates for functions tend to be pretty
4842  * phony, the results would also be pretty phony.
4843  */
4844  if (IsA(node, FuncExpr))
4845  {
4846  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4847  &context->total);
4848  }
4849  else if (IsA(node, OpExpr) ||
4850  IsA(node, DistinctExpr) ||
4851  IsA(node, NullIfExpr))
4852  {
4853  /* rely on struct equivalence to treat these all alike */
4854  set_opfuncid((OpExpr *) node);
4855  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4856  &context->total);
4857  }
4858  else if (IsA(node, ScalarArrayOpExpr))
4859  {
4860  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4861  Node *arraynode = (Node *) lsecond(saop->args);
4862  QualCost sacosts;
4863  QualCost hcosts;
4864  double estarraylen = estimate_array_length(context->root, arraynode);
4865 
4866  set_sa_opfuncid(saop);
4867  sacosts.startup = sacosts.per_tuple = 0;
4868  add_function_cost(context->root, saop->opfuncid, NULL,
4869  &sacosts);
4870 
4871  if (OidIsValid(saop->hashfuncid))
4872  {
4873  /* Handle costs for hashed ScalarArrayOpExpr */
4874  hcosts.startup = hcosts.per_tuple = 0;
4875 
4876  add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4877  context->total.startup += sacosts.startup + hcosts.startup;
4878 
4879  /* Estimate the cost of building the hashtable. */
4880  context->total.startup += estarraylen * hcosts.per_tuple;
4881 
4882  /*
4883  * XXX should we charge a little bit for sacosts.per_tuple when
4884  * building the table, or is it ok to assume there will be zero
4885  * hash collision?
4886  */
4887 
4888  /*
4889  * Charge for hashtable lookups. Charge a single hash and a
4890  * single comparison.
4891  */
4892  context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4893  }
4894  else
4895  {
4896  /*
4897  * Estimate that the operator will be applied to about half of the
4898  * array elements before the answer is determined.
4899  */
4900  context->total.startup += sacosts.startup;
4901  context->total.per_tuple += sacosts.per_tuple *
4902  estimate_array_length(context->root, arraynode) * 0.5;
4903  }
4904  }
4905  else if (IsA(node, Aggref) ||
4906  IsA(node, WindowFunc))
4907  {
4908  /*
4909  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4910  * ie, zero execution cost in the current model, because they behave
4911  * essentially like Vars at execution. We disregard the costs of
4912  * their input expressions for the same reason. The actual execution
4913  * costs of the aggregate/window functions and their arguments have to
4914  * be factored into plan-node-specific costing of the Agg or WindowAgg
4915  * plan node.
4916  */
4917  return false; /* don't recurse into children */
4918  }
4919  else if (IsA(node, GroupingFunc))
4920  {
4921  /* Treat this as having cost 1 */
4922  context->total.per_tuple += cpu_operator_cost;
4923  return false; /* don't recurse into children */
4924  }
4925  else if (IsA(node, CoerceViaIO))
4926  {
4927  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4928  Oid iofunc;
4929  Oid typioparam;
4930  bool typisvarlena;
4931 
4932  /* check the result type's input function */
4933  getTypeInputInfo(iocoerce->resulttype,
4934  &iofunc, &typioparam);
4935  add_function_cost(context->root, iofunc, NULL,
4936  &context->total);
4937  /* check the input type's output function */
4938  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4939  &iofunc, &typisvarlena);
4940  add_function_cost(context->root, iofunc, NULL,
4941  &context->total);
4942  }
4943  else if (IsA(node, ArrayCoerceExpr))
4944  {
4945  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4946  QualCost perelemcost;
4947 
4948  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4949  context->root);
4950  context->total.startup += perelemcost.startup;
4951  if (perelemcost.per_tuple > 0)
4952  context->total.per_tuple += perelemcost.per_tuple *
4953  estimate_array_length(context->root, (Node *) acoerce->arg);
4954  }
4955  else if (IsA(node, RowCompareExpr))
4956  {
4957  /* Conservatively assume we will check all the columns */
4958  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4959  ListCell *lc;
4960 
4961  foreach(lc, rcexpr->opnos)
4962  {
4963  Oid opid = lfirst_oid(lc);
4964 
4965  add_function_cost(context->root, get_opcode(opid), NULL,
4966  &context->total);
4967  }
4968  }
4969  else if (IsA(node, MinMaxExpr) ||
4970  IsA(node, SQLValueFunction) ||
4971  IsA(node, XmlExpr) ||
4972  IsA(node, CoerceToDomain) ||
4973  IsA(node, NextValueExpr) ||
4974  IsA(node, JsonExpr))
4975  {
4976  /* Treat all these as having cost 1 */
4977  context->total.per_tuple += cpu_operator_cost;
4978  }
4979  else if (IsA(node, SubLink))
4980  {
4981  /* This routine should not be applied to un-planned expressions */
4982  elog(ERROR, "cannot handle unplanned sub-select");
4983  }
4984  else if (IsA(node, SubPlan))
4985  {
4986  /*
4987  * A subplan node in an expression typically indicates that the
4988  * subplan will be executed on each evaluation, so charge accordingly.
4989  * (Sub-selects that can be executed as InitPlans have already been
4990  * removed from the expression.)
4991  */
4992  SubPlan *subplan = (SubPlan *) node;
4993 
4994  context->total.startup += subplan->startup_cost;
4995  context->total.per_tuple += subplan->per_call_cost;
4996 
4997  /*
4998  * We don't want to recurse into the testexpr, because it was already
4999  * counted in the SubPlan node's costs. So we're done.
5000  */
5001  return false;
5002  }
5003  else if (IsA(node, AlternativeSubPlan))
5004  {
5005  /*
5006  * Arbitrarily use the first alternative plan for costing. (We should
5007  * certainly only include one alternative, and we don't yet have
5008  * enough information to know which one the executor is most likely to
5009  * use.)
5010  */
5011  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
5012 
5013  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
5014  context);
5015  }
5016  else if (IsA(node, PlaceHolderVar))
5017  {
5018  /*
5019  * A PlaceHolderVar should be given cost zero when considering general
5020  * expression evaluation costs. The expense of doing the contained
5021  * expression is charged as part of the tlist eval costs of the scan
5022  * or join where the PHV is first computed (see set_rel_width and
5023  * add_placeholders_to_joinrel). If we charged it again here, we'd be
5024  * double-counting the cost for each level of plan that the PHV
5025  * bubbles up through. Hence, return without recursing into the
5026  * phexpr.
5027  */
5028  return false;
5029  }
5030 
5031  /* recurse into children */
5033 }
#define OidIsValid(objectId)
Definition: c.h:729
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2874
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1872
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1861
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define lsecond(l)
Definition: pg_list.h:183
#define lfirst_oid(lc)
Definition: pg_list.h:174
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2097
unsigned int Oid
Definition: postgres_ext.h:31
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2139
Expr * arg
Definition: primnodes.h:1207
Oid resulttype
Definition: primnodes.h:1208
Cost startup_cost
Definition: primnodes.h:1093
Cost per_call_cost
Definition: primnodes.h:1094
PlannerInfo * root
Definition: costsize.c:169

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

Referenced by cost_qual_eval(), and cost_qual_eval_node().

◆ cost_recursive_union()

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

Definition at line 1826 of file costsize.c.

1827 {
1828  Cost startup_cost;
1829  Cost total_cost;
1830  double total_rows;
1831 
1832  /* We probably have decent estimates for the non-recursive term */
1833  startup_cost = nrterm->startup_cost;
1834  total_cost = nrterm->total_cost;
1835  total_rows = nrterm->rows;
1836 
1837  /*
1838  * We arbitrarily assume that about 10 recursive iterations will be
1839  * needed, and that we've managed to get a good fix on the cost and output
1840  * size of each one of them. These are mighty shaky assumptions but it's
1841  * hard to see how to do better.
1842  */
1843  total_cost += 10 * rterm->total_cost;
1844  total_rows += 10 * rterm->rows;
1845 
1846  /*
1847  * Also charge cpu_tuple_cost per row to account for the costs of
1848  * manipulating the tuplestores. (We don't worry about possible
1849  * spill-to-disk costs.)
1850  */
1851  total_cost += cpu_tuple_cost * total_rows;
1852 
1853  runion->disabled_nodes = nrterm->disabled_nodes + rterm->disabled_nodes;
1854  runion->startup_cost = startup_cost;
1855  runion->total_cost = total_cost;
1856  runion->rows = total_rows;
1857  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1858  rterm->pathtarget->width);
1859 }

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

Referenced by create_recursiveunion_path().

◆ cost_rescan()

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

Definition at line 4617 of file costsize.c.

4620 {
4621  switch (path->pathtype)
4622  {
4623  case T_FunctionScan:
4624 
4625  /*
4626  * Currently, nodeFunctionscan.c always executes the function to
4627  * completion before returning any rows, and caches the results in
4628  * a tuplestore. So the function eval cost is all startup cost
4629  * and isn't paid over again on rescans. However, all run costs
4630  * will be paid over again.
4631  */
4632  *rescan_startup_cost = 0;
4633  *rescan_total_cost = path->total_cost - path->startup_cost;
4634  break;
4635  case T_HashJoin:
4636 
4637  /*
4638  * If it's a single-batch join, we don't need to rebuild the hash
4639  * table during a rescan.
4640  */
4641  if (((HashPath *) path)->num_batches == 1)
4642  {
4643  /* Startup cost is exactly the cost of hash table building */
4644  *rescan_startup_cost = 0;
4645  *rescan_total_cost = path->total_cost - path->startup_cost;
4646  }
4647  else
4648  {
4649  /* Otherwise, no special treatment */
4650  *rescan_startup_cost = path->startup_cost;
4651  *rescan_total_cost = path->total_cost;
4652  }
4653  break;
4654  case T_CteScan:
4655  case T_WorkTableScan:
4656  {
4657  /*
4658  * These plan types materialize their final result in a
4659  * tuplestore or tuplesort object. So the rescan cost is only
4660  * cpu_tuple_cost per tuple, unless the result is large enough
4661  * to spill to disk.
4662  */
4663  Cost run_cost = cpu_tuple_cost * path->rows;
4664  double nbytes = relation_byte_size(path->rows,
4665  path->pathtarget->width);
4666  long work_mem_bytes = work_mem * 1024L;
4667 
4668  if (nbytes > work_mem_bytes)
4669  {
4670  /* It will spill, so account for re-read cost */
4671  double npages = ceil(nbytes / BLCKSZ);
4672 
4673  run_cost += seq_page_cost * npages;
4674  }
4675  *rescan_startup_cost = 0;
4676  *rescan_total_cost = run_cost;
4677  }
4678  break;
4679  case T_Material:
4680  case T_Sort:
4681  {
4682  /*
4683  * These plan types not only materialize their results, but do
4684  * not implement qual filtering or projection. So they are
4685  * even cheaper to rescan than the ones above. We charge only
4686  * cpu_operator_cost per tuple. (Note: keep that in sync with
4687  * the run_cost charge in cost_sort, and also see comments in
4688  * cost_material before you change it.)
4689  */
4690  Cost run_cost = cpu_operator_cost * path->rows;
4691  double nbytes = relation_byte_size(path->rows,
4692  path->pathtarget->width);
4693  long work_mem_bytes = work_mem * 1024L;
4694 
4695  if (nbytes > work_mem_bytes)
4696  {
4697  /* It will spill, so account for re-read cost */
4698  double npages = ceil(nbytes / BLCKSZ);
4699 
4700  run_cost += seq_page_cost * npages;
4701  }
4702  *rescan_startup_cost = 0;
4703  *rescan_total_cost = run_cost;
4704  }
4705  break;
4706  case T_Memoize:
4707  /* All the hard work is done by cost_memoize_rescan */
4709  rescan_startup_cost, rescan_total_cost);
4710  break;
4711  default:
4712  *rescan_startup_cost = path->startup_cost;
4713  *rescan_total_cost = path->total_cost;
4714  break;
4715  }
4716 }
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:2541

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

Referenced by initial_cost_nestloop().

◆ cost_resultscan()

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

Definition at line 1788 of file costsize.c.

1790 {
1791  Cost startup_cost = 0;
1792  Cost run_cost = 0;
1793  QualCost qpqual_cost;
1794  Cost cpu_per_tuple;
1795 
1796  /* Should only be applied to RTE_RESULT base relations */
1797  Assert(baserel->relid > 0);
1798  Assert(baserel->rtekind == RTE_RESULT);
1799 
1800  /* Mark the path with the correct row estimate */
1801  if (param_info)
1802  path->rows = param_info->ppi_rows;
1803  else
1804  path->rows = baserel->rows;
1805 
1806  /* We charge qual cost plus cpu_tuple_cost */
1807  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1808 
1809  startup_cost += qpqual_cost.startup;
1810  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1811  run_cost += cpu_per_tuple * baserel->tuples;
1812 
1813  path->disabled_nodes = 0;
1814  path->startup_cost = startup_cost;
1815  path->total_cost = startup_cost + run_cost;
1816 }
@ RTE_RESULT
Definition: parsenodes.h:1025

References Assert, cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, 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 370 of file costsize.c.

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

References Assert, cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, RelOptInfo::pages, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, 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 295 of file costsize.c.

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

References Assert, clamp_row_est(), cpu_tuple_cost, Path::disabled_nodes, enable_seqscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), RelOptInfo::pages, Path::parallel_workers, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, 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,
int  input_disabled_nodes,
Cost  input_cost,
double  tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)

Definition at line 2144 of file costsize.c.

2150 {
2151  Cost startup_cost;
2152  Cost run_cost;
2153 
2154  cost_tuplesort(&startup_cost, &run_cost,
2155  tuples, width,
2156  comparison_cost, sort_mem,
2157  limit_tuples);
2158 
2159  startup_cost += input_cost;
2160 
2161  path->rows = tuples;
2162  path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
2163  path->startup_cost = startup_cost;
2164  path->total_cost = startup_cost + run_cost;
2165 }
bool enable_sort
Definition: costsize.c:150

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

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

◆ cost_subplan()

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

Definition at line 4524 of file costsize.c.

4525 {
4526  QualCost sp_cost;
4527 
4528  /* Figure any cost for evaluating the testexpr */
4529  cost_qual_eval(&sp_cost,
4530  make_ands_implicit((Expr *) subplan->testexpr),
4531  root);
4532 
4533  if (subplan->useHashTable)
4534  {
4535  /*
4536  * If we are using a hash table for the subquery outputs, then the
4537  * cost of evaluating the query is a one-time cost. We charge one
4538  * cpu_operator_cost per tuple for the work of loading the hashtable,
4539  * too.
4540  */
4541  sp_cost.startup += plan->total_cost +
4542  cpu_operator_cost * plan->plan_rows;
4543 
4544  /*
4545  * The per-tuple costs include the cost of evaluating the lefthand
4546  * expressions, plus the cost of probing the hashtable. We already
4547  * accounted for the lefthand expressions as part of the testexpr, and
4548  * will also have counted one cpu_operator_cost for each comparison
4549  * operator. That is probably too low for the probing cost, but it's
4550  * hard to make a better estimate, so live with it for now.
4551  */
4552  }
4553  else
4554  {
4555  /*
4556  * Otherwise we will be rescanning the subplan output on each
4557  * evaluation. We need to estimate how much of the output we will
4558  * actually need to scan. NOTE: this logic should agree with the
4559  * tuple_fraction estimates used by make_subplan() in
4560  * plan/subselect.c.
4561  */
4562  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4563 
4564  if (subplan->subLinkType == EXISTS_SUBLINK)
4565  {
4566  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4567  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4568  }
4569  else if (subplan->subLinkType == ALL_SUBLINK ||
4570  subplan->subLinkType == ANY_SUBLINK)
4571  {
4572  /* assume we need 50% of the tuples */
4573  sp_cost.per_tuple += 0.50 * plan_run_cost;
4574  /* also charge a cpu_operator_cost per row examined */
4575  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4576  }
4577  else
4578  {
4579  /* assume we need all tuples */
4580  sp_cost.per_tuple += plan_run_cost;
4581  }
4582 
4583  /*
4584  * Also account for subplan's startup cost. If the subplan is
4585  * uncorrelated or undirect correlated, AND its topmost node is one
4586  * that materializes its output, assume that we'll only need to pay
4587  * its startup cost once; otherwise assume we pay the startup cost
4588  * every time.
4589  */
4590  if (subplan->parParam == NIL &&
4592  sp_cost.startup += plan->startup_cost;
4593  else
4594  sp_cost.per_tuple += plan->startup_cost;
4595  }
4596 
4597  subplan->startup_cost = sp_cost.startup;
4598  subplan->per_call_cost = sp_cost.per_tuple;
4599 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:635
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:760
#define plan(x)
Definition: pg_regress.c:161
@ ANY_SUBLINK
Definition: primnodes.h:999
@ ALL_SUBLINK
Definition: primnodes.h:998
@ EXISTS_SUBLINK
Definition: primnodes.h:997
bool useHashTable
Definition: primnodes.h:1079
Node * testexpr
Definition: primnodes.h:1067
List * parParam
Definition: primnodes.h:1090
SubLinkType subLinkType
Definition: primnodes.h:1065

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, root, QualCost::startup, SubPlan::startup_cost, SubPlan::subLinkType, SubPlan::testexpr, and SubPlan::useHashTable.

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

◆ cost_subqueryscan()

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

Definition at line 1457 of file costsize.c.

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

References Assert, RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), NIL, SubqueryScanPath::path, QualCost::per_tuple, ParamPathInfo::ppi_clauses, RelOptInfo::relid, root, 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 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  RangeTblEntry *rte;
1608  QualCost exprcost;
1609 
1610  /* Should only be applied to base relations that are functions */
1611  Assert(baserel->relid > 0);
1612  rte = planner_rt_fetch(baserel->relid, root);
1613  Assert(rte->rtekind == RTE_TABLEFUNC);
1614 
1615  /* Mark the path with the correct row estimate */
1616  if (param_info)
1617  path->rows = param_info->ppi_rows;
1618  else
1619  path->rows = baserel->rows;
1620 
1621  /*
1622  * Estimate costs of executing the table func expression(s).
1623  *
1624  * XXX in principle we ought to charge tuplestore spill costs if the
1625  * number of rows is large. However, given how phony our rowcount
1626  * estimates for tablefuncs tend to be, there's not a lot of point in that
1627  * refinement right now.
1628  */
1629  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1630 
1631  startup_cost += exprcost.startup + exprcost.per_tuple;
1632 
1633  /* Add scanning CPU costs */
1634  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1635 
1636  startup_cost += qpqual_cost.startup;
1637  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1638  run_cost += cpu_per_tuple * baserel->tuples;
1639 
1640  /* tlist eval costs are paid per output row, not per tuple scanned */
1641  startup_cost += path->pathtarget->cost.startup;
1642  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1643 
1644  path->disabled_nodes = 0;
1645  path->startup_cost = startup_cost;
1646  path->total_cost = startup_cost + run_cost;
1647 }
@ RTE_TABLEFUNC
Definition: parsenodes.h:1021
TableFunc * tablefunc
Definition: parsenodes.h:1184

References Assert, cost_qual_eval_node(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, 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 1363 of file costsize.c.

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

References Assert, clauselist_selectivity(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, enable_tidscan, get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, RelOptInfo::pages, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, 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 1258 of file costsize.c.

1260 {
1261  Cost startup_cost = 0;
1262  Cost run_cost = 0;
1263  QualCost qpqual_cost;
1264  Cost cpu_per_tuple;
1265  QualCost tid_qual_cost;
1266  double ntuples;
1267  ListCell *l;
1268  double spc_random_page_cost;
1269 
1270  /* Should only be applied to base relations */
1271  Assert(baserel->relid > 0);
1272  Assert(baserel->rtekind == RTE_RELATION);
1273  Assert(tidquals != NIL);
1274 
1275  /* Mark the path with the correct row estimate */
1276  if (param_info)
1277  path->rows = param_info->ppi_rows;
1278  else
1279  path->rows = baserel->rows;
1280 
1281  /* Count how many tuples we expect to retrieve */
1282  ntuples = 0;
1283  foreach(l, tidquals)
1284  {
1285  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1286  Expr *qual = rinfo->clause;
1287 
1288  /*
1289  * We must use a TID scan for CurrentOfExpr; in any other case, we
1290  * should be generating a TID scan only if enable_tidscan=true. Also,
1291  * if CurrentOfExpr is the qual, there should be only one.
1292  */
1294  Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
1295 
1296  if (IsA(qual, ScalarArrayOpExpr))
1297  {
1298  /* Each element of the array yields 1 tuple */
1299  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1300  Node *arraynode = (Node *) lsecond(saop->args);
1301 
1302  ntuples += estimate_array_length(root, arraynode);
1303  }
1304  else if (IsA(qual, CurrentOfExpr))
1305  {
1306  /* CURRENT OF yields 1 tuple */
1307  ntuples++;
1308  }
1309  else
1310  {
1311  /* It's just CTID = something, count 1 tuple */
1312  ntuples++;
1313  }
1314  }
1315 
1316  /*
1317  * The TID qual expressions will be computed once, any other baserestrict
1318  * quals once per retrieved tuple.
1319  */
1320  cost_qual_eval(&tid_qual_cost, tidquals, root);
1321 
1322  /* fetch estimated page cost for tablespace containing table */
1324  &spc_random_page_cost,
1325  NULL);
1326 
1327  /* disk costs --- assume each tuple on a different page */
1328  run_cost += spc_random_page_cost * ntuples;
1329 
1330  /* Add scanning CPU costs */
1331  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1332 
1333  /* XXX currently we assume TID quals are a subset of qpquals */
1334  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1335  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1336  tid_qual_cost.per_tuple;
1337  run_cost += cpu_per_tuple * ntuples;
1338 
1339  /* tlist eval costs are paid per output row, not per tuple scanned */
1340  startup_cost += path->pathtarget->cost.startup;
1341  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1342 
1343  /*
1344  * There are assertions above verifying that we only reach this function
1345  * either when enable_tidscan=true or when the TID scan is the only legal
1346  * path, so it's safe to set disabled_nodes to zero here.
1347  */
1348  path->disabled_nodes = 0;
1349  path->startup_cost = startup_cost;
1350  path->total_cost = startup_cost + run_cost;
1351 }

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

Referenced by create_tidscan_path().

◆ cost_tuplesort()

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

Definition at line 1898 of file costsize.c.

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

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

Referenced by cost_incremental_sort(), and cost_sort().

◆ cost_valuesscan()

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

Definition at line 1657 of file costsize.c.

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

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

Referenced by create_valuesscan_path().

◆ cost_windowagg()

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

Definition at line 3099 of file costsize.c.

3104 {
3105  Cost startup_cost;
3106  Cost total_cost;
3107  double startup_tuples;
3108  int numPartCols;
3109  int numOrderCols;
3110  ListCell *lc;
3111 
3112  numPartCols = list_length(winclause->partitionClause);
3113  numOrderCols = list_length(winclause->orderClause);
3114 
3115  startup_cost = input_startup_cost;
3116  total_cost = input_total_cost;
3117 
3118  /*
3119  * Window functions are assumed to cost their stated execution cost, plus
3120  * the cost of evaluating their input expressions, per tuple. Since they
3121  * may in fact evaluate their inputs at multiple rows during each cycle,
3122  * this could be a drastic underestimate; but without a way to know how
3123  * many rows the window function will fetch, it's hard to do better. In
3124  * any case, it's a good estimate for all the built-in window functions,
3125  * so we'll just do this for now.
3126  */
3127  foreach(lc, windowFuncs)
3128  {
3129  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3130  Cost wfunccost;
3131  QualCost argcosts;
3132 
3133  argcosts.startup = argcosts.per_tuple = 0;
3134  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3135  &argcosts);
3136  startup_cost += argcosts.startup;
3137  wfunccost = argcosts.per_tuple;
3138 
3139  /* also add the input expressions' cost to per-input-row costs */
3140  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3141  startup_cost += argcosts.startup;
3142  wfunccost += argcosts.per_tuple;
3143 
3144  /*
3145  * Add the filter's cost to per-input-row costs. XXX We should reduce
3146  * input expression costs according to filter selectivity.
3147  */
3148  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3149  startup_cost += argcosts.startup;
3150  wfunccost += argcosts.per_tuple;
3151 
3152  total_cost += wfunccost * input_tuples;
3153  }
3154 
3155  /*
3156  * We also charge cpu_operator_cost per grouping column per tuple for
3157  * grouping comparisons, plus cpu_tuple_cost per tuple for general
3158  * overhead.
3159  *
3160  * XXX this neglects costs of spooling the data to disk when it overflows
3161  * work_mem. Sooner or later that should get accounted for.
3162  */
3163  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3164  total_cost += cpu_tuple_cost * input_tuples;
3165 
3166  path->rows = input_tuples;
3167  path->disabled_nodes = input_disabled_nodes;
3168  path->startup_cost = startup_cost;
3169  path->total_cost = total_cost;
3170 
3171  /*
3172  * Also, take into account how many tuples we need to read from the
3173  * subnode in order to produce the first tuple from the WindowAgg. To do
3174  * this we proportion the run cost (total cost not including startup cost)
3175  * over the estimated startup tuples. We already included the startup
3176  * cost of the subnode, so we only need to do this when the estimated
3177  * startup tuples is above 1.0.
3178  */
3179  startup_tuples = get_windowclause_startup_tuples(root, winclause,
3180  input_tuples);
3181 
3182  if (startup_tuples > 1.0)
3183  path->startup_cost += (total_cost - startup_cost) / input_tuples *
3184  (startup_tuples - 1.0);
3185 }
static double get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc, double input_tuples)
Definition: costsize.c:2885
List * partitionClause
Definition: parsenodes.h:1543
List * orderClause
Definition: parsenodes.h:1545
List * args
Definition: primnodes.h:575
Expr * aggfilter
Definition: primnodes.h:577
Oid winfnoid
Definition: primnodes.h:567

References add_function_cost(), WindowFunc::aggfilter, WindowFunc::args, cost_qual_eval_node(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, get_windowclause_startup_tuples(), lfirst_node, list_length(), WindowClause::orderClause, WindowClause::partitionClause, QualCost::per_tuple, root, 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 850 of file costsize.c.

851 {
852  List *result = NIL;
853  ListCell *lc;
854 
855  foreach(lc, qual_clauses)
856  {
857  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
858 
859  if (rinfo->pseudoconstant)
860  continue; /* we may drop pseudoconstants here */
861  if (is_redundant_with_indexclauses(rinfo, indexclauses))
862  continue; /* dup or derived from same EquivalenceClass */
863  /* ... skip the predicate proof attempt createplan.c will try ... */
864  result = lappend(result, rinfo);
865  }
866  return result;
867 }
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:3351

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

Referenced by cost_index().

◆ final_cost_hashjoin()

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

Definition at line 4275 of file costsize.c.

4278 {
4279  Path *outer_path = path->jpath.outerjoinpath;
4280  Path *inner_path = path->jpath.innerjoinpath;
4281  double outer_path_rows = outer_path->rows;
4282  double inner_path_rows = inner_path->rows;
4283  double inner_path_rows_total = workspace->inner_rows_total;
4284  List *hashclauses = path->path_hashclauses;
4285  Cost startup_cost = workspace->startup_cost;
4286  Cost run_cost = workspace->run_cost;
4287  int numbuckets = workspace->numbuckets;
4288  int numbatches = workspace->numbatches;
4289  Cost cpu_per_tuple;
4290  QualCost hash_qual_cost;
4291  QualCost qp_qual_cost;
4292  double hashjointuples;
4293  double virtualbuckets;
4294  Selectivity innerbucketsize;
4295  Selectivity innermcvfreq;
4296  ListCell *hcl;
4297 
4298  /* Set the number of disabled nodes. */
4299  path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4300 
4301  /* Mark the path with the correct row estimate */
4302  if (path->jpath.path.param_info)
4303  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4304  else
4305  path->jpath.path.rows = path->jpath.path.parent->rows;
4306 
4307  /* For partial paths, scale row estimate. */
4308  if (path->jpath.path.parallel_workers > 0)
4309  {
4310  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4311 
4312  path->jpath.path.rows =
4313  clamp_row_est(path->jpath.path.rows / parallel_divisor);
4314  }
4315 
4316  /* mark the path with estimated # of batches */
4317  path->num_batches = numbatches;
4318 
4319  /* store the total number of tuples (sum of partial row estimates) */
4320  path->inner_rows_total = inner_path_rows_total;
4321 
4322  /* and compute the number of "virtual" buckets in the whole join */
4323  virtualbuckets = (double) numbuckets * (double) numbatches;
4324 
4325  /*
4326  * Determine bucketsize fraction and MCV frequency for the inner relation.
4327  * We use the smallest bucketsize or MCV frequency estimated for any
4328  * individual hashclause; this is undoubtedly conservative.
4329  *
4330  * BUT: if inner relation has been unique-ified, we can assume it's good
4331  * for hashing. This is important both because it's the right answer, and
4332  * because we avoid contaminating the cache with a value that's wrong for
4333  * non-unique-ified paths.
4334  */
4335  if (IsA(inner_path, UniquePath))
4336  {
4337  innerbucketsize = 1.0 / virtualbuckets;
4338  innermcvfreq = 0.0;
4339  }
4340  else
4341  {
4342  innerbucketsize = 1.0;
4343  innermcvfreq = 1.0;
4344  foreach(hcl, hashclauses)
4345  {
4346  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4347  Selectivity thisbucketsize;
4348  Selectivity thismcvfreq;
4349 
4350  /*
4351  * First we have to figure out which side of the hashjoin clause
4352  * is the inner side.
4353  *
4354  * Since we tend to visit the same clauses over and over when
4355  * planning a large query, we cache the bucket stats estimates in
4356  * the RestrictInfo node to avoid repeated lookups of statistics.
4357  */
4358  if (bms_is_subset(restrictinfo->right_relids,
4359  inner_path->parent->relids))
4360  {
4361  /* righthand side is inner */
4362  thisbucketsize = restrictinfo->right_bucketsize;
4363  if (thisbucketsize < 0)
4364  {
4365  /* not cached yet */
4367  get_rightop(restrictinfo->clause),
4368  virtualbuckets,
4369  &restrictinfo->right_mcvfreq,
4370  &restrictinfo->right_bucketsize);
4371  thisbucketsize = restrictinfo->right_bucketsize;
4372  }
4373  thismcvfreq = restrictinfo->right_mcvfreq;
4374  }
4375  else
4376  {
4377  Assert(bms_is_subset(restrictinfo->left_relids,
4378  inner_path->parent->relids));
4379  /* lefthand side is inner */
4380  thisbucketsize = restrictinfo->left_bucketsize;
4381  if (thisbucketsize < 0)
4382  {
4383  /* not cached yet */
4385  get_leftop(restrictinfo->clause),
4386  virtualbuckets,
4387  &restrictinfo->left_mcvfreq,
4388  &restrictinfo->left_bucketsize);
4389  thisbucketsize = restrictinfo->left_bucketsize;
4390  }
4391  thismcvfreq = restrictinfo->left_mcvfreq;
4392  }
4393 
4394  if (innerbucketsize > thisbucketsize)
4395  innerbucketsize = thisbucketsize;
4396  if (innermcvfreq > thismcvfreq)
4397  innermcvfreq = thismcvfreq;
4398  }
4399  }
4400 
4401  /*
4402  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4403  * want to hash unless there is really no other alternative, so apply
4404  * disable_cost. (The executor normally copes with excessive memory usage
4405  * by splitting batches, but obviously it cannot separate equal values
4406  * that way, so it will be unable to drive the batch size below hash_mem
4407  * when this is true.)
4408  */
4409  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4410  inner_path->pathtarget->width) > get_hash_memory_limit())
4411  startup_cost += disable_cost;
4412 
4413  /*
4414  * Compute cost of the hashquals and qpquals (other restriction clauses)
4415  * separately.
4416  */
4417  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4418  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4419  qp_qual_cost.startup -= hash_qual_cost.startup;
4420  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4421 
4422  /* CPU costs */
4423 
4424  if (path->jpath.jointype == JOIN_SEMI ||
4425  path->jpath.jointype == JOIN_ANTI ||
4426  extra->inner_unique)
4427  {
4428  double outer_matched_rows;
4429  Selectivity inner_scan_frac;
4430 
4431  /*
4432  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4433  * executor will stop after the first match.
4434  *
4435  * For an outer-rel row that has at least one match, we can expect the
4436  * bucket scan to stop after a fraction 1/(match_count+1) of the
4437  * bucket's rows, if the matches are evenly distributed. Since they
4438  * probably aren't quite evenly distributed, we apply a fuzz factor of
4439  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4440  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4441  * at least 1, no such clamp is needed now.)
4442  */
4443  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4444  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4445 
4446  startup_cost += hash_qual_cost.startup;
4447  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4448  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4449 
4450  /*
4451  * For unmatched outer-rel rows, the picture is quite a lot different.
4452  * In the first place, there is no reason to assume that these rows
4453  * preferentially hit heavily-populated buckets; instead assume they
4454  * are uncorrelated with the inner distribution and so they see an
4455  * average bucket size of inner_path_rows / virtualbuckets. In the
4456  * second place, it seems likely that they will have few if any exact
4457  * hash-code matches and so very few of the tuples in the bucket will
4458  * actually require eval of the hash quals. We don't have any good
4459  * way to estimate how many will, but for the moment assume that the
4460  * effective cost per bucket entry is one-tenth what it is for
4461  * matchable tuples.
4462  */
4463  run_cost += hash_qual_cost.per_tuple *
4464  (outer_path_rows - outer_matched_rows) *
4465  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4466 
4467  /* Get # of tuples that will pass the basic join */
4468  if (path->jpath.jointype == JOIN_ANTI)
4469  hashjointuples = outer_path_rows - outer_matched_rows;
4470  else
4471  hashjointuples = outer_matched_rows;
4472  }
4473  else
4474  {
4475  /*
4476  * The number of tuple comparisons needed is the number of outer
4477  * tuples times the typical number of tuples in a hash bucket, which
4478  * is the inner relation size times its bucketsize fraction. At each
4479  * one, we need to evaluate the hashjoin quals. But actually,
4480  * charging the full qual eval cost at each tuple is pessimistic,
4481  * since we don't evaluate the quals unless the hash values match
4482  * exactly. For lack of a better idea, halve the cost estimate to
4483  * allow for that.
4484  */
4485  startup_cost += hash_qual_cost.startup;
4486  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4487  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4488 
4489  /*
4490  * Get approx # tuples passing the hashquals. We use
4491  * approx_tuple_count here because we need an estimate done with
4492  * JOIN_INNER semantics.
4493  */
4494  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4495  }
4496 
4497  /*
4498  * For each tuple that gets through the hashjoin proper, we charge
4499  * cpu_tuple_cost plus the cost of evaluating additional restriction
4500  * clauses that are to be applied at the join. (This is pessimistic since
4501  * not all of the quals may get evaluated at each tuple.)
4502  */
4503  startup_cost += qp_qual_cost.startup;
4504  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4505  run_cost += cpu_per_tuple * hashjointuples;
4506 
4507  /* tlist eval costs are paid per output row, not per tuple scanned */
4508  startup_cost += path->jpath.path.pathtarget->cost.startup;
4509  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4510 
4511  path->jpath.path.startup_cost = startup_cost;
4512  path->jpath.path.total_cost = startup_cost + run_cost;
4513 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:5280
Cost disable_cost
Definition: costsize.c:141
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:95
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:83
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3802
List * path_hashclauses
Definition: pathnodes.h:2162
Cardinality inner_rows_total
Definition: pathnodes.h:2164
int num_batches
Definition: pathnodes.h:2163
JoinPath jpath
Definition: pathnodes.h:2161
Cardinality inner_rows_total
Definition: pathnodes.h:3366
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3244
JoinType jointype
Definition: pathnodes.h:2079
List * joinrestrictinfo
Definition: pathnodes.h:2087

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3837 of file costsize.c.

3840 {
3841  Path *outer_path = path->jpath.outerjoinpath;
3842  Path *inner_path = path->jpath.innerjoinpath;
3843  double inner_path_rows = inner_path->rows;
3844  List *mergeclauses = path->path_mergeclauses;
3845  List *innersortkeys = path->innersortkeys;
3846  Cost startup_cost = workspace->startup_cost;
3847  Cost run_cost = workspace->run_cost;
3848  Cost inner_run_cost = workspace->inner_run_cost;
3849  double outer_rows = workspace->outer_rows;
3850  double inner_rows = workspace->inner_rows;
3851  double outer_skip_rows = workspace->outer_skip_rows;
3852  double inner_skip_rows = workspace->inner_skip_rows;
3853  Cost cpu_per_tuple,
3854  bare_inner_cost,
3855  mat_inner_cost;
3856  QualCost merge_qual_cost;
3857  QualCost qp_qual_cost;
3858  double mergejointuples,
3859  rescannedtuples;
3860  double rescanratio;
3861 
3862  /* Set the number of disabled nodes. */
3863  path->jpath.path.disabled_nodes = workspace->disabled_nodes;
3864 
3865  /* Protect some assumptions below that rowcounts aren't zero */
3866  if (inner_path_rows <= 0)
3867  inner_path_rows = 1;
3868 
3869  /* Mark the path with the correct row estimate */
3870  if (path->jpath.path.param_info)
3871  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3872  else
3873  path->jpath.path.rows = path->jpath.path.parent->rows;
3874 
3875  /* For partial paths, scale row estimate. */
3876  if (path->jpath.path.parallel_workers > 0)
3877  {
3878  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3879 
3880  path->jpath.path.rows =
3881  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3882  }
3883 
3884  /*
3885  * Compute cost of the mergequals and qpquals (other restriction clauses)
3886  * separately.
3887  */
3888  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3889  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3890  qp_qual_cost.startup -= merge_qual_cost.startup;
3891  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3892 
3893  /*
3894  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3895  * executor will stop scanning for matches after the first match. When
3896  * all the joinclauses are merge clauses, this means we don't ever need to
3897  * back up the merge, and so we can skip mark/restore overhead.
3898  */
3899  if ((path->jpath.jointype == JOIN_SEMI ||
3900  path->jpath.jointype == JOIN_ANTI ||
3901  extra->inner_unique) &&
3904  path->skip_mark_restore = true;
3905  else
3906  path->skip_mark_restore = false;
3907 
3908  /*
3909  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3910  * here because we need an estimate done with JOIN_INNER semantics.
3911  */
3912  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3913 
3914  /*
3915  * When there are equal merge keys in the outer relation, the mergejoin
3916  * must rescan any matching tuples in the inner relation. This means
3917  * re-fetching inner tuples; we have to estimate how often that happens.
3918  *
3919  * For regular inner and outer joins, the number of re-fetches can be
3920  * estimated approximately as size of merge join output minus size of
3921  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3922  * denote the number of values of each key in the outer relation as m1,
3923  * m2, ...; in the inner relation, n1, n2, ... Then we have
3924  *
3925  * size of join = m1 * n1 + m2 * n2 + ...
3926  *
3927  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3928  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3929  * relation
3930  *
3931  * This equation works correctly for outer tuples having no inner match
3932  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3933  * are effectively subtracting those from the number of rescanned tuples,
3934  * when we should not. Can we do better without expensive selectivity
3935  * computations?
3936  *
3937  * The whole issue is moot if we are working from a unique-ified outer
3938  * input, or if we know we don't need to mark/restore at all.
3939  */
3940  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3941  rescannedtuples = 0;
3942  else
3943  {
3944  rescannedtuples = mergejointuples - inner_path_rows;
3945  /* Must clamp because of possible underestimate */
3946  if (rescannedtuples < 0)
3947  rescannedtuples = 0;
3948  }
3949 
3950  /*
3951  * We'll inflate various costs this much to account for rescanning. Note
3952  * that this is to be multiplied by something involving inner_rows, or
3953  * another number related to the portion of the inner rel we'll scan.
3954  */
3955  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3956 
3957  /*
3958  * Decide whether we want to materialize the inner input to shield it from
3959  * mark/restore and performing re-fetches. Our cost model for regular
3960  * re-fetches is that a re-fetch costs the same as an original fetch,
3961  * which is probably an overestimate; but on the other hand we ignore the
3962  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3963  * a more refined model. So we just need to inflate the inner run cost by
3964  * rescanratio.
3965  */
3966  bare_inner_cost = inner_run_cost * rescanratio;
3967 
3968  /*
3969  * When we interpose a Material node the re-fetch cost is assumed to be
3970  * just cpu_operator_cost per tuple, independently of the underlying
3971  * plan's cost; and we charge an extra cpu_operator_cost per original
3972  * fetch as well. Note that we're assuming the materialize node will
3973  * never spill to disk, since it only has to remember tuples back to the
3974  * last mark. (If there are a huge number of duplicates, our other cost
3975  * factors will make the path so expensive that it probably won't get
3976  * chosen anyway.) So we don't use cost_rescan here.
3977  *
3978  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3979  * of the generated Material node.
3980  */
3981  mat_inner_cost = inner_run_cost +
3982  cpu_operator_cost * inner_rows * rescanratio;
3983 
3984  /*
3985  * If we don't need mark/restore at all, we don't need materialization.
3986  */
3987  if (path->skip_mark_restore)
3988  path->materialize_inner = false;
3989 
3990  /*
3991  * Prefer materializing if it looks cheaper, unless the user has asked to
3992  * suppress materialization.
3993  */
3994  else if (enable_material && mat_inner_cost < bare_inner_cost)
3995  path->materialize_inner = true;
3996 
3997  /*
3998  * Even if materializing doesn't look cheaper, we *must* do it if the
3999  * inner path is to be used directly (without sorting) and it doesn't
4000  * support mark/restore.
4001  *
4002  * Since the inner side must be ordered, and only Sorts and IndexScans can
4003  * create order to begin with, and they both support mark/restore, you
4004  * might think there's no problem --- but you'd be wrong. Nestloop and
4005  * merge joins can *preserve* the order of their inputs, so they can be
4006  * selected as the input of a mergejoin, and they don't support
4007  * mark/restore at present.
4008  *
4009  * We don't test the value of enable_material here, because
4010  * materialization is required for correctness in this case, and turning
4011  * it off does not entitle us to deliver an invalid plan.
4012  */
4013  else if (innersortkeys == NIL &&
4014  !ExecSupportsMarkRestore(inner_path))
4015  path->materialize_inner = true;
4016 
4017  /*
4018  * Also, force materializing if the inner path is to be sorted and the
4019  * sort is expected to spill to disk. This is because the final merge
4020  * pass can be done on-the-fly if it doesn't have to support mark/restore.
4021  * We don't try to adjust the cost estimates for this consideration,
4022  * though.
4023  *
4024  * Since materialization is a performance optimization in this case,
4025  * rather than necessary for correctness, we skip it if enable_material is
4026  * off.
4027  */
4028  else if (enable_material && innersortkeys != NIL &&
4029  relation_byte_size(inner_path_rows,
4030  inner_path->pathtarget->width) >
4031  (work_mem * 1024L))
4032  path->materialize_inner = true;
4033  else
4034  path->materialize_inner = false;
4035 
4036  /* Charge the right incremental cost for the chosen case */
4037  if (path->materialize_inner)
4038  run_cost += mat_inner_cost;
4039  else
4040  run_cost += bare_inner_cost;
4041 
4042  /* CPU costs */
4043 
4044  /*
4045  * The number of tuple comparisons needed is approximately number of outer
4046  * rows plus number of inner rows plus number of rescanned tuples (can we
4047  * refine this?). At each one, we need to evaluate the mergejoin quals.
4048  */
4049  startup_cost += merge_qual_cost.startup;
4050  startup_cost += merge_qual_cost.per_tuple *
4051  (outer_skip_rows + inner_skip_rows * rescanratio);
4052  run_cost += merge_qual_cost.per_tuple *
4053  ((outer_rows - outer_skip_rows) +
4054  (inner_rows - inner_skip_rows) * rescanratio);
4055 
4056  /*
4057  * For each tuple that gets through the mergejoin proper, we charge
4058  * cpu_tuple_cost plus the cost of evaluating additional restriction
4059  * clauses that are to be applied at the join. (This is pessimistic since
4060  * not all of the quals may get evaluated at each tuple.)
4061  *
4062  * Note: we could adjust for SEMI/ANTI joins skipping some qual
4063  * evaluations here, but it's probably not worth the trouble.
4064  */
4065  startup_cost += qp_qual_cost.startup;
4066  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4067  run_cost += cpu_per_tuple * mergejointuples;
4068 
4069  /* tlist eval costs are paid per output row, not per tuple scanned */
4070  startup_cost += path->jpath.path.pathtarget->cost.startup;
4071  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4072 
4073  path->jpath.path.startup_cost = startup_cost;
4074  path->jpath.path.total_cost = startup_cost + run_cost;
4075 }
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:417
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
Cardinality inner_rows
Definition: pathnodes.h:3359
Cardinality outer_rows
Definition: pathnodes.h:3358
Cardinality inner_skip_rows
Definition: pathnodes.h:3361
Cardinality outer_skip_rows
Definition: pathnodes.h:3360
bool skip_mark_restore
Definition: pathnodes.h:2146
List * innersortkeys
Definition: pathnodes.h:2145
JoinPath jpath
Definition: pathnodes.h:2142
bool materialize_inner
Definition: pathnodes.h:2147
List * path_mergeclauses
Definition: pathnodes.h:2143

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

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3350 of file costsize.c.

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

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

Referenced by create_nestloop_path().

◆ get_expr_width()

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

Definition at line 6380 of file costsize.c.

6381 {
6382  int32 width;
6383 
6384  if (IsA(expr, Var))
6385  {
6386  const Var *var = (const Var *) expr;
6387 
6388  /* We should not see any upper-level Vars here */
6389  Assert(var->varlevelsup == 0);
6390 
6391  /* Try to get data from RelOptInfo cache */
6392  if (!IS_SPECIAL_VARNO(var->varno) &&
6393  var->varno < root->simple_rel_array_size)
6394  {
6395  RelOptInfo *rel = root->simple_rel_array[var->varno];
6396 
6397  if (rel != NULL &&
6398  var->varattno >= rel->min_attr &&
6399  var->varattno <= rel->max_attr)
6400  {
6401  int ndx = var->varattno - rel->min_attr;
6402 
6403  if (rel->attr_widths[ndx] > 0)
6404  return rel->attr_widths[ndx];
6405  }
6406  }
6407 
6408  /*
6409  * No cached data available, so estimate using just the type info.
6410  */
6411  width = get_typavgwidth(var->vartype, var->vartypmod);
6412  Assert(width > 0);
6413 
6414  return width;
6415  }
6416 
6417  width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6418  Assert(width > 0);
6419  return width;
6420 }
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2578
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:241
AttrNumber max_attr
Definition: pathnodes.h:926
AttrNumber min_attr
Definition: pathnodes.h:924
Definition: primnodes.h:248
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280

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

Referenced by cost_memoize_rescan(), and set_pathtarget_cost_width().

◆ get_foreign_key_join_selectivity()

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

Definition at line 5627 of file costsize.c.

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