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

Go to the source code of this file.

Data Structures

struct  cost_qual_eval_context
 

Macros

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

Functions

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

Variables

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

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 109 of file costsize.c.

Referenced by cost_append(), and cost_merge_append().

◆ LOG2

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

Definition at line 102 of file costsize.c.

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

◆ MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

Definition at line 117 of file costsize.c.

Referenced by clamp_row_est().

Function Documentation

◆ append_nonpartial_cost()

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

Definition at line 2067 of file costsize.c.

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

Referenced by cost_append().

2068 {
2069  Cost *costarr;
2070  int arrlen;
2071  ListCell *l;
2072  ListCell *cell;
2073  int i;
2074  int path_index;
2075  int min_index;
2076  int max_index;
2077 
2078  if (numpaths == 0)
2079  return 0;
2080 
2081  /*
2082  * Array length is number of workers or number of relevant paths,
2083  * whichever is less.
2084  */
2085  arrlen = Min(parallel_workers, numpaths);
2086  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2087 
2088  /* The first few paths will each be claimed by a different worker. */
2089  path_index = 0;
2090  foreach(cell, subpaths)
2091  {
2092  Path *subpath = (Path *) lfirst(cell);
2093 
2094  if (path_index == arrlen)
2095  break;
2096  costarr[path_index++] = subpath->total_cost;
2097  }
2098 
2099  /*
2100  * Since subpaths are sorted by decreasing cost, the last one will have
2101  * the minimum cost.
2102  */
2103  min_index = arrlen - 1;
2104 
2105  /*
2106  * For each of the remaining subpaths, add its cost to the array element
2107  * with minimum cost.
2108  */
2109  for_each_cell(l, subpaths, cell)
2110  {
2111  Path *subpath = (Path *) lfirst(l);
2112  int i;
2113 
2114  /* Consider only the non-partial paths */
2115  if (path_index++ == numpaths)
2116  break;
2117 
2118  costarr[min_index] += subpath->total_cost;
2119 
2120  /* Update the new min cost array index */
2121  for (min_index = i = 0; i < arrlen; i++)
2122  {
2123  if (costarr[i] < costarr[min_index])
2124  min_index = i;
2125  }
2126  }
2127 
2128  /* Return the highest cost from the array */
2129  for (max_index = i = 0; i < arrlen; i++)
2130  {
2131  if (costarr[i] > costarr[max_index])
2132  max_index = i;
2133  }
2134 
2135  return costarr[max_index];
2136 }
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:417
#define Min(x, y)
Definition: c.h:986
Cost total_cost
Definition: pathnodes.h:1194
#define lfirst(lc)
Definition: pg_list.h:169
void * palloc(Size size)
Definition: mcxt.c:1062
int i
double Cost
Definition: nodes.h:671
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ approx_tuple_count()

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

Definition at line 4867 of file costsize.c.

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

Referenced by final_cost_hashjoin(), and final_cost_mergejoin().

4868 {
4869  double tuples;
4870  double outer_tuples = path->outerjoinpath->rows;
4871  double inner_tuples = path->innerjoinpath->rows;
4872  SpecialJoinInfo sjinfo;
4873  Selectivity selec = 1.0;
4874  ListCell *l;
4875 
4876  /*
4877  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4878  */
4879  sjinfo.type = T_SpecialJoinInfo;
4880  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4881  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4882  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4883  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4884  sjinfo.jointype = JOIN_INNER;
4885  /* we don't bother trying to make the remaining fields valid */
4886  sjinfo.lhs_strict = false;
4887  sjinfo.delay_upper_joins = false;
4888  sjinfo.semi_can_btree = false;
4889  sjinfo.semi_can_hash = false;
4890  sjinfo.semi_operators = NIL;
4891  sjinfo.semi_rhs_exprs = NIL;
4892 
4893  /* Get the approximate selectivity */
4894  foreach(l, quals)
4895  {
4896  Node *qual = (Node *) lfirst(l);
4897 
4898  /* Note that clause_selectivity will be able to cache its result */
4899  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4900  }
4901 
4902  /* Apply it to the input relation sizes */
4903  tuples = selec * outer_tuples * inner_tuples;
4904 
4905  return clamp_row_est(tuples);
4906 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2253
Path * innerjoinpath
Definition: pathnodes.h:1591
Definition: nodes.h:537
double Selectivity
Definition: nodes.h:670
Relids syn_lefthand
Definition: pathnodes.h:2254
Relids syn_righthand
Definition: pathnodes.h:2255
List * semi_rhs_exprs
Definition: pathnodes.h:2263
RelOptInfo * parent
Definition: pathnodes.h:1182
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:690
Relids relids
Definition: pathnodes.h:681
Path * outerjoinpath
Definition: pathnodes.h:1590
bool delay_upper_joins
Definition: pathnodes.h:2258
#define lfirst(lc)
Definition: pg_list.h:169
JoinType jointype
Definition: pathnodes.h:2256
List * semi_operators
Definition: pathnodes.h:2262
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
Relids min_lefthand
Definition: pathnodes.h:2252

◆ cached_scansel()

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

Definition at line 3662 of file costsize.c.

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

Referenced by initial_cost_mergejoin().

3663 {
3664  MergeScanSelCache *cache;
3665  ListCell *lc;
3666  Selectivity leftstartsel,
3667  leftendsel,
3668  rightstartsel,
3669  rightendsel;
3670  MemoryContext oldcontext;
3671 
3672  /* Do we have this result already? */
3673  foreach(lc, rinfo->scansel_cache)
3674  {
3675  cache = (MergeScanSelCache *) lfirst(lc);
3676  if (cache->opfamily == pathkey->pk_opfamily &&
3677  cache->collation == pathkey->pk_eclass->ec_collation &&
3678  cache->strategy == pathkey->pk_strategy &&
3679  cache->nulls_first == pathkey->pk_nulls_first)
3680  return cache;
3681  }
3682 
3683  /* Nope, do the computation */
3684  mergejoinscansel(root,
3685  (Node *) rinfo->clause,
3686  pathkey->pk_opfamily,
3687  pathkey->pk_strategy,
3688  pathkey->pk_nulls_first,
3689  &leftstartsel,
3690  &leftendsel,
3691  &rightstartsel,
3692  &rightendsel);
3693 
3694  /* Cache the result in suitably long-lived workspace */
3695  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3696 
3697  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3698  cache->opfamily = pathkey->pk_opfamily;
3699  cache->collation = pathkey->pk_eclass->ec_collation;
3700  cache->strategy = pathkey->pk_strategy;
3701  cache->nulls_first = pathkey->pk_nulls_first;
3702  cache->leftstartsel = leftstartsel;
3703  cache->leftendsel = leftendsel;
3704  cache->rightstartsel = rightstartsel;
3705  cache->rightendsel = rightendsel;
3706 
3707  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3708 
3709  MemoryContextSwitchTo(oldcontext);
3710 
3711  return cache;
3712 }
Selectivity leftendsel
Definition: pathnodes.h:2159
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2904
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:537
double Selectivity
Definition: nodes.h:670
int pk_strategy
Definition: pathnodes.h:1068
bool pk_nulls_first
Definition: pathnodes.h:1069
Selectivity rightstartsel
Definition: pathnodes.h:2160
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2056
#define lfirst(lc)
Definition: pg_list.h:169
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1066
Oid pk_opfamily
Definition: pathnodes.h:1067
void * palloc(Size size)
Definition: mcxt.c:1062
MemoryContext planner_cxt
Definition: pathnodes.h:335
Selectivity rightendsel
Definition: pathnodes.h:2161
List * scansel_cache
Definition: pathnodes.h:2111
Selectivity leftstartsel
Definition: pathnodes.h:2158

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

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

Referenced by get_parameterized_joinrel_size(), and set_joinrel_size_estimates().

5083 {
5084  /* This apparently-useless variable dodges a compiler bug in VS2013: */
5085  List *restrictlist = restrictlist_in;
5086  JoinType jointype = sjinfo->jointype;
5087  Selectivity fkselec;
5088  Selectivity jselec;
5089  Selectivity pselec;
5090  double nrows;
5091 
5092  /*
5093  * Compute joinclause selectivity. Note that we are only considering
5094  * clauses that become restriction clauses at this join level; we are not
5095  * double-counting them because they were not considered in estimating the
5096  * sizes of the component rels.
5097  *
5098  * First, see whether any of the joinclauses can be matched to known FK
5099  * constraints. If so, drop those clauses from the restrictlist, and
5100  * instead estimate their selectivity using FK semantics. (We do this
5101  * without regard to whether said clauses are local or "pushed down".
5102  * Probably, an FK-matching clause could never be seen as pushed down at
5103  * an outer join, since it would be strict and hence would be grounds for
5104  * join strength reduction.) fkselec gets the net selectivity for
5105  * FK-matching clauses, or 1.0 if there are none.
5106  */
5107  fkselec = get_foreign_key_join_selectivity(root,
5108  outer_rel->relids,
5109  inner_rel->relids,
5110  sjinfo,
5111  &restrictlist);
5112 
5113  /*
5114  * For an outer join, we have to distinguish the selectivity of the join's
5115  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5116  * down". For inner joins we just count them all as joinclauses.
5117  */
5118  if (IS_OUTER_JOIN(jointype))
5119  {
5120  List *joinquals = NIL;
5121  List *pushedquals = NIL;
5122  ListCell *l;
5123 
5124  /* Grovel through the clauses to separate into two lists */
5125  foreach(l, restrictlist)
5126  {
5127  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5128 
5129  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5130  pushedquals = lappend(pushedquals, rinfo);
5131  else
5132  joinquals = lappend(joinquals, rinfo);
5133  }
5134 
5135  /* Get the separate selectivities */
5136  jselec = clauselist_selectivity(root,
5137  joinquals,
5138  0,
5139  jointype,
5140  sjinfo);
5141  pselec = clauselist_selectivity(root,
5142  pushedquals,
5143  0,
5144  jointype,
5145  sjinfo);
5146 
5147  /* Avoid leaking a lot of ListCells */
5148  list_free(joinquals);
5149  list_free(pushedquals);
5150  }
5151  else
5152  {
5153  jselec = clauselist_selectivity(root,
5154  restrictlist,
5155  0,
5156  jointype,
5157  sjinfo);
5158  pselec = 0.0; /* not used, keep compiler quiet */
5159  }
5160 
5161  /*
5162  * Basically, we multiply size of Cartesian product by selectivity.
5163  *
5164  * If we are doing an outer join, take that into account: the joinqual
5165  * selectivity has to be clamped using the knowledge that the output must
5166  * be at least as large as the non-nullable input. However, any
5167  * pushed-down quals are applied after the outer join, so their
5168  * selectivity applies fully.
5169  *
5170  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5171  * of LHS rows that have matches, and we apply that straightforwardly.
5172  */
5173  switch (jointype)
5174  {
5175  case JOIN_INNER:
5176  nrows = outer_rows * inner_rows * fkselec * jselec;
5177  /* pselec not used */
5178  break;
5179  case JOIN_LEFT:
5180  nrows = outer_rows * inner_rows * fkselec * jselec;
5181  if (nrows < outer_rows)
5182  nrows = outer_rows;
5183  nrows *= pselec;
5184  break;
5185  case JOIN_FULL:
5186  nrows = outer_rows * inner_rows * fkselec * jselec;
5187  if (nrows < outer_rows)
5188  nrows = outer_rows;
5189  if (nrows < inner_rows)
5190  nrows = inner_rows;
5191  nrows *= pselec;
5192  break;
5193  case JOIN_SEMI:
5194  nrows = outer_rows * fkselec * jselec;
5195  /* pselec not used */
5196  break;
5197  case JOIN_ANTI:
5198  nrows = outer_rows * (1.0 - fkselec * jselec);
5199  nrows *= pselec;
5200  break;
5201  default:
5202  /* other values not expected here */
5203  elog(ERROR, "unrecognized join type: %d", (int) jointype);
5204  nrows = 0; /* keep compiler quiet */
5205  break;
5206  }
5207 
5208  return clamp_row_est(nrows);
5209 }
#define NIL
Definition: pg_list.h:65
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:754
double Selectivity
Definition: nodes.h:670
JoinType
Definition: nodes.h:705
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:5227
#define ERROR
Definition: elog.h:46
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Relids relids
Definition: pathnodes.h:681
List * lappend(List *list, void *datum)
Definition: list.c:336
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2139
JoinType jointype
Definition: pathnodes.h:2256
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:199
Definition: pg_list.h:50

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 199 of file costsize.c.

References MAXIMUM_ROWCOUNT.

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

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

◆ compute_bitmap_pages()

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

Definition at line 6075 of file costsize.c.

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

6077 {
6078  Cost indexTotalCost;
6079  Selectivity indexSelectivity;
6080  double T;
6081  double pages_fetched;
6082  double tuples_fetched;
6083  double heap_pages;
6084  long maxentries;
6085 
6086  /*
6087  * Fetch total cost of obtaining the bitmap, as well as its total
6088  * selectivity.
6089  */
6090  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6091 
6092  /*
6093  * Estimate number of main-table pages fetched.
6094  */
6095  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6096 
6097  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6098 
6099  /*
6100  * For a single scan, the number of heap pages that need to be fetched is
6101  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6102  * re-reads needed).
6103  */
6104  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6105 
6106  /*
6107  * Calculate the number of pages fetched from the heap. Then based on
6108  * current work_mem estimate get the estimated maxentries in the bitmap.
6109  * (Note that we always do this calculation based on the number of pages
6110  * that would be fetched in a single iteration, even if loop_count > 1.
6111  * That's correct, because only that number of entries will be stored in
6112  * the bitmap at one time.)
6113  */
6114  heap_pages = Min(pages_fetched, baserel->pages);
6115  maxentries = tbm_calculate_entries(work_mem * 1024L);
6116 
6117  if (loop_count > 1)
6118  {
6119  /*
6120  * For repeated bitmap scans, scale up the number of tuples fetched in
6121  * the Mackert and Lohman formula by the number of scans, so that we
6122  * estimate the number of pages fetched by all the scans. Then
6123  * pro-rate for one scan.
6124  */
6125  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6126  baserel->pages,
6127  get_indexpath_pages(bitmapqual),
6128  root);
6129  pages_fetched /= loop_count;
6130  }
6131 
6132  if (pages_fetched >= T)
6133  pages_fetched = T;
6134  else
6135  pages_fetched = ceil(pages_fetched);
6136 
6137  if (maxentries < heap_pages)
6138  {
6139  double exact_pages;
6140  double lossy_pages;
6141 
6142  /*
6143  * Crude approximation of the number of lossy pages. Because of the
6144  * way tbm_lossify() is coded, the number of lossy pages increases
6145  * very sharply as soon as we run short of memory; this formula has
6146  * that property and seems to perform adequately in testing, but it's
6147  * possible we could do better somehow.
6148  */
6149  lossy_pages = Max(0, heap_pages - maxentries / 2);
6150  exact_pages = heap_pages - lossy_pages;
6151 
6152  /*
6153  * If there are lossy pages then recompute the number of tuples
6154  * processed by the bitmap heap node. We assume here that the chance
6155  * of a given tuple coming from an exact page is the same as the
6156  * chance that a given page is exact. This might not be true, but
6157  * it's not clear how we can do any better.
6158  */
6159  if (lossy_pages > 0)
6160  tuples_fetched =
6161  clamp_row_est(indexSelectivity *
6162  (exact_pages / heap_pages) * baserel->tuples +
6163  (lossy_pages / heap_pages) * baserel->tuples);
6164  }
6165 
6166  if (cost)
6167  *cost = indexTotalCost;
6168  if (tuple)
6169  *tuple = tuples_fetched;
6170 
6171  return pages_fetched;
6172 }
#define Min(x, y)
Definition: c.h:986
double Selectivity
Definition: nodes.h:670
int work_mem
Definition: globals.c:124
#define Max(x, y)
Definition: c.h:980
static const uint32 T[65]
Definition: md5.c:119
BlockNumber pages
Definition: pathnodes.h:720
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:905
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:199
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:840
double Cost
Definition: nodes.h:671
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1056
Cardinality tuples
Definition: pathnodes.h:721

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

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

Referenced by add_paths_to_joinrel().

4673 {
4674  Selectivity jselec;
4675  Selectivity nselec;
4676  Selectivity avgmatch;
4677  SpecialJoinInfo norm_sjinfo;
4678  List *joinquals;
4679  ListCell *l;
4680 
4681  /*
4682  * In an ANTI join, we must ignore clauses that are "pushed down", since
4683  * those won't affect the match logic. In a SEMI join, we do not
4684  * distinguish joinquals from "pushed down" quals, so just use the whole
4685  * restrictinfo list. For other outer join types, we should consider only
4686  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4687  */
4688  if (IS_OUTER_JOIN(jointype))
4689  {
4690  joinquals = NIL;
4691  foreach(l, restrictlist)
4692  {
4693  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4694 
4695  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4696  joinquals = lappend(joinquals, rinfo);
4697  }
4698  }
4699  else
4700  joinquals = restrictlist;
4701 
4702  /*
4703  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4704  */
4705  jselec = clauselist_selectivity(root,
4706  joinquals,
4707  0,
4708  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4709  sjinfo);
4710 
4711  /*
4712  * Also get the normal inner-join selectivity of the join clauses.
4713  */
4714  norm_sjinfo.type = T_SpecialJoinInfo;
4715  norm_sjinfo.min_lefthand = outerrel->relids;
4716  norm_sjinfo.min_righthand = innerrel->relids;
4717  norm_sjinfo.syn_lefthand = outerrel->relids;
4718  norm_sjinfo.syn_righthand = innerrel->relids;
4719  norm_sjinfo.jointype = JOIN_INNER;
4720  /* we don't bother trying to make the remaining fields valid */
4721  norm_sjinfo.lhs_strict = false;
4722  norm_sjinfo.delay_upper_joins = false;
4723  norm_sjinfo.semi_can_btree = false;
4724  norm_sjinfo.semi_can_hash = false;
4725  norm_sjinfo.semi_operators = NIL;
4726  norm_sjinfo.semi_rhs_exprs = NIL;
4727 
4728  nselec = clauselist_selectivity(root,
4729  joinquals,
4730  0,
4731  JOIN_INNER,
4732  &norm_sjinfo);
4733 
4734  /* Avoid leaking a lot of ListCells */
4735  if (IS_OUTER_JOIN(jointype))
4736  list_free(joinquals);
4737 
4738  /*
4739  * jselec can be interpreted as the fraction of outer-rel rows that have
4740  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4741  * the fraction of the Cartesian product that matches. So, the average
4742  * number of matches for each outer-rel row that has at least one match is
4743  * nselec * inner_rows / jselec.
4744  *
4745  * Note: it is correct to use the inner rel's "rows" count here, even
4746  * though we might later be considering a parameterized inner path with
4747  * fewer rows. This is because we have included all the join clauses in
4748  * the selectivity estimate.
4749  */
4750  if (jselec > 0) /* protect against zero divide */
4751  {
4752  avgmatch = nselec * innerrel->rows / jselec;
4753  /* Clamp to sane range */
4754  avgmatch = Max(1.0, avgmatch);
4755  }
4756  else
4757  avgmatch = 1.0;
4758 
4759  semifactors->outer_match_frac = jselec;
4760  semifactors->match_count = avgmatch;
4761 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2253
Selectivity outer_match_frac
Definition: pathnodes.h:2510
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:754
double Selectivity
Definition: nodes.h:670
Relids syn_lefthand
Definition: pathnodes.h:2254
Relids syn_righthand
Definition: pathnodes.h:2255
List * semi_rhs_exprs
Definition: pathnodes.h:2263
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Relids relids
Definition: pathnodes.h:681
List * lappend(List *list, void *datum)
Definition: list.c:336
bool delay_upper_joins
Definition: pathnodes.h:2258
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2139
#define Max(x, y)
Definition: c.h:980
Cardinality rows
Definition: pathnodes.h:684
JoinType jointype
Definition: pathnodes.h:2256
Selectivity match_count
Definition: pathnodes.h:2511
List * semi_operators
Definition: pathnodes.h:2262
void list_free(List *list)
Definition: list.c:1391
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
Definition: pg_list.h:50
Relids min_lefthand
Definition: pathnodes.h:2252

◆ cost_agg()

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

Definition at line 2560 of file costsize.c.

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

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

2566 {
2567  double output_tuples;
2568  Cost startup_cost;
2569  Cost total_cost;
2570  AggClauseCosts dummy_aggcosts;
2571 
2572  /* Use all-zero per-aggregate costs if NULL is passed */
2573  if (aggcosts == NULL)
2574  {
2575  Assert(aggstrategy == AGG_HASHED);
2576  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2577  aggcosts = &dummy_aggcosts;
2578  }
2579 
2580  /*
2581  * The transCost.per_tuple component of aggcosts should be charged once
2582  * per input tuple, corresponding to the costs of evaluating the aggregate
2583  * transfns and their input expressions. The finalCost.per_tuple component
2584  * is charged once per output tuple, corresponding to the costs of
2585  * evaluating the finalfns. Startup costs are of course charged but once.
2586  *
2587  * If we are grouping, we charge an additional cpu_operator_cost per
2588  * grouping column per input tuple for grouping comparisons.
2589  *
2590  * We will produce a single output tuple if not grouping, and a tuple per
2591  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2592  *
2593  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2594  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2595  * input path is already sorted appropriately, AGG_SORTED should be
2596  * preferred (since it has no risk of memory overflow). This will happen
2597  * as long as the computed total costs are indeed exactly equal --- but if
2598  * there's roundoff error we might do the wrong thing. So be sure that
2599  * the computations below form the same intermediate values in the same
2600  * order.
2601  */
2602  if (aggstrategy == AGG_PLAIN)
2603  {
2604  startup_cost = input_total_cost;
2605  startup_cost += aggcosts->transCost.startup;
2606  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2607  startup_cost += aggcosts->finalCost.startup;
2608  startup_cost += aggcosts->finalCost.per_tuple;
2609  /* we aren't grouping */
2610  total_cost = startup_cost + cpu_tuple_cost;
2611  output_tuples = 1;
2612  }
2613  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2614  {
2615  /* Here we are able to deliver output on-the-fly */
2616  startup_cost = input_startup_cost;
2617  total_cost = input_total_cost;
2618  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2619  {
2620  startup_cost += disable_cost;
2621  total_cost += disable_cost;
2622  }
2623  /* calcs phrased this way to match HASHED case, see note above */
2624  total_cost += aggcosts->transCost.startup;
2625  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2626  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2627  total_cost += aggcosts->finalCost.startup;
2628  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2629  total_cost += cpu_tuple_cost * numGroups;
2630  output_tuples = numGroups;
2631  }
2632  else
2633  {
2634  /* must be AGG_HASHED */
2635  startup_cost = input_total_cost;
2636  if (!enable_hashagg)
2637  startup_cost += disable_cost;
2638  startup_cost += aggcosts->transCost.startup;
2639  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2640  /* cost of computing hash value */
2641  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2642  startup_cost += aggcosts->finalCost.startup;
2643 
2644  total_cost = startup_cost;
2645  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2646  /* cost of retrieving from hash table */
2647  total_cost += cpu_tuple_cost * numGroups;
2648  output_tuples = numGroups;
2649  }
2650 
2651  /*
2652  * Add the disk costs of hash aggregation that spills to disk.
2653  *
2654  * Groups that go into the hash table stay in memory until finalized, so
2655  * spilling and reprocessing tuples doesn't incur additional invocations
2656  * of transCost or finalCost. Furthermore, the computed hash value is
2657  * stored with the spilled tuples, so we don't incur extra invocations of
2658  * the hash function.
2659  *
2660  * Hash Agg begins returning tuples after the first batch is complete.
2661  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2662  * accrue reads only to total_cost.
2663  */
2664  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2665  {
2666  double pages;
2667  double pages_written = 0.0;
2668  double pages_read = 0.0;
2669  double spill_cost;
2670  double hashentrysize;
2671  double nbatches;
2672  Size mem_limit;
2673  uint64 ngroups_limit;
2674  int num_partitions;
2675  int depth;
2676 
2677  /*
2678  * Estimate number of batches based on the computed limits. If less
2679  * than or equal to one, all groups are expected to fit in memory;
2680  * otherwise we expect to spill.
2681  */
2682  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2683  input_width,
2684  aggcosts->transitionSpace);
2685  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2686  &ngroups_limit, &num_partitions);
2687 
2688  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2689  numGroups / ngroups_limit);
2690 
2691  nbatches = Max(ceil(nbatches), 1.0);
2692  num_partitions = Max(num_partitions, 2);
2693 
2694  /*
2695  * The number of partitions can change at different levels of
2696  * recursion; but for the purposes of this calculation assume it stays
2697  * constant.
2698  */
2699  depth = ceil(log(nbatches) / log(num_partitions));
2700 
2701  /*
2702  * Estimate number of pages read and written. For each level of
2703  * recursion, a tuple must be written and then later read.
2704  */
2705  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2706  pages_written = pages_read = pages * depth;
2707 
2708  /*
2709  * HashAgg has somewhat worse IO behavior than Sort on typical
2710  * hardware/OS combinations. Account for this with a generic penalty.
2711  */
2712  pages_read *= 2.0;
2713  pages_written *= 2.0;
2714 
2715  startup_cost += pages_written * random_page_cost;
2716  total_cost += pages_written * random_page_cost;
2717  total_cost += pages_read * seq_page_cost;
2718 
2719  /* account for CPU cost of spilling a tuple and reading it back */
2720  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2721  startup_cost += spill_cost;
2722  total_cost += spill_cost;
2723  }
2724 
2725  /*
2726  * If there are quals (HAVING quals), account for their cost and
2727  * selectivity.
2728  */
2729  if (quals)
2730  {
2731  QualCost qual_cost;
2732 
2733  cost_qual_eval(&qual_cost, quals, root);
2734  startup_cost += qual_cost.startup;
2735  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2736 
2737  output_tuples = clamp_row_est(output_tuples *
2739  quals,
2740  0,
2741  JOIN_INNER,
2742  NULL));
2743  }
2744 
2745  path->rows = output_tuples;
2746  path->startup_cost = startup_cost;
2747  path->total_cost = total_cost;
2748 }
QualCost finalCost
Definition: pathnodes.h:59
#define MemSet(start, val, len)
Definition: c.h:1008
QualCost transCost
Definition: pathnodes.h:58
Cost startup
Definition: pathnodes.h:45
double random_page_cost
Definition: costsize.c:120
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1676
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
List * aggtransinfos
Definition: pathnodes.h:358
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
Cost total_cost
Definition: pathnodes.h:1194
#define Max(x, y)
Definition: c.h:980
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
static int list_length(const List *l)
Definition: pg_list.h:149
double cpu_tuple_cost
Definition: costsize.c:121
bool enable_hashagg
Definition: costsize.c:140
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1780
Size transitionSpace
Definition: pathnodes.h:60
Cardinality rows
Definition: pathnodes.h:1192
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:199
double seq_page_cost
Definition: costsize.c:119
double Cost
Definition: nodes.h:671

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2143 of file costsize.c.

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

Referenced by create_append_path().

2144 {
2145  ListCell *l;
2146 
2147  apath->path.startup_cost = 0;
2148  apath->path.total_cost = 0;
2149  apath->path.rows = 0;
2150 
2151  if (apath->subpaths == NIL)
2152  return;
2153 
2154  if (!apath->path.parallel_aware)
2155  {
2156  List *pathkeys = apath->path.pathkeys;
2157 
2158  if (pathkeys == NIL)
2159  {
2160  Path *subpath = (Path *) linitial(apath->subpaths);
2161 
2162  /*
2163  * For an unordered, non-parallel-aware Append we take the startup
2164  * cost as the startup cost of the first subpath.
2165  */
2166  apath->path.startup_cost = subpath->startup_cost;
2167 
2168  /* Compute rows and costs as sums of subplan rows and costs. */
2169  foreach(l, apath->subpaths)
2170  {
2171  Path *subpath = (Path *) lfirst(l);
2172 
2173  apath->path.rows += subpath->rows;
2174  apath->path.total_cost += subpath->total_cost;
2175  }
2176  }
2177  else
2178  {
2179  /*
2180  * For an ordered, non-parallel-aware Append we take the startup
2181  * cost as the sum of the subpath startup costs. This ensures
2182  * that we don't underestimate the startup cost when a query's
2183  * LIMIT is such that several of the children have to be run to
2184  * satisfy it. This might be overkill --- another plausible hack
2185  * would be to take the Append's startup cost as the maximum of
2186  * the child startup costs. But we don't want to risk believing
2187  * that an ORDER BY LIMIT query can be satisfied at small cost
2188  * when the first child has small startup cost but later ones
2189  * don't. (If we had the ability to deal with nonlinear cost
2190  * interpolation for partial retrievals, we would not need to be
2191  * so conservative about this.)
2192  *
2193  * This case is also different from the above in that we have to
2194  * account for possibly injecting sorts into subpaths that aren't
2195  * natively ordered.
2196  */
2197  foreach(l, apath->subpaths)
2198  {
2199  Path *subpath = (Path *) lfirst(l);
2200  Path sort_path; /* dummy for result of cost_sort */
2201 
2202  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2203  {
2204  /*
2205  * We'll need to insert a Sort node, so include costs for
2206  * that. We can use the parent's LIMIT if any, since we
2207  * certainly won't pull more than that many tuples from
2208  * any child.
2209  */
2210  cost_sort(&sort_path,
2211  NULL, /* doesn't currently need root */
2212  pathkeys,
2213  subpath->total_cost,
2214  subpath->rows,
2215  subpath->pathtarget->width,
2216  0.0,
2217  work_mem,
2218  apath->limit_tuples);
2219  subpath = &sort_path;
2220  }
2221 
2222  apath->path.rows += subpath->rows;
2223  apath->path.startup_cost += subpath->startup_cost;
2224  apath->path.total_cost += subpath->total_cost;
2225  }
2226  }
2227  }
2228  else /* parallel-aware */
2229  {
2230  int i = 0;
2231  double parallel_divisor = get_parallel_divisor(&apath->path);
2232 
2233  /* Parallel-aware Append never produces ordered output. */
2234  Assert(apath->path.pathkeys == NIL);
2235 
2236  /* Calculate startup cost. */
2237  foreach(l, apath->subpaths)
2238  {
2239  Path *subpath = (Path *) lfirst(l);
2240 
2241  /*
2242  * Append will start returning tuples when the child node having
2243  * lowest startup cost is done setting up. We consider only the
2244  * first few subplans that immediately get a worker assigned.
2245  */
2246  if (i == 0)
2247  apath->path.startup_cost = subpath->startup_cost;
2248  else if (i < apath->path.parallel_workers)
2249  apath->path.startup_cost = Min(apath->path.startup_cost,
2250  subpath->startup_cost);
2251 
2252  /*
2253  * Apply parallel divisor to subpaths. Scale the number of rows
2254  * for each partial subpath based on the ratio of the parallel
2255  * divisor originally used for the subpath to the one we adopted.
2256  * Also add the cost of partial paths to the total cost, but
2257  * ignore non-partial paths for now.
2258  */
2259  if (i < apath->first_partial_path)
2260  apath->path.rows += subpath->rows / parallel_divisor;
2261  else
2262  {
2263  double subpath_parallel_divisor;
2264 
2265  subpath_parallel_divisor = get_parallel_divisor(subpath);
2266  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2267  parallel_divisor);
2268  apath->path.total_cost += subpath->total_cost;
2269  }
2270 
2271  apath->path.rows = clamp_row_est(apath->path.rows);
2272 
2273  i++;
2274  }
2275 
2276  /* Add cost for non-partial subpaths. */
2277  apath->path.total_cost +=
2279  apath->first_partial_path,
2280  apath->path.parallel_workers);
2281  }
2282 
2283  /*
2284  * Although Append does not do any selection or projection, it's not free;
2285  * add a small per-tuple overhead.
2286  */
2287  apath->path.total_cost +=
2289 }
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1183
#define Min(x, y)
Definition: c.h:986
int parallel_workers
Definition: pathnodes.h:1189
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2067
int first_partial_path
Definition: pathnodes.h:1454
List * subpaths
Definition: pathnodes.h:1452
#define linitial(l)
Definition: pg_list.h:174
Cardinality limit_tuples
Definition: pathnodes.h:1455
Cost startup_cost
Definition: pathnodes.h:1193
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6042
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:109
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:2036
int work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1194
List * pathkeys
Definition: pathnodes.h:1196
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
double cpu_tuple_cost
Definition: costsize.c:121
int i
bool parallel_aware
Definition: pathnodes.h:1187
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
Definition: pg_list.h:50
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1099 of file costsize.c.

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

Referenced by create_bitmap_and_path().

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

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1143 of file costsize.c.

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

Referenced by create_bitmap_or_path().

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

◆ cost_bitmap_tree_node()

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

Definition at line 1056 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

Definition at line 1608 of file costsize.c.

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

1610 {
1611  Cost startup_cost = 0;
1612  Cost run_cost = 0;
1613  QualCost qpqual_cost;
1614  Cost cpu_per_tuple;
1615 
1616  /* Should only be applied to base relations that are CTEs */
1617  Assert(baserel->relid > 0);
1618  Assert(baserel->rtekind == RTE_CTE);
1619 
1620  /* Mark the path with the correct row estimate */
1621  if (param_info)
1622  path->rows = param_info->ppi_rows;
1623  else
1624  path->rows = baserel->rows;
1625 
1626  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1627  cpu_per_tuple = cpu_tuple_cost;
1628 
1629  /* Add scanning CPU costs */
1630  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1631 
1632  startup_cost += qpqual_cost.startup;
1633  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1634  run_cost += cpu_per_tuple * baserel->tuples;
1635 
1636  /* tlist eval costs are paid per output row, not per tuple scanned */
1637  startup_cost += path->pathtarget->cost.startup;
1638  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1639 
1640  path->startup_cost = startup_cost;
1641  path->total_cost = startup_cost + run_cost;
1642 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_functionscan()

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

Definition at line 1441 of file costsize.c.

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

Referenced by create_functionscan_path().

1443 {
1444  Cost startup_cost = 0;
1445  Cost run_cost = 0;
1446  QualCost qpqual_cost;
1447  Cost cpu_per_tuple;
1448  RangeTblEntry *rte;
1449  QualCost exprcost;
1450 
1451  /* Should only be applied to base relations that are functions */
1452  Assert(baserel->relid > 0);
1453  rte = planner_rt_fetch(baserel->relid, root);
1454  Assert(rte->rtekind == RTE_FUNCTION);
1455 
1456  /* Mark the path with the correct row estimate */
1457  if (param_info)
1458  path->rows = param_info->ppi_rows;
1459  else
1460  path->rows = baserel->rows;
1461 
1462  /*
1463  * Estimate costs of executing the function expression(s).
1464  *
1465  * Currently, nodeFunctionscan.c always executes the functions to
1466  * completion before returning any rows, and caches the results in a
1467  * tuplestore. So the function eval cost is all startup cost, and per-row
1468  * costs are minimal.
1469  *
1470  * XXX in principle we ought to charge tuplestore spill costs if the
1471  * number of rows is large. However, given how phony our rowcount
1472  * estimates for functions tend to be, there's not a lot of point in that
1473  * refinement right now.
1474  */
1475  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1476 
1477  startup_cost += exprcost.startup + exprcost.per_tuple;
1478 
1479  /* Add scanning CPU costs */
1480  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1481 
1482  startup_cost += qpqual_cost.startup;
1483  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1484  run_cost += cpu_per_tuple * baserel->tuples;
1485 
1486  /* tlist eval costs are paid per output row, not per tuple scanned */
1487  startup_cost += path->pathtarget->cost.startup;
1488  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1489 
1490  path->startup_cost = startup_cost;
1491  path->total_cost = startup_cost + run_cost;
1492 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4334
PathTarget * pathtarget
Definition: pathnodes.h:1183
Definition: nodes.h:537
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:388
Index relid
Definition: pathnodes.h:709
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
List * functions
Definition: parsenodes.h:1101
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
RTEKind rtekind
Definition: parsenodes.h:1007
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_gather()

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

Definition at line 378 of file costsize.c.

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

Referenced by create_gather_path().

381 {
382  Cost startup_cost = 0;
383  Cost run_cost = 0;
384 
385  /* Mark the path with the correct row estimate */
386  if (rows)
387  path->path.rows = *rows;
388  else if (param_info)
389  path->path.rows = param_info->ppi_rows;
390  else
391  path->path.rows = rel->rows;
392 
393  startup_cost = path->subpath->startup_cost;
394 
395  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
396 
397  /* Parallel setup and communication cost. */
398  startup_cost += parallel_setup_cost;
399  run_cost += parallel_tuple_cost * path->path.rows;
400 
401  path->path.startup_cost = startup_cost;
402  path->path.total_cost = (startup_cost + run_cost);
403 }
double parallel_setup_cost
Definition: costsize.c:125
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup_cost
Definition: pathnodes.h:1193
Path * subpath
Definition: pathnodes.h:1560
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:684
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
double parallel_tuple_cost
Definition: costsize.c:124

◆ cost_gather_merge()

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

Definition at line 416 of file costsize.c.

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

Referenced by create_gather_merge_path().

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

◆ cost_group()

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

Definition at line 2832 of file costsize.c.

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

Referenced by choose_hashed_setop(), and create_group_path().

2837 {
2838  double output_tuples;
2839  Cost startup_cost;
2840  Cost total_cost;
2841 
2842  output_tuples = numGroups;
2843  startup_cost = input_startup_cost;
2844  total_cost = input_total_cost;
2845 
2846  /*
2847  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2848  * all columns get compared at most of the tuples.
2849  */
2850  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2851 
2852  /*
2853  * If there are quals (HAVING quals), account for their cost and
2854  * selectivity.
2855  */
2856  if (quals)
2857  {
2858  QualCost qual_cost;
2859 
2860  cost_qual_eval(&qual_cost, quals, root);
2861  startup_cost += qual_cost.startup;
2862  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2863 
2864  output_tuples = clamp_row_est(output_tuples *
2866  quals,
2867  0,
2868  JOIN_INNER,
2869  NULL));
2870  }
2871 
2872  path->rows = output_tuples;
2873  path->startup_cost = startup_cost;
2874  path->total_cost = total_cost;
2875 }
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
Cost startup_cost
Definition: pathnodes.h:1193
double cpu_operator_cost
Definition: costsize.c:123
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1192
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:199
double Cost
Definition: nodes.h:671

◆ cost_incremental_sort()

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

Definition at line 1896 of file costsize.c.

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

Referenced by create_incremental_sort_path().

1901 {
1902  Cost startup_cost = 0,
1903  run_cost = 0,
1904  input_run_cost = input_total_cost - input_startup_cost;
1905  double group_tuples,
1906  input_groups;
1907  Cost group_startup_cost,
1908  group_run_cost,
1909  group_input_run_cost;
1910  List *presortedExprs = NIL;
1911  ListCell *l;
1912  int i = 0;
1913  bool unknown_varno = false;
1914 
1915  Assert(presorted_keys != 0);
1916 
1917  /*
1918  * We want to be sure the cost of a sort is never estimated as zero, even
1919  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1920  */
1921  if (input_tuples < 2.0)
1922  input_tuples = 2.0;
1923 
1924  /* Default estimate of number of groups, capped to one group per row. */
1925  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
1926 
1927  /*
1928  * Extract presorted keys as list of expressions.
1929  *
1930  * We need to be careful about Vars containing "varno 0" which might have
1931  * been introduced by generate_append_tlist, which would confuse
1932  * estimate_num_groups (in fact it'd fail for such expressions). See
1933  * recurse_set_operations which has to deal with the same issue.
1934  *
1935  * Unlike recurse_set_operations we can't access the original target list
1936  * here, and even if we could it's not very clear how useful would that be
1937  * for a set operation combining multiple tables. So we simply detect if
1938  * there are any expressions with "varno 0" and use the default
1939  * DEFAULT_NUM_DISTINCT in that case.
1940  *
1941  * We might also use either 1.0 (a single group) or input_tuples (each row
1942  * being a separate group), pretty much the worst and best case for
1943  * incremental sort. But those are extreme cases and using something in
1944  * between seems reasonable. Furthermore, generate_append_tlist is used
1945  * for set operations, which are likely to produce mostly unique output
1946  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
1947  * while maintaining lower startup cost.
1948  */
1949  foreach(l, pathkeys)
1950  {
1951  PathKey *key = (PathKey *) lfirst(l);
1952  EquivalenceMember *member = (EquivalenceMember *)
1953  linitial(key->pk_eclass->ec_members);
1954 
1955  /*
1956  * Check if the expression contains Var with "varno 0" so that we
1957  * don't call estimate_num_groups in that case.
1958  */
1959  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
1960  {
1961  unknown_varno = true;
1962  break;
1963  }
1964 
1965  /* expression not containing any Vars with "varno 0" */
1966  presortedExprs = lappend(presortedExprs, member->em_expr);
1967 
1968  i++;
1969  if (i >= presorted_keys)
1970  break;
1971  }
1972 
1973  /* Estimate number of groups with equal presorted keys. */
1974  if (!unknown_varno)
1975  input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
1976  NULL, NULL);
1977 
1978  group_tuples = input_tuples / input_groups;
1979  group_input_run_cost = input_run_cost / input_groups;
1980 
1981  /*
1982  * Estimate average cost of sorting of one group where presorted keys are
1983  * equal. Incremental sort is sensitive to distribution of tuples to the
1984  * groups, where we're relying on quite rough assumptions. Thus, we're
1985  * pessimistic about incremental sort performance and increase its average
1986  * group size by half.
1987  */
1988  cost_tuplesort(&group_startup_cost, &group_run_cost,
1989  1.5 * group_tuples, width, comparison_cost, sort_mem,
1990  limit_tuples);
1991 
1992  /*
1993  * Startup cost of incremental sort is the startup cost of its first group
1994  * plus the cost of its input.
1995  */
1996  startup_cost += group_startup_cost
1997  + input_startup_cost + group_input_run_cost;
1998 
1999  /*
2000  * After we started producing tuples from the first group, the cost of
2001  * producing all the tuples is given by the cost to finish processing this
2002  * group, plus the total cost to process the remaining groups, plus the
2003  * remaining cost of input.
2004  */
2005  run_cost += group_run_cost
2006  + (group_run_cost + group_startup_cost) * (input_groups - 1)
2007  + group_input_run_cost * (input_groups - 1);
2008 
2009  /*
2010  * Incremental sort adds some overhead by itself. Firstly, it has to
2011  * detect the sort groups. This is roughly equal to one extra copy and
2012  * comparison per tuple. Secondly, it has to reset the tuplesort context
2013  * for every group.
2014  */
2015  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2016  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2017 
2018  path->rows = input_tuples;
2019  path->startup_cost = startup_cost;
2020  path->total_cost = startup_cost + run_cost;
2021 }
#define NIL
Definition: pg_list.h:65
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
#define Min(x, y)
Definition: c.h:986
Definition: nodes.h:537
#define linitial(l)
Definition: pg_list.h:174
Cost startup_cost
Definition: pathnodes.h:1193
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:1794
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
List * lappend(List *list, void *datum)
Definition: list.c:336
Cost total_cost
Definition: pathnodes.h:1194
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1066
double cpu_tuple_cost
Definition: costsize.c:121
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
int i
Cardinality rows
Definition: pathnodes.h:1192
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
double Cost
Definition: nodes.h:671
List * ec_members
Definition: pathnodes.h:989

◆ cost_index()

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

Definition at line 491 of file costsize.c.

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

Referenced by create_index_path(), and reparameterize_path().

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

◆ cost_material()

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

Definition at line 2365 of file costsize.c.

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

Referenced by create_material_path(), and materialize_finished_plan().

2368 {
2369  Cost startup_cost = input_startup_cost;
2370  Cost run_cost = input_total_cost - input_startup_cost;
2371  double nbytes = relation_byte_size(tuples, width);
2372  long work_mem_bytes = work_mem * 1024L;
2373 
2374  path->rows = tuples;
2375 
2376  /*
2377  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2378  * reflect bookkeeping overhead. (This rate must be more than what
2379  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2380  * if it is exactly the same then there will be a cost tie between
2381  * nestloop with A outer, materialized B inner and nestloop with B outer,
2382  * materialized A inner. The extra cost ensures we'll prefer
2383  * materializing the smaller rel.) Note that this is normally a good deal
2384  * less than cpu_tuple_cost; which is OK because a Material plan node
2385  * doesn't do qual-checking or projection, so it's got less overhead than
2386  * most plan nodes.
2387  */
2388  run_cost += 2 * cpu_operator_cost * tuples;
2389 
2390  /*
2391  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2392  * This cost is assumed to be evenly spread through the plan run phase,
2393  * which isn't exactly accurate but our cost model doesn't allow for
2394  * nonuniform costs within the run phase.
2395  */
2396  if (nbytes > work_mem_bytes)
2397  {
2398  double npages = ceil(nbytes / BLCKSZ);
2399 
2400  run_cost += seq_page_cost * npages;
2401  }
2402 
2403  path->startup_cost = startup_cost;
2404  path->total_cost = startup_cost + run_cost;
2405 }
Cost startup_cost
Definition: pathnodes.h:1193
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
int work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1192
double seq_page_cost
Definition: costsize.c:119
double Cost
Definition: nodes.h:671

◆ cost_memoize_rescan()

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

Definition at line 2421 of file costsize.c.

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

Referenced by cost_rescan().

2423 {
2424  EstimationInfo estinfo;
2425  Cost input_startup_cost = mpath->subpath->startup_cost;
2426  Cost input_total_cost = mpath->subpath->total_cost;
2427  double tuples = mpath->subpath->rows;
2428  double calls = mpath->calls;
2429  int width = mpath->subpath->pathtarget->width;
2430 
2431  double hash_mem_bytes;
2432  double est_entry_bytes;
2433  double est_cache_entries;
2434  double ndistinct;
2435  double evict_ratio;
2436  double hit_ratio;
2437  Cost startup_cost;
2438  Cost total_cost;
2439 
2440  /* available cache space */
2441  hash_mem_bytes = get_hash_memory_limit();
2442 
2443  /*
2444  * Set the number of bytes each cache entry should consume in the cache.
2445  * To provide us with better estimations on how many cache entries we can
2446  * store at once, we make a call to the executor here to ask it what
2447  * memory overheads there are for a single cache entry.
2448  *
2449  * XXX we also store the cache key, but that's not accounted for here.
2450  */
2451  est_entry_bytes = relation_byte_size(tuples, width) +
2453 
2454  /* estimate on the upper limit of cache entries we can hold at once */
2455  est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2456 
2457  /* estimate on the distinct number of parameter values */
2458  ndistinct = estimate_num_groups(root, mpath->param_exprs, calls, NULL,
2459  &estinfo);
2460 
2461  /*
2462  * When the estimation fell back on using a default value, it's a bit too
2463  * risky to assume that it's ok to use a Memoize node. The use of a
2464  * default could cause us to use a Memoize node when it's really
2465  * inappropriate to do so. If we see that this has been done, then we'll
2466  * assume that every call will have unique parameters, which will almost
2467  * certainly mean a MemoizePath will never survive add_path().
2468  */
2469  if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2470  ndistinct = calls;
2471 
2472  /*
2473  * Since we've already estimated the maximum number of entries we can
2474  * store at once and know the estimated number of distinct values we'll be
2475  * called with, we'll take this opportunity to set the path's est_entries.
2476  * This will ultimately determine the hash table size that the executor
2477  * will use. If we leave this at zero, the executor will just choose the
2478  * size itself. Really this is not the right place to do this, but it's
2479  * convenient since everything is already calculated.
2480  */
2481  mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2482  PG_UINT32_MAX);
2483 
2484  /*
2485  * When the number of distinct parameter values is above the amount we can
2486  * store in the cache, then we'll have to evict some entries from the
2487  * cache. This is not free. Here we estimate how often we'll incur the
2488  * cost of that eviction.
2489  */
2490  evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2491 
2492  /*
2493  * In order to estimate how costly a single scan will be, we need to
2494  * attempt to estimate what the cache hit ratio will be. To do that we
2495  * must look at how many scans are estimated in total for this node and
2496  * how many of those scans we expect to get a cache hit.
2497  */
2498  hit_ratio = 1.0 / ndistinct * Min(est_cache_entries, ndistinct) -
2499  (ndistinct / calls);
2500 
2501  /* Ensure we don't go negative */
2502  hit_ratio = Max(hit_ratio, 0.0);
2503 
2504  /*
2505  * Set the total_cost accounting for the expected cache hit ratio. We
2506  * also add on a cpu_operator_cost to account for a cache lookup. This
2507  * will happen regardless of whether it's a cache hit or not.
2508  */
2509  total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2510 
2511  /* Now adjust the total cost to account for cache evictions */
2512 
2513  /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2514  total_cost += cpu_tuple_cost * evict_ratio;
2515 
2516  /*
2517  * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2518  * The per-tuple eviction is really just a pfree, so charging a whole
2519  * cpu_operator_cost seems a little excessive.
2520  */
2521  total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2522 
2523  /*
2524  * Now adjust for storing things in the cache, since that's not free
2525  * either. Everything must go in the cache. We don't proportion this
2526  * over any ratio, just apply it once for the scan. We charge a
2527  * cpu_tuple_cost for the creation of the cache entry and also a
2528  * cpu_operator_cost for each tuple we expect to cache.
2529  */
2530  total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2531 
2532  /*
2533  * Getting the first row must be also be proportioned according to the
2534  * expected cache hit ratio.
2535  */
2536  startup_cost = input_startup_cost * (1.0 - hit_ratio);
2537 
2538  /*
2539  * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2540  * which we'll do regardless of whether it was a cache hit or not.
2541  */
2542  startup_cost += cpu_tuple_cost;
2543 
2544  *rescan_startup_cost = startup_cost;
2545  *rescan_total_cost = total_cost;
2546 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
uint32 est_entries
Definition: pathnodes.h:1519
#define Min(x, y)
Definition: c.h:986
#define PG_UINT32_MAX
Definition: c.h:525
Path * subpath
Definition: pathnodes.h:1513
Cardinality calls
Definition: pathnodes.h:1518
Cost startup_cost
Definition: pathnodes.h:1193
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
double cpu_operator_cost
Definition: costsize.c:123
double ExecEstimateCacheEntryOverheadBytes(double ntuples)
Definition: nodeMemoize.c:1033
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3368
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
List * param_exprs
Definition: pathnodes.h:1515
Cost total_cost
Definition: pathnodes.h:1194
#define Max(x, y)
Definition: c.h:980
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3401
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
uint32 flags
Definition: selfuncs.h:82

◆ cost_merge_append()

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

Definition at line 2316 of file costsize.c.

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

Referenced by create_merge_append_path().

2320 {
2321  Cost startup_cost = 0;
2322  Cost run_cost = 0;
2323  Cost comparison_cost;
2324  double N;
2325  double logN;
2326 
2327  /*
2328  * Avoid log(0)...
2329  */
2330  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2331  logN = LOG2(N);
2332 
2333  /* Assumed cost per tuple comparison */
2334  comparison_cost = 2.0 * cpu_operator_cost;
2335 
2336  /* Heap creation cost */
2337  startup_cost += comparison_cost * N * logN;
2338 
2339  /* Per-tuple heap maintenance cost */
2340  run_cost += tuples * comparison_cost * logN;
2341 
2342  /*
2343  * Although MergeAppend does not do any selection or projection, it's not
2344  * free; add a small per-tuple overhead.
2345  */
2346  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2347 
2348  path->startup_cost = startup_cost + input_startup_cost;
2349  path->total_cost = startup_cost + run_cost + input_total_cost;
2350 }
Cost startup_cost
Definition: pathnodes.h:1193
double cpu_operator_cost
Definition: costsize.c:123
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:109
Cost total_cost
Definition: pathnodes.h:1194
#define LOG2(x)
Definition: costsize.c:102
double cpu_tuple_cost
Definition: costsize.c:121
double Cost
Definition: nodes.h:671

◆ cost_namedtuplestorescan()

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

Definition at line 1649 of file costsize.c.

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

Referenced by create_namedtuplestorescan_path().

1651 {
1652  Cost startup_cost = 0;
1653  Cost run_cost = 0;
1654  QualCost qpqual_cost;
1655  Cost cpu_per_tuple;
1656 
1657  /* Should only be applied to base relations that are Tuplestores */
1658  Assert(baserel->relid > 0);
1659  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1660 
1661  /* Mark the path with the correct row estimate */
1662  if (param_info)
1663  path->rows = param_info->ppi_rows;
1664  else
1665  path->rows = baserel->rows;
1666 
1667  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1668  cpu_per_tuple = cpu_tuple_cost;
1669 
1670  /* Add scanning CPU costs */
1671  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1672 
1673  startup_cost += qpqual_cost.startup;
1674  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1675  run_cost += cpu_per_tuple * baserel->tuples;
1676 
1677  path->startup_cost = startup_cost;
1678  path->total_cost = startup_cost + run_cost;
1679 }
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_qual_eval()

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

Definition at line 4308 of file costsize.c.

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

Referenced by add_foreign_grouping_paths(), cost_agg(), cost_group(), cost_index(), cost_subplan(), cost_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().

4309 {
4310  cost_qual_eval_context context;
4311  ListCell *l;
4312 
4313  context.root = root;
4314  context.total.startup = 0;
4315  context.total.per_tuple = 0;
4316 
4317  /* We don't charge any cost for the implicit ANDing at top level ... */
4318 
4319  foreach(l, quals)
4320  {
4321  Node *qual = (Node *) lfirst(l);
4322 
4323  cost_qual_eval_walker(qual, &context);
4324  }
4325 
4326  *cost = context.total;
4327 }
PlannerInfo * root
Definition: costsize.c:156
Definition: nodes.h:537
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4348
#define lfirst(lc)
Definition: pg_list.h:169

◆ cost_qual_eval_node()

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

Definition at line 4334 of file costsize.c.

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

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

4335 {
4336  cost_qual_eval_context context;
4337 
4338  context.root = root;
4339  context.total.startup = 0;
4340  context.total.per_tuple = 0;
4341 
4342  cost_qual_eval_walker(qual, &context);
4343 
4344  *cost = context.total;
4345 }
PlannerInfo * root
Definition: costsize.c:156
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4348

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 4348 of file costsize.c.

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

Referenced by cost_qual_eval(), and cost_qual_eval_node().

4349 {
4350  if (node == NULL)
4351  return false;
4352 
4353  /*
4354  * RestrictInfo nodes contain an eval_cost field reserved for this
4355  * routine's use, so that it's not necessary to evaluate the qual clause's
4356  * cost more than once. If the clause's cost hasn't been computed yet,
4357  * the field's startup value will contain -1.
4358  */
4359  if (IsA(node, RestrictInfo))
4360  {
4361  RestrictInfo *rinfo = (RestrictInfo *) node;
4362 
4363  if (rinfo->eval_cost.startup < 0)
4364  {
4365  cost_qual_eval_context locContext;
4366 
4367  locContext.root = context->root;
4368  locContext.total.startup = 0;
4369  locContext.total.per_tuple = 0;
4370 
4371  /*
4372  * For an OR clause, recurse into the marked-up tree so that we
4373  * set the eval_cost for contained RestrictInfos too.
4374  */
4375  if (rinfo->orclause)
4376  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4377  else
4378  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4379 
4380  /*
4381  * If the RestrictInfo is marked pseudoconstant, it will be tested
4382  * only once, so treat its cost as all startup cost.
4383  */
4384  if (rinfo->pseudoconstant)
4385  {
4386  /* count one execution during startup */
4387  locContext.total.startup += locContext.total.per_tuple;
4388  locContext.total.per_tuple = 0;
4389  }
4390  rinfo->eval_cost = locContext.total;
4391  }
4392  context->total.startup += rinfo->eval_cost.startup;
4393  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4394  /* do NOT recurse into children */
4395  return false;
4396  }
4397 
4398  /*
4399  * For each operator or function node in the given tree, we charge the
4400  * estimated execution cost given by pg_proc.procost (remember to multiply
4401  * this by cpu_operator_cost).
4402  *
4403  * Vars and Consts are charged zero, and so are boolean operators (AND,
4404  * OR, NOT). Simplistic, but a lot better than no model at all.
4405  *
4406  * Should we try to account for the possibility of short-circuit
4407  * evaluation of AND/OR? Probably *not*, because that would make the
4408  * results depend on the clause ordering, and we are not in any position
4409  * to expect that the current ordering of the clauses is the one that's
4410  * going to end up being used. The above per-RestrictInfo caching would
4411  * not mix well with trying to re-order clauses anyway.
4412  *
4413  * Another issue that is entirely ignored here is that if a set-returning
4414  * function is below top level in the tree, the functions/operators above
4415  * it will need to be evaluated multiple times. In practical use, such
4416  * cases arise so seldom as to not be worth the added complexity needed;
4417  * moreover, since our rowcount estimates for functions tend to be pretty
4418  * phony, the results would also be pretty phony.
4419  */
4420  if (IsA(node, FuncExpr))
4421  {
4422  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4423  &context->total);
4424  }
4425  else if (IsA(node, OpExpr) ||
4426  IsA(node, DistinctExpr) ||
4427  IsA(node, NullIfExpr))
4428  {
4429  /* rely on struct equivalence to treat these all alike */
4430  set_opfuncid((OpExpr *) node);
4431  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4432  &context->total);
4433  }
4434  else if (IsA(node, ScalarArrayOpExpr))
4435  {
4436  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4437  Node *arraynode = (Node *) lsecond(saop->args);
4438  QualCost sacosts;
4439  QualCost hcosts;
4440  int estarraylen = estimate_array_length(arraynode);
4441 
4442  set_sa_opfuncid(saop);
4443  sacosts.startup = sacosts.per_tuple = 0;
4444  add_function_cost(context->root, saop->opfuncid, NULL,
4445  &sacosts);
4446 
4447  if (OidIsValid(saop->hashfuncid))
4448  {
4449  /* Handle costs for hashed ScalarArrayOpExpr */
4450  hcosts.startup = hcosts.per_tuple = 0;
4451 
4452  add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4453  context->total.startup += sacosts.startup + hcosts.startup;
4454 
4455  /* Estimate the cost of building the hashtable. */
4456  context->total.startup += estarraylen * hcosts.per_tuple;
4457 
4458  /*
4459  * XXX should we charge a little bit for sacosts.per_tuple when
4460  * building the table, or is it ok to assume there will be zero
4461  * hash collision?
4462  */
4463 
4464  /*
4465  * Charge for hashtable lookups. Charge a single hash and a
4466  * single comparison.
4467  */
4468  context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4469  }
4470  else
4471  {
4472  /*
4473  * Estimate that the operator will be applied to about half of the
4474  * array elements before the answer is determined.
4475  */
4476  context->total.startup += sacosts.startup;
4477  context->total.per_tuple += sacosts.per_tuple *
4478  estimate_array_length(arraynode) * 0.5;
4479  }
4480  }
4481  else if (IsA(node, Aggref) ||
4482  IsA(node, WindowFunc))
4483  {
4484  /*
4485  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4486  * ie, zero execution cost in the current model, because they behave
4487  * essentially like Vars at execution. We disregard the costs of
4488  * their input expressions for the same reason. The actual execution
4489  * costs of the aggregate/window functions and their arguments have to
4490  * be factored into plan-node-specific costing of the Agg or WindowAgg
4491  * plan node.
4492  */
4493  return false; /* don't recurse into children */
4494  }
4495  else if (IsA(node, CoerceViaIO))
4496  {
4497  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4498  Oid iofunc;
4499  Oid typioparam;
4500  bool typisvarlena;
4501 
4502  /* check the result type's input function */
4503  getTypeInputInfo(iocoerce->resulttype,
4504  &iofunc, &typioparam);
4505  add_function_cost(context->root, iofunc, NULL,
4506  &context->total);
4507  /* check the input type's output function */
4508  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4509  &iofunc, &typisvarlena);
4510  add_function_cost(context->root, iofunc, NULL,
4511  &context->total);
4512  }
4513  else if (IsA(node, ArrayCoerceExpr))
4514  {
4515  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4516  QualCost perelemcost;
4517 
4518  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4519  context->root);
4520  context->total.startup += perelemcost.startup;
4521  if (perelemcost.per_tuple > 0)
4522  context->total.per_tuple += perelemcost.per_tuple *
4523  estimate_array_length((Node *) acoerce->arg);
4524  }
4525  else if (IsA(node, RowCompareExpr))
4526  {
4527  /* Conservatively assume we will check all the columns */
4528  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4529  ListCell *lc;
4530 
4531  foreach(lc, rcexpr->opnos)
4532  {
4533  Oid opid = lfirst_oid(lc);
4534 
4535  add_function_cost(context->root, get_opcode(opid), NULL,
4536  &context->total);
4537  }
4538  }
4539  else if (IsA(node, MinMaxExpr) ||
4540  IsA(node, SQLValueFunction) ||
4541  IsA(node, XmlExpr) ||
4542  IsA(node, CoerceToDomain) ||
4543  IsA(node, NextValueExpr))
4544  {
4545  /* Treat all these as having cost 1 */
4546  context->total.per_tuple += cpu_operator_cost;
4547  }
4548  else if (IsA(node, CurrentOfExpr))
4549  {
4550  /* Report high cost to prevent selection of anything but TID scan */
4551  context->total.startup += disable_cost;
4552  }
4553  else if (IsA(node, SubLink))
4554  {
4555  /* This routine should not be applied to un-planned expressions */
4556  elog(ERROR, "cannot handle unplanned sub-select");
4557  }
4558  else if (IsA(node, SubPlan))
4559  {
4560  /*
4561  * A subplan node in an expression typically indicates that the
4562  * subplan will be executed on each evaluation, so charge accordingly.
4563  * (Sub-selects that can be executed as InitPlans have already been
4564  * removed from the expression.)
4565  */
4566  SubPlan *subplan = (SubPlan *) node;
4567 
4568  context->total.startup += subplan->startup_cost;
4569  context->total.per_tuple += subplan->per_call_cost;
4570 
4571  /*
4572  * We don't want to recurse into the testexpr, because it was already
4573  * counted in the SubPlan node's costs. So we're done.
4574  */
4575  return false;
4576  }
4577  else if (IsA(node, AlternativeSubPlan))
4578  {
4579  /*
4580  * Arbitrarily use the first alternative plan for costing. (We should
4581  * certainly only include one alternative, and we don't yet have
4582  * enough information to know which one the executor is most likely to
4583  * use.)
4584  */
4585  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4586 
4587  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4588  context);
4589  }
4590  else if (IsA(node, PlaceHolderVar))
4591  {
4592  /*
4593  * A PlaceHolderVar should be given cost zero when considering general
4594  * expression evaluation costs. The expense of doing the contained
4595  * expression is charged as part of the tlist eval costs of the scan
4596  * or join where the PHV is first computed (see set_rel_width and
4597  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4598  * double-counting the cost for each level of plan that the PHV
4599  * bubbles up through. Hence, return without recursing into the
4600  * phexpr.
4601  */
4602  return false;
4603  }
4604 
4605  /* recurse into children */
4607  (void *) context);
4608 }
QualCost eval_cost
Definition: pathnodes.h:2096
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4334
#define IsA(nodeptr, _type_)
Definition: nodes.h:588
PlannerInfo * root
Definition: costsize.c:156
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
Expr * orclause
Definition: pathnodes.h:2090
Oid resulttype
Definition: primnodes.h:881
bool pseudoconstant
Definition: pathnodes.h:2064
Definition: nodes.h:537
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1967
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define lsecond(l)
Definition: pg_list.h:179
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
Cost disable_cost
Definition: costsize.c:129
double cpu_operator_cost
Definition: costsize.c:123
Expr * arg
Definition: primnodes.h:880
Expr * elemexpr
Definition: primnodes.h:905
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2821
Expr * clause
Definition: pathnodes.h:2056
Cost per_call_cost
Definition: primnodes.h:776
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4348
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1683
#define elog(elevel,...)
Definition: elog.h:232
Cost startup_cost
Definition: primnodes.h:775
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1694
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ cost_recursive_union()

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

Definition at line 1723 of file costsize.c.

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

Referenced by create_recursiveunion_path().

1724 {
1725  Cost startup_cost;
1726  Cost total_cost;
1727  double total_rows;
1728 
1729  /* We probably have decent estimates for the non-recursive term */
1730  startup_cost = nrterm->startup_cost;
1731  total_cost = nrterm->total_cost;
1732  total_rows = nrterm->rows;
1733 
1734  /*
1735  * We arbitrarily assume that about 10 recursive iterations will be
1736  * needed, and that we've managed to get a good fix on the cost and output
1737  * size of each one of them. These are mighty shaky assumptions but it's
1738  * hard to see how to do better.
1739  */
1740  total_cost += 10 * rterm->total_cost;
1741  total_rows += 10 * rterm->rows;
1742 
1743  /*
1744  * Also charge cpu_tuple_cost per row to account for the costs of
1745  * manipulating the tuplestores. (We don't worry about possible
1746  * spill-to-disk costs.)
1747  */
1748  total_cost += cpu_tuple_cost * total_rows;
1749 
1750  runion->startup_cost = startup_cost;
1751  runion->total_cost = total_cost;
1752  runion->rows = total_rows;
1753  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1754  rterm->pathtarget->width);
1755 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Cost startup_cost
Definition: pathnodes.h:1193
Cost total_cost
Definition: pathnodes.h:1194
#define Max(x, y)
Definition: c.h:980
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671

◆ cost_rescan()

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

Definition at line 4196 of file costsize.c.

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

Referenced by initial_cost_nestloop().

4199 {
4200  switch (path->pathtype)
4201  {
4202  case T_FunctionScan:
4203 
4204  /*
4205  * Currently, nodeFunctionscan.c always executes the function to
4206  * completion before returning any rows, and caches the results in
4207  * a tuplestore. So the function eval cost is all startup cost
4208  * and isn't paid over again on rescans. However, all run costs
4209  * will be paid over again.
4210  */
4211  *rescan_startup_cost = 0;
4212  *rescan_total_cost = path->total_cost - path->startup_cost;
4213  break;
4214  case T_HashJoin:
4215 
4216  /*
4217  * If it's a single-batch join, we don't need to rebuild the hash
4218  * table during a rescan.
4219  */
4220  if (((HashPath *) path)->num_batches == 1)
4221  {
4222  /* Startup cost is exactly the cost of hash table building */
4223  *rescan_startup_cost = 0;
4224  *rescan_total_cost = path->total_cost - path->startup_cost;
4225  }
4226  else
4227  {
4228  /* Otherwise, no special treatment */
4229  *rescan_startup_cost = path->startup_cost;
4230  *rescan_total_cost = path->total_cost;
4231  }
4232  break;
4233  case T_CteScan:
4234  case T_WorkTableScan:
4235  {
4236  /*
4237  * These plan types materialize their final result in a
4238  * tuplestore or tuplesort object. So the rescan cost is only
4239  * cpu_tuple_cost per tuple, unless the result is large enough
4240  * to spill to disk.
4241  */
4242  Cost run_cost = cpu_tuple_cost * path->rows;
4243  double nbytes = relation_byte_size(path->rows,
4244  path->pathtarget->width);
4245  long work_mem_bytes = work_mem * 1024L;
4246 
4247  if (nbytes > work_mem_bytes)
4248  {
4249  /* It will spill, so account for re-read cost */
4250  double npages = ceil(nbytes / BLCKSZ);
4251 
4252  run_cost += seq_page_cost * npages;
4253  }
4254  *rescan_startup_cost = 0;
4255  *rescan_total_cost = run_cost;
4256  }
4257  break;
4258  case T_Material:
4259  case T_Sort:
4260  {
4261  /*
4262  * These plan types not only materialize their results, but do
4263  * not implement qual filtering or projection. So they are
4264  * even cheaper to rescan than the ones above. We charge only
4265  * cpu_operator_cost per tuple. (Note: keep that in sync with
4266  * the run_cost charge in cost_sort, and also see comments in
4267  * cost_material before you change it.)
4268  */
4269  Cost run_cost = cpu_operator_cost * path->rows;
4270  double nbytes = relation_byte_size(path->rows,
4271  path->pathtarget->width);
4272  long work_mem_bytes = work_mem * 1024L;
4273 
4274  if (nbytes > work_mem_bytes)
4275  {
4276  /* It will spill, so account for re-read cost */
4277  double npages = ceil(nbytes / BLCKSZ);
4278 
4279  run_cost += seq_page_cost * npages;
4280  }
4281  *rescan_startup_cost = 0;
4282  *rescan_total_cost = run_cost;
4283  }
4284  break;
4285  case T_Memoize:
4286  /* All the hard work is done by cost_memoize_rescan */
4287  cost_memoize_rescan(root, (MemoizePath *) path,
4288  rescan_startup_cost, rescan_total_cost);
4289  break;
4290  default:
4291  *rescan_startup_cost = path->startup_cost;
4292  *rescan_total_cost = path->total_cost;
4293  break;
4294  }
4295 }
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:2421
Definition: nodes.h:78
NodeTag pathtype
Definition: pathnodes.h:1180
Cost startup_cost
Definition: pathnodes.h:1193
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
int work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1194
double cpu_tuple_cost
Definition: costsize.c:121
double seq_page_cost
Definition: costsize.c:119
double Cost
Definition: nodes.h:671

◆ cost_resultscan()

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

Definition at line 1686 of file costsize.c.

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

Referenced by create_resultscan_path().

1688 {
1689  Cost startup_cost = 0;
1690  Cost run_cost = 0;
1691  QualCost qpqual_cost;
1692  Cost cpu_per_tuple;
1693 
1694  /* Should only be applied to RTE_RESULT base relations */
1695  Assert(baserel->relid > 0);
1696  Assert(baserel->rtekind == RTE_RESULT);
1697 
1698  /* Mark the path with the correct row estimate */
1699  if (param_info)
1700  path->rows = param_info->ppi_rows;
1701  else
1702  path->rows = baserel->rows;
1703 
1704  /* We charge qual cost plus cpu_tuple_cost */
1705  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1706 
1707  startup_cost += qpqual_cost.startup;
1708  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1709  run_cost += cpu_per_tuple * baserel->tuples;
1710 
1711  path->startup_cost = startup_cost;
1712  path->total_cost = startup_cost + run_cost;
1713 }
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_samplescan()

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

Definition at line 303 of file costsize.c.

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

Referenced by create_samplescan_path().

305 {
306  Cost startup_cost = 0;
307  Cost run_cost = 0;
308  RangeTblEntry *rte;
309  TableSampleClause *tsc;
310  TsmRoutine *tsm;
311  double spc_seq_page_cost,
312  spc_random_page_cost,
313  spc_page_cost;
314  QualCost qpqual_cost;
315  Cost cpu_per_tuple;
316 
317  /* Should only be applied to base relations with tablesample clauses */
318  Assert(baserel->relid > 0);
319  rte = planner_rt_fetch(baserel->relid, root);
320  Assert(rte->rtekind == RTE_RELATION);
321  tsc = rte->tablesample;
322  Assert(tsc != NULL);
323  tsm = GetTsmRoutine(tsc->tsmhandler);
324 
325  /* Mark the path with the correct row estimate */
326  if (param_info)
327  path->rows = param_info->ppi_rows;
328  else
329  path->rows = baserel->rows;
330 
331  /* fetch estimated page cost for tablespace containing table */
333  &spc_random_page_cost,
334  &spc_seq_page_cost);
335 
336  /* if NextSampleBlock is used, assume random access, else sequential */
337  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
338  spc_random_page_cost : spc_seq_page_cost;
339 
340  /*
341  * disk costs (recall that baserel->pages has already been set to the
342  * number of pages the sampling method will visit)
343  */
344  run_cost += spc_page_cost * baserel->pages;
345 
346  /*
347  * CPU costs (recall that baserel->tuples has already been set to the
348  * number of tuples the sampling method will select). Note that we ignore
349  * execution cost of the TABLESAMPLE parameter expressions; they will be
350  * evaluated only once per scan, and in most usages they'll likely be
351  * simple constants anyway. We also don't charge anything for the
352  * calculations the sampling method might do internally.
353  */
354  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
355 
356  startup_cost += qpqual_cost.startup;
357  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
358  run_cost += cpu_per_tuple * baserel->tuples;
359  /* tlist eval costs are paid per output row, not per tuple scanned */
360  startup_cost += path->pathtarget->cost.startup;
361  run_cost += path->pathtarget->cost.per_tuple * path->rows;
362 
363  path->startup_cost = startup_cost;
364  path->total_cost = startup_cost + run_cost;
365 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Oid reltablespace
Definition: pathnodes.h:710
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:388
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:709
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: pathnodes.h:720
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
RTEKind rtekind
Definition: parsenodes.h:1007
Cardinality rows
Definition: pathnodes.h:1192
struct TableSampleClause * tablesample
Definition: parsenodes.h:1037
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_seqscan()

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

Definition at line 226 of file costsize.c.

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

Referenced by create_seqscan_path().

228 {
229  Cost startup_cost = 0;
230  Cost cpu_run_cost;
231  Cost disk_run_cost;
232  double spc_seq_page_cost;
233  QualCost qpqual_cost;
234  Cost cpu_per_tuple;
235 
236  /* Should only be applied to base relations */
237  Assert(baserel->relid > 0);
238  Assert(baserel->rtekind == RTE_RELATION);
239 
240  /* Mark the path with the correct row estimate */
241  if (param_info)
242  path->rows = param_info->ppi_rows;
243  else
244  path->rows = baserel->rows;
245 
246  if (!enable_seqscan)
247  startup_cost += disable_cost;
248 
249  /* fetch estimated page cost for tablespace containing table */
251  NULL,
252  &spc_seq_page_cost);
253 
254  /*
255  * disk costs
256  */
257  disk_run_cost = spc_seq_page_cost * baserel->pages;
258 
259  /* CPU costs */
260  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
261 
262  startup_cost += qpqual_cost.startup;
263  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
264  cpu_run_cost = cpu_per_tuple * baserel->tuples;
265  /* tlist eval costs are paid per output row, not per tuple scanned */
266  startup_cost += path->pathtarget->cost.startup;
267  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
268 
269  /* Adjust costing for parallelism, if used. */
270  if (path->parallel_workers > 0)
271  {
272  double parallel_divisor = get_parallel_divisor(path);
273 
274  /* The CPU cost is divided among all the workers. */
275  cpu_run_cost /= parallel_divisor;
276 
277  /*
278  * It may be possible to amortize some of the I/O cost, but probably
279  * not very much, because most operating systems already do aggressive
280  * prefetching. For now, we assume that the disk run cost can't be
281  * amortized at all.
282  */
283 
284  /*
285  * In the case of a parallel plan, the row count needs to represent
286  * the number of tuples processed per worker.
287  */
288  path->rows = clamp_row_est(path->rows / parallel_divisor);
289  }
290 
291  path->startup_cost = startup_cost;
292  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
293 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Oid reltablespace
Definition: pathnodes.h:710
int parallel_workers
Definition: pathnodes.h:1189
Cardinality ppi_rows
Definition: pathnodes.h:1142
bool enable_seqscan
Definition: costsize.c:133
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6042
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
BlockNumber pages
Definition: pathnodes.h:720
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_sort()

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

Definition at line 2036 of file costsize.c.

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

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

2041 {
2042  Cost startup_cost;
2043  Cost run_cost;
2044 
2045  cost_tuplesort(&startup_cost, &run_cost,
2046  tuples, width,
2047  comparison_cost, sort_mem,
2048  limit_tuples);
2049 
2050  if (!enable_sort)
2051  startup_cost += disable_cost;
2052 
2053  startup_cost += input_cost;
2054 
2055  path->rows = tuples;
2056  path->startup_cost = startup_cost;
2057  path->total_cost = startup_cost + run_cost;
2058 }
bool enable_sort
Definition: costsize.c:138
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
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:1794
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671

◆ cost_subplan()

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

Definition at line 4103 of file costsize.c.

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

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

4104 {
4105  QualCost sp_cost;
4106 
4107  /* Figure any cost for evaluating the testexpr */
4108  cost_qual_eval(&sp_cost,
4109  make_ands_implicit((Expr *) subplan->testexpr),
4110  root);
4111 
4112  if (subplan->useHashTable)
4113  {
4114  /*
4115  * If we are using a hash table for the subquery outputs, then the
4116  * cost of evaluating the query is a one-time cost. We charge one
4117  * cpu_operator_cost per tuple for the work of loading the hashtable,
4118  * too.
4119  */
4120  sp_cost.startup += plan->total_cost +
4121  cpu_operator_cost * plan->plan_rows;
4122 
4123  /*
4124  * The per-tuple costs include the cost of evaluating the lefthand
4125  * expressions, plus the cost of probing the hashtable. We already
4126  * accounted for the lefthand expressions as part of the testexpr, and
4127  * will also have counted one cpu_operator_cost for each comparison
4128  * operator. That is probably too low for the probing cost, but it's
4129  * hard to make a better estimate, so live with it for now.
4130  */
4131  }
4132  else
4133  {
4134  /*
4135  * Otherwise we will be rescanning the subplan output on each
4136  * evaluation. We need to estimate how much of the output we will
4137  * actually need to scan. NOTE: this logic should agree with the
4138  * tuple_fraction estimates used by make_subplan() in
4139  * plan/subselect.c.
4140  */
4141  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4142 
4143  if (subplan->subLinkType == EXISTS_SUBLINK)
4144  {
4145  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4146  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4147  }
4148  else if (subplan->subLinkType == ALL_SUBLINK ||
4149  subplan->subLinkType == ANY_SUBLINK)
4150  {
4151  /* assume we need 50% of the tuples */
4152  sp_cost.per_tuple += 0.50 * plan_run_cost;
4153  /* also charge a cpu_operator_cost per row examined */
4154  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4155  }
4156  else
4157  {
4158  /* assume we need all tuples */
4159  sp_cost.per_tuple += plan_run_cost;
4160  }
4161 
4162  /*
4163  * Also account for subplan's startup cost. If the subplan is
4164  * uncorrelated or undirect correlated, AND its topmost node is one
4165  * that materializes its output, assume that we'll only need to pay
4166  * its startup cost once; otherwise assume we pay the startup cost
4167  * every time.
4168  */
4169  if (subplan->parParam == NIL &&
4171  sp_cost.startup += plan->startup_cost;
4172  else
4173  sp_cost.per_tuple += plan->startup_cost;
4174  }
4175 
4176  subplan->startup_cost = sp_cost.startup;
4177  subplan->per_call_cost = sp_cost.per_tuple;
4178 }
#define NIL
Definition: pg_list.h:65
SubLinkType subLinkType
Definition: primnodes.h:747
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
Cost startup_cost
Definition: plannodes.h:117
double cpu_operator_cost
Definition: costsize.c:123
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Node * testexpr
Definition: primnodes.h:749
Cost per_call_cost
Definition: primnodes.h:776
Cardinality plan_rows
Definition: plannodes.h:123
List * parParam
Definition: primnodes.h:772
#define nodeTag(nodeptr)
Definition: nodes.h:542
Cost total_cost
Definition: plannodes.h:118
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
bool useHashTable
Definition: primnodes.h:761
Cost startup_cost
Definition: primnodes.h:775
double clamp_row_est(double nrows)
Definition: costsize.c:199
double Cost
Definition: nodes.h:671

◆ cost_subqueryscan()

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

Definition at line 1392 of file costsize.c.

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

Referenced by create_subqueryscan_path().

1394 {
1395  Cost startup_cost;
1396  Cost run_cost;
1397  QualCost qpqual_cost;
1398  Cost cpu_per_tuple;
1399 
1400  /* Should only be applied to base relations that are subqueries */
1401  Assert(baserel->relid > 0);
1402  Assert(baserel->rtekind == RTE_SUBQUERY);
1403 
1404  /* Mark the path with the correct row estimate */
1405  if (param_info)
1406  path->path.rows = param_info->ppi_rows;
1407  else
1408  path->path.rows = baserel->rows;
1409 
1410  /*
1411  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1412  * any restriction clauses and tlist that will be attached to the
1413  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1414  * projection overhead.
1415  */
1416  path->path.startup_cost = path->subpath->startup_cost;
1417  path->path.total_cost = path->subpath->total_cost;
1418 
1419  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1420 
1421  startup_cost = qpqual_cost.startup;
1422  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1423  run_cost = cpu_per_tuple * baserel->tuples;
1424 
1425  /* tlist eval costs are paid per output row, not per tuple scanned */
1426  startup_cost += path->path.pathtarget->cost.startup;
1427  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1428 
1429  path->path.startup_cost += startup_cost;
1430  path->path.total_cost += startup_cost + run_cost;
1431 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_tablefuncscan()

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

Definition at line 1502 of file costsize.c.

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

Referenced by create_tablefuncscan_path().

1504 {
1505  Cost startup_cost = 0;
1506  Cost run_cost = 0;
1507  QualCost qpqual_cost;
1508  Cost cpu_per_tuple;
1509  RangeTblEntry *rte;
1510  QualCost exprcost;
1511 
1512  /* Should only be applied to base relations that are functions */
1513  Assert(baserel->relid > 0);
1514  rte = planner_rt_fetch(baserel->relid, root);
1515  Assert(rte->rtekind == RTE_TABLEFUNC);
1516 
1517  /* Mark the path with the correct row estimate */
1518  if (param_info)
1519  path->rows = param_info->ppi_rows;
1520  else
1521  path->rows = baserel->rows;
1522 
1523  /*
1524  * Estimate costs of executing the table func expression(s).
1525  *
1526  * XXX in principle we ought to charge tuplestore spill costs if the
1527  * number of rows is large. However, given how phony our rowcount
1528  * estimates for tablefuncs tend to be, there's not a lot of point in that
1529  * refinement right now.
1530  */
1531  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1532 
1533  startup_cost += exprcost.startup + exprcost.per_tuple;
1534 
1535  /* Add scanning CPU costs */
1536  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1537 
1538  startup_cost += qpqual_cost.startup;
1539  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1540  run_cost += cpu_per_tuple * baserel->tuples;
1541 
1542  /* tlist eval costs are paid per output row, not per tuple scanned */
1543  startup_cost += path->pathtarget->cost.startup;
1544  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1545 
1546  path->startup_cost = startup_cost;
1547  path->total_cost = startup_cost + run_cost;
1548 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4334
PathTarget * pathtarget
Definition: pathnodes.h:1183
Definition: nodes.h:537
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
TableFunc * tablefunc
Definition: parsenodes.h:1107
Cost startup_cost
Definition: pathnodes.h:1193
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:388
Index relid
Definition: pathnodes.h:709
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
RTEKind rtekind
Definition: parsenodes.h:1007
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_tidrangescan()

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

Definition at line 1299 of file costsize.c.

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

Referenced by create_tidrangescan_path().

1302 {
1303  Selectivity selectivity;
1304  double pages;
1305  Cost startup_cost = 0;
1306  Cost run_cost = 0;
1307  QualCost qpqual_cost;
1308  Cost cpu_per_tuple;
1309  QualCost tid_qual_cost;
1310  double ntuples;
1311  double nseqpages;
1312  double spc_random_page_cost;
1313  double spc_seq_page_cost;
1314 
1315  /* Should only be applied to base relations */
1316  Assert(baserel->relid > 0);
1317  Assert(baserel->rtekind == RTE_RELATION);
1318 
1319  /* Mark the path with the correct row estimate */
1320  if (param_info)
1321  path->rows = param_info->ppi_rows;
1322  else
1323  path->rows = baserel->rows;
1324 
1325  /* Count how many tuples and pages we expect to scan */
1326  selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1327  JOIN_INNER, NULL);
1328  pages = ceil(selectivity * baserel->pages);
1329 
1330  if (pages <= 0.0)
1331  pages = 1.0;
1332 
1333  /*
1334  * The first page in a range requires a random seek, but each subsequent
1335  * page is just a normal sequential page read. NOTE: it's desirable for
1336  * TID Range Scans to cost more than the equivalent Sequential Scans,
1337  * because Seq Scans have some performance advantages such as scan
1338  * synchronization and parallelizability, and we'd prefer one of them to
1339  * be picked unless a TID Range Scan really is better.
1340  */
1341  ntuples = selectivity * baserel->tuples;
1342  nseqpages = pages - 1.0;
1343 
1344  if (!enable_tidscan)
1345  startup_cost += disable_cost;
1346 
1347  /*
1348  * The TID qual expressions will be computed once, any other baserestrict
1349  * quals once per retrieved tuple.
1350  */
1351  cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1352 
1353  /* fetch estimated page cost for tablespace containing table */
1355  &spc_random_page_cost,
1356  &spc_seq_page_cost);
1357 
1358  /* disk costs; 1 random page and the remainder as seq pages */
1359  run_cost += spc_random_page_cost + spc_seq_page_cost * nseqpages;
1360 
1361  /* Add scanning CPU costs */
1362  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1363 
1364  /*
1365  * XXX currently we assume TID quals are a subset of qpquals at this
1366  * point; they will be removed (if possible) when we create the plan, so
1367  * we subtract their cost from the total qpqual cost. (If the TID quals
1368  * can't be removed, this is a mistake and we're going to underestimate
1369  * the CPU cost a bit.)
1370  */
1371  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1372  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1373  tid_qual_cost.per_tuple;
1374  run_cost += cpu_per_tuple * ntuples;
1375 
1376  /* tlist eval costs are paid per output row, not per tuple scanned */
1377  startup_cost += path->pathtarget->cost.startup;
1378  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1379 
1380  path->startup_cost = startup_cost;
1381  path->total_cost = startup_cost + run_cost;
1382 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
bool enable_tidscan
Definition: costsize.c:137
Oid reltablespace
Definition: pathnodes.h:710
double Selectivity
Definition: nodes.h:670
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
BlockNumber pages
Definition: pathnodes.h:720
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_tidscan()

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

Definition at line 1191 of file costsize.c.

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

Referenced by create_tidscan_path().

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

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

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

Referenced by cost_incremental_sort(), and cost_sort().

1798 {
1799  double input_bytes = relation_byte_size(tuples, width);
1800  double output_bytes;
1801  double output_tuples;
1802  long sort_mem_bytes = sort_mem * 1024L;
1803 
1804  /*
1805  * We want to be sure the cost of a sort is never estimated as zero, even
1806  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1807  */
1808  if (tuples < 2.0)
1809  tuples = 2.0;
1810 
1811  /* Include the default cost-per-comparison */
1812  comparison_cost += 2.0 * cpu_operator_cost;
1813 
1814  /* Do we have a useful LIMIT? */
1815  if (limit_tuples > 0 && limit_tuples < tuples)
1816  {
1817  output_tuples = limit_tuples;
1818  output_bytes = relation_byte_size(output_tuples, width);
1819  }
1820  else
1821  {
1822  output_tuples = tuples;
1823  output_bytes = input_bytes;
1824  }
1825 
1826  if (output_bytes > sort_mem_bytes)
1827  {
1828  /*
1829  * We'll have to use a disk-based sort of all the tuples
1830  */
1831  double npages = ceil(input_bytes / BLCKSZ);
1832  double nruns = input_bytes / sort_mem_bytes;
1833  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1834  double log_runs;
1835  double npageaccesses;
1836 
1837  /*
1838  * CPU costs
1839  *
1840  * Assume about N log2 N comparisons
1841  */
1842  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1843 
1844  /* Disk costs */
1845 
1846  /* Compute logM(r) as log(r) / log(M) */
1847  if (nruns > mergeorder)
1848  log_runs = ceil(log(nruns) / log(mergeorder));
1849  else
1850  log_runs = 1.0;
1851  npageaccesses = 2.0 * npages * log_runs;
1852  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1853  *startup_cost += npageaccesses *
1854  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1855  }
1856  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1857  {
1858  /*
1859  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1860  * a total number of tuple comparisons of N log2 K; but the constant
1861  * factor is a bit higher than for quicksort. Tweak it so that the
1862  * cost curve is continuous at the crossover point.
1863  */
1864  *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
1865  }
1866  else
1867  {
1868  /* We'll use plain quicksort on all the input tuples */
1869  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1870  }
1871 
1872  /*
1873  * Also charge a small amount (arbitrarily set equal to operator cost) per
1874  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1875  * doesn't do qual-checking or projection, so it has less overhead than
1876  * most plan nodes. Note it's correct to use tuples not output_tuples
1877  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1878  * counting the LIMIT otherwise.
1879  */
1880  *run_cost = cpu_operator_cost * tuples;
1881 }
double random_page_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
#define LOG2(x)
Definition: costsize.c:102
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2602
double seq_page_cost
Definition: costsize.c:119

◆ cost_valuesscan()

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

Definition at line 1558 of file costsize.c.

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

Referenced by create_valuesscan_path().

1560 {
1561  Cost startup_cost = 0;
1562  Cost run_cost = 0;
1563  QualCost qpqual_cost;
1564  Cost cpu_per_tuple;
1565 
1566  /* Should only be applied to base relations that are values lists */
1567  Assert(baserel->relid > 0);
1568  Assert(baserel->rtekind == RTE_VALUES);
1569 
1570  /* Mark the path with the correct row estimate */
1571  if (param_info)
1572  path->rows = param_info->ppi_rows;
1573  else
1574  path->rows = baserel->rows;
1575 
1576  /*
1577  * For now, estimate list evaluation cost at one operator eval per list
1578  * (probably pretty bogus, but is it worth being smarter?)
1579  */
1580  cpu_per_tuple = cpu_operator_cost;
1581 
1582  /* Add scanning CPU costs */
1583  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1584 
1585  startup_cost += qpqual_cost.startup;
1586  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1587  run_cost += cpu_per_tuple * baserel->tuples;
1588 
1589  /* tlist eval costs are paid per output row, not per tuple scanned */
1590  startup_cost += path->pathtarget->cost.startup;
1591  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1592 
1593  path->startup_cost = startup_cost;
1594  path->total_cost = startup_cost + run_cost;
1595 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
double cpu_operator_cost
Definition: costsize.c:123
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_windowagg()

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

Definition at line 2758 of file costsize.c.

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

Referenced by create_windowagg_path().

2762 {
2763  Cost startup_cost;
2764  Cost total_cost;
2765  ListCell *lc;
2766 
2767  startup_cost = input_startup_cost;
2768  total_cost = input_total_cost;
2769 
2770  /*
2771  * Window functions are assumed to cost their stated execution cost, plus
2772  * the cost of evaluating their input expressions, per tuple. Since they
2773  * may in fact evaluate their inputs at multiple rows during each cycle,
2774  * this could be a drastic underestimate; but without a way to know how
2775  * many rows the window function will fetch, it's hard to do better. In
2776  * any case, it's a good estimate for all the built-in window functions,
2777  * so we'll just do this for now.
2778  */
2779  foreach(lc, windowFuncs)
2780  {
2781  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2782  Cost wfunccost;
2783  QualCost argcosts;
2784 
2785  argcosts.startup = argcosts.per_tuple = 0;
2786  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2787  &argcosts);
2788  startup_cost += argcosts.startup;
2789  wfunccost = argcosts.per_tuple;
2790 
2791  /* also add the input expressions' cost to per-input-row costs */
2792  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2793  startup_cost += argcosts.startup;
2794  wfunccost += argcosts.per_tuple;
2795 
2796  /*
2797  * Add the filter's cost to per-input-row costs. XXX We should reduce
2798  * input expression costs according to filter selectivity.
2799  */
2800  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2801  startup_cost += argcosts.startup;
2802  wfunccost += argcosts.per_tuple;
2803 
2804  total_cost += wfunccost * input_tuples;
2805  }
2806 
2807  /*
2808  * We also charge cpu_operator_cost per grouping column per tuple for
2809  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2810  * overhead.
2811  *
2812  * XXX this neglects costs of spooling the data to disk when it overflows
2813  * work_mem. Sooner or later that should get accounted for.
2814  */
2815  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2816  total_cost += cpu_tuple_cost * input_tuples;
2817 
2818  path->rows = input_tuples;
2819  path->startup_cost = startup_cost;
2820  path->total_cost = total_cost;
2821 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4334
List * args
Definition: primnodes.h:390
Definition: nodes.h:537
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1967
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
#define lfirst_node(type, lc)
Definition: pg_list.h:172
double cpu_operator_cost
Definition: costsize.c:123
Oid winfnoid
Definition: primnodes.h:386
Cost total_cost
Definition: pathnodes.h:1194
Expr * aggfilter
Definition: primnodes.h:391
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:671

◆ extract_nonindex_conditions()

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

Definition at line 782 of file costsize.c.

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

Referenced by cost_index().

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

◆ final_cost_hashjoin()

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

Definition at line 3849 of file costsize.c.

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

Referenced by create_hashjoin_path().

3852 {
3853  Path *outer_path = path->jpath.outerjoinpath;
3854  Path *inner_path = path->jpath.innerjoinpath;
3855  double outer_path_rows = outer_path->rows;
3856  double inner_path_rows = inner_path->rows;
3857  double inner_path_rows_total = workspace->inner_rows_total;
3858  List *hashclauses = path->path_hashclauses;
3859  Cost startup_cost = workspace->startup_cost;
3860  Cost run_cost = workspace->run_cost;
3861  int numbuckets = workspace->numbuckets;
3862  int numbatches = workspace->numbatches;
3863  Cost cpu_per_tuple;
3864  QualCost hash_qual_cost;
3865  QualCost qp_qual_cost;
3866  double hashjointuples;
3867  double virtualbuckets;
3868  Selectivity innerbucketsize;
3869  Selectivity innermcvfreq;
3870  ListCell *hcl;
3871 
3872  /* Mark the path with the correct row estimate */
3873  if (path->jpath.path.param_info)
3874  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3875  else
3876  path->jpath.path.rows = path->jpath.path.parent->rows;
3877 
3878  /* For partial paths, scale row estimate. */
3879  if (path->jpath.path.parallel_workers > 0)
3880  {
3881  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3882 
3883  path->jpath.path.rows =
3884  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3885  }
3886 
3887  /*
3888  * We could include disable_cost in the preliminary estimate, but that
3889  * would amount to optimizing for the case where the join method is
3890  * disabled, which doesn't seem like the way to bet.
3891  */
3892  if (!enable_hashjoin)
3893  startup_cost += disable_cost;
3894 
3895  /* mark the path with estimated # of batches */
3896  path->num_batches = numbatches;
3897 
3898  /* store the total number of tuples (sum of partial row estimates) */
3899  path->inner_rows_total = inner_path_rows_total;
3900 
3901  /* and compute the number of "virtual" buckets in the whole join */
3902  virtualbuckets = (double) numbuckets * (double) numbatches;
3903 
3904  /*
3905  * Determine bucketsize fraction and MCV frequency for the inner relation.
3906  * We use the smallest bucketsize or MCV frequency estimated for any
3907  * individual hashclause; this is undoubtedly conservative.
3908  *
3909  * BUT: if inner relation has been unique-ified, we can assume it's good
3910  * for hashing. This is important both because it's the right answer, and
3911  * because we avoid contaminating the cache with a value that's wrong for
3912  * non-unique-ified paths.
3913  */
3914  if (IsA(inner_path, UniquePath))
3915  {
3916  innerbucketsize = 1.0 / virtualbuckets;
3917  innermcvfreq = 0.0;
3918  }
3919  else
3920  {
3921  innerbucketsize = 1.0;
3922  innermcvfreq = 1.0;
3923  foreach(hcl, hashclauses)
3924  {
3925  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3926  Selectivity thisbucketsize;
3927  Selectivity thismcvfreq;
3928 
3929  /*
3930  * First we have to figure out which side of the hashjoin clause
3931  * is the inner side.
3932  *
3933  * Since we tend to visit the same clauses over and over when
3934  * planning a large query, we cache the bucket stats estimates in
3935  * the RestrictInfo node to avoid repeated lookups of statistics.
3936  */
3937  if (bms_is_subset(restrictinfo->right_relids,
3938  inner_path->parent->relids))
3939  {
3940  /* righthand side is inner */
3941  thisbucketsize = restrictinfo->right_bucketsize;
3942  if (thisbucketsize < 0)
3943  {
3944  /* not cached yet */
3946  get_rightop(restrictinfo->clause),
3947  virtualbuckets,
3948  &restrictinfo->right_mcvfreq,
3949  &restrictinfo->right_bucketsize);
3950  thisbucketsize = restrictinfo->right_bucketsize;
3951  }
3952  thismcvfreq = restrictinfo->right_mcvfreq;
3953  }
3954  else
3955  {
3956  Assert(bms_is_subset(restrictinfo->left_relids,
3957  inner_path->parent->relids));
3958  /* lefthand side is inner */
3959  thisbucketsize = restrictinfo->left_bucketsize;
3960  if (thisbucketsize < 0)
3961  {
3962  /* not cached yet */
3964  get_leftop(restrictinfo->clause),
3965  virtualbuckets,
3966  &restrictinfo->left_mcvfreq,
3967  &restrictinfo->left_bucketsize);
3968  thisbucketsize = restrictinfo->left_bucketsize;
3969  }
3970  thismcvfreq = restrictinfo->left_mcvfreq;
3971  }
3972 
3973  if (innerbucketsize > thisbucketsize)
3974  innerbucketsize = thisbucketsize;
3975  if (innermcvfreq > thismcvfreq)
3976  innermcvfreq = thismcvfreq;
3977  }
3978  }
3979 
3980  /*
3981  * If the bucket holding the inner MCV would exceed hash_mem, we don't
3982  * want to hash unless there is really no other alternative, so apply
3983  * disable_cost. (The executor normally copes with excessive memory usage
3984  * by splitting batches, but obviously it cannot separate equal values
3985  * that way, so it will be unable to drive the batch size below hash_mem
3986  * when this is true.)
3987  */
3988  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3989  inner_path->pathtarget->width) > get_hash_memory_limit())
3990  startup_cost += disable_cost;
3991 
3992  /*
3993  * Compute cost of the hashquals and qpquals (other restriction clauses)
3994  * separately.
3995  */
3996  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3997  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3998  qp_qual_cost.startup -= hash_qual_cost.startup;
3999  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4000 
4001  /* CPU costs */
4002 
4003  if (path->jpath.jointype == JOIN_SEMI