PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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/nodeHash.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.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)
 

Functions

static Listextract_nonindex_conditions (List *qual_clauses, List *indexquals)
 
static MergeScanSelCachecached_scansel (PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
 
static void cost_rescan (PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
static bool cost_qual_eval_walker (Node *node, cost_qual_eval_context *context)
 
static void get_restriction_qual_cost (PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
 
static bool has_indexed_join_quals (NestPath *joinpath)
 
static double approx_tuple_count (PlannerInfo *root, JoinPath *path, List *quals)
 
static double calc_joinrel_size_estimate (PlannerInfo *root, RelOptInfo *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 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_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
static double get_indexpath_pages (Path *bitmapqual)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_ctescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
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_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
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, 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, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, SpecialJoinInfo *sjinfo)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, SpecialJoinInfo *sjinfo)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
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 *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_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
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_hashagg = true
 
bool enable_nestloop = true
 
bool enable_material = true
 
bool enable_mergejoin = true
 
bool enable_hashjoin = true
 

Macro Definition Documentation

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

Definition at line 101 of file costsize.c.

Referenced by cost_merge_append(), and cost_sort().

Function Documentation

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

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

3710 {
3711  double tuples;
3712  double outer_tuples = path->outerjoinpath->rows;
3713  double inner_tuples = path->innerjoinpath->rows;
3714  SpecialJoinInfo sjinfo;
3715  Selectivity selec = 1.0;
3716  ListCell *l;
3717 
3718  /*
3719  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
3720  */
3721  sjinfo.type = T_SpecialJoinInfo;
3722  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
3723  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
3724  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
3725  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
3726  sjinfo.jointype = JOIN_INNER;
3727  /* we don't bother trying to make the remaining fields valid */
3728  sjinfo.lhs_strict = false;
3729  sjinfo.delay_upper_joins = false;
3730  sjinfo.semi_can_btree = false;
3731  sjinfo.semi_can_hash = false;
3732  sjinfo.semi_operators = NIL;
3733  sjinfo.semi_rhs_exprs = NIL;
3734 
3735  /* Get the approximate selectivity */
3736  foreach(l, quals)
3737  {
3738  Node *qual = (Node *) lfirst(l);
3739 
3740  /* Note that clause_selectivity will be able to cache its result */
3741  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
3742  }
3743 
3744  /* Apply it to the input relation sizes */
3745  tuples = selec * outer_tuples * inner_tuples;
3746 
3747  return clamp_row_est(tuples);
3748 }
#define NIL
Definition: pg_list.h:69
bool semi_can_btree
Definition: relation.h:1815
Relids min_righthand
Definition: relation.h:1808
Path * innerjoinpath
Definition: relation.h:1217
NodeTag type
Definition: relation.h:1806
Definition: nodes.h:508
double Selectivity
Definition: nodes.h:631
Relids syn_lefthand
Definition: relation.h:1809
Relids syn_righthand
Definition: relation.h:1810
List * semi_rhs_exprs
Definition: relation.h:1818
bool semi_can_hash
Definition: relation.h:1816
RelOptInfo * parent
Definition: relation.h:894
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:483
Relids relids
Definition: relation.h:490
Path * outerjoinpath
Definition: relation.h:1216
bool delay_upper_joins
Definition: relation.h:1813
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
JoinType jointype
Definition: relation.h:1811
List * semi_operators
Definition: relation.h:1817
double clamp_row_est(double nrows)
Definition: costsize.c:172
Relids min_lefthand
Definition: relation.h:1807
static MergeScanSelCache * cached_scansel ( PlannerInfo root,
RestrictInfo rinfo,
PathKey pathkey 
)
static

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

2609 {
2610  MergeScanSelCache *cache;
2611  ListCell *lc;
2612  Selectivity leftstartsel,
2613  leftendsel,
2614  rightstartsel,
2615  rightendsel;
2616  MemoryContext oldcontext;
2617 
2618  /* Do we have this result already? */
2619  foreach(lc, rinfo->scansel_cache)
2620  {
2621  cache = (MergeScanSelCache *) lfirst(lc);
2622  if (cache->opfamily == pathkey->pk_opfamily &&
2623  cache->collation == pathkey->pk_eclass->ec_collation &&
2624  cache->strategy == pathkey->pk_strategy &&
2625  cache->nulls_first == pathkey->pk_nulls_first)
2626  return cache;
2627  }
2628 
2629  /* Nope, do the computation */
2630  mergejoinscansel(root,
2631  (Node *) rinfo->clause,
2632  pathkey->pk_opfamily,
2633  pathkey->pk_strategy,
2634  pathkey->pk_nulls_first,
2635  &leftstartsel,
2636  &leftendsel,
2637  &rightstartsel,
2638  &rightendsel);
2639 
2640  /* Cache the result in suitably long-lived workspace */
2641  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2642 
2643  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
2644  cache->opfamily = pathkey->pk_opfamily;
2645  cache->collation = pathkey->pk_eclass->ec_collation;
2646  cache->strategy = pathkey->pk_strategy;
2647  cache->nulls_first = pathkey->pk_nulls_first;
2648  cache->leftstartsel = leftstartsel;
2649  cache->leftendsel = leftendsel;
2650  cache->rightstartsel = rightstartsel;
2651  cache->rightendsel = rightendsel;
2652 
2653  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
2654 
2655  MemoryContextSwitchTo(oldcontext);
2656 
2657  return cache;
2658 }
Selectivity leftendsel
Definition: relation.h:1718
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2848
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:508
double Selectivity
Definition: nodes.h:631
int pk_strategy
Definition: relation.h:793
bool pk_nulls_first
Definition: relation.h:794
Selectivity rightstartsel
Definition: relation.h:1719
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1637
#define lfirst(lc)
Definition: pg_list.h:106
EquivalenceClass * pk_eclass
Definition: relation.h:791
Oid pk_opfamily
Definition: relation.h:792
void * palloc(Size size)
Definition: mcxt.c:891
MemoryContext planner_cxt
Definition: relation.h:282
Selectivity rightendsel
Definition: relation.h:1720
List * scansel_cache
Definition: relation.h:1689
Selectivity leftstartsel
Definition: relation.h:1717
static double calc_joinrel_size_estimate ( PlannerInfo root,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
double  outer_rows,
double  inner_rows,
SpecialJoinInfo sjinfo,
List restrictlist 
)
static

Definition at line 3916 of file costsize.c.

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

Referenced by get_parameterized_joinrel_size(), and set_joinrel_size_estimates().

3923 {
3924  /* This apparently-useless variable dodges a compiler bug in VS2013: */
3925  List *restrictlist = restrictlist_in;
3926  JoinType jointype = sjinfo->jointype;
3927  Selectivity fkselec;
3928  Selectivity jselec;
3929  Selectivity pselec;
3930  double nrows;
3931 
3932  /*
3933  * Compute joinclause selectivity. Note that we are only considering
3934  * clauses that become restriction clauses at this join level; we are not
3935  * double-counting them because they were not considered in estimating the
3936  * sizes of the component rels.
3937  *
3938  * First, see whether any of the joinclauses can be matched to known FK
3939  * constraints. If so, drop those clauses from the restrictlist, and
3940  * instead estimate their selectivity using FK semantics. (We do this
3941  * without regard to whether said clauses are local or "pushed down".
3942  * Probably, an FK-matching clause could never be seen as pushed down at
3943  * an outer join, since it would be strict and hence would be grounds for
3944  * join strength reduction.) fkselec gets the net selectivity for
3945  * FK-matching clauses, or 1.0 if there are none.
3946  */
3947  fkselec = get_foreign_key_join_selectivity(root,
3948  outer_rel->relids,
3949  inner_rel->relids,
3950  sjinfo,
3951  &restrictlist);
3952 
3953  /*
3954  * For an outer join, we have to distinguish the selectivity of the join's
3955  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
3956  * down". For inner joins we just count them all as joinclauses.
3957  */
3958  if (IS_OUTER_JOIN(jointype))
3959  {
3960  List *joinquals = NIL;
3961  List *pushedquals = NIL;
3962  ListCell *l;
3963 
3964  /* Grovel through the clauses to separate into two lists */
3965  foreach(l, restrictlist)
3966  {
3967  RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
3968 
3969  if (rinfo->is_pushed_down)
3970  pushedquals = lappend(pushedquals, rinfo);
3971  else
3972  joinquals = lappend(joinquals, rinfo);
3973  }
3974 
3975  /* Get the separate selectivities */
3976  jselec = clauselist_selectivity(root,
3977  joinquals,
3978  0,
3979  jointype,
3980  sjinfo);
3981  pselec = clauselist_selectivity(root,
3982  pushedquals,
3983  0,
3984  jointype,
3985  sjinfo);
3986 
3987  /* Avoid leaking a lot of ListCells */
3988  list_free(joinquals);
3989  list_free(pushedquals);
3990  }
3991  else
3992  {
3993  jselec = clauselist_selectivity(root,
3994  restrictlist,
3995  0,
3996  jointype,
3997  sjinfo);
3998  pselec = 0.0; /* not used, keep compiler quiet */
3999  }
4000 
4001  /*
4002  * Basically, we multiply size of Cartesian product by selectivity.
4003  *
4004  * If we are doing an outer join, take that into account: the joinqual
4005  * selectivity has to be clamped using the knowledge that the output must
4006  * be at least as large as the non-nullable input. However, any
4007  * pushed-down quals are applied after the outer join, so their
4008  * selectivity applies fully.
4009  *
4010  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
4011  * of LHS rows that have matches, and we apply that straightforwardly.
4012  */
4013  switch (jointype)
4014  {
4015  case JOIN_INNER:
4016  nrows = outer_rows * inner_rows * fkselec * jselec;
4017  /* pselec not used */
4018  break;
4019  case JOIN_LEFT:
4020  nrows = outer_rows * inner_rows * fkselec * jselec;
4021  if (nrows < outer_rows)
4022  nrows = outer_rows;
4023  nrows *= pselec;
4024  break;
4025  case JOIN_FULL:
4026  nrows = outer_rows * inner_rows * fkselec * jselec;
4027  if (nrows < outer_rows)
4028  nrows = outer_rows;
4029  if (nrows < inner_rows)
4030  nrows = inner_rows;
4031  nrows *= pselec;
4032  break;
4033  case JOIN_SEMI:
4034  nrows = outer_rows * fkselec * jselec;
4035  /* pselec not used */
4036  break;
4037  case JOIN_ANTI:
4038  nrows = outer_rows * (1.0 - fkselec * jselec);
4039  nrows *= pselec;
4040  break;
4041  default:
4042  /* other values not expected here */
4043  elog(ERROR, "unrecognized join type: %d", (int) jointype);
4044  nrows = 0; /* keep compiler quiet */
4045  break;
4046  }
4047 
4048  return clamp_row_est(nrows);
4049 }
#define NIL
Definition: pg_list.h:69
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:714
double Selectivity
Definition: nodes.h:631
JoinType
Definition: nodes.h:665
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:4067
#define ERROR
Definition: elog.h:43
Relids relids
Definition: relation.h:490
List * lappend(List *list, void *datum)
Definition: list.c:128
bool is_pushed_down
Definition: relation.h:1639
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1811
void list_free(List *list)
Definition: list.c:1133
#define elog
Definition: elog.h:219
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
double clamp_row_est(double nrows)
Definition: costsize.c:172
Definition: pg_list.h:45
double clamp_row_est ( double  nrows)

Definition at line 172 of file costsize.c.

References rint().

Referenced by approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), cost_index(), cost_seqscan(), cost_subplan(), create_bitmap_subplan(), create_limit_path(), estimate_hash_bucketsize(), estimate_num_groups(), estimate_path_cost_size(), estimate_size(), expression_returns_set_rows(), final_cost_hashjoin(), 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().

173 {
174  /*
175  * Force estimate to be at least one row, to make explain output look
176  * better and to avoid possible divide-by-zero when interpolating costs.
177  * Make it an integer, too.
178  */
179  if (nrows <= 1.0)
180  nrows = 1.0;
181  else
182  nrows = rint(nrows);
183 
184  return nrows;
185 }
double rint(double x)
Definition: rint.c:22
double compute_bitmap_pages ( PlannerInfo root,
RelOptInfo baserel,
Path bitmapqual,
int  loop_count,
Cost cost,
double *  tuple 
)

Definition at line 4830 of file costsize.c.

References clamp_row_est(), cost_bitmap_tree_node(), get_indexpath_pages(), index_pages_fetched(), RelOptInfo::pages, T, and RelOptInfo::tuples.

Referenced by cost_bitmap_heap_scan().

4832 {
4833  Cost indexTotalCost;
4834  Selectivity indexSelectivity;
4835  double T;
4836  double pages_fetched;
4837  double tuples_fetched;
4838 
4839  /*
4840  * Fetch total cost of obtaining the bitmap, as well as its total
4841  * selectivity.
4842  */
4843  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
4844 
4845  /*
4846  * Estimate number of main-table pages fetched.
4847  */
4848  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
4849 
4850  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
4851 
4852  if (loop_count > 1)
4853  {
4854  /*
4855  * For repeated bitmap scans, scale up the number of tuples fetched in
4856  * the Mackert and Lohman formula by the number of scans, so that we
4857  * estimate the number of pages fetched by all the scans. Then
4858  * pro-rate for one scan.
4859  */
4860  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
4861  baserel->pages,
4862  get_indexpath_pages(bitmapqual),
4863  root);
4864  pages_fetched /= loop_count;
4865  }
4866  else
4867  {
4868  /*
4869  * For a single scan, the number of heap pages that need to be fetched
4870  * is the same as the Mackert and Lohman formula for the case T <= b
4871  * (ie, no re-reads needed).
4872  */
4873  pages_fetched =
4874  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
4875  }
4876 
4877  if (pages_fetched >= T)
4878  pages_fetched = T;
4879  else
4880  pages_fetched = ceil(pages_fetched);
4881 
4882  if (cost)
4883  *cost = indexTotalCost;
4884  if (tuple)
4885  *tuple = tuples_fetched;
4886 
4887  return pages_fetched;
4888 }
double tuples
Definition: relation.h:529
double Selectivity
Definition: nodes.h:631
static const uint32 T[65]
Definition: md5.c:101
BlockNumber pages
Definition: relation.h:528
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:803
double clamp_row_est(double nrows)
Definition: costsize.c:172
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:738
double Cost
Definition: nodes.h:632
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:940
void compute_semi_anti_join_factors ( PlannerInfo root,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist,
SemiAntiJoinFactors semifactors 
)

Definition at line 3506 of file costsize.c.

References Assert, castNode, clauselist_selectivity(), SpecialJoinInfo::delay_upper_joins, RestrictInfo::is_pushed_down, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, SpecialJoinInfo::lhs_strict, list_free(), SemiAntiJoinFactors::match_count, Max, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, SemiAntiJoinFactors::outer_match_frac, RelOptInfo::relids, 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().

3513 {
3514  Selectivity jselec;
3515  Selectivity nselec;
3516  Selectivity avgmatch;
3517  SpecialJoinInfo norm_sjinfo;
3518  List *joinquals;
3519  ListCell *l;
3520 
3521  /* Should only be called in these cases */
3522  Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
3523 
3524  /*
3525  * In an ANTI join, we must ignore clauses that are "pushed down", since
3526  * those won't affect the match logic. In a SEMI join, we do not
3527  * distinguish joinquals from "pushed down" quals, so just use the whole
3528  * restrictinfo list.
3529  */
3530  if (jointype == JOIN_ANTI)
3531  {
3532  joinquals = NIL;
3533  foreach(l, restrictlist)
3534  {
3535  RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
3536 
3537  if (!rinfo->is_pushed_down)
3538  joinquals = lappend(joinquals, rinfo);
3539  }
3540  }
3541  else
3542  joinquals = restrictlist;
3543 
3544  /*
3545  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
3546  */
3547  jselec = clauselist_selectivity(root,
3548  joinquals,
3549  0,
3550  jointype,
3551  sjinfo);
3552 
3553  /*
3554  * Also get the normal inner-join selectivity of the join clauses.
3555  */
3556  norm_sjinfo.type = T_SpecialJoinInfo;
3557  norm_sjinfo.min_lefthand = outerrel->relids;
3558  norm_sjinfo.min_righthand = innerrel->relids;
3559  norm_sjinfo.syn_lefthand = outerrel->relids;
3560  norm_sjinfo.syn_righthand = innerrel->relids;
3561  norm_sjinfo.jointype = JOIN_INNER;
3562  /* we don't bother trying to make the remaining fields valid */
3563  norm_sjinfo.lhs_strict = false;
3564  norm_sjinfo.delay_upper_joins = false;
3565  norm_sjinfo.semi_can_btree = false;
3566  norm_sjinfo.semi_can_hash = false;
3567  norm_sjinfo.semi_operators = NIL;
3568  norm_sjinfo.semi_rhs_exprs = NIL;
3569 
3570  nselec = clauselist_selectivity(root,
3571  joinquals,
3572  0,
3573  JOIN_INNER,
3574  &norm_sjinfo);
3575 
3576  /* Avoid leaking a lot of ListCells */
3577  if (jointype == JOIN_ANTI)
3578  list_free(joinquals);
3579 
3580  /*
3581  * jselec can be interpreted as the fraction of outer-rel rows that have
3582  * any matches (this is true for both SEMI and ANTI cases). And nselec is
3583  * the fraction of the Cartesian product that matches. So, the average
3584  * number of matches for each outer-rel row that has at least one match is
3585  * nselec * inner_rows / jselec.
3586  *
3587  * Note: it is correct to use the inner rel's "rows" count here, even
3588  * though we might later be considering a parameterized inner path with
3589  * fewer rows. This is because we have included all the join clauses in
3590  * the selectivity estimate.
3591  */
3592  if (jselec > 0) /* protect against zero divide */
3593  {
3594  avgmatch = nselec * innerrel->rows / jselec;
3595  /* Clamp to sane range */
3596  avgmatch = Max(1.0, avgmatch);
3597  }
3598  else
3599  avgmatch = 1.0;
3600 
3601  semifactors->outer_match_frac = jselec;
3602  semifactors->match_count = avgmatch;
3603 }
#define NIL
Definition: pg_list.h:69
bool semi_can_btree
Definition: relation.h:1815
Relids min_righthand
Definition: relation.h:1808
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Selectivity outer_match_frac
Definition: relation.h:2032
NodeTag type
Definition: relation.h:1806
double Selectivity
Definition: nodes.h:631
Relids syn_lefthand
Definition: relation.h:1809
Relids syn_righthand
Definition: relation.h:1810
List * semi_rhs_exprs
Definition: relation.h:1818
bool semi_can_hash
Definition: relation.h:1816
Relids relids
Definition: relation.h:490
List * lappend(List *list, void *datum)
Definition: list.c:128
bool delay_upper_joins
Definition: relation.h:1813
double rows
Definition: relation.h:493
bool is_pushed_down
Definition: relation.h:1639
#define Max(x, y)
Definition: c.h:796
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1811
Selectivity match_count
Definition: relation.h:2033
List * semi_operators
Definition: relation.h:1817
void list_free(List *list)
Definition: list.c:1133
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
Definition: pg_list.h:45
Relids min_lefthand
Definition: relation.h:1807
void cost_agg ( Path path,
PlannerInfo root,
AggStrategy  aggstrategy,
const AggClauseCosts aggcosts,
int  numGroupCols,
double  numGroups,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 1691 of file costsize.c.

References AGG_HASHED, AGG_PLAIN, AGG_SORTED, Assert, cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_hashagg, AggClauseCosts::finalCost, MemSet, NULL, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and AggClauseCosts::transCost.

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

1696 {
1697  double output_tuples;
1698  Cost startup_cost;
1699  Cost total_cost;
1700  AggClauseCosts dummy_aggcosts;
1701 
1702  /* Use all-zero per-aggregate costs if NULL is passed */
1703  if (aggcosts == NULL)
1704  {
1705  Assert(aggstrategy == AGG_HASHED);
1706  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1707  aggcosts = &dummy_aggcosts;
1708  }
1709 
1710  /*
1711  * The transCost.per_tuple component of aggcosts should be charged once
1712  * per input tuple, corresponding to the costs of evaluating the aggregate
1713  * transfns and their input expressions (with any startup cost of course
1714  * charged but once). The finalCost component is charged once per output
1715  * tuple, corresponding to the costs of evaluating the finalfns.
1716  *
1717  * If we are grouping, we charge an additional cpu_operator_cost per
1718  * grouping column per input tuple for grouping comparisons.
1719  *
1720  * We will produce a single output tuple if not grouping, and a tuple per
1721  * group otherwise. We charge cpu_tuple_cost for each output tuple.
1722  *
1723  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1724  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1725  * input path is already sorted appropriately, AGG_SORTED should be
1726  * preferred (since it has no risk of memory overflow). This will happen
1727  * as long as the computed total costs are indeed exactly equal --- but if
1728  * there's roundoff error we might do the wrong thing. So be sure that
1729  * the computations below form the same intermediate values in the same
1730  * order.
1731  */
1732  if (aggstrategy == AGG_PLAIN)
1733  {
1734  startup_cost = input_total_cost;
1735  startup_cost += aggcosts->transCost.startup;
1736  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1737  startup_cost += aggcosts->finalCost;
1738  /* we aren't grouping */
1739  total_cost = startup_cost + cpu_tuple_cost;
1740  output_tuples = 1;
1741  }
1742  else if (aggstrategy == AGG_SORTED)
1743  {
1744  /* Here we are able to deliver output on-the-fly */
1745  startup_cost = input_startup_cost;
1746  total_cost = input_total_cost;
1747  /* calcs phrased this way to match HASHED case, see note above */
1748  total_cost += aggcosts->transCost.startup;
1749  total_cost += aggcosts->transCost.per_tuple * input_tuples;
1750  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1751  total_cost += aggcosts->finalCost * numGroups;
1752  total_cost += cpu_tuple_cost * numGroups;
1753  output_tuples = numGroups;
1754  }
1755  else
1756  {
1757  /* must be AGG_HASHED */
1758  startup_cost = input_total_cost;
1759  if (!enable_hashagg)
1760  startup_cost += disable_cost;
1761  startup_cost += aggcosts->transCost.startup;
1762  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1763  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1764  total_cost = startup_cost;
1765  total_cost += aggcosts->finalCost * numGroups;
1766  total_cost += cpu_tuple_cost * numGroups;
1767  output_tuples = numGroups;
1768  }
1769 
1770  path->rows = output_tuples;
1771  path->startup_cost = startup_cost;
1772  path->total_cost = total_cost;
1773 }
#define MemSet(start, val, len)
Definition: c.h:853
QualCost transCost
Definition: relation.h:62
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
double cpu_operator_cost
Definition: costsize.c:108
Cost finalCost
Definition: relation.h:63
Cost total_cost
Definition: relation.h:907
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
bool enable_hashagg
Definition: costsize.c:124
double Cost
Definition: nodes.h:632
void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 983 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 bitmap_and_cost_est(), and create_bitmap_and_path().

984 {
985  Cost totalCost;
986  Selectivity selec;
987  ListCell *l;
988 
989  /*
990  * We estimate AND selectivity on the assumption that the inputs are
991  * independent. This is probably often wrong, but we don't have the info
992  * to do better.
993  *
994  * The runtime cost of the BitmapAnd itself is estimated at 100x
995  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
996  * definitely too simplistic?
997  */
998  totalCost = 0.0;
999  selec = 1.0;
1000  foreach(l, path->bitmapquals)
1001  {
1002  Path *subpath = (Path *) lfirst(l);
1003  Cost subCost;
1004  Selectivity subselec;
1005 
1006  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1007 
1008  selec *= subselec;
1009 
1010  totalCost += subCost;
1011  if (l != list_head(path->bitmapquals))
1012  totalCost += 100.0 * cpu_operator_cost;
1013  }
1014  path->bitmapselectivity = selec;
1015  path->path.rows = 0; /* per above, not used */
1016  path->path.startup_cost = totalCost;
1017  path->path.total_cost = totalCost;
1018 }
double Selectivity
Definition: nodes.h:631
Selectivity bitmapselectivity
Definition: relation.h:1016
List * bitmapquals
Definition: relation.h:1015
Cost startup_cost
Definition: relation.h:906
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
Definition: relation.h:888
double Cost
Definition: nodes.h:632
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:940
void cost_bitmap_heap_scan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
Path bitmapqual,
double  loop_count 
)

Definition at line 853 of file costsize.c.

References Assert, compute_bitmap_pages(), PathTarget::cost, cpu_tuple_cost, disable_cost, enable_bitmapscan, get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, 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, T, and Path::total_cost.

Referenced by bitmap_and_cost_est(), bitmap_scan_cost_est(), and create_bitmap_heap_path().

856 {
857  Cost startup_cost = 0;
858  Cost run_cost = 0;
859  Cost indexTotalCost;
860  QualCost qpqual_cost;
861  Cost cpu_per_tuple;
862  Cost cost_per_page;
863  double tuples_fetched;
864  double pages_fetched;
865  double spc_seq_page_cost,
866  spc_random_page_cost;
867  double T;
868 
869  /* Should only be applied to base relations */
870  Assert(IsA(baserel, RelOptInfo));
871  Assert(baserel->relid > 0);
872  Assert(baserel->rtekind == RTE_RELATION);
873 
874  /* Mark the path with the correct row estimate */
875  if (param_info)
876  path->rows = param_info->ppi_rows;
877  else
878  path->rows = baserel->rows;
879 
880  if (!enable_bitmapscan)
881  startup_cost += disable_cost;
882 
883  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
884  loop_count, &indexTotalCost,
885  &tuples_fetched);
886 
887  startup_cost += indexTotalCost;
888  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
889 
890  /* Fetch estimated page costs for tablespace containing table. */
892  &spc_random_page_cost,
893  &spc_seq_page_cost);
894 
895  /*
896  * For small numbers of pages we should charge spc_random_page_cost
897  * apiece, while if nearly all the table's pages are being read, it's more
898  * appropriate to charge spc_seq_page_cost apiece. The effect is
899  * nonlinear, too. For lack of a better idea, interpolate like this to
900  * determine the cost per page.
901  */
902  if (pages_fetched >= 2.0)
903  cost_per_page = spc_random_page_cost -
904  (spc_random_page_cost - spc_seq_page_cost)
905  * sqrt(pages_fetched / T);
906  else
907  cost_per_page = spc_random_page_cost;
908 
909  run_cost += pages_fetched * cost_per_page;
910 
911  /*
912  * Estimate CPU costs per tuple.
913  *
914  * Often the indexquals don't need to be rechecked at each tuple ... but
915  * not always, especially not if there are enough tuples involved that the
916  * bitmaps become lossy. For the moment, just assume they will be
917  * rechecked always. This means we charge the full freight for all the
918  * scan clauses.
919  */
920  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
921 
922  startup_cost += qpqual_cost.startup;
923  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
924 
925  run_cost += cpu_per_tuple * tuples_fetched;
926 
927  /* tlist eval costs are paid per output row, not per tuple scanned */
928  startup_cost += path->pathtarget->cost.startup;
929  run_cost += path->pathtarget->cost.per_tuple * path->rows;
930 
931  path->startup_cost = startup_cost;
932  path->total_cost = startup_cost + run_cost;
933 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
Oid reltablespace
Definition: relation.h:519
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
static const uint32 T[65]
Definition: md5.c:101
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
bool enable_bitmapscan
Definition: costsize.c:121
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
BlockNumber pages
Definition: relation.h:528
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:4830
double Cost
Definition: nodes.h:632
void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

1028 {
1029  Cost totalCost;
1030  Selectivity selec;
1031  ListCell *l;
1032 
1033  /*
1034  * We estimate OR selectivity on the assumption that the inputs are
1035  * non-overlapping, since that's often the case in "x IN (list)" type
1036  * situations. Of course, we clamp to 1.0 at the end.
1037  *
1038  * The runtime cost of the BitmapOr itself is estimated at 100x
1039  * cpu_operator_cost for each tbm_union needed. Probably too small,
1040  * definitely too simplistic? We are aware that the tbm_unions are
1041  * optimized out when the inputs are BitmapIndexScans.
1042  */
1043  totalCost = 0.0;
1044  selec = 0.0;
1045  foreach(l, path->bitmapquals)
1046  {
1047  Path *subpath = (Path *) lfirst(l);
1048  Cost subCost;
1049  Selectivity subselec;
1050 
1051  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1052 
1053  selec += subselec;
1054 
1055  totalCost += subCost;
1056  if (l != list_head(path->bitmapquals) &&
1057  !IsA(subpath, IndexPath))
1058  totalCost += 100.0 * cpu_operator_cost;
1059  }
1060  path->bitmapselectivity = Min(selec, 1.0);
1061  path->path.rows = 0; /* per above, not used */
1062  path->path.startup_cost = totalCost;
1063  path->path.total_cost = totalCost;
1064 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define Min(x, y)
Definition: c.h:802
double Selectivity
Definition: nodes.h:631
List * bitmapquals
Definition: relation.h:1028
Cost startup_cost
Definition: relation.h:906
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:108
Selectivity bitmapselectivity
Definition: relation.h:1029
Cost total_cost
Definition: relation.h:907
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
Definition: relation.h:888
double Cost
Definition: nodes.h:632
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:940
void cost_bitmap_tree_node ( Path path,
Cost cost,
Selectivity selec 
)

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

941 {
942  if (IsA(path, IndexPath))
943  {
944  *cost = ((IndexPath *) path)->indextotalcost;
945  *selec = ((IndexPath *) path)->indexselectivity;
946 
947  /*
948  * Charge a small amount per retrieved tuple to reflect the costs of
949  * manipulating the bitmap. This is mostly to make sure that a bitmap
950  * scan doesn't look to be the same cost as an indexscan to retrieve a
951  * single tuple.
952  */
953  *cost += 0.1 * cpu_operator_cost * path->rows;
954  }
955  else if (IsA(path, BitmapAndPath))
956  {
957  *cost = path->total_cost;
958  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
959  }
960  else if (IsA(path, BitmapOrPath))
961  {
962  *cost = path->total_cost;
963  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
964  }
965  else
966  {
967  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
968  *cost = *selec = 0; /* keep compiler quiet */
969  }
970 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define ERROR
Definition: elog.h:43
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
#define nodeTag(nodeptr)
Definition: nodes.h:513
#define elog
Definition: elog.h:219
void cost_ctescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1340 {
1341  Cost startup_cost = 0;
1342  Cost run_cost = 0;
1343  QualCost qpqual_cost;
1344  Cost cpu_per_tuple;
1345 
1346  /* Should only be applied to base relations that are CTEs */
1347  Assert(baserel->relid > 0);
1348  Assert(baserel->rtekind == RTE_CTE);
1349 
1350  /* Mark the path with the correct row estimate */
1351  if (param_info)
1352  path->rows = param_info->ppi_rows;
1353  else
1354  path->rows = baserel->rows;
1355 
1356  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1357  cpu_per_tuple = cpu_tuple_cost;
1358 
1359  /* Add scanning CPU costs */
1360  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1361 
1362  startup_cost += qpqual_cost.startup;
1363  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1364  run_cost += cpu_per_tuple * baserel->tuples;
1365 
1366  /* tlist eval costs are paid per output row, not per tuple scanned */
1367  startup_cost += path->pathtarget->cost.startup;
1368  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1369 
1370  path->startup_cost = startup_cost;
1371  path->total_cost = startup_cost + run_cost;
1372 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double Cost
Definition: nodes.h:632
void cost_functionscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1229 {
1230  Cost startup_cost = 0;
1231  Cost run_cost = 0;
1232  QualCost qpqual_cost;
1233  Cost cpu_per_tuple;
1234  RangeTblEntry *rte;
1235  QualCost exprcost;
1236 
1237  /* Should only be applied to base relations that are functions */
1238  Assert(baserel->relid > 0);
1239  rte = planner_rt_fetch(baserel->relid, root);
1240  Assert(rte->rtekind == RTE_FUNCTION);
1241 
1242  /* Mark the path with the correct row estimate */
1243  if (param_info)
1244  path->rows = param_info->ppi_rows;
1245  else
1246  path->rows = baserel->rows;
1247 
1248  /*
1249  * Estimate costs of executing the function expression(s).
1250  *
1251  * Currently, nodeFunctionscan.c always executes the functions to
1252  * completion before returning any rows, and caches the results in a
1253  * tuplestore. So the function eval cost is all startup cost, and per-row
1254  * costs are minimal.
1255  *
1256  * XXX in principle we ought to charge tuplestore spill costs if the
1257  * number of rows is large. However, given how phony our rowcount
1258  * estimates for functions tend to be, there's not a lot of point in that
1259  * refinement right now.
1260  */
1261  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1262 
1263  startup_cost += exprcost.startup + exprcost.per_tuple;
1264 
1265  /* Add scanning CPU costs */
1266  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1267 
1268  startup_cost += qpqual_cost.startup;
1269  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1270  run_cost += cpu_per_tuple * baserel->tuples;
1271 
1272  /* tlist eval costs are paid per output row, not per tuple scanned */
1273  startup_cost += path->pathtarget->cost.startup;
1274  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1275 
1276  path->startup_cost = startup_cost;
1277  path->total_cost = startup_cost + run_cost;
1278 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3225
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Definition: nodes.h:508
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
Cost startup_cost
Definition: relation.h:906
Index relid
Definition: relation.h:518
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
List * functions
Definition: parsenodes.h:931
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
RTEKind rtekind
Definition: parsenodes.h:882
double Cost
Definition: nodes.h:632
void cost_gather ( GatherPath path,
PlannerInfo root,
RelOptInfo rel,
ParamPathInfo param_info,
double *  rows 
)

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

351 {
352  Cost startup_cost = 0;
353  Cost run_cost = 0;
354 
355  /* Mark the path with the correct row estimate */
356  if (rows)
357  path->path.rows = *rows;
358  else if (param_info)
359  path->path.rows = param_info->ppi_rows;
360  else
361  path->path.rows = rel->rows;
362 
363  startup_cost = path->subpath->startup_cost;
364 
365  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
366 
367  /* Parallel setup and communication cost. */
368  startup_cost += parallel_setup_cost;
369  run_cost += parallel_tuple_cost * path->path.rows;
370 
371  path->path.startup_cost = startup_cost;
372  path->path.total_cost = (startup_cost + run_cost);
373 }
double parallel_setup_cost
Definition: costsize.c:110
Cost startup_cost
Definition: relation.h:906
Path * subpath
Definition: relation.h:1202
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double ppi_rows
Definition: relation.h:854
Path path
Definition: relation.h:1201
double Cost
Definition: nodes.h:632
double parallel_tuple_cost
Definition: costsize.c:109
void cost_group ( Path path,
PlannerInfo root,
int  numGroupCols,
double  numGroups,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 1853 of file costsize.c.

References cpu_operator_cost, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by choose_hashed_setop(), and create_group_path().

1857 {
1858  Cost startup_cost;
1859  Cost total_cost;
1860 
1861  startup_cost = input_startup_cost;
1862  total_cost = input_total_cost;
1863 
1864  /*
1865  * Charge one cpu_operator_cost per comparison per input tuple. We assume
1866  * all columns get compared at most of the tuples.
1867  */
1868  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1869 
1870  path->rows = numGroups;
1871  path->startup_cost = startup_cost;
1872  path->total_cost = total_cost;
1873 }
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double Cost
Definition: nodes.h:632
void cost_index ( IndexPath path,
PlannerInfo root,
double  loop_count,
bool  partial_path 
)

Definition at line 394 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::indexinfo, IndexPath::indexquals, IndexPath::indexselectivity, IndexPath::indextotalcost, IndexOptInfo::indrestrictinfo, IsA, list_concat(), 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().

396 {
397  IndexOptInfo *index = path->indexinfo;
398  RelOptInfo *baserel = index->rel;
399  bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
400  amcostestimate_function amcostestimate;
401  List *qpquals;
402  Cost startup_cost = 0;
403  Cost run_cost = 0;
404  Cost cpu_run_cost = 0;
405  Cost indexStartupCost;
406  Cost indexTotalCost;
407  Selectivity indexSelectivity;
408  double indexCorrelation,
409  csquared;
410  double spc_seq_page_cost,
411  spc_random_page_cost;
412  Cost min_IO_cost,
413  max_IO_cost;
414  QualCost qpqual_cost;
415  Cost cpu_per_tuple;
416  double tuples_fetched;
417  double pages_fetched;
418  double rand_heap_pages;
419  double index_pages;
420 
421  /* Should only be applied to base relations */
422  Assert(IsA(baserel, RelOptInfo) &&
423  IsA(index, IndexOptInfo));
424  Assert(baserel->relid > 0);
425  Assert(baserel->rtekind == RTE_RELATION);
426 
427  /*
428  * Mark the path with the correct row estimate, and identify which quals
429  * will need to be enforced as qpquals. We need not check any quals that
430  * are implied by the index's predicate, so we can use indrestrictinfo not
431  * baserestrictinfo as the list of relevant restriction clauses for the
432  * rel.
433  */
434  if (path->path.param_info)
435  {
436  path->path.rows = path->path.param_info->ppi_rows;
437  /* qpquals come from the rel's restriction clauses and ppi_clauses */
438  qpquals = list_concat(
440  path->indexquals),
442  path->indexquals));
443  }
444  else
445  {
446  path->path.rows = baserel->rows;
447  /* qpquals come from just the rel's restriction clauses */
449  path->indexquals);
450  }
451 
452  if (!enable_indexscan)
453  startup_cost += disable_cost;
454  /* we don't need to check enable_indexonlyscan; indxpath.c does that */
455 
456  /*
457  * Call index-access-method-specific code to estimate the processing cost
458  * for scanning the index, as well as the selectivity of the index (ie,
459  * the fraction of main-table tuples we will have to retrieve) and its
460  * correlation to the main-table tuple order. We need a cast here because
461  * relation.h uses a weak function type to avoid including amapi.h.
462  */
463  amcostestimate = (amcostestimate_function) index->amcostestimate;
464  amcostestimate(root, path, loop_count,
465  &indexStartupCost, &indexTotalCost,
466  &indexSelectivity, &indexCorrelation,
467  &index_pages);
468 
469  /*
470  * Save amcostestimate's results for possible use in bitmap scan planning.
471  * We don't bother to save indexStartupCost or indexCorrelation, because a
472  * bitmap scan doesn't care about either.
473  */
474  path->indextotalcost = indexTotalCost;
475  path->indexselectivity = indexSelectivity;
476 
477  /* all costs for touching index itself included here */
478  startup_cost += indexStartupCost;
479  run_cost += indexTotalCost - indexStartupCost;
480 
481  /* estimate number of main-table tuples fetched */
482  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
483 
484  /* fetch estimated page costs for tablespace containing table */
486  &spc_random_page_cost,
487  &spc_seq_page_cost);
488 
489  /*----------
490  * Estimate number of main-table pages fetched, and compute I/O cost.
491  *
492  * When the index ordering is uncorrelated with the table ordering,
493  * we use an approximation proposed by Mackert and Lohman (see
494  * index_pages_fetched() for details) to compute the number of pages
495  * fetched, and then charge spc_random_page_cost per page fetched.
496  *
497  * When the index ordering is exactly correlated with the table ordering
498  * (just after a CLUSTER, for example), the number of pages fetched should
499  * be exactly selectivity * table_size. What's more, all but the first
500  * will be sequential fetches, not the random fetches that occur in the
501  * uncorrelated case. So if the number of pages is more than 1, we
502  * ought to charge
503  * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
504  * For partially-correlated indexes, we ought to charge somewhere between
505  * these two estimates. We currently interpolate linearly between the
506  * estimates based on the correlation squared (XXX is that appropriate?).
507  *
508  * If it's an index-only scan, then we will not need to fetch any heap
509  * pages for which the visibility map shows all tuples are visible.
510  * Hence, reduce the estimated number of heap fetches accordingly.
511  * We use the measured fraction of the entire heap that is all-visible,
512  * which might not be particularly relevant to the subset of the heap
513  * that this query will fetch; but it's not clear how to do better.
514  *----------
515  */
516  if (loop_count > 1)
517  {
518  /*
519  * For repeated indexscans, the appropriate estimate for the
520  * uncorrelated case is to scale up the number of tuples fetched in
521  * the Mackert and Lohman formula by the number of scans, so that we
522  * estimate the number of pages fetched by all the scans; then
523  * pro-rate the costs for one scan. In this case we assume all the
524  * fetches are random accesses.
525  */
526  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
527  baserel->pages,
528  (double) index->pages,
529  root);
530 
531  if (indexonly)
532  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
533 
534  rand_heap_pages = pages_fetched;
535 
536  max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
537 
538  /*
539  * In the perfectly correlated case, the number of pages touched by
540  * each scan is selectivity * table_size, and we can use the Mackert
541  * and Lohman formula at the page level to estimate how much work is
542  * saved by caching across scans. We still assume all the fetches are
543  * random, though, which is an overestimate that's hard to correct for
544  * without double-counting the cache effects. (But in most cases
545  * where such a plan is actually interesting, only one page would get
546  * fetched per scan anyway, so it shouldn't matter much.)
547  */
548  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
549 
550  pages_fetched = index_pages_fetched(pages_fetched * loop_count,
551  baserel->pages,
552  (double) index->pages,
553  root);
554 
555  if (indexonly)
556  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
557 
558  min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
559  }
560  else
561  {
562  /*
563  * Normal case: apply the Mackert and Lohman formula, and then
564  * interpolate between that and the correlation-derived result.
565  */
566  pages_fetched = index_pages_fetched(tuples_fetched,
567  baserel->pages,
568  (double) index->pages,
569  root);
570 
571  if (indexonly)
572  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
573 
574  rand_heap_pages = pages_fetched;
575 
576  /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
577  max_IO_cost = pages_fetched * spc_random_page_cost;
578 
579  /* min_IO_cost is for the perfectly correlated case (csquared=1) */
580  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
581 
582  if (indexonly)
583  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
584 
585  if (pages_fetched > 0)
586  {
587  min_IO_cost = spc_random_page_cost;
588  if (pages_fetched > 1)
589  min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
590  }
591  else
592  min_IO_cost = 0;
593  }
594 
595  if (partial_path)
596  {
597  /*
598  * Estimate the number of parallel workers required to scan index. Use
599  * the number of heap pages computed considering heap fetches won't be
600  * sequential as for parallel scans the pages are accessed in random
601  * order.
602  */
604  (BlockNumber) rand_heap_pages,
605  (BlockNumber) index_pages);
606 
607  /*
608  * Fall out if workers can't be assigned for parallel scan, because in
609  * such a case this path will be rejected. So there is no benefit in
610  * doing extra computation.
611  */
612  if (path->path.parallel_workers <= 0)
613  return;
614 
615  path->path.parallel_aware = true;
616  }
617 
618  /*
619  * Now interpolate based on estimated index order correlation to get total
620  * disk I/O cost for main table accesses.
621  */
622  csquared = indexCorrelation * indexCorrelation;
623 
624  run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
625 
626  /*
627  * Estimate CPU costs per tuple.
628  *
629  * What we want here is cpu_tuple_cost plus the evaluation costs of any
630  * qual clauses that we have to evaluate as qpquals.
631  */
632  cost_qual_eval(&qpqual_cost, qpquals, root);
633 
634  startup_cost += qpqual_cost.startup;
635  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
636 
637  cpu_run_cost += cpu_per_tuple * tuples_fetched;
638 
639  /* tlist eval costs are paid per output row, not per tuple scanned */
640  startup_cost += path->path.pathtarget->cost.startup;
641  cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
642 
643  /* Adjust costing for parallelism, if used. */
644  if (path->path.parallel_workers > 0)
645  {
646  double parallel_divisor = get_parallel_divisor(&path->path);
647 
648  path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
649 
650  /* The CPU cost is divided among all the workers. */
651  cpu_run_cost /= parallel_divisor;
652  }
653 
654  run_cost += cpu_run_cost;
655 
656  path->path.startup_cost = startup_cost;
657  path->path.total_cost = startup_cost + run_cost;
658 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
Path path
Definition: relation.h:971
IndexOptInfo * indexinfo
Definition: relation.h:972
int compute_parallel_worker(RelOptInfo *rel, BlockNumber heap_pages, BlockNumber index_pages)
Definition: allpaths.c:2887
double tuples
Definition: relation.h:529
Oid reltablespace
Definition: relation.h:519
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
List * list_concat(List *list1, List *list2)
Definition: list.c:321
uint32 BlockNumber
Definition: block.h:31
static List * extract_nonindex_conditions(List *qual_clauses, List *indexquals)
Definition: costsize.c:678
double Selectivity
Definition: nodes.h:631
Cost startup
Definition: relation.h:45
double allvisfrac
Definition: relation.h:530
Definition: type.h:90
BlockNumber pages
Definition: relation.h:593
NodeTag pathtype
Definition: relation.h:892
Cost per_tuple
Definition: relation.h:46
List * indexquals
Definition: relation.h:974
RelOptInfo * rel
Definition: relation.h:590
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: relation.h:906
Cost indextotalcost
Definition: relation.h:979
Cost disable_cost
Definition: costsize.c:114
Selectivity indexselectivity
Definition: relation.h:980
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
List * indrestrictinfo
Definition: relation.h:615
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
BlockNumber pages
Definition: relation.h:528
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
List * ppi_clauses
Definition: relation.h:855
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
bool parallel_aware
Definition: relation.h:899
void(* amcostestimate)()
Definition: relation.h:634
double clamp_row_est(double nrows)
Definition: costsize.c:172
Definition: pg_list.h:45
bool enable_indexscan
Definition: costsize.c:119
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:92
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:738
double Cost
Definition: nodes.h:632
void cost_material ( Path path,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples,
int  width 
)

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

1640 {
1641  Cost startup_cost = input_startup_cost;
1642  Cost run_cost = input_total_cost - input_startup_cost;
1643  double nbytes = relation_byte_size(tuples, width);
1644  long work_mem_bytes = work_mem * 1024L;
1645 
1646  path->rows = tuples;
1647 
1648  /*
1649  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1650  * reflect bookkeeping overhead. (This rate must be more than what
1651  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1652  * if it is exactly the same then there will be a cost tie between
1653  * nestloop with A outer, materialized B inner and nestloop with B outer,
1654  * materialized A inner. The extra cost ensures we'll prefer
1655  * materializing the smaller rel.) Note that this is normally a good deal
1656  * less than cpu_tuple_cost; which is OK because a Material plan node
1657  * doesn't do qual-checking or projection, so it's got less overhead than
1658  * most plan nodes.
1659  */
1660  run_cost += 2 * cpu_operator_cost * tuples;
1661 
1662  /*
1663  * If we will spill to disk, charge at the rate of seq_page_cost per page.
1664  * This cost is assumed to be evenly spread through the plan run phase,
1665  * which isn't exactly accurate but our cost model doesn't allow for
1666  * nonuniform costs within the run phase.
1667  */
1668  if (nbytes > work_mem_bytes)
1669  {
1670  double npages = ceil(nbytes / BLCKSZ);
1671 
1672  run_cost += seq_page_cost * npages;
1673  }
1674 
1675  path->startup_cost = startup_cost;
1676  path->total_cost = startup_cost + run_cost;
1677 }
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4780
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
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 1586 of file costsize.c.

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

Referenced by create_merge_append_path().

1590 {
1591  Cost startup_cost = 0;
1592  Cost run_cost = 0;
1593  Cost comparison_cost;
1594  double N;
1595  double logN;
1596 
1597  /*
1598  * Avoid log(0)...
1599  */
1600  N = (n_streams < 2) ? 2.0 : (double) n_streams;
1601  logN = LOG2(N);
1602 
1603  /* Assumed cost per tuple comparison */
1604  comparison_cost = 2.0 * cpu_operator_cost;
1605 
1606  /* Heap creation cost */
1607  startup_cost += comparison_cost * N * logN;
1608 
1609  /* Per-tuple heap maintenance cost */
1610  run_cost += tuples * comparison_cost * logN;
1611 
1612  /*
1613  * Also charge a small amount (arbitrarily set equal to operator cost) per
1614  * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1615  * node doesn't do qual-checking or projection, so it has less overhead
1616  * than most plan nodes.
1617  */
1618  run_cost += cpu_operator_cost * tuples;
1619 
1620  path->startup_cost = startup_cost + input_startup_cost;
1621  path->total_cost = startup_cost + run_cost + input_total_cost;
1622 }
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
#define LOG2(x)
Definition: costsize.c:101
double Cost
Definition: nodes.h:632
void cost_qual_eval ( QualCost cost,
List quals,
PlannerInfo root 
)

Definition at line 3199 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 cost_index(), cost_subplan(), cost_tidscan(), create_result_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().

3200 {
3201  cost_qual_eval_context context;
3202  ListCell *l;
3203 
3204  context.root = root;
3205  context.total.startup = 0;
3206  context.total.per_tuple = 0;
3207 
3208  /* We don't charge any cost for the implicit ANDing at top level ... */
3209 
3210  foreach(l, quals)
3211  {
3212  Node *qual = (Node *) lfirst(l);
3213 
3214  cost_qual_eval_walker(qual, &context);
3215  }
3216 
3217  *cost = context.total;
3218 }
PlannerInfo * root
Definition: costsize.c:132
Definition: nodes.h:508
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3239
#define lfirst(lc)
Definition: pg_list.h:106
void cost_qual_eval_node ( QualCost cost,
Node qual,
PlannerInfo root 
)

Definition at line 3225 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_windowagg(), get_agg_clause_costs_walker(), make_sort_input_target(), order_qual_clauses(), orderby_operands_eval_cost(), other_operands_eval_cost(), set_pathtarget_cost_width(), and set_rel_width().

3226 {
3227  cost_qual_eval_context context;
3228 
3229  context.root = root;
3230  context.total.startup = 0;
3231  context.total.per_tuple = 0;
3232 
3233  cost_qual_eval_walker(qual, &context);
3234 
3235  *cost = context.total;
3236 }
PlannerInfo * root
Definition: costsize.c:132
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3239
static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 3239 of file costsize.c.

References CoerceViaIO::arg, ArrayCoerceExpr::arg, ScalarArrayOpExpr::args, RestrictInfo::clause, cpu_operator_cost, disable_cost, ArrayCoerceExpr::elemfuncid, elog, ERROR, estimate_array_length(), RestrictInfo::eval_cost, expression_tree_walker(), exprType(), get_func_cost(), get_opcode(), getTypeInputInfo(), getTypeOutputInfo(), IsA, lfirst_oid, linitial, lsecond, NULL, 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().

3240 {
3241  if (node == NULL)
3242  return false;
3243 
3244  /*
3245  * RestrictInfo nodes contain an eval_cost field reserved for this
3246  * routine's use, so that it's not necessary to evaluate the qual clause's
3247  * cost more than once. If the clause's cost hasn't been computed yet,
3248  * the field's startup value will contain -1.
3249  */
3250  if (IsA(node, RestrictInfo))
3251  {
3252  RestrictInfo *rinfo = (RestrictInfo *) node;
3253 
3254  if (rinfo->eval_cost.startup < 0)
3255  {
3256  cost_qual_eval_context locContext;
3257 
3258  locContext.root = context->root;
3259  locContext.total.startup = 0;
3260  locContext.total.per_tuple = 0;
3261 
3262  /*
3263  * For an OR clause, recurse into the marked-up tree so that we
3264  * set the eval_cost for contained RestrictInfos too.
3265  */
3266  if (rinfo->orclause)
3267  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
3268  else
3269  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
3270 
3271  /*
3272  * If the RestrictInfo is marked pseudoconstant, it will be tested
3273  * only once, so treat its cost as all startup cost.
3274  */
3275  if (rinfo->pseudoconstant)
3276  {
3277  /* count one execution during startup */
3278  locContext.total.startup += locContext.total.per_tuple;
3279  locContext.total.per_tuple = 0;
3280  }
3281  rinfo->eval_cost = locContext.total;
3282  }
3283  context->total.startup += rinfo->eval_cost.startup;
3284  context->total.per_tuple += rinfo->eval_cost.per_tuple;
3285  /* do NOT recurse into children */
3286  return false;
3287  }
3288 
3289  /*
3290  * For each operator or function node in the given tree, we charge the
3291  * estimated execution cost given by pg_proc.procost (remember to multiply
3292  * this by cpu_operator_cost).
3293  *
3294  * Vars and Consts are charged zero, and so are boolean operators (AND,
3295  * OR, NOT). Simplistic, but a lot better than no model at all.
3296  *
3297  * Should we try to account for the possibility of short-circuit
3298  * evaluation of AND/OR? Probably *not*, because that would make the
3299  * results depend on the clause ordering, and we are not in any position
3300  * to expect that the current ordering of the clauses is the one that's
3301  * going to end up being used. The above per-RestrictInfo caching would
3302  * not mix well with trying to re-order clauses anyway.
3303  *
3304  * Another issue that is entirely ignored here is that if a set-returning
3305  * function is below top level in the tree, the functions/operators above
3306  * it will need to be evaluated multiple times. In practical use, such
3307  * cases arise so seldom as to not be worth the added complexity needed;
3308  * moreover, since our rowcount estimates for functions tend to be pretty
3309  * phony, the results would also be pretty phony.
3310  */
3311  if (IsA(node, FuncExpr))
3312  {
3313  context->total.per_tuple +=
3314  get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
3315  }
3316  else if (IsA(node, OpExpr) ||
3317  IsA(node, DistinctExpr) ||
3318  IsA(node, NullIfExpr))
3319  {
3320  /* rely on struct equivalence to treat these all alike */
3321  set_opfuncid((OpExpr *) node);
3322  context->total.per_tuple +=
3323  get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
3324  }
3325  else if (IsA(node, ScalarArrayOpExpr))
3326  {
3327  /*
3328  * Estimate that the operator will be applied to about half of the
3329  * array elements before the answer is determined.
3330  */
3331  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
3332  Node *arraynode = (Node *) lsecond(saop->args);
3333 
3334  set_sa_opfuncid(saop);
3335  context->total.per_tuple += get_func_cost(saop->opfuncid) *
3336  cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
3337  }
3338  else if (IsA(node, Aggref) ||
3339  IsA(node, WindowFunc))
3340  {
3341  /*
3342  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
3343  * ie, zero execution cost in the current model, because they behave
3344  * essentially like Vars in execQual.c. We disregard the costs of
3345  * their input expressions for the same reason. The actual execution
3346  * costs of the aggregate/window functions and their arguments have to
3347  * be factored into plan-node-specific costing of the Agg or WindowAgg
3348  * plan node.
3349  */
3350  return false; /* don't recurse into children */
3351  }
3352  else if (IsA(node, CoerceViaIO))
3353  {
3354  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3355  Oid iofunc;
3356  Oid typioparam;
3357  bool typisvarlena;
3358 
3359  /* check the result type's input function */
3360  getTypeInputInfo(iocoerce->resulttype,
3361  &iofunc, &typioparam);
3362  context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3363  /* check the input type's output function */
3364  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3365  &iofunc, &typisvarlena);
3366  context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
3367  }
3368  else if (IsA(node, ArrayCoerceExpr))
3369  {
3370  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3371  Node *arraynode = (Node *) acoerce->arg;
3372 
3373  if (OidIsValid(acoerce->elemfuncid))
3374  context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
3376  }
3377  else if (IsA(node, RowCompareExpr))
3378  {
3379  /* Conservatively assume we will check all the columns */
3380  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3381  ListCell *lc;
3382 
3383  foreach(lc, rcexpr->opnos)
3384  {
3385  Oid opid = lfirst_oid(lc);
3386 
3387  context->total.per_tuple += get_func_cost(get_opcode(opid)) *
3389  }
3390  }
3391  else if (IsA(node, CurrentOfExpr))
3392  {
3393  /* Report high cost to prevent selection of anything but TID scan */
3394  context->total.startup += disable_cost;
3395  }
3396  else if (IsA(node, SubLink))
3397  {
3398  /* This routine should not be applied to un-planned expressions */
3399  elog(ERROR, "cannot handle unplanned sub-select");
3400  }
3401  else if (IsA(node, SubPlan))
3402  {
3403  /*
3404  * A subplan node in an expression typically indicates that the
3405  * subplan will be executed on each evaluation, so charge accordingly.
3406  * (Sub-selects that can be executed as InitPlans have already been
3407  * removed from the expression.)
3408  */
3409  SubPlan *subplan = (SubPlan *) node;
3410 
3411  context->total.startup += subplan->startup_cost;
3412  context->total.per_tuple += subplan->per_call_cost;
3413 
3414  /*
3415  * We don't want to recurse into the testexpr, because it was already
3416  * counted in the SubPlan node's costs. So we're done.
3417  */
3418  return false;
3419  }
3420  else if (IsA(node, AlternativeSubPlan))
3421  {
3422  /*
3423  * Arbitrarily use the first alternative plan for costing. (We should
3424  * certainly only include one alternative, and we don't yet have
3425  * enough information to know which one the executor is most likely to
3426  * use.)
3427  */
3428  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
3429 
3430  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
3431  context);
3432  }
3433  else if (IsA(node, PlaceHolderVar))
3434  {
3435  /*
3436  * A PlaceHolderVar should be given cost zero when considering general
3437  * expression evaluation costs. The expense of doing the contained
3438  * expression is charged as part of the tlist eval costs of the scan
3439  * or join where the PHV is first computed (see set_rel_width and
3440  * add_placeholders_to_joinrel). If we charged it again here, we'd be
3441  * double-counting the cost for each level of plan that the PHV
3442  * bubbles up through. Hence, return without recursing into the
3443  * phexpr.
3444  */
3445  return false;
3446  }
3447 
3448  /* recurse into children */
3450  (void *) context);
3451 }
QualCost eval_cost
Definition: relation.h:1674
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PlannerInfo * root
Definition: costsize.c:132
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2600
Expr * orclause
Definition: relation.h:1668
Oid resulttype
Definition: primnodes.h:788
bool pseudoconstant
Definition: relation.h:1645
Definition: nodes.h:508
float4 get_func_cost(Oid funcid)
Definition: lsyscache.c:1609
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
#define lsecond(l)
Definition: pg_list.h:114
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2078
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
Cost disable_cost
Definition: costsize.c:114
double cpu_operator_cost
Definition: costsize.c:108
Expr * arg
Definition: primnodes.h:787
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2567
Expr * clause
Definition: relation.h:1637
Cost per_call_cost
Definition: primnodes.h:689
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1062
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3239
#define NULL
Definition: c.h:226
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1852
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1622
Cost startup_cost
Definition: primnodes.h:688
#define elog
Definition: elog.h:219
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1633
#define lfirst_oid(lc)
Definition: pg_list.h:108
void cost_recursive_union ( Path runion,
Path nrterm,
Path rterm 
)

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

1383 {
1384  Cost startup_cost;
1385  Cost total_cost;
1386  double total_rows;
1387 
1388  /* We probably have decent estimates for the non-recursive term */
1389  startup_cost = nrterm->startup_cost;
1390  total_cost = nrterm->total_cost;
1391  total_rows = nrterm->rows;
1392 
1393  /*
1394  * We arbitrarily assume that about 10 recursive iterations will be
1395  * needed, and that we've managed to get a good fix on the cost and output
1396  * size of each one of them. These are mighty shaky assumptions but it's
1397  * hard to see how to do better.
1398  */
1399  total_cost += 10 * rterm->total_cost;
1400  total_rows += 10 * rterm->rows;
1401 
1402  /*
1403  * Also charge cpu_tuple_cost per row to account for the costs of
1404  * manipulating the tuplestores. (We don't worry about possible
1405  * spill-to-disk costs.)
1406  */
1407  total_cost += cpu_tuple_cost * total_rows;
1408 
1409  runion->startup_cost = startup_cost;
1410  runion->total_cost = total_cost;
1411  runion->rows = total_rows;
1412  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1413  rterm->pathtarget->width);
1414 }
PathTarget * pathtarget
Definition: relation.h:895
Cost startup_cost
Definition: relation.h:906
Cost total_cost
Definition: relation.h:907
#define Max(x, y)
Definition: c.h:796
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
int width
Definition: relation.h:827
double Cost
Definition: nodes.h:632
static void cost_rescan ( PlannerInfo root,
Path path,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 3092 of file costsize.c.

References cpu_operator_cost, cpu_tuple_cost, Path::pathtarget, Path::pathtype, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, T_CteScan, T_FunctionScan, T_HashJoin, T_Material, T_Sort, T_WorkTableScan, Path::total_cost, PathTarget::width, and work_mem.

Referenced by initial_cost_nestloop().

3095 {
3096  switch (path->pathtype)
3097  {
3098  case T_FunctionScan:
3099 
3100  /*
3101  * Currently, nodeFunctionscan.c always executes the function to
3102  * completion before returning any rows, and caches the results in
3103  * a tuplestore. So the function eval cost is all startup cost
3104  * and isn't paid over again on rescans. However, all run costs
3105  * will be paid over again.
3106  */
3107  *rescan_startup_cost = 0;
3108  *rescan_total_cost = path->total_cost - path->startup_cost;
3109  break;
3110  case T_HashJoin:
3111 
3112  /*
3113  * If it's a single-batch join, we don't need to rebuild the hash
3114  * table during a rescan.
3115  */
3116  if (((HashPath *) path)->num_batches == 1)
3117  {
3118  /* Startup cost is exactly the cost of hash table building */
3119  *rescan_startup_cost = 0;
3120  *rescan_total_cost = path->total_cost - path->startup_cost;
3121  }
3122  else
3123  {
3124  /* Otherwise, no special treatment */
3125  *rescan_startup_cost = path->startup_cost;
3126  *rescan_total_cost = path->total_cost;
3127  }
3128  break;
3129  case T_CteScan:
3130  case T_WorkTableScan:
3131  {
3132  /*
3133  * These plan types materialize their final result in a
3134  * tuplestore or tuplesort object. So the rescan cost is only
3135  * cpu_tuple_cost per tuple, unless the result is large enough
3136  * to spill to disk.
3137  */
3138  Cost run_cost = cpu_tuple_cost * path->rows;
3139  double nbytes = relation_byte_size(path->rows,
3140  path->pathtarget->width);
3141  long work_mem_bytes = work_mem * 1024L;
3142 
3143  if (nbytes > work_mem_bytes)
3144  {
3145  /* It will spill, so account for re-read cost */
3146  double npages = ceil(nbytes / BLCKSZ);
3147 
3148  run_cost += seq_page_cost * npages;
3149  }
3150  *rescan_startup_cost = 0;
3151  *rescan_total_cost = run_cost;
3152  }
3153  break;
3154  case T_Material:
3155  case T_Sort:
3156  {
3157  /*
3158  * These plan types not only materialize their results, but do
3159  * not implement qual filtering or projection. So they are
3160  * even cheaper to rescan than the ones above. We charge only
3161  * cpu_operator_cost per tuple. (Note: keep that in sync with
3162  * the run_cost charge in cost_sort, and also see comments in
3163  * cost_material before you change it.)
3164  */
3165  Cost run_cost = cpu_operator_cost * path->rows;
3166  double nbytes = relation_byte_size(path->rows,
3167  path->pathtarget->width);
3168  long work_mem_bytes = work_mem * 1024L;
3169 
3170  if (nbytes > work_mem_bytes)
3171  {
3172  /* It will spill, so account for re-read cost */
3173  double npages = ceil(nbytes / BLCKSZ);
3174 
3175  run_cost += seq_page_cost * npages;
3176  }
3177  *rescan_startup_cost = 0;
3178  *rescan_total_cost = run_cost;
3179  }
3180  break;
3181  default:
3182  *rescan_startup_cost = path->startup_cost;
3183  *rescan_total_cost = path->total_cost;
3184  break;
3185  }
3186 }
PathTarget * pathtarget
Definition: relation.h:895
Definition: nodes.h:73
NodeTag pathtype
Definition: relation.h:892
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4780
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
int width
Definition: relation.h:827
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
void cost_samplescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 273 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, NULL, 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().

275 {
276  Cost startup_cost = 0;
277  Cost run_cost = 0;
278  RangeTblEntry *rte;
279  TableSampleClause *tsc;
280  TsmRoutine *tsm;
281  double spc_seq_page_cost,
282  spc_random_page_cost,
283  spc_page_cost;
284  QualCost qpqual_cost;
285  Cost cpu_per_tuple;
286 
287  /* Should only be applied to base relations with tablesample clauses */
288  Assert(baserel->relid > 0);
289  rte = planner_rt_fetch(baserel->relid, root);
290  Assert(rte->rtekind == RTE_RELATION);
291  tsc = rte->tablesample;
292  Assert(tsc != NULL);
293  tsm = GetTsmRoutine(tsc->tsmhandler);
294 
295  /* Mark the path with the correct row estimate */
296  if (param_info)
297  path->rows = param_info->ppi_rows;
298  else
299  path->rows = baserel->rows;
300 
301  /* fetch estimated page cost for tablespace containing table */
303  &spc_random_page_cost,
304  &spc_seq_page_cost);
305 
306  /* if NextSampleBlock is used, assume random access, else sequential */
307  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
308  spc_random_page_cost : spc_seq_page_cost;
309 
310  /*
311  * disk costs (recall that baserel->pages has already been set to the
312  * number of pages the sampling method will visit)
313  */
314  run_cost += spc_page_cost * baserel->pages;
315 
316  /*
317  * CPU costs (recall that baserel->tuples has already been set to the
318  * number of tuples the sampling method will select). Note that we ignore
319  * execution cost of the TABLESAMPLE parameter expressions; they will be
320  * evaluated only once per scan, and in most usages they'll likely be
321  * simple constants anyway. We also don't charge anything for the
322  * calculations the sampling method might do internally.
323  */
324  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
325 
326  startup_cost += qpqual_cost.startup;
327  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
328  run_cost += cpu_per_tuple * baserel->tuples;
329  /* tlist eval costs are paid per output row, not per tuple scanned */
330  startup_cost += path->pathtarget->cost.startup;
331  run_cost += path->pathtarget->cost.per_tuple * path->rows;
332 
333  path->startup_cost = startup_cost;
334  path->total_cost = startup_cost + run_cost;
335 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Oid reltablespace
Definition: relation.h:519
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
Cost startup_cost
Definition: relation.h:906
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:72
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: relation.h:528
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
RTEKind rtekind
Definition: parsenodes.h:882
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
double Cost
Definition: nodes.h:632
void cost_seqscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 196 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(), NULL, 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().

198 {
199  Cost startup_cost = 0;
200  Cost cpu_run_cost;
201  Cost disk_run_cost;
202  double spc_seq_page_cost;
203  QualCost qpqual_cost;
204  Cost cpu_per_tuple;
205 
206  /* Should only be applied to base relations */
207  Assert(baserel->relid > 0);
208  Assert(baserel->rtekind == RTE_RELATION);
209 
210  /* Mark the path with the correct row estimate */
211  if (param_info)
212  path->rows = param_info->ppi_rows;
213  else
214  path->rows = baserel->rows;
215 
216  if (!enable_seqscan)
217  startup_cost += disable_cost;
218 
219  /* fetch estimated page cost for tablespace containing table */
221  NULL,
222  &spc_seq_page_cost);
223 
224  /*
225  * disk costs
226  */
227  disk_run_cost = spc_seq_page_cost * baserel->pages;
228 
229  /* CPU costs */
230  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
231 
232  startup_cost += qpqual_cost.startup;
233  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
234  cpu_run_cost = cpu_per_tuple * baserel->tuples;
235  /* tlist eval costs are paid per output row, not per tuple scanned */
236  startup_cost += path->pathtarget->cost.startup;
237  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
238 
239  /* Adjust costing for parallelism, if used. */
240  if (path->parallel_workers > 0)
241  {
242  double parallel_divisor = get_parallel_divisor(path);
243 
244  /* The CPU cost is divided among all the workers. */
245  cpu_run_cost /= parallel_divisor;
246 
247  /*
248  * It may be possible to amortize some of the I/O cost, but probably
249  * not very much, because most operating systems already do aggressive
250  * prefetching. For now, we assume that the disk run cost can't be
251  * amortized at all.
252  */
253 
254  /*
255  * In the case of a parallel plan, the row count needs to represent
256  * the number of tuples processed per worker.
257  */
258  path->rows = clamp_row_est(path->rows / parallel_divisor);
259  }
260 
261  path->startup_cost = startup_cost;
262  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
263 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Oid reltablespace
Definition: relation.h:519
int parallel_workers
Definition: relation.h:901
bool enable_seqscan
Definition: costsize.c:118
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
BlockNumber pages
Definition: relation.h:528
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double clamp_row_est(double nrows)
Definition: costsize.c:172
double Cost
Definition: nodes.h:632
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 1462 of file costsize.c.

References cpu_operator_cost, disable_cost, enable_sort, LOG2, random_page_cost, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, Path::total_cost, and tuplesort_merge_order().

Referenced by choose_hashed_setop(), 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().

1466 {
1467  Cost startup_cost = input_cost;
1468  Cost run_cost = 0;
1469  double input_bytes = relation_byte_size(tuples, width);
1470  double output_bytes;
1471  double output_tuples;
1472  long sort_mem_bytes = sort_mem * 1024L;
1473 
1474  if (!enable_sort)
1475  startup_cost += disable_cost;
1476 
1477  path->rows = tuples;
1478 
1479  /*
1480  * We want to be sure the cost of a sort is never estimated as zero, even
1481  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1482  */
1483  if (tuples < 2.0)
1484  tuples = 2.0;
1485 
1486  /* Include the default cost-per-comparison */
1487  comparison_cost += 2.0 * cpu_operator_cost;
1488 
1489  /* Do we have a useful LIMIT? */
1490  if (limit_tuples > 0 && limit_tuples < tuples)
1491  {
1492  output_tuples = limit_tuples;
1493  output_bytes = relation_byte_size(output_tuples, width);
1494  }
1495  else
1496  {
1497  output_tuples = tuples;
1498  output_bytes = input_bytes;
1499  }
1500 
1501  if (output_bytes > sort_mem_bytes)
1502  {
1503  /*
1504  * We'll have to use a disk-based sort of all the tuples
1505  */
1506  double npages = ceil(input_bytes / BLCKSZ);
1507  double nruns = input_bytes / sort_mem_bytes;
1508  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1509  double log_runs;
1510  double npageaccesses;
1511 
1512  /*
1513  * CPU costs
1514  *
1515  * Assume about N log2 N comparisons
1516  */
1517  startup_cost += comparison_cost * tuples * LOG2(tuples);
1518 
1519  /* Disk costs */
1520 
1521  /* Compute logM(r) as log(r) / log(M) */
1522  if (nruns > mergeorder)
1523  log_runs = ceil(log(nruns) / log(mergeorder));
1524  else
1525  log_runs = 1.0;
1526  npageaccesses = 2.0 * npages * log_runs;
1527  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1528  startup_cost += npageaccesses *
1529  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1530  }
1531  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1532  {
1533  /*
1534  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1535  * a total number of tuple comparisons of N log2 K; but the constant
1536  * factor is a bit higher than for quicksort. Tweak it so that the
1537  * cost curve is continuous at the crossover point.
1538  */
1539  startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1540  }
1541  else
1542  {
1543  /* We'll use plain quicksort on all the input tuples */
1544  startup_cost += comparison_cost * tuples * LOG2(tuples);
1545  }
1546 
1547  /*
1548  * Also charge a small amount (arbitrarily set equal to operator cost) per
1549  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1550  * doesn't do qual-checking or projection, so it has less overhead than
1551  * most plan nodes. Note it's correct to use tuples not output_tuples
1552  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1553  * counting the LIMIT otherwise.
1554  */
1555  run_cost += cpu_operator_cost * tuples;
1556 
1557  path->startup_cost = startup_cost;
1558  path->total_cost = startup_cost + run_cost;
1559 }
bool enable_sort
Definition: costsize.c:123
double random_page_cost
Definition: costsize.c:105
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4780
Cost total_cost
Definition: relation.h:907
#define LOG2(x)
Definition: costsize.c:101
double rows
Definition: relation.h:905
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2289
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
void cost_subplan ( PlannerInfo root,
SubPlan subplan,
Plan plan 
)

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

3000 {
3001  QualCost sp_cost;
3002 
3003  /* Figure any cost for evaluating the testexpr */
3004  cost_qual_eval(&sp_cost,
3005  make_ands_implicit((Expr *) subplan->testexpr),
3006  root);
3007 
3008  if (subplan->useHashTable)
3009  {
3010  /*
3011  * If we are using a hash table for the subquery outputs, then the
3012  * cost of evaluating the query is a one-time cost. We charge one
3013  * cpu_operator_cost per tuple for the work of loading the hashtable,
3014  * too.
3015  */
3016  sp_cost.startup += plan->total_cost +
3017  cpu_operator_cost * plan->plan_rows;
3018 
3019  /*
3020  * The per-tuple costs include the cost of evaluating the lefthand
3021  * expressions, plus the cost of probing the hashtable. We already
3022  * accounted for the lefthand expressions as part of the testexpr, and
3023  * will also have counted one cpu_operator_cost for each comparison
3024  * operator. That is probably too low for the probing cost, but it's
3025  * hard to make a better estimate, so live with it for now.
3026  */
3027  }
3028  else
3029  {
3030  /*
3031  * Otherwise we will be rescanning the subplan output on each
3032  * evaluation. We need to estimate how much of the output we will
3033  * actually need to scan. NOTE: this logic should agree with the
3034  * tuple_fraction estimates used by make_subplan() in
3035  * plan/subselect.c.
3036  */
3037  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3038 
3039  if (subplan->subLinkType == EXISTS_SUBLINK)
3040  {
3041  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3042  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3043  }
3044  else if (subplan->subLinkType == ALL_SUBLINK ||
3045  subplan->subLinkType == ANY_SUBLINK)
3046  {
3047  /* assume we need 50% of the tuples */
3048  sp_cost.per_tuple += 0.50 * plan_run_cost;
3049  /* also charge a cpu_operator_cost per row examined */
3050  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3051  }
3052  else
3053  {
3054  /* assume we need all tuples */
3055  sp_cost.per_tuple += plan_run_cost;
3056  }
3057 
3058  /*
3059  * Also account for subplan's startup cost. If the subplan is
3060  * uncorrelated or undirect correlated, AND its topmost node is one
3061  * that materializes its output, assume that we'll only need to pay
3062  * its startup cost once; otherwise assume we pay the startup cost
3063  * every time.
3064  */
3065  if (subplan->parParam == NIL &&
3067  sp_cost.startup += plan->startup_cost;
3068  else
3069  sp_cost.per_tuple += plan->startup_cost;
3070  }
3071 
3072  subplan->startup_cost = sp_cost.startup;
3073  subplan->per_call_cost = sp_cost.per_tuple;
3074 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:117
SubLinkType subLinkType
Definition: primnodes.h:661
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: plannodes.h:111
double cpu_operator_cost
Definition: costsize.c:108
Node * testexpr
Definition: primnodes.h:663
Cost per_call_cost
Definition: primnodes.h:689
List * parParam
Definition: primnodes.h:685
#define nodeTag(nodeptr)
Definition: nodes.h:513
Cost total_cost
Definition: plannodes.h:112
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:561
bool useHashTable
Definition: primnodes.h:675
Cost startup_cost
Definition: primnodes.h:688
double clamp_row_est(double nrows)
Definition: costsize.c:172
double Cost
Definition: nodes.h:632
void cost_subqueryscan ( SubqueryScanPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1180 {
1181  Cost startup_cost;
1182  Cost run_cost;
1183  QualCost qpqual_cost;
1184  Cost cpu_per_tuple;
1185 
1186  /* Should only be applied to base relations that are subqueries */
1187  Assert(baserel->relid > 0);
1188  Assert(baserel->rtekind == RTE_SUBQUERY);
1189 
1190  /* Mark the path with the correct row estimate */
1191  if (param_info)
1192  path->path.rows = param_info->ppi_rows;
1193  else
1194  path->path.rows = baserel->rows;
1195 
1196  /*
1197  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1198  * any restriction clauses and tlist that will be attached to the
1199  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1200  * projection overhead.
1201  */
1202  path->path.startup_cost = path->subpath->startup_cost;
1203  path->path.total_cost = path->subpath->total_cost;
1204 
1205  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1206 
1207  startup_cost = qpqual_cost.startup;
1208  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1209  run_cost = cpu_per_tuple * baserel->tuples;
1210 
1211  /* tlist eval costs are paid per output row, not per tuple scanned */
1212  startup_cost += path->path.pathtarget->cost.startup;
1213  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1214 
1215  path->path.startup_cost += startup_cost;
1216  path->path.total_cost += startup_cost + run_cost;
1217 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double Cost
Definition: nodes.h:632
void cost_tidscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidquals,
ParamPathInfo param_info 
)

Definition at line 1075 of file costsize.c.

References ScalarArrayOpExpr::args, Assert, RelOptInfo::baserestrictcost, 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, lsecond, NULL, 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().

1077 {
1078  Cost startup_cost = 0;
1079  Cost run_cost = 0;
1080  bool isCurrentOf = false;
1081  QualCost qpqual_cost;
1082  Cost cpu_per_tuple;
1083  QualCost tid_qual_cost;
1084  int ntuples;
1085  ListCell *l;
1086  double spc_random_page_cost;
1087 
1088  /* Should only be applied to base relations */
1089  Assert(baserel->relid > 0);
1090  Assert(baserel->rtekind == RTE_RELATION);
1091 
1092  /* Mark the path with the correct row estimate */
1093  if (param_info)
1094  path->rows = param_info->ppi_rows;
1095  else
1096  path->rows = baserel->rows;
1097 
1098  /* Count how many tuples we expect to retrieve */
1099  ntuples = 0;
1100  foreach(l, tidquals)
1101  {
1102  if (IsA(lfirst(l), ScalarArrayOpExpr))
1103  {
1104  /* Each element of the array yields 1 tuple */
1106  Node *arraynode = (Node *) lsecond(saop->args);
1107 
1108  ntuples += estimate_array_length(arraynode);
1109  }
1110  else if (IsA(lfirst(l), CurrentOfExpr))
1111  {
1112  /* CURRENT OF yields 1 tuple */
1113  isCurrentOf = true;
1114  ntuples++;
1115  }
1116  else
1117  {
1118  /* It's just CTID = something, count 1 tuple */
1119  ntuples++;
1120  }
1121  }
1122 
1123  /*
1124  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1125  * understands how to do it correctly. Therefore, honor enable_tidscan
1126  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1127  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1128  * subtract off here; that's to prevent other plan types such as seqscan
1129  * from winning.
1130  */
1131  if (isCurrentOf)
1132  {
1134  startup_cost -= disable_cost;
1135  }
1136  else if (!enable_tidscan)
1137  startup_cost += disable_cost;
1138 
1139  /*
1140  * The TID qual expressions will be computed once, any other baserestrict
1141  * quals once per retrieved tuple.
1142  */
1143  cost_qual_eval(&tid_qual_cost, tidquals, root);
1144 
1145  /* fetch estimated page cost for tablespace containing table */
1147  &spc_random_page_cost,
1148  NULL);
1149 
1150  /* disk costs --- assume each tuple on a different page */
1151  run_cost += spc_random_page_cost * ntuples;
1152 
1153  /* Add scanning CPU costs */
1154  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1155 
1156  /* XXX currently we assume TID quals are a subset of qpquals */
1157  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1158  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1159  tid_qual_cost.per_tuple;
1160  run_cost += cpu_per_tuple * ntuples;
1161 
1162  /* tlist eval costs are paid per output row, not per tuple scanned */
1163  startup_cost += path->pathtarget->cost.startup;
1164  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1165 
1166  path->startup_cost = startup_cost;
1167  path->total_cost = startup_cost + run_cost;
1168 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
bool enable_tidscan
Definition: costsize.c:122
Oid reltablespace
Definition: relation.h:519
Definition: nodes.h:508
#define lsecond(l)
Definition: pg_list.h:114
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2078
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
QualCost baserestrictcost
Definition: relation.h:546
double Cost
Definition: nodes.h:632
void cost_valuesscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1290 {
1291  Cost startup_cost = 0;
1292  Cost run_cost = 0;
1293  QualCost qpqual_cost;
1294  Cost cpu_per_tuple;
1295 
1296  /* Should only be applied to base relations that are values lists */
1297  Assert(baserel->relid > 0);
1298  Assert(baserel->rtekind == RTE_VALUES);
1299 
1300  /* Mark the path with the correct row estimate */
1301  if (param_info)
1302  path->rows = param_info->ppi_rows;
1303  else
1304  path->rows = baserel->rows;
1305 
1306  /*
1307  * For now, estimate list evaluation cost at one operator eval per list
1308  * (probably pretty bogus, but is it worth being smarter?)
1309  */
1310  cpu_per_tuple = cpu_operator_cost;
1311 
1312  /* Add scanning CPU costs */
1313  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1314 
1315  startup_cost += qpqual_cost.startup;
1316  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1317  run_cost += cpu_per_tuple * baserel->tuples;
1318 
1319  /* tlist eval costs are paid per output row, not per tuple scanned */
1320  startup_cost += path->pathtarget->cost.startup;
1321  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1322 
1323  path->startup_cost = startup_cost;
1324  path->total_cost = startup_cost + run_cost;
1325 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double Cost
Definition: nodes.h:632
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 1783 of file costsize.c.

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

Referenced by create_windowagg_path().

1787 {
1788  Cost startup_cost;
1789  Cost total_cost;
1790  ListCell *lc;
1791 
1792  startup_cost = input_startup_cost;
1793  total_cost = input_total_cost;
1794 
1795  /*
1796  * Window functions are assumed to cost their stated execution cost, plus
1797  * the cost of evaluating their input expressions, per tuple. Since they
1798  * may in fact evaluate their inputs at multiple rows during each cycle,
1799  * this could be a drastic underestimate; but without a way to know how
1800  * many rows the window function will fetch, it's hard to do better. In
1801  * any case, it's a good estimate for all the built-in window functions,
1802  * so we'll just do this for now.
1803  */
1804  foreach(lc, windowFuncs)
1805  {
1806  WindowFunc *wfunc = castNode(WindowFunc, lfirst(lc));
1807  Cost wfunccost;
1808  QualCost argcosts;
1809 
1810  wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1811 
1812  /* also add the input expressions' cost to per-input-row costs */
1813  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1814  startup_cost += argcosts.startup;
1815  wfunccost += argcosts.per_tuple;
1816 
1817  /*
1818  * Add the filter's cost to per-input-row costs. XXX We should reduce
1819  * input expression costs according to filter selectivity.
1820  */
1821  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
1822  startup_cost += argcosts.startup;
1823  wfunccost += argcosts.per_tuple;
1824 
1825  total_cost += wfunccost * input_tuples;
1826  }
1827 
1828  /*
1829  * We also charge cpu_operator_cost per grouping column per tuple for
1830  * grouping comparisons, plus cpu_tuple_cost per tuple for general
1831  * overhead.
1832  *
1833  * XXX this neglects costs of spooling the data to disk when it overflows
1834  * work_mem. Sooner or later that should get accounted for.
1835  */
1836  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1837  total_cost += cpu_tuple_cost * input_tuples;
1838 
1839  path->rows = input_tuples;
1840  path->startup_cost = startup_cost;
1841  path->total_cost = total_cost;
1842 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3225
List * args
Definition: primnodes.h:337
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Definition: nodes.h:508
float4 get_func_cost(Oid funcid)
Definition: lsyscache.c:1609
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Oid winfnoid
Definition: primnodes.h:333
Cost total_cost
Definition: relation.h:907
#define lfirst(lc)
Definition: pg_list.h:106
Expr * aggfilter
Definition: primnodes.h:338
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
double Cost
Definition: nodes.h:632
static List * extract_nonindex_conditions ( List qual_clauses,
List indexquals 
)
static

Definition at line 678 of file costsize.c.

References castNode, is_redundant_derived_clause(), lappend(), lfirst, list_member_ptr(), NIL, and RestrictInfo::pseudoconstant.

Referenced by cost_index().

679 {
680  List *result = NIL;
681  ListCell *lc;
682 
683  foreach(lc, qual_clauses)
684  {
685  RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lc));
686 
687  if (rinfo->pseudoconstant)
688  continue; /* we may drop pseudoconstants here */
689  if (list_member_ptr(indexquals, rinfo))
690  continue; /* simple duplicate */
691  if (is_redundant_derived_clause(rinfo, indexquals))
692  continue; /* derived from same EquivalenceClass */
693  /* ... skip the predicate proof attempt createplan.c will try ... */
694  result = lappend(result, rinfo);
695  }
696  return result;
697 }
#define NIL
Definition: pg_list.h:69
bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
Definition: equivclass.c:2448
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
bool pseudoconstant
Definition: relation.h:1645
List * lappend(List *list, void *datum)
Definition: list.c:128
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:465
#define lfirst(lc)
Definition: pg_list.h:106
Definition: pg_list.h:45
void final_cost_hashjoin ( PlannerInfo root,
HashPath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 2780 of file costsize.c.

References approx_tuple_count(), Assert, bms_is_subset(), castNode, clamp_row_est(), RestrictInfo::clause, PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucketsize(), get_leftop(), get_parallel_divisor(), get_rightop(), JoinPath::innerjoinpath, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, RestrictInfo::left_bucketsize, RestrictInfo::left_relids, lfirst, 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, RelOptInfo::relids, RestrictInfo::right_bucketsize, RestrictInfo::right_relids, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_hashjoin_path().

2784 {
2785  Path *outer_path = path->jpath.outerjoinpath;
2786  Path *inner_path = path->jpath.innerjoinpath;
2787  double outer_path_rows = outer_path->rows;
2788  double inner_path_rows = inner_path->rows;
2789  List *hashclauses = path->path_hashclauses;
2790  Cost startup_cost = workspace->startup_cost;
2791  Cost run_cost = workspace->run_cost;
2792  int numbuckets = workspace->numbuckets;
2793  int numbatches = workspace->numbatches;
2794  Cost cpu_per_tuple;
2795  QualCost hash_qual_cost;
2796  QualCost qp_qual_cost;
2797  double hashjointuples;
2798  double virtualbuckets;
2799  Selectivity innerbucketsize;
2800  ListCell *hcl;
2801 
2802  /* Mark the path with the correct row estimate */
2803  if (path->jpath.path.param_info)
2804  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2805  else
2806  path->jpath.path.rows = path->jpath.path.parent->rows;
2807 
2808  /* For partial paths, scale row estimate. */
2809  if (path->jpath.path.parallel_workers > 0)
2810  path->jpath.path.rows /= get_parallel_divisor(&path->jpath.path);
2811 
2812  /*
2813  * We could include disable_cost in the preliminary estimate, but that
2814  * would amount to optimizing for the case where the join method is
2815  * disabled, which doesn't seem like the way to bet.
2816  */
2817  if (!enable_hashjoin)
2818  startup_cost += disable_cost;
2819 
2820  /* mark the path with estimated # of batches */
2821  path->num_batches = numbatches;
2822 
2823  /* and compute the number of "virtual" buckets in the whole join */
2824  virtualbuckets = (double) numbuckets *(double) numbatches;
2825 
2826  /*
2827  * Determine bucketsize fraction for inner relation. We use the smallest
2828  * bucketsize estimated for any individual hashclause; this is undoubtedly
2829  * conservative.
2830  *
2831  * BUT: if inner relation has been unique-ified, we can assume it's good
2832  * for hashing. This is important both because it's the right answer, and
2833  * because we avoid contaminating the cache with a value that's wrong for
2834  * non-unique-ified paths.
2835  */
2836  if (IsA(inner_path, UniquePath))
2837  innerbucketsize = 1.0 / virtualbuckets;
2838  else
2839  {
2840  innerbucketsize = 1.0;
2841  foreach(hcl, hashclauses)
2842  {
2843  RestrictInfo *restrictinfo = castNode(RestrictInfo, lfirst(hcl));
2844  Selectivity thisbucketsize;
2845 
2846  /*
2847  * First we have to figure out which side of the hashjoin clause
2848  * is the inner side.
2849  *
2850  * Since we tend to visit the same clauses over and over when
2851  * planning a large query, we cache the bucketsize estimate in the
2852  * RestrictInfo node to avoid repeated lookups of statistics.
2853  */
2854  if (bms_is_subset(restrictinfo->right_relids,
2855  inner_path->parent->relids))
2856  {
2857  /* righthand side is inner */
2858  thisbucketsize = restrictinfo->right_bucketsize;
2859  if (thisbucketsize < 0)
2860  {
2861  /* not cached yet */
2862  thisbucketsize =
2864  get_rightop(restrictinfo->clause),
2865  virtualbuckets);
2866  restrictinfo->right_bucketsize = thisbucketsize;
2867  }
2868  }
2869  else
2870  {
2871  Assert(bms_is_subset(restrictinfo->left_relids,
2872  inner_path->parent->relids));
2873  /* lefthand side is inner */
2874  thisbucketsize = restrictinfo->left_bucketsize;
2875  if (thisbucketsize < 0)
2876  {
2877  /* not cached yet */
2878  thisbucketsize =
2880  get_leftop(restrictinfo->clause),
2881  virtualbuckets);
2882  restrictinfo->left_bucketsize = thisbucketsize;
2883  }
2884  }
2885 
2886  if (innerbucketsize > thisbucketsize)
2887  innerbucketsize = thisbucketsize;
2888  }
2889  }
2890 
2891  /*
2892  * Compute cost of the hashquals and qpquals (other restriction clauses)
2893  * separately.
2894  */
2895  cost_qual_eval(&hash_qual_cost, hashclauses, root);
2896  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2897  qp_qual_cost.startup -= hash_qual_cost.startup;
2898  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2899 
2900  /* CPU costs */
2901 
2902  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
2903  {
2904  double outer_matched_rows;
2905  Selectivity inner_scan_frac;
2906 
2907  /*
2908  * SEMI or ANTI join: executor will stop after first match.
2909  *
2910  * For an outer-rel row that has at least one match, we can expect the
2911  * bucket scan to stop after a fraction 1/(match_count+1) of the
2912  * bucket's rows, if the matches are evenly distributed. Since they
2913  * probably aren't quite evenly distributed, we apply a fuzz factor of
2914  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2915  * to clamp inner_scan_frac to at most 1.0; but since match_count is
2916  * at least 1, no such clamp is needed now.)
2917  */
2918  outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2919  inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2920 
2921  startup_cost += hash_qual_cost.startup;
2922  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2923  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2924 
2925  /*
2926  * For unmatched outer-rel rows, the picture is quite a lot different.
2927  * In the first place, there is no reason to assume that these rows
2928  * preferentially hit heavily-populated buckets; instead assume they
2929  * are uncorrelated with the inner distribution and so they see an
2930  * average bucket size of inner_path_rows / virtualbuckets. In the
2931  * second place, it seems likely that they will have few if any exact
2932  * hash-code matches and so very few of the tuples in the bucket will
2933  * actually require eval of the hash quals. We don't have any good
2934  * way to estimate how many will, but for the moment assume that the
2935  * effective cost per bucket entry is one-tenth what it is for
2936  * matchable tuples.
2937  */
2938  run_cost += hash_qual_cost.per_tuple *
2939  (outer_path_rows - outer_matched_rows) *
2940  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2941 
2942  /* Get # of tuples that will pass the basic join */
2943  if (path->jpath.jointype == JOIN_SEMI)
2944  hashjointuples = outer_matched_rows;
2945  else
2946  hashjointuples = outer_path_rows - outer_matched_rows;
2947  }
2948  else
2949  {
2950  /*
2951  * The number of tuple comparisons needed is the number of outer
2952  * tuples times the typical number of tuples in a hash bucket, which
2953  * is the inner relation size times its bucketsize fraction. At each
2954  * one, we need to evaluate the hashjoin quals. But actually,
2955  * charging the full qual eval cost at each tuple is pessimistic,
2956  * since we don't evaluate the quals unless the hash values match
2957  * exactly. For lack of a better idea, halve the cost estimate to
2958  * allow for that.
2959  */
2960  startup_cost += hash_qual_cost.startup;
2961  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2962  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2963 
2964  /*
2965  * Get approx # tuples passing the hashquals. We use
2966  * approx_tuple_count here because we need an estimate done with
2967  * JOIN_INNER semantics.
2968  */
2969  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2970  }
2971 
2972  /*
2973  * For each tuple that gets through the hashjoin proper, we charge
2974  * cpu_tuple_cost plus the cost of evaluating additional restriction
2975  * clauses that are to be applied at the join. (This is pessimistic since
2976  * not all of the quals may get evaluated at each tuple.)
2977  */
2978  startup_cost += qp_qual_cost.startup;
2979  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2980  run_cost += cpu_per_tuple * hashjointuples;
2981 
2982  /* tlist eval costs are paid per output row, not per tuple scanned */
2983  startup_cost += path->jpath.path.pathtarget->cost.startup;
2984  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
2985 
2986  path->jpath.path.startup_cost = startup_cost;
2987  path->jpath.path.total_cost = startup_cost + run_cost;
2988 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
JoinPath jpath
Definition: relation.h:1282
PathTarget * pathtarget
Definition: relation.h:895
int num_batches
Definition: relation.h:1284
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Selectivity outer_match_frac
Definition: relation.h:2032
Path * innerjoinpath
Definition: relation.h:1217
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:3709
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
Relids left_relids
Definition: relation.h:1664
double Selectivity
Definition: nodes.h:631
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Node * get_leftop(const Expr *clause)
Definition: clauses.c:198
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:307
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
Relids relids
Definition: relation.h:490
double rint(double x)
Definition: rint.c:22
Expr * clause
Definition: relation.h:1637
Path * outerjoinpath
Definition: relation.h:1216
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
Selectivity left_bucketsize
Definition: relation.h:1698
Relids right_relids
Definition: relation.h:1665
Path path
Definition: relation.h:1212
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
Node * get_rightop(const Expr *clause)
Definition: clauses.c:215
double ppi_rows
Definition: relation.h:854
bool enable_hashjoin
Definition: costsize.c:128
Selectivity estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
Definition: selfuncs.c:3554
Selectivity match_count
Definition: relation.h:2033
Selectivity right_bucketsize
Definition: relation.h:1699
JoinType jointype
Definition: relation.h:1214
List * path_hashclauses
Definition: relation.h:1283
double clamp_row_est(double nrows)
Definition: costsize.c:172
Definition: pg_list.h:45
Definition: relation.h:888
double Cost
Definition: nodes.h:632
void final_cost_mergejoin ( PlannerInfo root,
MergePath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo 
)

Definition at line 2390 of file costsize.c.

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

Referenced by create_mergejoin_path().

2393 {
2394  Path *outer_path = path->jpath.outerjoinpath;
2395  Path *inner_path = path->jpath.innerjoinpath;
2396  double inner_path_rows = inner_path->rows;
2397  List *mergeclauses = path->path_mergeclauses;
2398  List *innersortkeys = path->innersortkeys;
2399  Cost startup_cost = workspace->startup_cost;
2400  Cost run_cost = workspace->run_cost;
2401  Cost inner_run_cost = workspace->inner_run_cost;
2402  double outer_rows = workspace->outer_rows;
2403  double inner_rows = workspace->inner_rows;
2404  double outer_skip_rows = workspace->outer_skip_rows;
2405  double inner_skip_rows = workspace->inner_skip_rows;
2406  Cost cpu_per_tuple,
2407  bare_inner_cost,
2408  mat_inner_cost;
2409  QualCost merge_qual_cost;
2410  QualCost qp_qual_cost;
2411  double mergejointuples,
2412  rescannedtuples;
2413  double rescanratio;
2414 
2415  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2416  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2417  inner_path_rows = 1;
2418 
2419  /* Mark the path with the correct row estimate */
2420  if (path->jpath.path.param_info)
2421  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2422  else
2423  path->jpath.path.rows = path->jpath.path.parent->rows;
2424 
2425  /* For partial paths, scale row estimate. */
2426  if (path->jpath.path.parallel_workers > 0)
2427  path->jpath.path.rows /= get_parallel_divisor(&path->jpath.path);
2428 
2429  /*
2430  * We could include disable_cost in the preliminary estimate, but that
2431  * would amount to optimizing for the case where the join method is
2432  * disabled, which doesn't seem like the way to bet.
2433  */
2434  if (!enable_mergejoin)
2435  startup_cost += disable_cost;
2436 
2437  /*
2438  * Compute cost of the mergequals and qpquals (other restriction clauses)
2439  * separately.
2440  */
2441  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2442  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2443  qp_qual_cost.startup -= merge_qual_cost.startup;
2444  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2445 
2446  /*
2447  * Get approx # tuples passing the mergequals. We use approx_tuple_count
2448  * here because we need an estimate done with JOIN_INNER semantics.
2449  */
2450  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2451 
2452  /*
2453  * When there are equal merge keys in the outer relation, the mergejoin
2454  * must rescan any matching tuples in the inner relation. This means
2455  * re-fetching inner tuples; we have to estimate how often that happens.
2456  *
2457  * For regular inner and outer joins, the number of re-fetches can be
2458  * estimated approximately as size of merge join output minus size of
2459  * inner relation. Assume that the distinct key values are 1, 2, ..., and
2460  * denote the number of values of each key in the outer relation as m1,
2461  * m2, ...; in the inner relation, n1, n2, ... Then we have
2462  *
2463  * size of join = m1 * n1 + m2 * n2 + ...
2464  *
2465  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2466  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2467  * relation
2468  *
2469  * This equation works correctly for outer tuples having no inner match
2470  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2471  * are effectively subtracting those from the number of rescanned tuples,
2472  * when we should not. Can we do better without expensive selectivity
2473  * computations?
2474  *
2475  * The whole issue is moot if we are working from a unique-ified outer
2476  * input.
2477  */
2478  if (IsA(outer_path, UniquePath))
2479  rescannedtuples = 0;
2480  else
2481  {
2482  rescannedtuples = mergejointuples - inner_path_rows;
2483  /* Must clamp because of possible underestimate */
2484  if (rescannedtuples < 0)
2485  rescannedtuples = 0;
2486  }
2487  /* We'll inflate various costs this much to account for rescanning */
2488  rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2489 
2490  /*
2491  * Decide whether we want to materialize the inner input to shield it from
2492  * mark/restore and performing re-fetches. Our cost model for regular
2493  * re-fetches is that a re-fetch costs the same as an original fetch,
2494  * which is probably an overestimate; but on the other hand we ignore the
2495  * bookkeeping costs of mark/restore. Not clear if it's worth developing
2496  * a more refined model. So we just need to inflate the inner run cost by
2497  * rescanratio.
2498  */
2499  bare_inner_cost = inner_run_cost * rescanratio;
2500 
2501  /*
2502  * When we interpose a Material node the re-fetch cost is assumed to be
2503  * just cpu_operator_cost per tuple, independently of the underlying
2504  * plan's cost; and we charge an extra cpu_operator_cost per original
2505  * fetch as well. Note that we're assuming the materialize node will
2506  * never spill to disk, since it only has to remember tuples back to the
2507  * last mark. (If there are a huge number of duplicates, our other cost
2508  * factors will make the path so expensive that it probably won't get
2509  * chosen anyway.) So we don't use cost_rescan here.
2510  *
2511  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2512  * of the generated Material node.
2513  */
2514  mat_inner_cost = inner_run_cost +
2515  cpu_operator_cost * inner_path_rows * rescanratio;
2516 
2517  /*
2518  * Prefer materializing if it looks cheaper, unless the user has asked to
2519  * suppress materialization.
2520  */
2521  if (enable_material && mat_inner_cost < bare_inner_cost)
2522  path->materialize_inner = true;
2523 
2524  /*
2525  * Even if materializing doesn't look cheaper, we *must* do it if the
2526  * inner path is to be used directly (without sorting) and it doesn't
2527  * support mark/restore.
2528  *
2529  * Since the inner side must be ordered, and only Sorts and IndexScans can
2530  * create order to begin with, and they both support mark/restore, you
2531  * might think there's no problem --- but you'd be wrong. Nestloop and
2532  * merge joins can *preserve* the order of their inputs, so they can be
2533  * selected as the input of a mergejoin, and they don't support
2534  * mark/restore at present.
2535  *
2536  * We don't test the value of enable_material here, because
2537  * materialization is required for correctness in this case, and turning
2538  * it off does not entitle us to deliver an invalid plan.
2539  */
2540  else if (innersortkeys == NIL &&
2541  !ExecSupportsMarkRestore(inner_path))
2542  path->materialize_inner = true;
2543 
2544  /*
2545  * Also, force materializing if the inner path is to be sorted and the
2546  * sort is expected to spill to disk. This is because the final merge
2547  * pass can be done on-the-fly if it doesn't have to support mark/restore.
2548  * We don't try to adjust the cost estimates for this consideration,
2549  * though.
2550  *
2551  * Since materialization is a performance optimization in this case,
2552  * rather than necessary for correctness, we skip it if enable_material is
2553  * off.
2554  */
2555  else if (enable_material && innersortkeys != NIL &&
2556  relation_byte_size(inner_path_rows,
2557  inner_path->pathtarget->width) >
2558  (work_mem * 1024L))
2559  path->materialize_inner = true;
2560  else
2561  path->materialize_inner = false;
2562 
2563  /* Charge the right incremental cost for the chosen case */
2564  if (path->materialize_inner)
2565  run_cost += mat_inner_cost;
2566  else
2567  run_cost += bare_inner_cost;
2568 
2569  /* CPU costs */
2570 
2571  /*
2572  * The number of tuple comparisons needed is approximately number of outer
2573  * rows plus number of inner rows plus number of rescanned tuples (can we
2574  * refine this?). At each one, we need to evaluate the mergejoin quals.
2575  */
2576  startup_cost += merge_qual_cost.startup;
2577  startup_cost += merge_qual_cost.per_tuple *
2578  (outer_skip_rows + inner_skip_rows * rescanratio);
2579  run_cost += merge_qual_cost.per_tuple *
2580  ((outer_rows - outer_skip_rows) +
2581  (inner_rows - inner_skip_rows) * rescanratio);
2582 
2583  /*
2584  * For each tuple that gets through the mergejoin proper, we charge
2585  * cpu_tuple_cost plus the cost of evaluating additional restriction
2586  * clauses that are to be applied at the join. (This is pessimistic since
2587  * not all of the quals may get evaluated at each tuple.)
2588  *
2589  * Note: we could adjust for SEMI/ANTI joins skipping some qual
2590  * evaluations here, but it's probably not worth the trouble.
2591  */
2592  startup_cost += qp_qual_cost.startup;
2593  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2594  run_cost += cpu_per_tuple * mergejointuples;
2595 
2596  /* tlist eval costs are paid per output row, not per tuple scanned */
2597  startup_cost += path->jpath.path.pathtarget->cost.startup;
2598  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
2599 
2600  path->jpath.path.startup_cost = startup_cost;
2601  path->jpath.path.total_cost = startup_cost + run_cost;
2602 }
#define NIL
Definition: pg_list.h:69
List * path_mergeclauses
Definition: relation.h:1265
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:390
bool materialize_inner
Definition: relation.h:1268
Path * innerjoinpath
Definition: relation.h:1217
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:3709
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4780
Path * outerjoinpath
Definition: relation.h:1216
int work_mem
Definition: globals.c:112
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
double outer_skip_rows
Definition: relation.h:2084
bool enable_mergejoin
Definition: costsize.c:127
Path path
Definition: relation.h:1212
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
List * innersortkeys
Definition: relation.h:1267
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
int width
Definition: relation.h:827
JoinPath jpath
Definition: relation.h:1264
double inner_skip_rows
Definition: relation.h:2085
Definition: pg_list.h:45
Definition: relation.h:888
double Cost
Definition: nodes.h:632
bool enable_material
Definition: costsize.c:126
void final_cost_nestloop ( PlannerInfo root,
NestPath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 1976 of file costsize.c.

References PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_nestloop, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_nestloop_path().

1980 {
1981  Path *outer_path = path->outerjoinpath;
1982  Path *inner_path = path->innerjoinpath;
1983  double outer_path_rows = outer_path->rows;
1984  double inner_path_rows = inner_path->rows;
1985  Cost startup_cost = workspace->startup_cost;
1986  Cost run_cost = workspace->run_cost;
1987  Cost cpu_per_tuple;
1988  QualCost restrict_qual_cost;
1989  double ntuples;
1990 
1991  /* Protect some assumptions below that rowcounts aren't zero or NaN */
1992  if (outer_path_rows <= 0 || isnan(outer_path_rows))
1993  outer_path_rows = 1;
1994  if (inner_path_rows <= 0 || isnan(inner_path_rows))
1995  inner_path_rows = 1;
1996 
1997  /* Mark the path with the correct row estimate */
1998  if (path->path.param_info)
1999  path->path.rows = path->path.param_info->ppi_rows;
2000  else
2001  path->path.rows = path->path.parent->rows;
2002 
2003  /* For partial paths, scale row estimate. */
2004  if (path->path.parallel_workers > 0)
2005  path->path.rows /= get_parallel_divisor(&path->path);
2006 
2007  /*
2008  * We could include disable_cost in the preliminary estimate, but that
2009  * would amount to optimizing for the case where the join method is
2010  * disabled, which doesn't seem like the way to bet.
2011  */
2012  if (!enable_nestloop)
2013  startup_cost += disable_cost;
2014 
2015  /* cost of inner-relation source data (we already dealt with outer rel) */
2016 
2017  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
2018  {
2019  /*
2020  * SEMI or ANTI join: executor will stop after first match.
2021  */
2022  Cost inner_run_cost = workspace->inner_run_cost;
2023  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2024  double outer_matched_rows;
2025  Selectivity inner_scan_frac;
2026 
2027  /*
2028  * For an outer-rel row that has at least one match, we can expect the
2029  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2030  * rows, if the matches are evenly distributed. Since they probably
2031  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2032  * that fraction. (If we used a larger fuzz factor, we'd have to
2033  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2034  * least 1, no such clamp is needed now.)
2035  */
2036  outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2037  inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2038 
2039  /*
2040  * Compute number of tuples processed (not number emitted!). First,
2041  * account for successfully-matched outer rows.
2042  */
2043  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2044 
2045  /*
2046  * Now we need to estimate the actual costs of scanning the inner
2047  * relation, which may be quite a bit less than N times inner_run_cost
2048  * due to early scan stops. We consider two cases. If the inner path
2049  * is an indexscan using all the joinquals as indexquals, then an
2050  * unmatched outer row results in an indexscan returning no rows,
2051  * which is probably quite cheap. Otherwise, the executor will have
2052  * to scan the whole inner rel for an unmatched row; not so cheap.
2053  */
2054  if (has_indexed_join_quals(path))
2055  {
2056  /*
2057  * Successfully-matched outer rows will only require scanning
2058  * inner_scan_frac of the inner relation. In this case, we don't
2059  * need to charge the full inner_run_cost even when that's more
2060  * than inner_rescan_run_cost, because we can assume that none of
2061  * the inner scans ever scan the whole inner relation. So it's
2062  * okay to assume that all the inner scan executions can be
2063  * fractions of the full cost, even if materialization is reducing
2064  * the rescan cost. At this writing, it's impossible to get here
2065  * for a materialized inner scan, so inner_run_cost and
2066  * inner_rescan_run_cost will be the same anyway; but just in
2067  * case, use inner_run_cost for the first matched tuple and
2068  * inner_rescan_run_cost for additional ones.
2069  */
2070  run_cost += inner_run_cost * inner_scan_frac;
2071  if (outer_matched_rows > 1)
2072  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2073 
2074  /*
2075  * Add the cost of inner-scan executions for unmatched outer rows.
2076  * We estimate this as the same cost as returning the first tuple
2077  * of a nonempty scan. We consider that these are all rescans,
2078  * since we used inner_run_cost once already.
2079  */
2080  run_cost += (outer_path_rows - outer_matched_rows) *
2081  inner_rescan_run_cost / inner_path_rows;
2082 
2083  /*
2084  * We won't be evaluating any quals at all for unmatched rows, so
2085  * don't add them to ntuples.
2086  */
2087  }
2088  else
2089  {
2090  /*
2091  * Here, a complicating factor is that rescans may be cheaper than
2092  * first scans. If we never scan all the way to the end of the
2093  * inner rel, it might be (depending on the plan type) that we'd
2094  * never pay the whole inner first-scan run cost. However it is
2095  * difficult to estimate whether that will happen (and it could
2096  * not happen if there are any unmatched outer rows!), so be
2097  * conservative and always charge the whole first-scan cost once.
2098  */
2099  run_cost += inner_run_cost;
2100 
2101  /* Add inner run cost for additional outer tuples having matches */
2102  if (outer_matched_rows > 1)
2103  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2104 
2105  /* Add inner run cost for unmatched outer tuples */
2106  run_cost += (outer_path_rows - outer_matched_rows) *
2107  inner_rescan_run_cost;
2108 
2109  /* And count the unmatched join tuples as being processed */
2110  ntuples += (outer_path_rows - outer_matched_rows) *
2111  inner_path_rows;
2112  }
2113  }
2114  else
2115  {
2116  /* Normal-case source costs were included in preliminary estimate */
2117 
2118  /* Compute number of tuples processed (not number emitted!) */
2119  ntuples = outer_path_rows * inner_path_rows;
2120  }
2121 
2122  /* CPU costs */
2123  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2124  startup_cost += restrict_qual_cost.startup;
2125  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2126  run_cost += cpu_per_tuple * ntuples;
2127 
2128  /* tlist eval costs are paid per output row, not per tuple scanned */
2129  startup_cost += path->path.pathtarget->cost.startup;
2130  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
2131 
2132  path->path.startup_cost = startup_cost;
2133  path->path.total_cost = startup_cost + run_cost;
2134 }
PathTarget * pathtarget
Definition: relation.h:895
bool enable_nestloop
Definition: costsize.c:125
Selectivity outer_match_frac
Definition: relation.h:2032
Path * innerjoinpath
Definition: relation.h:1217
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
double Selectivity
Definition: nodes.h:631
Cost inner_rescan_run_cost
Definition: relation.h:2079
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
double rint(double x)
Definition: rint.c:22
Path * outerjoinpath
Definition: relation.h:1216
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
Path path
Definition: relation.h:1212
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:3616
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
Selectivity match_count
Definition: relation.h:2033
JoinType jointype
Definition: relation.h:1214
Definition: relation.h:888
double Cost
Definition: nodes.h:632
static Selectivity get_foreign_key_join_selectivity ( PlannerInfo root,
Relids  outer_relids,
Relids  inner_relids,
SpecialJoinInfo sjinfo,
List **  restrictlist 
)
static

Definition at line 4067 of file costsize.c.

References bms_is_member(), bms_membership(), BMS_SINGLETON, clause_selectivity(), ForeignKeyOptInfo::con_relid, ForeignKeyOptInfo::eclass, find_base_rel(), PlannerInfo::fkey_list, i, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, list_concat(), list_copy(), list_delete_cell(), list_head(), list_length(), list_member_ptr(), lnext, Max, Min, next, NIL, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_ri, NULL, RestrictInfo::parent_ec, ForeignKeyOptInfo::ref_relid, ForeignKeyOptInfo::rinfos, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by calc_joinrel_size_estimate().

4072 {
4073  Selectivity fkselec = 1.0;
4074  JoinType jointype = sjinfo->jointype;
4075  List *worklist = *restrictlist;
4076  ListCell *lc;
4077 
4078  /* Consider each FK constraint that is known to match the query */
4079  foreach(lc, root->fkey_list)
4080  {
4081  ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
4082  bool ref_is_outer;
4083  bool use_smallest_selectivity = false;
4084  List *removedlist;
4085  ListCell *cell;
4086  ListCell *prev;
4087  ListCell *next;
4088 
4089  /*
4090  * This FK is not relevant unless it connects a baserel on one side of
4091  * this join to a baserel on the other side.
4092  */
4093  if (bms_is_member(fkinfo->con_relid, outer_relids) &&
4094  bms_is_member(fkinfo->ref_relid, inner_relids))
4095  ref_is_outer = false;
4096  else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
4097  bms_is_member(fkinfo->con_relid, inner_relids))
4098  ref_is_outer = true;
4099  else
4100  continue;
4101 
4102  /*
4103  * Modify the restrictlist by removing clauses that match the FK (and
4104  * putting them into removedlist instead). It seems unsafe to modify
4105  * the originally-passed List structure, so we make a shallow copy the
4106  * first time through.
4107  */
4108  if (worklist == *restrictlist)
4109  worklist = list_copy(worklist);
4110 
4111  removedlist = NIL;
4112  prev = NULL;
4113  for (cell = list_head(worklist); cell; cell = next)
4114  {
4115  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
4116  bool remove_it = false;
4117  int i;
4118 
4119  next = lnext(cell);
4120  /* Drop this clause if it matches any column of the FK */
4121  for (i = 0; i < fkinfo->nkeys; i++)
4122  {
4123  if (rinfo->parent_ec)
4124  {
4125  /*
4126  * EC-derived clauses can only match by EC. It is okay to
4127  * consider any clause derived from the same EC as
4128  * matching the FK: even if equivclass.c chose to generate
4129  * a clause equating some other pair of Vars, it could
4130  * have generated one equating the FK's Vars. So for
4131  * purposes of estimation, we can act as though it did so.
4132  *
4133  * Note: checking parent_ec is a bit of a cheat because
4134  * there are EC-derived clauses that don't have parent_ec
4135  * set; but such clauses must compare expressions that
4136  * aren't just Vars, so they cannot match the FK anyway.
4137  */
4138  if (fkinfo->eclass[i] == rinfo->parent_ec)
4139  {
4140  remove_it = true;
4141  break;
4142  }
4143  }
4144  else
4145  {
4146  /*
4147  * Otherwise, see if rinfo was previously matched to FK as
4148  * a "loose" clause.
4149  */
4150  if (list_member_ptr(fkinfo->rinfos[i], rinfo))
4151  {
4152  remove_it = true;
4153  break;
4154  }
4155  }
4156  }
4157  if (remove_it)
4158  {
4159  worklist = list_delete_cell(worklist, cell, prev);
4160  removedlist = lappend(removedlist, rinfo);
4161  }
4162  else
4163  prev = cell;
4164  }
4165 
4166  /*
4167  * If we failed to remove all the matching clauses we expected to
4168  * find, chicken out and ignore this FK; applying its selectivity
4169  * might result in double-counting. Put any clauses we did manage to
4170  * remove back into the worklist.
4171  *
4172  * Since the matching clauses are known not outerjoin-delayed, they
4173  * should certainly have appeared in the initial joinclause list. If
4174  * we didn't find them, they must have been matched to, and removed
4175  * by, some other FK in a previous iteration of this loop. (A likely
4176  * case is that two FKs are matched to the same EC; there will be only
4177  * one EC-derived clause in the initial list, so the first FK will
4178  * consume it.) Applying both FKs' selectivity independently risks
4179  * underestimating the join size; in particular, this would undo one
4180  * of the main things that ECs were invented for, namely to avoid
4181  * double-counting the selectivity of redundant equality conditions.
4182  * Later we might think of a reasonable way to combine the estimates,
4183  * but for now, just punt, since this is a fairly uncommon situation.
4184  */
4185  if (list_length(removedlist) !=
4186  (fkinfo->nmatched_ec + fkinfo->nmatched_ri))
4187  {
4188  worklist = list_concat(worklist, removedlist);
4189  continue;
4190  }
4191 
4192  /*
4193  * Finally we get to the payoff: estimate selectivity using the
4194  * knowledge that each referencing row will match exactly one row in
4195  * the referenced table.
4196  *
4197  * XXX that's not true in the presence of nulls in the referencing
4198  * column(s), so in principle we should derate the estimate for those.
4199  * However (1) if there are any strict restriction clauses for the
4200  * referencing column(s) elsewhere in the query, derating here would
4201  * be double-counting the null fraction, and (2) it's not very clear
4202  * how to combine null fractions for multiple referencing columns.
4203  *
4204  * In the use_smallest_selectivity code below, null derating is done
4205  * implicitly by relying on clause_selectivity(); in the other cases,
4206  * we do nothing for now about correcting for nulls.
4207  *
4208  * XXX another point here is that if either side of an FK constraint
4209  * is an inheritance parent, we estimate as though the constraint
4210  * covers all its children as well. This is not an unreasonable
4211  * assumption for a referencing table, ie the user probably applied
4212  * identical constraints to all child tables (though perhaps we ought
4213  * to check that). But it's not possible to have done that for a
4214  * referenced table. Fortunately, precisely because that doesn't
4215  * work, it is uncommon in practice to have an FK referencing a parent
4216  * table. So, at least for now, disregard inheritance here.
4217  */
4218  if (ref_is_outer && jointype != JOIN_INNER)
4219  {
4220  /*
4221  * When the referenced table is on the outer side of a non-inner
4222  * join, knowing that each inner row has exactly one match is not
4223  * as useful as one could wish, since we really need to know the
4224  * fraction of outer rows with a match. Still, we can avoid the
4225  * folly of multiplying the per-column estimates together. Take
4226  * the smallest per-column selectivity, instead. (This should
4227  * correspond to the FK column with the most nulls.)
4228  */
4229  use_smallest_selectivity = true;
4230  }
4231  else if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
4232  {
4233  /*
4234  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the
4235  * fraction of LHS rows that have matches. The referenced table
4236  * is on the inner side (we already handled the other case above),
4237  * so the FK implies that every LHS row has a match *in the
4238  * referenced table*. But any restriction or join clauses below
4239  * here will reduce the number of matches.
4240  */
4241  if (bms_membership(inner_relids) == BMS_SINGLETON)
4242  {
4243  /*
4244  * When the inner side of the semi/anti join is just the
4245  * referenced table, we may take the FK selectivity as equal
4246  * to the selectivity of the table's restriction clauses.
4247  */
4248  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
4249  double ref_tuples = Max(ref_rel->tuples, 1.0);
4250 
4251  fkselec *= ref_rel->rows / ref_tuples;
4252  }
4253  else
4254  {
4255  /*
4256  * When the inner side of the semi/anti join is itself a join,
4257  * it's hard to guess what fraction of the referenced table
4258  * will get through the join. But we still don't want to
4259  * multiply per-column estimates together. Take the smallest
4260  * per-column selectivity, instead.
4261  */
4262  use_smallest_selectivity = true;
4263  }
4264  }
4265  else
4266  {
4267  /*
4268  * Otherwise, selectivity is exactly 1/referenced-table-size; but
4269  * guard against tuples == 0. Note we should use the raw table
4270  * tuple count, not any estimate of its filtered or joined size.
4271  */
4272  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
4273  double ref_tuples = Max(ref_rel->tuples, 1.0);
4274 
4275  fkselec *= 1.0 / ref_tuples;
4276  }
4277 
4278  /*
4279  * Common code for cases where we should use the smallest selectivity
4280  * that would be computed for any one of the FK's clauses.
4281  */
4282  if (use_smallest_selectivity)
4283  {
4284  Selectivity thisfksel = 1.0;
4285 
4286  foreach(cell, removedlist)
4287  {
4288  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
4289  Selectivity csel;
4290 
4291  csel = clause_selectivity(root, (Node *) rinfo,
4292  0, jointype, sjinfo);
4293  thisfksel = Min(thisfksel, csel);
4294  }
4295  fkselec *= thisfksel;
4296  }
4297  }
4298 
4299  *restrictlist = worklist;
4300  return fkselec;
4301 }
#define NIL
Definition: pg_list.h:69
static int32 next
Definition: blutils.c:210
double tuples
Definition: relation.h:529
#define Min(x, y)
Definition: c.h:802
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:508
List * list_concat(List *list1, List *list2)
Definition: list.c:321
double Selectivity
Definition: nodes.h:631
List * fkey_list
Definition: relation.h:255
JoinType
Definition: nodes.h:665
EquivalenceClass * parent_ec
Definition: relation.h:1671
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:483
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: relation.h:662
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:604
double rows
Definition: relation.h:493
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:465
#define Max(x, y)
Definition: c.h:796
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1811
static int list_length(const List *l)
Definition: pg_list.h:89
int i
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
List * rinfos[INDEX_MAX_KEYS]
Definition: relation.h:664
static double get_indexpath_pages ( Path bitmapqual)
static

Definition at line 803 of file costsize.c.

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

Referenced by compute_bitmap_pages().

804 {
805  double result = 0;
806  ListCell *l;
807 
808  if (IsA(bitmapqual, BitmapAndPath))
809  {
810  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
811 
812  foreach(l, apath->bitmapquals)
813  {
814  result += get_indexpath_pages((Path *) lfirst(l));
815  }
816  }
817  else if (IsA(bitmapqual, BitmapOrPath))
818  {
819  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
820 
821  foreach(l, opath->bitmapquals)
822  {
823  result += get_indexpath_pages((Path *) lfirst(l));
824  }
825  }
826  else if (IsA(bitmapqual, IndexPath))
827  {
828  IndexPath *ipath = (IndexPath *) bitmapqual;
829 
830  result = (double) ipath->indexinfo->pages;
831  }
832  else
833  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
834 
835  return result;
836 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
IndexOptInfo * indexinfo
Definition: relation.h:972
List * bitmapquals
Definition: relation.h:1015
List * bitmapquals
Definition: relation.h:1028
BlockNumber pages
Definition: relation.h:593
#define ERROR
Definition: elog.h:43
#define lfirst(lc)
Definition: pg_list.h:106
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:803
#define nodeTag(nodeptr)
Definition: nodes.h:513
#define elog
Definition: elog.h:219
Definition: relation.h:888
static double get_parallel_divisor ( Path path)
static

Definition at line 4801 of file costsize.c.

References Path::parallel_workers.

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

4802 {
4803  double parallel_divisor = path->parallel_workers;
4804  double leader_contribution;
4805 
4806  /*
4807  * Early experience with parallel query suggests that when there is only
4808  * one worker, the leader often makes a very substantial contribution to
4809  * executing the parallel portion of the plan, but as more workers are
4810  * added, it does less and less, because it's busy reading tuples from the
4811  * workers and doing whatever non-parallel post-processing is needed. By
4812  * the time we reach 4 workers, the leader no longer makes a meaningful
4813  * contribution. Thus, for now, estimate that the leader spends 30% of
4814  * its time servicing each worker, and the remainder executing the
4815  * parallel plan.
4816  */
4817  leader_contribution = 1.0 - (0.3 * path->parallel_workers);
4818  if (leader_contribution > 0)
4819  parallel_divisor += leader_contribution;
4820 
4821  return parallel_divisor;
4822 }
int parallel_workers
Definition: relation.h:901
double get_parameterized_baserel_size ( PlannerInfo root,
RelOptInfo rel,
List param_clauses 
)

Definition at line 3795 of file costsize.c.

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), JOIN_INNER, list_concat(), list_copy(), NULL, RelOptInfo::relid, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by get_baserel_parampathinfo().

3797 {
3798  List *allclauses;
3799  double nrows;
3800 
3801  /*
3802  * Estimate the number of rows returned by the parameterized scan, knowing
3803  * that it will apply all the extra join clauses as well as the rel's own
3804  * restriction clauses. Note that we force the clauses to be treated as
3805  * non-join clauses during selectivity estimation.
3806  */
3807  allclauses = list_concat(list_copy(param_clauses),
3808  rel->baserestrictinfo);
3809  nrows = rel->tuples *
3811  allclauses,
3812  rel->relid, /* do not use 0! */
3813  JOIN_INNER,
3814  NULL);
3815  nrows = clamp_row_est(nrows);
3816  /* For safety, make sure result is not more than the base estimate */
3817  if (nrows > rel->rows)
3818  nrows = rel->rows;
3819  return nrows;
3820 }
double tuples
Definition: relation.h:529
List * baserestrictinfo
Definition: relation.h:544
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Index relid
Definition: relation.h:518
double rows
Definition: relation.h:493
#define NULL
Definition: c.h:226
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
double clamp_row_est(double nrows)
Definition: costsize.c:172
Definition: pg_list.h:45
double get_parameterized_joinrel_size ( PlannerInfo root,
RelOptInfo rel,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
List restrict_clauses 
)

Definition at line 3876 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

3881 {
3882  double nrows;
3883 
3884  /*
3885  * Estimate the number of rows returned by the parameterized join as the
3886  * sizes of the input paths times the selectivity of the clauses that have
3887  * ended up at this join node.
3888  *
3889  * As with set_joinrel_size_estimates, the rowcount estimate could depend
3890  * on the pair of input paths provided, though ideally we'd get the same
3891  * estimate for any pair with the same parameterization.
3892  */
3893  nrows = calc_joinrel_size_estimate(root,
3894  outer_path->parent,
3895  inner_path->parent,
3896  outer_path->rows,
3897  inner_path->rows,
3898  sjinfo,
3899  restrict_clauses);
3900  /* For safety, make sure result is not more than the base estimate */
3901  if (nrows > rel->rows)
3902  nrows = rel->rows;
3903  return nrows;
3904 }
RelOptInfo * parent
Definition: relation.h:894
double rows
Definition: relation.h:493
double rows
Definition: relation.h:905
static double calc_joinrel_size_estimate(PlannerInfo *root, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
Definition: costsize.c:3916
static void get_restriction_qual_cost ( PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
QualCost qpqual_cost 
)
static

Definition at line 3466 of file costsize.c.

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

Referenced by cost_bitmap_heap_scan(), cost_ctescan(), cost_functionscan(), cost_samplescan(), cost_seqscan(), cost_subqueryscan(), cost_tidscan(), and cost_valuesscan().

3469 {
3470  if (param_info)
3471  {
3472  /* Include costs of pushed-down clauses */
3473  cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
3474 
3475  qpqual_cost->startup += baserel->baserestrictcost.startup;
3476  qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
3477  }
3478  else
3479  *qpqual_cost = baserel->baserestrictcost;
3480 }
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
List * ppi_clauses
Definition: relation.h:855
QualCost baserestrictcost
Definition: relation.h:546
static bool has_indexed_join_quals ( NestPath joinpath)
static

Definition at line 3616 of file costsize.c.

References JoinPath::innerjoinpath, is_redundant_derived_clause(), IsA, join_clause_is_movable_into(), JoinPath::joinrestrictinfo, lfirst, list_member_ptr(), NIL, NULL, Path::param_info, Path::parent, JoinPath::path, Path::pathtype, ParamPathInfo::ppi_clauses, RelOptInfo::relids, T_BitmapHeapScan, T_IndexOnlyScan, and T_IndexScan.

Referenced by final_cost_nestloop().

3617 {
3618  Relids joinrelids = joinpath->path.parent->relids;
3619  Path *innerpath = joinpath->innerjoinpath;
3620  List *indexclauses;
3621  bool found_one;
3622  ListCell *lc;
3623 
3624  /* If join still has quals to evaluate, it's not fast */
3625  if (joinpath->joinrestrictinfo != NIL)
3626  return false;
3627  /* Nor if the inner path isn't parameterized at all */
3628  if (innerpath->param_info == NULL)
3629  return false;
3630 
3631  /* Find the indexclauses list for the inner scan */
3632  switch (innerpath->pathtype)
3633  {
3634  case T_IndexScan:
3635  case T_IndexOnlyScan:
3636  indexclauses = ((IndexPath *) innerpath)->indexclauses;
3637  break;
3638  case T_BitmapHeapScan:
3639  {
3640  /* Accept only a simple bitmap scan, not AND/OR cases */
3641  Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
3642 
3643  if (IsA(bmqual, IndexPath))
3644  indexclauses = ((IndexPath *) bmqual)->indexclauses;
3645  else
3646  return false;
3647  break;
3648  }
3649  default:
3650 
3651  /*
3652  * If it's not a simple indexscan, it probably doesn't run quickly
3653  * for zero rows out, even if it's a parameterized path using all
3654  * the joinquals.
3655  */
3656  return false;
3657  }
3658 
3659  /*
3660  * Examine the inner path's param clauses. Any that are from the outer
3661  * path must be found in the indexclauses list, either exactly or in an
3662  * equivalent form generated by equivclass.c. Also, we must find at least
3663  * one such clause, else it's a clauseless join which isn't fast.
3664  */
3665  found_one = false;
3666  foreach(lc, innerpath->param_info->ppi_clauses)
3667  {
3668  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3669 
3670  if (join_clause_is_movable_into(rinfo,
3671  innerpath->parent->relids,
3672  joinrelids))
3673  {
3674  if (!(list_member_ptr(indexclauses, rinfo) ||
3675  is_redundant_derived_clause(rinfo, indexclauses)))
3676  return false;
3677  found_one = true;
3678  }
3679  }
3680  return found_one;
3681 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
Definition: equivclass.c:2448
Path * innerjoinpath
Definition: relation.h:1217
ParamPathInfo * param_info
Definition: relation.h:897
NodeTag pathtype
Definition: relation.h:892
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
Relids relids
Definition: relation.h:490
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)
Definition: restrictinfo.c:508
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:465
#define NULL
Definition: c.h:226
Path path
Definition: relation.h:1212
#define lfirst(lc)
Definition: pg_list.h:106
List * ppi_clauses
Definition: relation.h:855
Definition: pg_list.h:45
Definition: relation.h:888
double index_pages_fetched ( double  tuples_fetched,
BlockNumber  pages,
double  index_pages,
PlannerInfo root 
)

Definition at line 738 of file costsize.c.

References Assert, effective_cache_size, Max, T, and PlannerInfo::total_table_pages.

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

740 {
741  double pages_fetched;
742  double total_pages;
743  double T,
744  b;
745 
746  /* T is # pages in table, but don't allow it to be zero */
747  T = (pages > 1) ? (double) pages : 1.0;
748 
749  /* Compute number of pages assumed to be competing for cache space */
750  total_pages = root->total_table_pages + index_pages;
751  total_pages = Max(total_pages, 1.0);
752  Assert(T <= total_pages);
753 
754  /* b is pro-rated share of effective_cache_size */
755  b = (double) effective_cache_size *T / total_pages;
756 
757  /* force it positive and integral */
758  if (b <= 1.0)
759  b = 1.0;
760  else
761  b = ceil(b);
762 
763  /* This part is the Mackert and Lohman formula */
764  if (T <= b)
765  {
766  pages_fetched =
767  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
768  if (pages_fetched >= T)
769  pages_fetched = T;
770  else
771  pages_fetched = ceil(pages_fetched);
772  }
773  else
774  {
775  double lim;
776 
777  lim = (2.0 * T * b) / (2.0 * T - b);
778  if (tuples_fetched <= lim)
779  {
780  pages_fetched =
781  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
782  }
783  else
784  {
785  pages_fetched =
786  b + (tuples_fetched - lim) * (T - b) / T;
787  }
788  pages_fetched = ceil(pages_fetched);
789  }
790  return pages_fetched;
791 }
int effective_cache_size
Definition: costsize.c:112
static const uint32 T[65]
Definition: md5.c:101
double total_table_pages
Definition: relation.h:284
#define Max(x, y)
Definition: c.h:796
#define Assert(condition)
Definition: c.h:671
void initial_cost_hashjoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List hashclauses,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 2686 of file costsize.c.

References cpu_operator_cost, cpu_tuple_cost, ExecChooseHashTableSize(), list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), Path::pathtarget, Path::rows, JoinCostWorkspace::run_cost, seq_page_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, and PathTarget::width.

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

2692 {
2693  Cost startup_cost = 0;
2694  Cost run_cost = 0;
2695  double outer_path_rows = outer_path->rows;
2696  double inner_path_rows = inner_path->rows;
2697  int num_hashclauses = list_length(hashclauses);
2698  int numbuckets;
2699  int numbatches;
2700  int num_skew_mcvs;
2701 
2702  /* cost of source data */
2703  startup_cost += outer_path->startup_cost;
2704  run_cost += outer_path->total_cost - outer_path->startup_cost;
2705  startup_cost += inner_path->total_cost;
2706 
2707  /*
2708  * Cost of computing hash function: must do it once per input tuple. We
2709  * charge one cpu_operator_cost for each column's hash function. Also,
2710  * tack on one cpu_tuple_cost per inner row, to model the costs of
2711  * inserting the row into the hashtable.
2712  *
2713  * XXX when a hashclause is more complex than a single operator, we really
2714  * should charge the extra eval costs of the left or right side, as
2715  * appropriate, here. This seems more work than it's worth at the moment.
2716  */
2717  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2718  * inner_path_rows;
2719  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2720 
2721  /*
2722  * Get hash table size that executor would use for inner relation.
2723  *
2724  * XXX for the moment, always assume that skew optimization will be
2725  * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2726  * trying to determine that for sure.
2727  *
2728  * XXX at some point it might be interesting to try to account for skew
2729  * optimization in the cost estimate, but for now, we don't.
2730  */
2731  ExecChooseHashTableSize(inner_path_rows,
2732  inner_path->pathtarget->width,
2733  true, /* useskew */
2734  &numbuckets,
2735  &numbatches,
2736  &num_skew_mcvs);
2737 
2738  /*
2739  * If inner relation is too big then we will need to "batch" the join,
2740  * which implies writing and reading most of the tuples to disk an extra
2741  * time. Charge seq_page_cost per page, since the I/O should be nice and
2742  * sequential. Writing the inner rel counts as startup cost, all the rest
2743  * as run cost.
2744  */
2745  if (numbatches > 1)
2746  {
2747  double outerpages = page_size(outer_path_rows,
2748  outer_path->pathtarget->width);
2749  double innerpages = page_size(inner_path_rows,
2750  inner_path->pathtarget->width);
2751 
2752  startup_cost += seq_page_cost * innerpages;
2753  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2754  }
2755 
2756  /* CPU costs left for later */
2757 
2758  /* Public result fields */
2759  workspace->startup_cost = startup_cost;
2760  workspace->total_cost = startup_cost + run_cost;
2761  /* Save private data for final_cost_hashjoin */
2762  workspace->run_cost = run_cost;
2763  workspace->numbuckets = numbuckets;
2764  workspace->numbatches = numbatches;
2765 }
PathTarget * pathtarget
Definition: relation.h:895
static double page_size(double tuples, int width)
Definition: costsize.c:4791
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:404
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
static int list_length(const List *l)
Definition: pg_list.h:89
double cpu_tuple_cost
Definition: costsize.c:106
int width
Definition: relation.h:827
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
void initial_cost_mergejoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List mergeclauses,
Path outer_path,
Path inner_path,
List outersortkeys,
List innersortkeys,
SpecialJoinInfo sjinfo 
)