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 7685 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().

7689 {
7690  IndexOptInfo *index = path->indexinfo;
7691  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7692  double numPages = index->pages;
7693  RelOptInfo *baserel = index->rel;
7694  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7695  Cost spc_seq_page_cost;
7696  Cost spc_random_page_cost;
7697  double qual_arg_cost;
7698  double qualSelectivity;
7699  BrinStatsData statsData;
7700  double indexRanges;
7701  double minimalRanges;
7702  double estimatedRanges;
7703  double selec;
7704  Relation indexRel;
7705  ListCell *l;
7706  VariableStatData vardata;
7707 
7708  Assert(rte->rtekind == RTE_RELATION);
7709 
7710  /* fetch estimated page cost for the tablespace containing the index */
7712  &spc_random_page_cost,
7713  &spc_seq_page_cost);
7714 
7715  /*
7716  * Obtain some data from the index itself, if possible. Otherwise invent
7717  * some plausible internal statistics based on the relation page count.
7718  */
7719  if (!index->hypothetical)
7720  {
7721  /*
7722  * A lock should have already been obtained on the index in plancat.c.
7723  */
7724  indexRel = index_open(index->indexoid, NoLock);
7725  brinGetStats(indexRel, &statsData);
7726  index_close(indexRel, NoLock);
7727 
7728  /* work out the actual number of ranges in the index */
7729  indexRanges = Max(ceil((double) baserel->pages /
7730  statsData.pagesPerRange), 1.0);
7731  }
7732  else
7733  {
7734  /*
7735  * Assume default number of pages per range, and estimate the number
7736  * of ranges based on that.
7737  */
7738  indexRanges = Max(ceil((double) baserel->pages /
7740 
7742  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7743  }
7744 
7745  /*
7746  * Compute index correlation
7747  *
7748  * Because we can use all index quals equally when scanning, we can use
7749  * the largest correlation (in absolute value) among columns used by the
7750  * query. Start at zero, the worst possible case. If we cannot find any
7751  * correlation statistics, we will keep it as 0.
7752  */
7753  *indexCorrelation = 0;
7754 
7755  foreach(l, path->indexclauses)
7756  {
7757  IndexClause *iclause = lfirst_node(IndexClause, l);
7758  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7759 
7760  /* attempt to lookup stats in relation for this index column */
7761  if (attnum != 0)
7762  {
7763  /* Simple variable -- look to stats for the underlying table */
7765  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7766  {
7767  /*
7768  * The hook took control of acquiring a stats tuple. If it
7769  * did supply a tuple, it'd better have supplied a freefunc.
7770  */
7771  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7772  elog(ERROR,
7773  "no function provided to release variable stats with");
7774  }
7775  else
7776  {
7777  vardata.statsTuple =
7779  ObjectIdGetDatum(rte->relid),
7780  Int16GetDatum(attnum),
7781  BoolGetDatum(false));
7782  vardata.freefunc = ReleaseSysCache;
7783  }
7784  }
7785  else
7786  {
7787  /*
7788  * Looks like we've found an expression column in the index. Let's
7789  * see if there's any stats for it.
7790  */
7791 
7792  /* get the attnum from the 0-based index. */
7793  attnum = iclause->indexcol + 1;
7794 
7795  if (get_index_stats_hook &&
7796  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7797  {
7798  /*
7799  * The hook took control of acquiring a stats tuple. If it
7800  * did supply a tuple, it'd better have supplied a freefunc.
7801  */
7802  if (HeapTupleIsValid(vardata.statsTuple) &&
7803  !vardata.freefunc)
7804  elog(ERROR, "no function provided to release variable stats with");
7805  }
7806  else
7807  {
7809  ObjectIdGetDatum(index->indexoid),
7810  Int16GetDatum(attnum),
7811  BoolGetDatum(false));
7812  vardata.freefunc = ReleaseSysCache;
7813  }
7814  }
7815 
7816  if (HeapTupleIsValid(vardata.statsTuple))
7817  {
7818  AttStatsSlot sslot;
7819 
7820  if (get_attstatsslot(&sslot, vardata.statsTuple,
7821  STATISTIC_KIND_CORRELATION, InvalidOid,
7823  {
7824  double varCorrelation = 0.0;
7825 
7826  if (sslot.nnumbers > 0)
7827  varCorrelation = Abs(sslot.numbers[0]);
7828 
7829  if (varCorrelation > *indexCorrelation)
7830  *indexCorrelation = varCorrelation;
7831 
7832  free_attstatsslot(&sslot);
7833  }
7834  }
7835 
7836  ReleaseVariableStats(vardata);
7837  }
7838 
7839  qualSelectivity = clauselist_selectivity(root, indexQuals,
7840  baserel->relid,
7841  JOIN_INNER, NULL);
7842 
7843  /*
7844  * Now calculate the minimum possible ranges we could match with if all of
7845  * the rows were in the perfect order in the table's heap.
7846  */
7847  minimalRanges = ceil(indexRanges * qualSelectivity);
7848 
7849  /*
7850  * Now estimate the number of ranges that we'll touch by using the
7851  * indexCorrelation from the stats. Careful not to divide by zero (note
7852  * we're using the absolute value of the correlation).
7853  */
7854  if (*indexCorrelation < 1.0e-10)
7855  estimatedRanges = indexRanges;
7856  else
7857  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7858 
7859  /* we expect to visit this portion of the table */
7860  selec = estimatedRanges / indexRanges;
7861 
7862  CLAMP_PROBABILITY(selec);
7863 
7864  *indexSelectivity = selec;
7865 
7866  /*
7867  * Compute the index qual costs, much as in genericcostestimate, to add to
7868  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7869  * support those.
7870  */
7871  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7872 
7873  /*
7874  * Compute the startup cost as the cost to read the whole revmap
7875  * sequentially, including the cost to execute the index quals.
7876  */
7877  *indexStartupCost =
7878  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7879  *indexStartupCost += qual_arg_cost;
7880 
7881  /*
7882  * To read a BRIN index there might be a bit of back and forth over
7883  * regular pages, as revmap might point to them out of sequential order;
7884  * calculate the total cost as reading the whole index in random order.
7885  */
7886  *indexTotalCost = *indexStartupCost +
7887  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7888 
7889  /*
7890  * Charge a small amount per range tuple which we expect to match to. This
7891  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7892  * will set a bit for each page in the range when we find a matching
7893  * range, so we must multiply the charge by the number of pages in the
7894  * range.
7895  */
7896  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7897  statsData.pagesPerRange;
7898 
7899  *indexPages = index->pages;
7900 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
HeapTuple statsTuple
Definition: selfuncs.h:91
int nnumbers
Definition: lsyscache.h:57
#define Min(x, y)
Definition: c.h:986
#define Int16GetDatum(X)
Definition: postgres.h:495
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:93
Oid reltablespace
Definition: pathnodes.h:831
bool hypothetical
Definition: pathnodes.h:869
List * indexclauses
Definition: pathnodes.h:1238
#define Abs(x)
Definition: c.h:992
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:835
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
RelOptInfo * rel
Definition: pathnodes.h:832
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
AttrNumber indexcol
Definition: pathnodes.h:1286
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NoLock
Definition: lockdefs.h:34
float4 * numbers
Definition: lsyscache.h:56
double cpu_operator_cost
Definition: costsize.c:123
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:6267
#define BRIN_DEFAULT_PAGES_PER_RANGE
Definition: brin.h:38
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:704
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define REVMAP_PAGE_MAXITEMS
Definition: brin_page.h:93
#define BoolGetDatum(X)
Definition: postgres.h:446
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
int16 attnum
Definition: pg_attribute.h:83
#define Max(x, y)
Definition: c.h:980
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6297
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:715
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3177
#define Assert(condition)
Definition: c.h:804
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:145
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RTEKind rtekind
Definition: parsenodes.h:995
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
e
Definition: preproc-init.c:82
#define elog(elevel,...)
Definition: elog.h:232
int * indexkeys
Definition: pathnodes.h:842
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
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:673
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1227
BlockNumber revmapNumPages
Definition: brin.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3294

◆ 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 6590 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().

6594 {
6595  IndexOptInfo *index = path->indexinfo;
6596  GenericCosts costs;
6597  Oid relid;
6598  AttrNumber colnum;
6599  VariableStatData vardata;
6600  double numIndexTuples;
6601  Cost descentCost;
6602  List *indexBoundQuals;
6603  int indexcol;
6604  bool eqQualHere;
6605  bool found_saop;
6606  bool found_is_null_op;
6607  double num_sa_scans;
6608  ListCell *lc;
6609 
6610  /*
6611  * For a btree scan, only leading '=' quals plus inequality quals for the
6612  * immediately next attribute contribute to index selectivity (these are
6613  * the "boundary quals" that determine the starting and stopping points of
6614  * the index scan). Additional quals can suppress visits to the heap, so
6615  * it's OK to count them in indexSelectivity, but they should not count
6616  * for estimating numIndexTuples. So we must examine the given indexquals
6617  * to find out which ones count as boundary quals. We rely on the
6618  * knowledge that they are given in index column order.
6619  *
6620  * For a RowCompareExpr, we consider only the first column, just as
6621  * rowcomparesel() does.
6622  *
6623  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6624  * index scans not one, but the ScalarArrayOpExpr's operator can be
6625  * considered to act the same as it normally does.
6626  */
6627  indexBoundQuals = NIL;
6628  indexcol = 0;
6629  eqQualHere = false;
6630  found_saop = false;
6631  found_is_null_op = false;
6632  num_sa_scans = 1;
6633  foreach(lc, path->indexclauses)
6634  {
6635  IndexClause *iclause = lfirst_node(IndexClause, lc);
6636  ListCell *lc2;
6637 
6638  if (indexcol != iclause->indexcol)
6639  {
6640  /* Beginning of a new column's quals */
6641  if (!eqQualHere)
6642  break; /* done if no '=' qual for indexcol */
6643  eqQualHere = false;
6644  indexcol++;
6645  if (indexcol != iclause->indexcol)
6646  break; /* no quals at all for indexcol */
6647  }
6648 
6649  /* Examine each indexqual associated with this index clause */
6650  foreach(lc2, iclause->indexquals)
6651  {
6652  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6653  Expr *clause = rinfo->clause;
6654  Oid clause_op = InvalidOid;
6655  int op_strategy;
6656 
6657  if (IsA(clause, OpExpr))
6658  {
6659  OpExpr *op = (OpExpr *) clause;
6660 
6661  clause_op = op->opno;
6662  }
6663  else if (IsA(clause, RowCompareExpr))
6664  {
6665  RowCompareExpr *rc = (RowCompareExpr *) clause;
6666 
6667  clause_op = linitial_oid(rc->opnos);
6668  }
6669  else if (IsA(clause, ScalarArrayOpExpr))
6670  {
6671  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6672  Node *other_operand = (Node *) lsecond(saop->args);
6673  int alength = estimate_array_length(other_operand);
6674 
6675  clause_op = saop->opno;
6676  found_saop = true;
6677  /* count number of SA scans induced by indexBoundQuals only */
6678  if (alength > 1)
6679  num_sa_scans *= alength;
6680  }
6681  else if (IsA(clause, NullTest))
6682  {
6683  NullTest *nt = (NullTest *) clause;
6684 
6685  if (nt->nulltesttype == IS_NULL)
6686  {
6687  found_is_null_op = true;
6688  /* IS NULL is like = for selectivity purposes */
6689  eqQualHere = true;
6690  }
6691  }
6692  else
6693  elog(ERROR, "unsupported indexqual type: %d",
6694  (int) nodeTag(clause));
6695 
6696  /* check for equality operator */
6697  if (OidIsValid(clause_op))
6698  {
6699  op_strategy = get_op_opfamily_strategy(clause_op,
6700  index->opfamily[indexcol]);
6701  Assert(op_strategy != 0); /* not a member of opfamily?? */
6702  if (op_strategy == BTEqualStrategyNumber)
6703  eqQualHere = true;
6704  }
6705 
6706  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6707  }
6708  }
6709 
6710  /*
6711  * If index is unique and we found an '=' clause for each column, we can
6712  * just assume numIndexTuples = 1 and skip the expensive
6713  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6714  * NullTest invalidates that theory, even though it sets eqQualHere.
6715  */
6716  if (index->unique &&
6717  indexcol == index->nkeycolumns - 1 &&
6718  eqQualHere &&
6719  !found_saop &&
6720  !found_is_null_op)
6721  numIndexTuples = 1.0;
6722  else
6723  {
6724  List *selectivityQuals;
6725  Selectivity btreeSelectivity;
6726 
6727  /*
6728  * If the index is partial, AND the index predicate with the
6729  * index-bound quals to produce a more accurate idea of the number of
6730  * rows covered by the bound conditions.
6731  */
6732  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6733 
6734  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6735  index->rel->relid,
6736  JOIN_INNER,
6737  NULL);
6738  numIndexTuples = btreeSelectivity * index->rel->tuples;
6739 
6740  /*
6741  * As in genericcostestimate(), we have to adjust for any
6742  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6743  * to integer.
6744  */
6745  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6746  }
6747 
6748  /*
6749  * Now do generic index cost estimation.
6750  */
6751  MemSet(&costs, 0, sizeof(costs));
6752  costs.numIndexTuples = numIndexTuples;
6753 
6754  genericcostestimate(root, path, loop_count, &costs);
6755 
6756  /*
6757  * Add a CPU-cost component to represent the costs of initial btree
6758  * descent. We don't charge any I/O cost for touching upper btree levels,
6759  * since they tend to stay in cache, but we still have to do about log2(N)
6760  * comparisons to descend a btree of N leaf tuples. We charge one
6761  * cpu_operator_cost per comparison.
6762  *
6763  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6764  * ones after the first one are not startup cost so far as the overall
6765  * plan is concerned, so add them only to "total" cost.
6766  */
6767  if (index->tuples > 1) /* avoid computing log(0) */
6768  {
6769  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6770  costs.indexStartupCost += descentCost;
6771  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6772  }
6773 
6774  /*
6775  * Even though we're not charging I/O cost for touching upper btree pages,
6776  * it's still reasonable to charge some CPU cost per page descended
6777  * through. Moreover, if we had no such charge at all, bloated indexes
6778  * would appear to have the same search cost as unbloated ones, at least
6779  * in cases where only a single leaf page is expected to be visited. This
6780  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6781  * touched. The number of such pages is btree tree height plus one (ie,
6782  * we charge for the leaf page too). As above, charge once per SA scan.
6783  */
6784  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6785  costs.indexStartupCost += descentCost;
6786  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6787 
6788  /*
6789  * If we can get an estimate of the first column's ordering correlation C
6790  * from pg_statistic, estimate the index correlation as C for a
6791  * single-column index, or C * 0.75 for multiple columns. (The idea here
6792  * is that multiple columns dilute the importance of the first column's
6793  * ordering, but don't negate it entirely. Before 8.0 we divided the
6794  * correlation by the number of columns, but that seems too strong.)
6795  */
6796  MemSet(&vardata, 0, sizeof(vardata));
6797 
6798  if (index->indexkeys[0] != 0)
6799  {
6800  /* Simple variable --- look to stats for the underlying table */
6801  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6802 
6803  Assert(rte->rtekind == RTE_RELATION);
6804  relid = rte->relid;
6805  Assert(relid != InvalidOid);
6806  colnum = index->indexkeys[0];
6807 
6809  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6810  {
6811  /*
6812  * The hook took control of acquiring a stats tuple. If it did
6813  * supply a tuple, it'd better have supplied a freefunc.
6814  */
6815  if (HeapTupleIsValid(vardata.statsTuple) &&
6816  !vardata.freefunc)
6817  elog(ERROR, "no function provided to release variable stats with");
6818  }
6819  else
6820  {
6822  ObjectIdGetDatum(relid),
6823  Int16GetDatum(colnum),
6824  BoolGetDatum(rte->inh));
6825  vardata.freefunc = ReleaseSysCache;
6826  }
6827  }
6828  else
6829  {
6830  /* Expression --- maybe there are stats for the index itself */
6831  relid = index->indexoid;
6832  colnum = 1;
6833 
6834  if (get_index_stats_hook &&
6835  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6836  {
6837  /*
6838  * The hook took control of acquiring a stats tuple. If it did
6839  * supply a tuple, it'd better have supplied a freefunc.
6840  */
6841  if (HeapTupleIsValid(vardata.statsTuple) &&
6842  !vardata.freefunc)
6843  elog(ERROR, "no function provided to release variable stats with");
6844  }
6845  else
6846  {
6848  ObjectIdGetDatum(relid),
6849  Int16GetDatum(colnum),
6850  BoolGetDatum(false));
6851  vardata.freefunc = ReleaseSysCache;
6852  }
6853  }
6854 
6855  if (HeapTupleIsValid(vardata.statsTuple))
6856  {
6857  Oid sortop;
6858  AttStatsSlot sslot;
6859 
6860  sortop = get_opfamily_member(index->opfamily[0],
6861  index->opcintype[0],
6862  index->opcintype[0],
6864  if (OidIsValid(sortop) &&
6865  get_attstatsslot(&sslot, vardata.statsTuple,
6866  STATISTIC_KIND_CORRELATION, sortop,
6868  {
6869  double varCorrelation;
6870 
6871  Assert(sslot.nnumbers == 1);
6872  varCorrelation = sslot.numbers[0];
6873 
6874  if (index->reverse_sort[0])
6875  varCorrelation = -varCorrelation;
6876 
6877  if (index->nkeycolumns > 1)
6878  costs.indexCorrelation = varCorrelation * 0.75;
6879  else
6880  costs.indexCorrelation = varCorrelation;
6881 
6882  free_attstatsslot(&sslot);
6883  }
6884  }
6885 
6886  ReleaseVariableStats(vardata);
6887 
6888  *indexStartupCost = costs.indexStartupCost;
6889  *indexTotalCost = costs.indexTotalCost;
6890  *indexSelectivity = costs.indexSelectivity;
6891  *indexCorrelation = costs.indexCorrelation;
6892  *indexPages = costs.numIndexPages;
6893 }
Selectivity indexSelectivity
Definition: selfuncs.h:126
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
HeapTuple statsTuple
Definition: selfuncs.h:91
int nnumbers
Definition: lsyscache.h:57
double tuples
Definition: pathnodes.h:716
#define Int16GetDatum(X)
Definition: postgres.h:495
Definition: nodes.h:539
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:93
#define MemSet(start, val, len)
Definition: c.h:1008
List * indexclauses
Definition: pathnodes.h:1238
double Selectivity
Definition: nodes.h:672
double tuples
Definition: pathnodes.h:836
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: pathnodes.h:837
#define OidIsValid(objectId)
Definition: c.h:710
#define lsecond(l)
Definition: pg_list.h:179
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
RelOptInfo * rel
Definition: pathnodes.h:832
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
AttrNumber indexcol
Definition: pathnodes.h:1286
double num_sa_scans
Definition: selfuncs.h:133
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:6351
float4 * numbers
Definition: lsyscache.h:56
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
double cpu_operator_cost
Definition: costsize.c:123
Cost indexTotalCost
Definition: selfuncs.h:125
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
List * indexquals
Definition: pathnodes.h:1284
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
double indexCorrelation
Definition: selfuncs.h:127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
NullTestType nulltesttype
Definition: primnodes.h:1256
#define BoolGetDatum(X)
Definition: postgres.h:446
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:131
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3177
#define Assert(condition)
Definition: c.h:804
#define linitial_oid(l)
Definition: pg_list.h:176
int nkeycolumns
Definition: pathnodes.h:841
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:145
Oid * opcintype
Definition: pathnodes.h:846
#define nodeTag(nodeptr)
Definition: nodes.h:544
Cost indexStartupCost
Definition: selfuncs.h:124
Oid * opfamily
Definition: pathnodes.h:845
RTEKind rtekind
Definition: parsenodes.h:995
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:81
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
#define elog(elevel,...)
Definition: elog.h:232
int * indexkeys
Definition: pathnodes.h:842
Oid opno
Definition: primnodes.h:542
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
bool * reverse_sort
Definition: pathnodes.h:848
#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:673
double numIndexPages
Definition: selfuncs.h:130
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3294
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6569

◆ 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 7354 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().

7358 {
7359  IndexOptInfo *index = path->indexinfo;
7360  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7361  List *selectivityQuals;
7362  double numPages = index->pages,
7363  numTuples = index->tuples;
7364  double numEntryPages,
7365  numDataPages,
7366  numPendingPages,
7367  numEntries;
7368  GinQualCounts counts;
7369  bool matchPossible;
7370  bool fullIndexScan;
7371  double partialScale;
7372  double entryPagesFetched,
7373  dataPagesFetched,
7374  dataPagesFetchedBySel;
7375  double qual_op_cost,
7376  qual_arg_cost,
7377  spc_random_page_cost,
7378  outer_scans;
7379  Relation indexRel;
7380  GinStatsData ginStats;
7381  ListCell *lc;
7382  int i;
7383 
7384  /*
7385  * Obtain statistical information from the meta page, if possible. Else
7386  * set ginStats to zeroes, and we'll cope below.
7387  */
7388  if (!index->hypothetical)
7389  {
7390  /* Lock should have already been obtained in plancat.c */
7391  indexRel = index_open(index->indexoid, NoLock);
7392  ginGetStats(indexRel, &ginStats);
7393  index_close(indexRel, NoLock);
7394  }
7395  else
7396  {
7397  memset(&ginStats, 0, sizeof(ginStats));
7398  }
7399 
7400  /*
7401  * Assuming we got valid (nonzero) stats at all, nPendingPages can be
7402  * trusted, but the other fields are data as of the last VACUUM. We can
7403  * scale them up to account for growth since then, but that method only
7404  * goes so far; in the worst case, the stats might be for a completely
7405  * empty index, and scaling them will produce pretty bogus numbers.
7406  * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
7407  * it's grown more than that, fall back to estimating things only from the
7408  * assumed-accurate index size. But we'll trust nPendingPages in any case
7409  * so long as it's not clearly insane, ie, more than the index size.
7410  */
7411  if (ginStats.nPendingPages < numPages)
7412  numPendingPages = ginStats.nPendingPages;
7413  else
7414  numPendingPages = 0;
7415 
7416  if (numPages > 0 && ginStats.nTotalPages <= numPages &&
7417  ginStats.nTotalPages > numPages / 4 &&
7418  ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
7419  {
7420  /*
7421  * OK, the stats seem close enough to sane to be trusted. But we
7422  * still need to scale them by the ratio numPages / nTotalPages to
7423  * account for growth since the last VACUUM.
7424  */
7425  double scale = numPages / ginStats.nTotalPages;
7426 
7427  numEntryPages = ceil(ginStats.nEntryPages * scale);
7428  numDataPages = ceil(ginStats.nDataPages * scale);
7429  numEntries = ceil(ginStats.nEntries * scale);
7430  /* ensure we didn't round up too much */
7431  numEntryPages = Min(numEntryPages, numPages - numPendingPages);
7432  numDataPages = Min(numDataPages,
7433  numPages - numPendingPages - numEntryPages);
7434  }
7435  else
7436  {
7437  /*
7438  * We might get here because it's a hypothetical index, or an index
7439  * created pre-9.1 and never vacuumed since upgrading (in which case
7440  * its stats would read as zeroes), or just because it's grown too
7441  * much since the last VACUUM for us to put our faith in scaling.
7442  *
7443  * Invent some plausible internal statistics based on the index page
7444  * count (and clamp that to at least 10 pages, just in case). We
7445  * estimate that 90% of the index is entry pages, and the rest is data
7446  * pages. Estimate 100 entries per entry page; this is rather bogus
7447  * since it'll depend on the size of the keys, but it's more robust
7448  * than trying to predict the number of entries per heap tuple.
7449  */
7450  numPages = Max(numPages, 10);
7451  numEntryPages = floor((numPages - numPendingPages) * 0.90);
7452  numDataPages = numPages - numPendingPages - numEntryPages;
7453  numEntries = floor(numEntryPages * 100);
7454  }
7455 
7456  /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
7457  if (numEntries < 1)
7458  numEntries = 1;
7459 
7460  /*
7461  * If the index is partial, AND the index predicate with the index-bound
7462  * quals to produce a more accurate idea of the number of rows covered by
7463  * the bound conditions.
7464  */
7465  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7466 
7467  /* Estimate the fraction of main-table tuples that will be visited */
7468  *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7469  index->rel->relid,
7470  JOIN_INNER,
7471  NULL);
7472 
7473  /* fetch estimated page cost for tablespace containing index */
7475  &spc_random_page_cost,
7476  NULL);
7477 
7478  /*
7479  * Generic assumption about index correlation: there isn't any.
7480  */
7481  *indexCorrelation = 0.0;
7482 
7483  /*
7484  * Examine quals to estimate number of search entries & partial matches
7485  */
7486  memset(&counts, 0, sizeof(counts));
7487  counts.arrayScans = 1;
7488  matchPossible = true;
7489 
7490  foreach(lc, path->indexclauses)
7491  {
7492  IndexClause *iclause = lfirst_node(IndexClause, lc);
7493  ListCell *lc2;
7494 
7495  foreach(lc2, iclause->indexquals)
7496  {
7497  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7498  Expr *clause = rinfo->clause;
7499 
7500  if (IsA(clause, OpExpr))
7501  {
7502  matchPossible = gincost_opexpr(root,
7503  index,
7504  iclause->indexcol,
7505  (OpExpr *) clause,
7506  &counts);
7507  if (!matchPossible)
7508  break;
7509  }
7510  else if (IsA(clause, ScalarArrayOpExpr))
7511  {
7512  matchPossible = gincost_scalararrayopexpr(root,
7513  index,
7514  iclause->indexcol,
7515  (ScalarArrayOpExpr *) clause,
7516  numEntries,
7517  &counts);
7518  if (!matchPossible)
7519  break;
7520  }
7521  else
7522  {
7523  /* shouldn't be anything else for a GIN index */
7524  elog(ERROR, "unsupported GIN indexqual type: %d",
7525  (int) nodeTag(clause));
7526  }
7527  }
7528  }
7529 
7530  /* Fall out if there were any provably-unsatisfiable quals */
7531  if (!matchPossible)
7532  {
7533  *indexStartupCost = 0;
7534  *indexTotalCost = 0;
7535  *indexSelectivity = 0;
7536  return;
7537  }
7538 
7539  /*
7540  * If attribute has a full scan and at the same time doesn't have normal
7541  * scan, then we'll have to scan all non-null entries of that attribute.
7542  * Currently, we don't have per-attribute statistics for GIN. Thus, we
7543  * must assume the whole GIN index has to be scanned in this case.
7544  */
7545  fullIndexScan = false;
7546  for (i = 0; i < index->nkeycolumns; i++)
7547  {
7548  if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
7549  {
7550  fullIndexScan = true;
7551  break;
7552  }
7553  }
7554 
7555  if (fullIndexScan || indexQuals == NIL)
7556  {
7557  /*
7558  * Full index scan will be required. We treat this as if every key in
7559  * the index had been listed in the query; is that reasonable?
7560  */
7561  counts.partialEntries = 0;
7562  counts.exactEntries = numEntries;
7563  counts.searchEntries = numEntries;
7564  }
7565 
7566  /* Will we have more than one iteration of a nestloop scan? */
7567  outer_scans = loop_count;
7568 
7569  /*
7570  * Compute cost to begin scan, first of all, pay attention to pending
7571  * list.
7572  */
7573  entryPagesFetched = numPendingPages;
7574 
7575  /*
7576  * Estimate number of entry pages read. We need to do
7577  * counts.searchEntries searches. Use a power function as it should be,
7578  * but tuples on leaf pages usually is much greater. Here we include all
7579  * searches in entry tree, including search of first entry in partial
7580  * match algorithm
7581  */
7582  entryPagesFetched += ceil(counts.searchEntries * rint(pow(numEntryPages, 0.15)));
7583 
7584  /*
7585  * Add an estimate of entry pages read by partial match algorithm. It's a
7586  * scan over leaf pages in entry tree. We haven't any useful stats here,
7587  * so estimate it as proportion. Because counts.partialEntries is really
7588  * pretty bogus (see code above), it's possible that it is more than
7589  * numEntries; clamp the proportion to ensure sanity.
7590  */
7591  partialScale = counts.partialEntries / numEntries;
7592  partialScale = Min(partialScale, 1.0);
7593 
7594  entryPagesFetched += ceil(numEntryPages * partialScale);
7595 
7596  /*
7597  * Partial match algorithm reads all data pages before doing actual scan,
7598  * so it's a startup cost. Again, we haven't any useful stats here, so
7599  * estimate it as proportion.
7600  */
7601  dataPagesFetched = ceil(numDataPages * partialScale);
7602 
7603  /*
7604  * Calculate cache effects if more than one scan due to nestloops or array
7605  * quals. The result is pro-rated per nestloop scan, but the array qual
7606  * factor shouldn't be pro-rated (compare genericcostestimate).
7607  */
7608  if (outer_scans > 1 || counts.arrayScans > 1)
7609  {
7610  entryPagesFetched *= outer_scans * counts.arrayScans;
7611  entryPagesFetched = index_pages_fetched(entryPagesFetched,
7612  (BlockNumber) numEntryPages,
7613  numEntryPages, root);
7614  entryPagesFetched /= outer_scans;
7615  dataPagesFetched *= outer_scans * counts.arrayScans;
7616  dataPagesFetched = index_pages_fetched(dataPagesFetched,
7617  (BlockNumber) numDataPages,
7618  numDataPages, root);
7619  dataPagesFetched /= outer_scans;
7620  }
7621 
7622  /*
7623  * Here we use random page cost because logically-close pages could be far
7624  * apart on disk.
7625  */
7626  *indexStartupCost = (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
7627 
7628  /*
7629  * Now compute the number of data pages fetched during the scan.
7630  *
7631  * We assume every entry to have the same number of items, and that there
7632  * is no overlap between them. (XXX: tsvector and array opclasses collect
7633  * statistics on the frequency of individual keys; it would be nice to use
7634  * those here.)
7635  */
7636  dataPagesFetched = ceil(numDataPages * counts.exactEntries / numEntries);
7637 
7638  /*
7639  * If there is a lot of overlap among the entries, in particular if one of
7640  * the entries is very frequent, the above calculation can grossly
7641  * under-estimate. As a simple cross-check, calculate a lower bound based
7642  * on the overall selectivity of the quals. At a minimum, we must read
7643  * one item pointer for each matching entry.
7644  *
7645  * The width of each item pointer varies, based on the level of
7646  * compression. We don't have statistics on that, but an average of
7647  * around 3 bytes per item is fairly typical.
7648  */
7649  dataPagesFetchedBySel = ceil(*indexSelectivity *
7650  (numTuples / (BLCKSZ / 3)));
7651  if (dataPagesFetchedBySel > dataPagesFetched)
7652  dataPagesFetched = dataPagesFetchedBySel;
7653 
7654  /* Account for cache effects, the same as above */
7655  if (outer_scans > 1 || counts.arrayScans > 1)
7656  {
7657  dataPagesFetched *= outer_scans * counts.arrayScans;
7658  dataPagesFetched = index_pages_fetched(dataPagesFetched,
7659  (BlockNumber) numDataPages,
7660  numDataPages, root);
7661  dataPagesFetched /= outer_scans;
7662  }
7663 
7664  /* And apply random_page_cost as the cost per page */
7665  *indexTotalCost = *indexStartupCost +
7666  dataPagesFetched * spc_random_page_cost;
7667 
7668  /*
7669  * Add on index qual eval costs, much as in genericcostestimate. But we
7670  * can disregard indexorderbys, since GIN doesn't support those.
7671  */
7672  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7673  qual_op_cost = cpu_operator_cost * list_length(indexQuals);
7674 
7675  *indexStartupCost += qual_arg_cost;
7676  *indexTotalCost += qual_arg_cost;
7677  *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost + qual_op_cost);
7678  *indexPages = dataPagesFetched;
7679 }
#define NIL
Definition: pg_list.h:65
BlockNumber nEntryPages
Definition: gin.h:46
bool attHasNormalScan[INDEX_MAX_KEYS]
Definition: selfuncs.c:7061
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
bool attHasFullScan[INDEX_MAX_KEYS]
Definition: selfuncs.c:7060
#define Min(x, y)
Definition: c.h:986
double partialEntries
Definition: selfuncs.c:7062
double searchEntries
Definition: selfuncs.c:7064
Oid reltablespace
Definition: pathnodes.h:831
int scale
Definition: pgbench.c:189
int64 nEntries
Definition: gin.h:48
uint32 BlockNumber
Definition: block.h:31
bool hypothetical
Definition: pathnodes.h:869
List * indexclauses
Definition: pathnodes.h:1238
double tuples
Definition: pathnodes.h:836
Definition: type.h:89
double exactEntries
Definition: selfuncs.c:7063
BlockNumber pages
Definition: pathnodes.h:835
RelOptInfo * rel
Definition: pathnodes.h:832
#define ERROR
Definition: elog.h:46
AttrNumber indexcol
Definition: pathnodes.h:1286
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NoLock
Definition: lockdefs.h:34
double cpu_operator_cost
Definition: costsize.c:123
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:6267
List * indexquals
Definition: pathnodes.h:1284
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:704
Expr * clause
Definition: pathnodes.h:2045
BlockNumber nPendingPages
Definition: gin.h:44
double arrayScans
Definition: selfuncs.c:7065
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:7188
static bool gincost_scalararrayopexpr(PlannerInfo *root, IndexOptInfo *index, int indexcol, ScalarArrayOpExpr *clause, double numIndexEntries, GinQualCounts *counts)
Definition: selfuncs.c:7238
BlockNumber nDataPages
Definition: gin.h:47
#define Max(x, y)
Definition: c.h:980
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6297
static int list_length(const List *l)
Definition: pg_list.h:149
BlockNumber nTotalPages
Definition: gin.h:45
int nkeycolumns
Definition: pathnodes.h:841
#define nodeTag(nodeptr)
Definition: nodes.h:544
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define elog(elevel,...)
Definition: elog.h:232
int i
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
Definition: pg_list.h:50
double cpu_index_tuple_cost
Definition: costsize.c:122
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:840
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6569

◆ 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 6940 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().

6944 {
6945  IndexOptInfo *index = path->indexinfo;
6946  GenericCosts costs;
6947  Cost descentCost;
6948 
6949  MemSet(&costs, 0, sizeof(costs));
6950 
6951  genericcostestimate(root, path, loop_count, &costs);
6952 
6953  /*
6954  * We model index descent costs similarly to those for btree, but to do
6955  * that we first need an idea of the tree height. We somewhat arbitrarily
6956  * assume that the fanout is 100, meaning the tree height is at most
6957  * log100(index->pages).
6958  *
6959  * Although this computation isn't really expensive enough to require
6960  * caching, we might as well use index->tree_height to cache it.
6961  */
6962  if (index->tree_height < 0) /* unknown? */
6963  {
6964  if (index->pages > 1) /* avoid computing log(0) */
6965  index->tree_height = (int) (log(index->pages) / log(100.0));
6966  else
6967  index->tree_height = 0;
6968  }
6969 
6970  /*
6971  * Add a CPU-cost component to represent the costs of initial descent. We
6972  * just use log(N) here not log2(N) since the branching factor isn't
6973  * necessarily two anyway. As for btree, charge once per SA scan.
6974  */
6975  if (index->tuples > 1) /* avoid computing log(0) */
6976  {
6977  descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
6978  costs.indexStartupCost += descentCost;
6979  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6980  }
6981 
6982  /*
6983  * Likewise add a per-page charge, calculated the same as for btrees.
6984  */
6985  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6986  costs.indexStartupCost += descentCost;
6987  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6988 
6989  *indexStartupCost = costs.indexStartupCost;
6990  *indexTotalCost = costs.indexTotalCost;
6991  *indexSelectivity = costs.indexSelectivity;
6992  *indexCorrelation = costs.indexCorrelation;
6993  *indexPages = costs.numIndexPages;
6994 }
Selectivity indexSelectivity
Definition: selfuncs.h:126
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
#define MemSet(start, val, len)
Definition: c.h:1008
double tuples
Definition: pathnodes.h:836
int tree_height
Definition: pathnodes.h:837
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:835
double num_sa_scans
Definition: selfuncs.h:133
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:6351
double cpu_operator_cost
Definition: costsize.c:123
Cost indexTotalCost
Definition: selfuncs.h:125
double indexCorrelation
Definition: selfuncs.h:127
Cost indexStartupCost
Definition: selfuncs.h:124
double Cost
Definition: nodes.h:673
double numIndexPages
Definition: selfuncs.h:130

◆ 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 6896 of file selfuncs.c.

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

Referenced by hashhandler().

6900 {
6901  GenericCosts costs;
6902 
6903  MemSet(&costs, 0, sizeof(costs));
6904 
6905  genericcostestimate(root, path, loop_count, &costs);
6906 
6907  /*
6908  * A hash index has no descent costs as such, since the index AM can go
6909  * directly to the target bucket after computing the hash value. There
6910  * are a couple of other hash-specific costs that we could conceivably add
6911  * here, though:
6912  *
6913  * Ideally we'd charge spc_random_page_cost for each page in the target
6914  * bucket, not just the numIndexPages pages that genericcostestimate
6915  * thought we'd visit. However in most cases we don't know which bucket
6916  * that will be. There's no point in considering the average bucket size
6917  * because the hash AM makes sure that's always one page.
6918  *
6919  * Likewise, we could consider charging some CPU for each index tuple in
6920  * the bucket, if we knew how many there were. But the per-tuple cost is
6921  * just a hash value comparison, not a general datatype-dependent
6922  * comparison, so any such charge ought to be quite a bit less than
6923  * cpu_operator_cost; which makes it probably not worth worrying about.
6924  *
6925  * A bigger issue is that chance hash-value collisions will result in
6926  * wasted probes into the heap. We don't currently attempt to model this
6927  * cost on the grounds that it's rare, but maybe it's not rare enough.
6928  * (Any fix for this ought to consider the generic lossy-operator problem,
6929  * though; it's not entirely hash-specific.)
6930  */
6931 
6932  *indexStartupCost = costs.indexStartupCost;
6933  *indexTotalCost = costs.indexTotalCost;
6934  *indexSelectivity = costs.indexSelectivity;
6935  *indexCorrelation = costs.indexCorrelation;
6936  *indexPages = costs.numIndexPages;
6937 }
Selectivity indexSelectivity
Definition: selfuncs.h:126
#define MemSet(start, val, len)
Definition: c.h:1008
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:6351
Cost indexTotalCost
Definition: selfuncs.h:125
double indexCorrelation
Definition: selfuncs.h:127
Cost indexStartupCost
Definition: selfuncs.h:124
double numIndexPages
Definition: selfuncs.h:130

◆ 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 6997 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().

7001 {
7002  IndexOptInfo *index = path->indexinfo;
7003  GenericCosts costs;
7004  Cost descentCost;
7005 
7006  MemSet(&costs, 0, sizeof(costs));
7007 
7008  genericcostestimate(root, path, loop_count, &costs);
7009 
7010  /*
7011  * We model index descent costs similarly to those for btree, but to do
7012  * that we first need an idea of the tree height. We somewhat arbitrarily
7013  * assume that the fanout is 100, meaning the tree height is at most
7014  * log100(index->pages).
7015  *
7016  * Although this computation isn't really expensive enough to require
7017  * caching, we might as well use index->tree_height to cache it.
7018  */
7019  if (index->tree_height < 0) /* unknown? */
7020  {
7021  if (index->pages > 1) /* avoid computing log(0) */
7022  index->tree_height = (int) (log(index->pages) / log(100.0));
7023  else
7024  index->tree_height = 0;
7025  }
7026 
7027  /*
7028  * Add a CPU-cost component to represent the costs of initial descent. We
7029  * just use log(N) here not log2(N) since the branching factor isn't
7030  * necessarily two anyway. As for btree, charge once per SA scan.
7031  */
7032  if (index->tuples > 1) /* avoid computing log(0) */
7033  {
7034  descentCost = ceil(log(index->tuples)) * cpu_operator_cost;
7035  costs.indexStartupCost += descentCost;
7036  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7037  }
7038 
7039  /*
7040  * Likewise add a per-page charge, calculated the same as for btrees.
7041  */
7042  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
7043  costs.indexStartupCost += descentCost;
7044  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7045 
7046  *indexStartupCost = costs.indexStartupCost;
7047  *indexTotalCost = costs.indexTotalCost;
7048  *indexSelectivity = costs.indexSelectivity;
7049  *indexCorrelation = costs.indexCorrelation;
7050  *indexPages = costs.numIndexPages;
7051 }
Selectivity indexSelectivity
Definition: selfuncs.h:126
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
#define MemSet(start, val, len)
Definition: c.h:1008
double tuples
Definition: pathnodes.h:836
int tree_height
Definition: pathnodes.h:837
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:835
double num_sa_scans
Definition: selfuncs.h:133
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:6351
double cpu_operator_cost
Definition: costsize.c:123
Cost indexTotalCost
Definition: selfuncs.h:125
double indexCorrelation
Definition: selfuncs.h:127
Cost indexStartupCost
Definition: selfuncs.h:124
double Cost
Definition: nodes.h:673
double numIndexPages
Definition: selfuncs.h:130