PostgreSQL Source Code  git master
index_selfuncs.h File Reference
#include "access/amapi.h"
Include dependency graph for index_selfuncs.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void brincostestimate (struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void btcostestimate (struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void hashcostestimate (struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void gistcostestimate (struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void spgcostestimate (struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void gincostestimate (struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 

Function Documentation

◆ brincostestimate()

void brincostestimate ( struct PlannerInfo root,
struct IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6977 of file selfuncs.c.

References Abs, Assert, attnum, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BRIN_DEFAULT_PAGES_PER_RANGE, brinGetStats(), CLAMP_PROBABILITY, clauselist_selectivity(), cpu_operator_cost, elog, ERROR, free_attstatsslot(), VariableStatData::freefunc, get_attstatsslot(), get_index_stats_hook, get_quals_from_indexclauses(), get_relation_stats_hook, get_tablespace_page_costs(), HeapTupleIsValid, IndexOptInfo::hypothetical, index_close(), index_open(), index_other_operands_eval_cost(), IndexPath::indexclauses, IndexClause::indexcol, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, Int16GetDatum, InvalidOid, JOIN_INNER, lfirst_node, Max, Min, AttStatsSlot::nnumbers, NoLock, AttStatsSlot::numbers, ObjectIdGetDatum, RelOptInfo::pages, IndexOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reltablespace, REVMAP_PAGE_MAXITEMS, BrinStatsData::revmapNumPages, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

6981 {
6982  IndexOptInfo *index = path->indexinfo;
6983  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6984  double numPages = index->pages;
6985  RelOptInfo *baserel = index->rel;
6986  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
6987  Cost spc_seq_page_cost;
6988  Cost spc_random_page_cost;
6989  double qual_arg_cost;
6990  double qualSelectivity;
6991  BrinStatsData statsData;
6992  double indexRanges;
6993  double minimalRanges;
6994  double estimatedRanges;
6995  double selec;
6996  Relation indexRel;
6997  ListCell *l;
6998  VariableStatData vardata;
6999 
7000  Assert(rte->rtekind == RTE_RELATION);
7001 
7002  /* fetch estimated page cost for the tablespace containing the index */
7004  &spc_random_page_cost,
7005  &spc_seq_page_cost);
7006 
7007  /*
7008  * Obtain some data from the index itself, if possible. Otherwise invent
7009  * some plausible internal statistics based on the relation page count.
7010  */
7011  if (!index->hypothetical)
7012  {
7013  /*
7014  * A lock should have already been obtained on the index in plancat.c.
7015  */
7016  indexRel = index_open(index->indexoid, NoLock);
7017  brinGetStats(indexRel, &statsData);
7018  index_close(indexRel, NoLock);
7019 
7020  /* work out the actual number of ranges in the index */
7021  indexRanges = Max(ceil((double) baserel->pages /
7022  statsData.pagesPerRange), 1.0);
7023  }
7024  else
7025  {
7026  /*
7027  * Assume default number of pages per range, and estimate the number
7028  * of ranges based on that.
7029  */
7030  indexRanges = Max(ceil((double) baserel->pages /
7032 
7034  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7035  }
7036 
7037  /*
7038  * Compute index correlation
7039  *
7040  * Because we can use all index quals equally when scanning, we can use
7041  * the largest correlation (in absolute value) among columns used by the
7042  * query. Start at zero, the worst possible case. If we cannot find any
7043  * correlation statistics, we will keep it as 0.
7044  */
7045  *indexCorrelation = 0;
7046 
7047  foreach(l, path->indexclauses)
7048  {
7049  IndexClause *iclause = lfirst_node(IndexClause, l);
7050  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7051 
7052  /* attempt to lookup stats in relation for this index column */
7053  if (attnum != 0)
7054  {
7055  /* Simple variable -- look to stats for the underlying table */
7057  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7058  {
7059  /*
7060  * The hook took control of acquiring a stats tuple. If it
7061  * did supply a tuple, it'd better have supplied a freefunc.
7062  */
7063  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7064  elog(ERROR,
7065  "no function provided to release variable stats with");
7066  }
7067  else
7068  {
7069  vardata.statsTuple =
7071  ObjectIdGetDatum(rte->relid),
7072  Int16GetDatum(attnum),
7073  BoolGetDatum(false));
7074  vardata.freefunc = ReleaseSysCache;
7075  }
7076  }
7077  else
7078  {
7079  /*
7080  * Looks like we've found an expression column in the index. Let's
7081  * see if there's any stats for it.
7082  */
7083 
7084  /* get the attnum from the 0-based index. */
7085  attnum = iclause->indexcol + 1;
7086 
7087  if (get_index_stats_hook &&
7088  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7089  {
7090  /*
7091  * The hook took control of acquiring a stats tuple. If it
7092  * did supply a tuple, it'd better have supplied a freefunc.
7093  */
7094  if (HeapTupleIsValid(vardata.statsTuple) &&
7095  !vardata.freefunc)
7096  elog(ERROR, "no function provided to release variable stats with");
7097  }
7098  else
7099  {
7101  ObjectIdGetDatum(index->indexoid),
7102  Int16GetDatum(attnum),
7103  BoolGetDatum(false));
7104  vardata.freefunc = ReleaseSysCache;
7105  }
7106  }
7107 
7108  if (HeapTupleIsValid(vardata.statsTuple))
7109  {
7110  AttStatsSlot sslot;
7111 
7112  if (get_attstatsslot(&sslot, vardata.statsTuple,
7113  STATISTIC_KIND_CORRELATION, InvalidOid,
7115  {
7116  double varCorrelation = 0.0;
7117 
7118  if (sslot.nnumbers > 0)
7119  varCorrelation = Abs(sslot.numbers[0]);
7120 
7121  if (varCorrelation > *indexCorrelation)
7122  *indexCorrelation = varCorrelation;
7123 
7124  free_attstatsslot(&sslot);
7125  }
7126  }
7127 
7128  ReleaseVariableStats(vardata);
7129  }
7130 
7131  qualSelectivity = clauselist_selectivity(root, indexQuals,
7132  baserel->relid,
7133  JOIN_INNER, NULL);
7134 
7135  /*
7136  * Now calculate the minimum possible ranges we could match with if all of
7137  * the rows were in the perfect order in the table's heap.
7138  */
7139  minimalRanges = ceil(indexRanges * qualSelectivity);
7140 
7141  /*
7142  * Now estimate the number of ranges that we'll touch by using the
7143  * indexCorrelation from the stats. Careful not to divide by zero (note
7144  * we're using the absolute value of the correlation).
7145  */
7146  if (*indexCorrelation < 1.0e-10)
7147  estimatedRanges = indexRanges;
7148  else
7149  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7150 
7151  /* we expect to visit this portion of the table */
7152  selec = estimatedRanges / indexRanges;
7153 
7154  CLAMP_PROBABILITY(selec);
7155 
7156  *indexSelectivity = selec;
7157 
7158  /*
7159  * Compute the index qual costs, much as in genericcostestimate, to add to
7160  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7161  * support those.
7162  */
7163  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7164 
7165  /*
7166  * Compute the startup cost as the cost to read the whole revmap
7167  * sequentially, including the cost to execute the index quals.
7168  */
7169  *indexStartupCost =
7170  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7171  *indexStartupCost += qual_arg_cost;
7172 
7173  /*
7174  * To read a BRIN index there might be a bit of back and forth over
7175  * regular pages, as revmap might point to them out of sequential order;
7176  * calculate the total cost as reading the whole index in random order.
7177  */
7178  *indexTotalCost = *indexStartupCost +
7179  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7180 
7181  /*
7182  * Charge a small amount per range tuple which we expect to match to. This
7183  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7184  * will set a bit for each page in the range when we find a matching
7185  * range, so we must multiply the charge by the number of pages in the
7186  * range.
7187  */
7188  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7189  statsData.pagesPerRange;
7190 
7191  *indexPages = index->pages;
7192 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1180
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
#define Min(x, y)
Definition: c.h:920
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
Oid reltablespace
Definition: pathnodes.h:792
bool hypothetical
Definition: pathnodes.h:830
List * indexclauses
Definition: pathnodes.h:1181
#define Abs(x)
Definition: c.h:926
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:796
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
RelOptInfo * rel
Definition: pathnodes.h:793
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
AttrNumber indexcol
Definition: pathnodes.h:1229
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
float4 * numbers
Definition: lsyscache.h:53
double cpu_operator_cost
Definition: costsize.c:115
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5559
#define BRIN_DEFAULT_PAGES_PER_RANGE
Definition: brin.h:38
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:148
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:671
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define REVMAP_PAGE_MAXITEMS
Definition: brin_page.h:93
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
int16 attnum
Definition: pg_attribute.h:79
#define Max(x, y)
Definition: c.h:914
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5589
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:682
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3003
#define Assert(condition)
Definition: c.h:738
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:149
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RTEKind rtekind
Definition: parsenodes.h:975
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
#define elog(elevel,...)
Definition: elog.h:214
int * indexkeys
Definition: pathnodes.h:803
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
double Cost
Definition: nodes.h:660
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1085
BlockNumber revmapNumPages
Definition: brin.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3133

◆ btcostestimate()

void btcostestimate ( struct PlannerInfo root,
struct IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 5882 of file selfuncs.c.

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BTEqualStrategyNumber, BTLessStrategyNumber, RestrictInfo::clause, clauselist_selectivity(), cpu_operator_cost, elog, ERROR, estimate_array_length(), free_attstatsslot(), VariableStatData::freefunc, genericcostestimate(), get_attstatsslot(), get_index_stats_hook, get_op_opfamily_strategy(), get_opfamily_member(), get_relation_stats_hook, HeapTupleIsValid, IndexPath::indexclauses, IndexClause::indexcol, GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, IndexClause::indexquals, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, RangeTblEntry::inh, Int16GetDatum, InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst_node, linitial_oid, lsecond, MemSet, NIL, IndexOptInfo::nkeycolumns, AttStatsSlot::nnumbers, nodeTag, NullTest::nulltesttype, GenericCosts::num_sa_scans, AttStatsSlot::numbers, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, ObjectIdGetDatum, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, OpExpr::opno, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by bthandler().

5886 {
5887  IndexOptInfo *index = path->indexinfo;
5888  GenericCosts costs;
5889  Oid relid;
5890  AttrNumber colnum;
5891  VariableStatData vardata;
5892  double numIndexTuples;
5893  Cost descentCost;
5894  List *indexBoundQuals;
5895  int indexcol;
5896  bool eqQualHere;
5897  bool found_saop;
5898  bool found_is_null_op;
5899  double num_sa_scans;
5900  ListCell *lc;
5901 
5902  /*
5903  * For a btree scan, only leading '=' quals plus inequality quals for the
5904  * immediately next attribute contribute to index selectivity (these are
5905  * the "boundary quals" that determine the starting and stopping points of
5906  * the index scan). Additional quals can suppress visits to the heap, so
5907  * it's OK to count them in indexSelectivity, but they should not count
5908  * for estimating numIndexTuples. So we must examine the given indexquals
5909  * to find out which ones count as boundary quals. We rely on the
5910  * knowledge that they are given in index column order.
5911  *
5912  * For a RowCompareExpr, we consider only the first column, just as
5913  * rowcomparesel() does.
5914  *
5915  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
5916  * index scans not one, but the ScalarArrayOpExpr's operator can be
5917  * considered to act the same as it normally does.
5918  */
5919  indexBoundQuals = NIL;
5920  indexcol = 0;
5921  eqQualHere = false;
5922  found_saop = false;
5923  found_is_null_op = false;
5924  num_sa_scans = 1;
5925  foreach(lc, path->indexclauses)
5926  {
5927  IndexClause *iclause = lfirst_node(IndexClause, lc);
5928  ListCell *lc2;
5929 
5930  if (indexcol != iclause->indexcol)
5931  {
5932  /* Beginning of a new column's quals */
5933  if (!eqQualHere)
5934  break; /* done if no '=' qual for indexcol */
5935  eqQualHere = false;
5936  indexcol++;
5937  if (indexcol != iclause->indexcol)
5938  break; /* no quals at all for indexcol */
5939  }
5940 
5941  /* Examine each indexqual associated with this index clause */
5942  foreach(lc2, iclause->indexquals)
5943  {
5944  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5945  Expr *clause = rinfo->clause;
5946  Oid clause_op = InvalidOid;
5947  int op_strategy;
5948 
5949  if (IsA(clause, OpExpr))
5950  {
5951  OpExpr *op = (OpExpr *) clause;
5952 
5953  clause_op = op->opno;
5954  }
5955  else if (IsA(clause, RowCompareExpr))
5956  {
5957  RowCompareExpr *rc = (RowCompareExpr *) clause;
5958 
5959  clause_op = linitial_oid(rc->opnos);
5960  }
5961  else if (IsA(clause, ScalarArrayOpExpr))
5962  {
5963  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
5964  Node *other_operand = (Node *) lsecond(saop->args);
5965  int alength = estimate_array_length(other_operand);
5966 
5967  clause_op = saop->opno;
5968  found_saop = true;
5969  /* count number of SA scans induced by indexBoundQuals only */
5970  if (alength > 1)
5971  num_sa_scans *= alength;
5972  }
5973  else if (IsA(clause, NullTest))
5974  {
5975  NullTest *nt = (NullTest *) clause;
5976 
5977  if (nt->nulltesttype == IS_NULL)
5978  {
5979  found_is_null_op = true;
5980  /* IS NULL is like = for selectivity purposes */
5981  eqQualHere = true;
5982  }
5983  }
5984  else
5985  elog(ERROR, "unsupported indexqual type: %d",
5986  (int) nodeTag(clause));
5987 
5988  /* check for equality operator */
5989  if (OidIsValid(clause_op))
5990  {
5991  op_strategy = get_op_opfamily_strategy(clause_op,
5992  index->opfamily[indexcol]);
5993  Assert(op_strategy != 0); /* not a member of opfamily?? */
5994  if (op_strategy == BTEqualStrategyNumber)
5995  eqQualHere = true;
5996  }
5997 
5998  indexBoundQuals = lappend(indexBoundQuals, rinfo);
5999  }
6000  }
6001 
6002  /*
6003  * If index is unique and we found an '=' clause for each column, we can
6004  * just assume numIndexTuples = 1 and skip the expensive
6005  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6006  * NullTest invalidates that theory, even though it sets eqQualHere.
6007  */
6008  if (index->unique &&
6009  indexcol == index->nkeycolumns - 1 &&
6010  eqQualHere &&
6011  !found_saop &&
6012  !found_is_null_op)
6013  numIndexTuples = 1.0;
6014  else
6015  {
6016  List *selectivityQuals;
6017  Selectivity btreeSelectivity;
6018 
6019  /*
6020  * If the index is partial, AND the index predicate with the
6021  * index-bound quals to produce a more accurate idea of the number of
6022  * rows covered by the bound conditions.
6023  */
6024  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6025 
6026  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6027  index->rel->relid,
6028  JOIN_INNER,
6029  NULL);
6030  numIndexTuples = btreeSelectivity * index->rel->tuples;
6031 
6032  /*
6033  * As in genericcostestimate(), we have to adjust for any
6034  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6035  * to integer.
6036  */
6037  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6038  }
6039 
6040  /*
6041  * Now do generic index cost estimation.
6042  */
6043  MemSet(&costs, 0, sizeof(costs));
6044  costs.numIndexTuples = numIndexTuples;
6045 
6046  genericcostestimate(root, path, loop_count, &costs);
6047 
6048  /*
6049  * Add a CPU-cost component to represent the costs of initial btree
6050  * descent. We don't charge any I/O cost for touching upper btree levels,
6051  * since they tend to stay in cache, but we still have to do about log2(N)
6052  * comparisons to descend a btree of N leaf tuples. We charge one
6053  * cpu_operator_cost per comparison.
6054  *
6055  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6056  * ones after the first one are not startup cost so far as the overall
6057  * plan is concerned, so add them only to "total" cost.
6058  */
6059  if (index->tuples > 1) /* avoid computing log(0) */
6060  {
6061  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6062  costs.indexStartupCost += descentCost;
6063  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6064  }
6065 
6066  /*
6067  * Even though we're not charging I/O cost for touching upper btree pages,
6068  * it's still reasonable to charge some CPU cost per page descended
6069  * through. Moreover, if we had no such charge at all, bloated indexes
6070  * would appear to have the same search cost as unbloated ones, at least
6071  * in cases where only a single leaf page is expected to be visited. This
6072  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6073  * touched. The number of such pages is btree tree height plus one (ie,
6074  * we charge for the leaf page too). As above, charge once per SA scan.
6075  */
6076  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6077  costs.indexStartupCost += descentCost;
6078  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6079 
6080  /*
6081  * If we can get an estimate of the first column's ordering correlation C
6082  * from pg_statistic, estimate the index correlation as C for a
6083  * single-column index, or C * 0.75 for multiple columns. (The idea here
6084  * is that multiple columns dilute the importance of the first column's
6085  * ordering, but don't negate it entirely. Before 8.0 we divided the
6086  * correlation by the number of columns, but that seems too strong.)
6087  */
6088  MemSet(&vardata, 0, sizeof(vardata));
6089 
6090  if (index->indexkeys[0] != 0)
6091  {
6092  /* Simple variable --- look to stats for the underlying table */
6093  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6094 
6095  Assert(rte->rtekind == RTE_RELATION);
6096  relid = rte->relid;
6097  Assert(relid != InvalidOid);
6098  colnum = index->indexkeys[0];
6099 
6101  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6102  {
6103  /*
6104  * The hook took control of acquiring a stats tuple. If it did
6105  * supply a tuple, it'd better have supplied a freefunc.
6106  */
6107  if (HeapTupleIsValid(vardata.statsTuple) &&
6108  !vardata.freefunc)
6109  elog(ERROR, "no function provided to release variable stats with");
6110  }
6111  else
6112  {
6114  ObjectIdGetDatum(relid),
6115  Int16GetDatum(colnum),
6116  BoolGetDatum(rte->inh));
6117  vardata.freefunc = ReleaseSysCache;
6118  }
6119  }
6120  else
6121  {
6122  /* Expression --- maybe there are stats for the index itself */
6123  relid = index->indexoid;
6124  colnum = 1;
6125 
6126  if (get_index_stats_hook &&
6127  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6128  {
6129  /*
6130  * The hook took control of acquiring a stats tuple. If it did
6131  * supply a tuple, it'd better have supplied a freefunc.
6132  */
6133  if (HeapTupleIsValid(vardata.statsTuple) &&
6134  !vardata.freefunc)
6135  elog(ERROR, "no function provided to release variable stats with");
6136  }
6137  else
6138  {
6140  ObjectIdGetDatum(relid),
6141  Int16GetDatum(colnum),
6142  BoolGetDatum(false));
6143  vardata.freefunc = ReleaseSysCache;
6144  }
6145  }
6146 
6147  if (HeapTupleIsValid(vardata.statsTuple))
6148  {
6149  Oid sortop;
6150  AttStatsSlot sslot;
6151 
6152  sortop = get_opfamily_member(index->opfamily[0],
6153  index->opcintype[0],
6154  index->opcintype[0],
6156  if (OidIsValid(sortop) &&
6157  get_attstatsslot(&sslot, vardata.statsTuple,
6158  STATISTIC_KIND_CORRELATION, sortop,
6160  {
6161  double varCorrelation;
6162 
6163  Assert(sslot.nnumbers == 1);
6164  varCorrelation = sslot.numbers[0];
6165 
6166  if (index->reverse_sort[0])
6167  varCorrelation = -varCorrelation;
6168 
6169  if (index->nkeycolumns > 1)
6170  costs.indexCorrelation = varCorrelation * 0.75;
6171  else
6172  costs.indexCorrelation = varCorrelation;
6173 
6174  free_attstatsslot(&sslot);
6175  }
6176  }
6177 
6178  ReleaseVariableStats(vardata);
6179 
6180  *indexStartupCost = costs.indexStartupCost;
6181  *indexTotalCost = costs.indexTotalCost;
6182  *indexSelectivity = costs.indexSelectivity;
6183  *indexCorrelation = costs.indexCorrelation;
6184  *indexPages = costs.numIndexPages;
6185 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
IndexOptInfo * indexinfo
Definition: pathnodes.h:1180
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:683
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:526
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:971
List * indexclauses
Definition: pathnodes.h:1181
double Selectivity
Definition: nodes.h:659
double tuples
Definition: pathnodes.h:797
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: pathnodes.h:798
#define OidIsValid(objectId)
Definition: c.h:644
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1892
RelOptInfo * rel
Definition: pathnodes.h:793
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
AttrNumber indexcol
Definition: pathnodes.h:1229
double num_sa_scans
Definition: selfuncs.h:113
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5643
float4 * numbers
Definition: lsyscache.h:53
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
double cpu_operator_cost
Definition: costsize.c:115
Cost indexTotalCost
Definition: selfuncs.h:105
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:148
List * indexquals
Definition: pathnodes.h:1227
Index relid
Definition: pathnodes.h:671
List * lappend(List *list, void *datum)
Definition: list.c:322
Expr * clause
Definition: pathnodes.h:1948
double indexCorrelation
Definition: selfuncs.h:107
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
NullTestType nulltesttype
Definition: primnodes.h:1220
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:111
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3003
#define Assert(condition)
Definition: c.h:738
#define linitial_oid(l)
Definition: pg_list.h:197
int nkeycolumns
Definition: pathnodes.h:802
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:149
Oid * opcintype
Definition: pathnodes.h:807
#define nodeTag(nodeptr)
Definition: nodes.h:531
Cost indexStartupCost
Definition: selfuncs.h:104
Oid * opfamily
Definition: pathnodes.h:806
RTEKind rtekind
Definition: parsenodes.h:975
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:81
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog(elevel,...)
Definition: elog.h:214
int * indexkeys
Definition: pathnodes.h:803
Oid opno
Definition: primnodes.h:516
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
bool * reverse_sort
Definition: pathnodes.h:809
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define BTEqualStrategyNumber
Definition: stratnum.h:31
double Cost
Definition: nodes.h:660
double numIndexPages
Definition: selfuncs.h:110
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3133
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:5861

◆ gincostestimate()

void gincostestimate ( struct PlannerInfo root,
struct IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6646 of file selfuncs.c.

References add_predicate_to_index_quals(), GinQualCounts::arrayScans, GinQualCounts::attHasFullScan, GinQualCounts::attHasNormalScan, RestrictInfo::clause, clauselist_selectivity(), cpu_index_tuple_cost, cpu_operator_cost, elog, ERROR, GinQualCounts::exactEntries, get_quals_from_indexclauses(), get_tablespace_page_costs(), gincost_opexpr(), gincost_scalararrayopexpr(), ginGetStats(), IndexOptInfo::hypothetical, i, index_close(), index_open(), index_other_operands_eval_cost(), index_pages_fetched(), IndexPath::indexclauses, IndexClause::indexcol, IndexPath::indexinfo, IndexOptInfo::indexoid, IndexClause::indexquals, IsA, JOIN_INNER, lfirst_node, list_length(), Max, Min, GinStatsData::nDataPages, GinStatsData::nEntries, GinStatsData::nEntryPages, NIL, IndexOptInfo::nkeycolumns, nodeTag, NoLock, GinStatsData::nPendingPages, GinStatsData::nTotalPages, IndexOptInfo::pages, GinQualCounts::partialEntries, IndexOptInfo::rel, RelOptInfo::relid, IndexOptInfo::reltablespace, scale, GinQualCounts::searchEntries, and IndexOptInfo::tuples.

Referenced by ginhandler().

6650 {
6651  IndexOptInfo *index = path->indexinfo;
6652  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6653  List *selectivityQuals;
6654  double numPages = index->pages,
6655  numTuples = index->tuples;
6656  double numEntryPages,
6657  numDataPages,
6658  numPendingPages,
6659  numEntries;
6660  GinQualCounts counts;
6661  bool matchPossible;
6662  bool fullIndexScan;
6663  double partialScale;
6664  double entryPagesFetched,
6665  dataPagesFetched,
6666  dataPagesFetchedBySel;
6667  double qual_op_cost,
6668  qual_arg_cost,
6669  spc_random_page_cost,
6670  outer_scans;
6671  Relation indexRel;
6672  GinStatsData ginStats;
6673  ListCell *lc;
6674  int i;
6675 
6676  /*
6677  * Obtain statistical information from the meta page, if possible. Else
6678  * set ginStats to zeroes, and we'll cope below.
6679  */
6680  if (!index->hypothetical)
6681  {
6682  /* Lock should have already been obtained in plancat.c */
6683  indexRel = index_open(index->indexoid, NoLock);
6684  ginGetStats(indexRel, &ginStats);
6685  index_close(indexRel, NoLock);
6686  }
6687  else
6688  {
6689  memset(&ginStats, 0, sizeof(ginStats));
6690  }
6691 
6692  /*
6693  * Assuming we got valid (nonzero) stats at all, nPendingPages can be
6694  * trusted, but the other fields are data as of the last VACUUM. We can
6695  * scale them up to account for growth since then, but that method only
6696  * goes so far; in the worst case, the stats might be for a completely
6697  * empty index, and scaling them will produce pretty bogus numbers.
6698  * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
6699  * it's grown more than that, fall back to estimating things only from the
6700  * assumed-accurate index size. But we'll trust nPendingPages in any case
6701  * so long as it's not clearly insane, ie, more than the index size.
6702  */
6703  if (ginStats.nPendingPages < numPages)
6704  numPendingPages = ginStats.nPendingPages;
6705  else
6706  numPendingPages = 0;
6707 
6708  if (numPages > 0 && ginStats.nTotalPages <= numPages &&
6709  ginStats.nTotalPages > numPages / 4 &&
6710  ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
6711  {
6712  /*
6713  * OK, the stats seem close enough to sane to be trusted. But we
6714  * still need to scale them by the ratio numPages / nTotalPages to
6715  * account for growth since the last VACUUM.
6716  */
6717  double scale = numPages / ginStats.nTotalPages;
6718 
6719  numEntryPages = ceil(ginStats.nEntryPages * scale);
6720  numDataPages = ceil(ginStats.nDataPages * scale);
6721  numEntries = ceil(ginStats.nEntries * scale);
6722  /* ensure we didn't round up too much */
6723  numEntryPages = Min(numEntryPages, numPages - numPendingPages);
6724  numDataPages = Min(numDataPages,
6725  numPages - numPendingPages - numEntryPages);
6726  }
6727  else
6728  {
6729  /*
6730  * We might get here because it's a hypothetical index, or an index
6731  * created pre-9.1 and never vacuumed since upgrading (in which case
6732  * its stats would read as zeroes), or just because it's grown too
6733  * much since the last VACUUM for us to put our faith in scaling.
6734  *
6735  * Invent some plausible internal statistics based on the index page
6736  * count (and clamp that to at least 10 pages, just in case). We
6737  * estimate that 90% of the index is entry pages, and the rest is data
6738  * pages. Estimate 100 entries per entry page; this is rather bogus
6739  * since it'll depend on the size of the keys, but it's more robust
6740  * than trying to predict the number of entries per heap tuple.
6741  */
6742  numPages = Max(numPages, 10);
6743  numEntryPages = floor((numPages - numPendingPages) * 0.90);
6744  numDataPages = numPages - numPendingPages - numEntryPages;
6745  numEntries = floor(numEntryPages * 100);
6746  }
6747 
6748  /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
6749  if (numEntries < 1)
6750  numEntries = 1;
6751 
6752  /*
6753  * If the index is partial, AND the index predicate with the index-bound
6754  * quals to produce a more accurate idea of the number of rows covered by
6755  * the bound conditions.
6756  */
6757  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6758 
6759  /* Estimate the fraction of main-table tuples that will be visited */
6760  *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6761  index->rel->relid,
6762  JOIN_INNER,
6763  NULL);
6764 
6765  /* fetch estimated page cost for tablespace containing index */
6767  &spc_random_page_cost,
6768  NULL);
6769 
6770  /*
6771  * Generic assumption about index correlation: there isn't any.
6772  */
6773  *indexCorrelation = 0.0;
6774 
6775  /*
6776  * Examine quals to estimate number of search entries & partial matches
6777  */
6778  memset(&counts, 0, sizeof(counts));
6779  counts.arrayScans = 1;
6780  matchPossible = true;
6781 
6782  foreach(lc, path->indexclauses)
6783  {
6784  IndexClause *iclause = lfirst_node(IndexClause, lc);
6785  ListCell *lc2;
6786 
6787  foreach(lc2, iclause->indexquals)
6788  {
6789  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6790  Expr *clause = rinfo->clause;
6791 
6792  if (IsA(clause, OpExpr))
6793  {
6794  matchPossible = gincost_opexpr(root,
6795  index,
6796  iclause->indexcol,
6797  (OpExpr *) clause,
6798  &counts);
6799  if (!matchPossible)
6800  break;
6801  }
6802  else if (IsA(clause, ScalarArrayOpExpr))
6803  {
6804  matchPossible = gincost_scalararrayopexpr(root,
6805  index,
6806  iclause->indexcol,
6807  (ScalarArrayOpExpr *) clause,
6808  numEntries,
6809  &counts);
6810  if (!matchPossible)
6811  break;
6812  }
6813  else
6814  {
6815  /* shouldn't be anything else for a GIN index */
6816  elog(ERROR, "unsupported GIN indexqual type: %d",
6817  (int) nodeTag(clause));
6818  }
6819  }
6820  }
6821 
6822  /* Fall out if there were any provably-unsatisfiable quals */
6823  if (!matchPossible)
6824  {
6825  *indexStartupCost = 0;
6826  *indexTotalCost = 0;
6827  *indexSelectivity = 0;
6828  return;
6829  }
6830 
6831  /*
6832  * If attribute has a full scan and at the same time doesn't have normal
6833  * scan, then we'll have to scan all non-null entries of that attribute.
6834  * Currently, we don't have per-attribute statistics for GIN. Thus, we
6835  * must assume the whole GIN index has to be scanned in this case.
6836  */
6837  fullIndexScan = false;
6838  for (i = 0; i < index->nkeycolumns; i++)
6839  {
6840  if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
6841  {
6842  fullIndexScan = true;
6843  break;
6844  }
6845  }
6846 
6847  if (fullIndexScan || indexQuals == NIL)
6848  {
6849  /*
6850  * Full index scan will be required. We treat this as if every key in
6851  * the index had been listed in the query; is that reasonable?
6852  */
6853  counts.partialEntries = 0;
6854  counts.exactEntries = numEntries;
6855  counts.searchEntries = numEntries;
6856  }
6857 
6858  /* Will we have more than one iteration of a nestloop scan? */
6859  outer_scans = loop_count;
6860 
6861  /*
6862  * Compute cost to begin scan, first of all, pay attention to pending
6863  * list.
6864  */
6865  entryPagesFetched = numPendingPages;
6866 
6867  /*
6868  * Estimate number of entry pages read. We need to do
6869  * counts.searchEntries searches. Use a power function as it should be,
6870  * but tuples on leaf pages usually is much greater. Here we include all
6871  * searches in entry tree, including search of first entry in partial
6872  * match algorithm
6873  */
6874  entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
6875 
6876  /*
6877  * Add an estimate of entry pages read by partial match algorithm. It's a
6878  * scan over leaf pages in entry tree. We haven't any useful stats here,
6879  * so estimate it as proportion. Because counts.partialEntries is really
6880  * pretty bogus (see code above), it's possible that it is more than
6881  * numEntries; clamp the proportion to ensure sanity.
6882  */
6883  partialScale = counts.partialEntries / numEntries;
6884  partialScale = Min(partialScale, 1.0);
6885 
6886  entryPagesFetched += ceil(numEntryPages * partialScale);
6887 
6888  /*
6889  * Partial match algorithm reads all data pages before doing actual scan,
6890  * so it's a startup cost. Again, we haven't any useful stats here, so
6891  * estimate it as proportion.
6892  */
6893  dataPagesFetched = ceil(numDataPages * partialScale);
6894 
6895  /*
6896  * Calculate cache effects if more than one scan due to nestloops or array
6897  * quals. The result is pro-rated per nestloop scan, but the array qual
6898  * factor shouldn't be pro-rated (compare genericcostestimate).
6899  */
6900  if (outer_scans > 1 || counts.arrayScans > 1)
6901  {
6902  entryPagesFetched *= outer_scans * counts.arrayScans;
6903  entryPagesFetched = index_pages_fetched(entryPagesFetched,
6904  (BlockNumber) numEntryPages,
6905  numEntryPages, root);
6906  entryPagesFetched /= outer_scans;
6907  dataPagesFetched *= outer_scans * counts.arrayScans;
6908  dataPagesFetched = index_pages_fetched(dataPagesFetched,
6909  (BlockNumber) numDataPages,
6910  numDataPages, root);
6911  dataPagesFetched /= outer_scans;
6912  }
6913 
6914  /*
6915  * Here we use random page cost because logically-close pages could be far
6916  * apart on disk.
6917  */
6918  *indexStartupCost = (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
6919 
6920  /*
6921  * Now compute the number of data pages fetched during the scan.
6922  *
6923  * We assume every entry to have the same number of items, and that there
6924  * is no overlap between them. (XXX: tsvector and array opclasses collect
6925  * statistics on the frequency of individual keys; it would be nice to use
6926  * those here.)
6927  */
6928  dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
6929 
6930  /*
6931  * If there is a lot of overlap among the entries, in particular if one of
6932  * the entries is very frequent, the above calculation can grossly
6933  * under-estimate. As a simple cross-check, calculate a lower bound based
6934  * on the overall selectivity of the quals. At a minimum, we must read
6935  * one item pointer for each matching entry.
6936  *
6937  * The width of each item pointer varies, based on the level of
6938  * compression. We don't have statistics on that, but an average of
6939  * around 3 bytes per item is fairly typical.
6940  */
6941  dataPagesFetchedBySel = ceil(*indexSelectivity *
6942  (numTuples / (BLCKSZ / 3)));
6943  if (dataPagesFetchedBySel > dataPagesFetched)
6944  dataPagesFetched = dataPagesFetchedBySel;
6945 
6946  /* Account for cache effects, the same as above */
6947  if (outer_scans > 1 || counts.arrayScans > 1)
6948  {
6949  dataPagesFetched *= outer_scans * counts.arrayScans;
6950  dataPagesFetched = index_pages_fetched(dataPagesFetched,
6951  (BlockNumber) numDataPages,
6952  numDataPages, root);
6953  dataPagesFetched /= outer_scans;
6954  }
6955 
6956  /* And apply random_page_cost as the cost per page */
6957  *indexTotalCost = *indexStartupCost +
6958  dataPagesFetched * spc_random_page_cost;
6959 
6960  /*
6961  * Add on index qual eval costs, much as in genericcostestimate. But we
6962  * can disregard indexorderbys, since GIN doesn't support those.
6963  */
6964  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
6965  qual_op_cost = cpu_operator_cost * list_length(indexQuals);
6966 
6967  *indexStartupCost += qual_arg_cost;
6968  *indexTotalCost += qual_arg_cost;
6969  *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);
6970  *indexPages = dataPagesFetched;
6971 }
#define NIL
Definition: pg_list.h:65
BlockNumber nEntryPages
Definition: gin.h:46
bool attHasNormalScan[INDEX_MAX_KEYS]
Definition: selfuncs.c:6353
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
IndexOptInfo * indexinfo
Definition: pathnodes.h:1180
bool attHasFullScan[INDEX_MAX_KEYS]
Definition: selfuncs.c:6352
#define Min(x, y)
Definition: c.h:920
double partialEntries
Definition: selfuncs.c:6354
double searchEntries
Definition: selfuncs.c:6356
Oid reltablespace
Definition: pathnodes.h:792
int scale
Definition: pgbench.c:153
int64 nEntries
Definition: gin.h:48
uint32 BlockNumber
Definition: block.h:31
bool hypothetical
Definition: pathnodes.h:830
List * indexclauses
Definition: pathnodes.h:1181
double tuples
Definition: pathnodes.h:797
Definition: type.h:89
double exactEntries
Definition: selfuncs.c:6355
BlockNumber pages
Definition: pathnodes.h:796
RelOptInfo * rel
Definition: pathnodes.h:793
#define ERROR
Definition: elog.h:43
AttrNumber indexcol
Definition: pathnodes.h:1229
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
double cpu_operator_cost
Definition: costsize.c:115
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5559
List * indexquals
Definition: pathnodes.h:1227
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:671
Expr * clause
Definition: pathnodes.h:1948
BlockNumber nPendingPages
Definition: gin.h:44
double arrayScans
Definition: selfuncs.c:6357
void ginGetStats(Relation index, GinStatsData *stats)
Definition: ginutil.c:629
static bool gincost_opexpr(PlannerInfo *root, IndexOptInfo *index, int indexcol, OpExpr *clause, GinQualCounts *counts)
Definition: selfuncs.c:6480
static bool gincost_scalararrayopexpr(PlannerInfo *root, IndexOptInfo *index, int indexcol, ScalarArrayOpExpr *clause, double numIndexEntries, GinQualCounts *counts)
Definition: selfuncs.c:6530
BlockNumber nDataPages
Definition: gin.h:47
#define Max(x, y)
Definition: c.h:914
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5589
static int list_length(const List *l)
Definition: pg_list.h:169
BlockNumber nTotalPages
Definition: gin.h:45
int nkeycolumns
Definition: pathnodes.h:802
#define nodeTag(nodeptr)
Definition: nodes.h:531
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define elog(elevel,...)
Definition: elog.h:214
int i
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
double cpu_index_tuple_cost
Definition: costsize.c:114
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:828
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:5861

◆ gistcostestimate()

void gistcostestimate ( struct PlannerInfo root,
struct IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6232 of file selfuncs.c.

References cpu_operator_cost, genericcostestimate(), GenericCosts::indexCorrelation, IndexPath::indexinfo, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, MemSet, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, IndexOptInfo::pages, IndexOptInfo::tree_height, and IndexOptInfo::tuples.

Referenced by gisthandler().

6236 {
6237  IndexOptInfo *index = path->indexinfo;
6238  GenericCosts costs;
6239  Cost descentCost;
6240 
6241  MemSet(&costs, 0, sizeof(costs));
6242 
6243  genericcostestimate(root, path, loop_count, &costs);
6244 
6245  /*
6246  * We model index descent costs similarly to those for btree, but to do
6247  * that we first need an idea of the tree height. We somewhat arbitrarily
6248  * assume that the fanout is 100, meaning the tree height is at most
6249  * log100(index->pages).
6250  *
6251  * Although this computation isn't really expensive enough to require
6252  * caching, we might as well use index->tree_height to cache it.
6253  */
6254  if (index->tree_height < 0) /* unknown? */
6255  {
6256  if (index->pages > 1) /* avoid computing log(0) */
6257  index->tree_height = (int) (log(index->pages) / log(100.0));
6258  else
6259  index->tree_height = 0;
6260  }
6261 
6262  /*
6263  * Add a CPU-cost component to represent the costs of initial descent. We
6264  * just use log(N) here not log2(N) since the branching factor isn't
6265  * necessarily two anyway. As for btree, charge once per SA scan.
6266  */
6267  if (index->tuples > 1) /* avoid computing log(0) */
6268  {
6269  descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6270  costs.indexStartupCost += descentCost;
6271  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6272  }
6273 
6274  /*
6275  * Likewise add a per-page charge, calculated the same as for btrees.
6276  */
6277  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6278  costs.indexStartupCost += descentCost;
6279  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6280 
6281  *indexStartupCost = costs.indexStartupCost;
6282  *indexTotalCost = costs.indexTotalCost;
6283  *indexSelectivity = costs.indexSelectivity;
6284  *indexCorrelation = costs.indexCorrelation;
6285  *indexPages = costs.numIndexPages;
6286 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
IndexOptInfo * indexinfo
Definition: pathnodes.h:1180
#define MemSet(start, val, len)
Definition: c.h:971
double tuples
Definition: pathnodes.h:797
int tree_height
Definition: pathnodes.h:798
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:796
double num_sa_scans
Definition: selfuncs.h:113
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5643
double cpu_operator_cost
Definition: costsize.c:115
Cost indexTotalCost
Definition: selfuncs.h:105
double indexCorrelation
Definition: selfuncs.h:107
Cost indexStartupCost
Definition: selfuncs.h:104
double Cost
Definition: nodes.h:660
double numIndexPages
Definition: selfuncs.h:110

◆ hashcostestimate()

void hashcostestimate ( struct PlannerInfo root,
struct IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6188 of file selfuncs.c.

References genericcostestimate(), GenericCosts::indexCorrelation, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, MemSet, and GenericCosts::numIndexPages.

Referenced by hashhandler().

6192 {
6193  GenericCosts costs;
6194 
6195  MemSet(&costs, 0, sizeof(costs));
6196 
6197  genericcostestimate(root, path, loop_count, &costs);
6198 
6199  /*
6200  * A hash index has no descent costs as such, since the index AM can go
6201  * directly to the target bucket after computing the hash value. There
6202  * are a couple of other hash-specific costs that we could conceivably add
6203  * here, though:
6204  *
6205  * Ideally we'd charge spc_random_page_cost for each page in the target
6206  * bucket, not just the numIndexPages pages that genericcostestimate
6207  * thought we'd visit. However in most cases we don't know which bucket
6208  * that will be. There's no point in considering the average bucket size
6209  * because the hash AM makes sure that's always one page.
6210  *
6211  * Likewise, we could consider charging some CPU for each index tuple in
6212  * the bucket, if we knew how many there were. But the per-tuple cost is
6213  * just a hash value comparison, not a general datatype-dependent
6214  * comparison, so any such charge ought to be quite a bit less than
6215  * cpu_operator_cost; which makes it probably not worth worrying about.
6216  *
6217  * A bigger issue is that chance hash-value collisions will result in
6218  * wasted probes into the heap. We don't currently attempt to model this
6219  * cost on the grounds that it's rare, but maybe it's not rare enough.
6220  * (Any fix for this ought to consider the generic lossy-operator problem,
6221  * though; it's not entirely hash-specific.)
6222  */
6223 
6224  *indexStartupCost = costs.indexStartupCost;
6225  *indexTotalCost = costs.indexTotalCost;
6226  *indexSelectivity = costs.indexSelectivity;
6227  *indexCorrelation = costs.indexCorrelation;
6228  *indexPages = costs.numIndexPages;
6229 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
#define MemSet(start, val, len)
Definition: c.h:971
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5643
Cost indexTotalCost
Definition: selfuncs.h:105
double indexCorrelation
Definition: selfuncs.h:107
Cost indexStartupCost
Definition: selfuncs.h:104
double numIndexPages
Definition: selfuncs.h:110

◆ spgcostestimate()

void spgcostestimate ( struct PlannerInfo root,
struct IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6289 of file selfuncs.c.

References cpu_operator_cost, genericcostestimate(), GenericCosts::indexCorrelation, IndexPath::indexinfo, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, MemSet, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, IndexOptInfo::pages, IndexOptInfo::tree_height, and IndexOptInfo::tuples.

Referenced by spghandler().

6293 {
6294  IndexOptInfo *index = path->indexinfo;
6295  GenericCosts costs;
6296  Cost descentCost;
6297 
6298  MemSet(&costs, 0, sizeof(costs));
6299 
6300  genericcostestimate(root, path, loop_count, &costs);
6301 
6302  /*
6303  * We model index descent costs similarly to those for btree, but to do
6304  * that we first need an idea of the tree height. We somewhat arbitrarily
6305  * assume that the fanout is 100, meaning the tree height is at most
6306  * log100(index->pages).
6307  *
6308  * Although this computation isn't really expensive enough to require
6309  * caching, we might as well use index->tree_height to cache it.
6310  */
6311  if (index->tree_height < 0) /* unknown? */
6312  {
6313  if (index->pages > 1) /* avoid computing log(0) */
6314  index->tree_height = (int) (log(index->pages) / log(100.0));
6315  else
6316  index->tree_height = 0;
6317  }
6318 
6319  /*
6320  * Add a CPU-cost component to represent the costs of initial descent. We
6321  * just use log(N) here not log2(N) since the branching factor isn't
6322  * necessarily two anyway. As for btree, charge once per SA scan.
6323  */
6324  if (index->tuples > 1) /* avoid computing log(0) */
6325  {
6326  descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6327  costs.indexStartupCost += descentCost;
6328  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6329  }
6330 
6331  /*
6332  * Likewise add a per-page charge, calculated the same as for btrees.
6333  */
6334  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6335  costs.indexStartupCost += descentCost;
6336  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6337 
6338  *indexStartupCost = costs.indexStartupCost;
6339  *indexTotalCost = costs.indexTotalCost;
6340  *indexSelectivity = costs.indexSelectivity;
6341  *indexCorrelation = costs.indexCorrelation;
6342  *indexPages = costs.numIndexPages;
6343 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
IndexOptInfo * indexinfo
Definition: pathnodes.h:1180
#define MemSet(start, val, len)
Definition: c.h:971
double tuples
Definition: pathnodes.h:797
int tree_height
Definition: pathnodes.h:798
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:796
double num_sa_scans
Definition: selfuncs.h:113
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5643
double cpu_operator_cost
Definition: costsize.c:115
Cost indexTotalCost
Definition: selfuncs.h:105
double indexCorrelation
Definition: selfuncs.h:107
Cost indexStartupCost
Definition: selfuncs.h:104
double Cost
Definition: nodes.h:660
double numIndexPages
Definition: selfuncs.h:110