PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 
)
extern

Definition at line 9027 of file selfuncs.c.

9031{
9032 IndexOptInfo *index = path->indexinfo;
9034 double numPages = index->pages;
9035 RelOptInfo *baserel = index->rel;
9038 Cost spc_random_page_cost;
9039 double qual_arg_cost;
9040 double qualSelectivity;
9042 double indexRanges;
9043 double minimalRanges;
9044 double estimatedRanges;
9045 double selec;
9046 Relation indexRel;
9047 ListCell *l;
9049
9050 Assert(rte->rtekind == RTE_RELATION);
9051
9052 /* fetch estimated page cost for the tablespace containing the index */
9053 get_tablespace_page_costs(index->reltablespace,
9054 &spc_random_page_cost,
9056
9057 /*
9058 * Obtain some data from the index itself, if possible. Otherwise invent
9059 * some plausible internal statistics based on the relation page count.
9060 */
9061 if (!index->hypothetical)
9062 {
9063 /*
9064 * A lock should have already been obtained on the index in plancat.c.
9065 */
9066 indexRel = index_open(index->indexoid, NoLock);
9067 brinGetStats(indexRel, &statsData);
9068 index_close(indexRel, NoLock);
9069
9070 /* work out the actual number of ranges in the index */
9071 indexRanges = Max(ceil((double) baserel->pages /
9072 statsData.pagesPerRange), 1.0);
9073 }
9074 else
9075 {
9076 /*
9077 * Assume default number of pages per range, and estimate the number
9078 * of ranges based on that.
9079 */
9080 indexRanges = Max(ceil((double) baserel->pages /
9082
9084 statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
9085 }
9086
9087 /*
9088 * Compute index correlation
9089 *
9090 * Because we can use all index quals equally when scanning, we can use
9091 * the largest correlation (in absolute value) among columns used by the
9092 * query. Start at zero, the worst possible case. If we cannot find any
9093 * correlation statistics, we will keep it as 0.
9094 */
9095 *indexCorrelation = 0;
9096
9097 foreach(l, path->indexclauses)
9098 {
9100 AttrNumber attnum = index->indexkeys[iclause->indexcol];
9101
9102 /* attempt to lookup stats in relation for this index column */
9103 if (attnum != 0)
9104 {
9105 /* Simple variable -- look to stats for the underlying table */
9108 {
9109 /*
9110 * The hook took control of acquiring a stats tuple. If it
9111 * did supply a tuple, it'd better have supplied a freefunc.
9112 */
9113 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
9114 elog(ERROR,
9115 "no function provided to release variable stats with");
9116 }
9117 else
9118 {
9119 vardata.statsTuple =
9121 ObjectIdGetDatum(rte->relid),
9123 BoolGetDatum(false));
9124 vardata.freefunc = ReleaseSysCache;
9125 }
9126 }
9127 else
9128 {
9129 /*
9130 * Looks like we've found an expression column in the index. Let's
9131 * see if there's any stats for it.
9132 */
9133
9134 /* get the attnum from the 0-based index. */
9135 attnum = iclause->indexcol + 1;
9136
9138 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
9139 {
9140 /*
9141 * The hook took control of acquiring a stats tuple. If it
9142 * did supply a tuple, it'd better have supplied a freefunc.
9143 */
9144 if (HeapTupleIsValid(vardata.statsTuple) &&
9145 !vardata.freefunc)
9146 elog(ERROR, "no function provided to release variable stats with");
9147 }
9148 else
9149 {
9151 ObjectIdGetDatum(index->indexoid),
9153 BoolGetDatum(false));
9154 vardata.freefunc = ReleaseSysCache;
9155 }
9156 }
9157
9158 if (HeapTupleIsValid(vardata.statsTuple))
9159 {
9161
9162 if (get_attstatsslot(&sslot, vardata.statsTuple,
9165 {
9166 double varCorrelation = 0.0;
9167
9168 if (sslot.nnumbers > 0)
9169 varCorrelation = fabs(sslot.numbers[0]);
9170
9171 if (varCorrelation > *indexCorrelation)
9172 *indexCorrelation = varCorrelation;
9173
9175 }
9176 }
9177
9179 }
9180
9182 baserel->relid,
9183 JOIN_INNER, NULL);
9184
9185 /*
9186 * Now calculate the minimum possible ranges we could match with if all of
9187 * the rows were in the perfect order in the table's heap.
9188 */
9190
9191 /*
9192 * Now estimate the number of ranges that we'll touch by using the
9193 * indexCorrelation from the stats. Careful not to divide by zero (note
9194 * we're using the absolute value of the correlation).
9195 */
9196 if (*indexCorrelation < 1.0e-10)
9198 else
9199 estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
9200
9201 /* we expect to visit this portion of the table */
9203
9205
9206 *indexSelectivity = selec;
9207
9208 /*
9209 * Compute the index qual costs, much as in genericcostestimate, to add to
9210 * the index costs. We can disregard indexorderbys, since BRIN doesn't
9211 * support those.
9212 */
9214
9215 /*
9216 * Compute the startup cost as the cost to read the whole revmap
9217 * sequentially, including the cost to execute the index quals.
9218 */
9219 *indexStartupCost =
9220 spc_seq_page_cost * statsData.revmapNumPages * loop_count;
9221 *indexStartupCost += qual_arg_cost;
9222
9223 /*
9224 * To read a BRIN index there might be a bit of back and forth over
9225 * regular pages, as revmap might point to them out of sequential order;
9226 * calculate the total cost as reading the whole index in random order.
9227 */
9228 *indexTotalCost = *indexStartupCost +
9229 spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
9230
9231 /*
9232 * Charge a small amount per range tuple which we expect to match to. This
9233 * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
9234 * will set a bit for each page in the range when we find a matching
9235 * range, so we must multiply the charge by the number of pages in the
9236 * range.
9237 */
9238 *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
9239 statsData.pagesPerRange;
9240
9241 *indexPages = index->pages;
9242}
int16 AttrNumber
Definition attnum.h:21
void brinGetStats(Relation index, BrinStatsData *stats)
Definition brin.c:1653
#define BRIN_DEFAULT_PAGES_PER_RANGE
Definition brin.h:40
#define REVMAP_PAGE_MAXITEMS
Definition brin_page.h:93
#define Min(x, y)
Definition c.h:1091
#define Max(x, y)
Definition c.h:1085
#define Assert(condition)
Definition c.h:943
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition clausesel.c:100
double cpu_operator_cost
Definition costsize.c:135
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define HeapTupleIsValid(tuple)
Definition htup.h:78
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
#define NoLock
Definition lockdefs.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition lsyscache.c:3652
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition lsyscache.c:3542
#define ATTSTATSSLOT_NUMBERS
Definition lsyscache.h:44
double Cost
Definition nodes.h:261
@ JOIN_INNER
Definition nodes.h:303
@ RTE_RELATION
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:704
int16 attnum
#define lfirst_node(type, lc)
Definition pg_list.h:176
static Datum Int16GetDatum(int16 X)
Definition postgres.h:172
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
#define InvalidOid
static int fb(int x)
tree ctl root
Definition radixtree.h:1857
List * get_quals_from_indexclauses(List *indexclauses)
Definition selfuncs.c:7323
get_index_stats_hook_type get_index_stats_hook
Definition selfuncs.c:184
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition selfuncs.c:7353
get_relation_stats_hook_type get_relation_stats_hook
Definition selfuncs.c:183
#define ReleaseVariableStats(vardata)
Definition selfuncs.h:101
#define CLAMP_PROBABILITY(p)
Definition selfuncs.h:63
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition spccache.c:183
List * indexclauses
Definition pathnodes.h:2057
IndexOptInfo * indexinfo
Definition pathnodes.h:2056
Definition pg_list.h:54
Definition type.h:97
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache3(SysCacheIdentifier cacheId, Datum key1, Datum key2, Datum key3)
Definition syscache.c:241

References Assert, attnum, ATTSTATSSLOT_NUMBERS, BoolGetDatum(), BRIN_DEFAULT_PAGES_PER_RANGE, brinGetStats(), CLAMP_PROBABILITY, clauselist_selectivity(), cpu_operator_cost, elog, ERROR, fb(), free_attstatsslot(), get_attstatsslot(), get_index_stats_hook, get_quals_from_indexclauses(), get_relation_stats_hook, get_tablespace_page_costs(), HeapTupleIsValid, index_close(), index_open(), index_other_operands_eval_cost(), IndexPath::indexclauses, IndexPath::indexinfo, Int16GetDatum(), InvalidOid, JOIN_INNER, lfirst_node, Max, Min, NoLock, ObjectIdGetDatum(), planner_rt_fetch, ReleaseSysCache(), ReleaseVariableStats, REVMAP_PAGE_MAXITEMS, root, RTE_RELATION, and SearchSysCache3().

Referenced by brinhandler().

◆ btcostestimate()

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

Definition at line 7705 of file selfuncs.c.

7709{
7710 IndexOptInfo *index = path->indexinfo;
7711 GenericCosts costs = {0};
7713 double numIndexTuples;
7717 int indexcol;
7718 bool eqQualHere;
7719 bool found_row_compare;
7720 bool found_array;
7721 bool found_is_null_op;
7722 bool have_correlation = false;
7723 double num_sa_scans;
7724 double correlation = 0.0;
7725 ListCell *lc;
7726
7727 /*
7728 * For a btree scan, only leading '=' quals plus inequality quals for the
7729 * immediately next attribute contribute to index selectivity (these are
7730 * the "boundary quals" that determine the starting and stopping points of
7731 * the index scan). Additional quals can suppress visits to the heap, so
7732 * it's OK to count them in indexSelectivity, but they should not count
7733 * for estimating numIndexTuples. So we must examine the given indexquals
7734 * to find out which ones count as boundary quals. We rely on the
7735 * knowledge that they are given in index column order. Note that nbtree
7736 * preprocessing can add skip arrays that act as leading '=' quals in the
7737 * absence of ordinary input '=' quals, so in practice _most_ input quals
7738 * are able to act as index bound quals (which we take into account here).
7739 *
7740 * For a RowCompareExpr, we consider only the first column, just as
7741 * rowcomparesel() does.
7742 *
7743 * If there's a SAOP or skip array in the quals, we'll actually perform up
7744 * to N index descents (not just one), but the underlying array key's
7745 * operator can be considered to act the same as it normally does.
7746 */
7749 indexcol = 0;
7750 eqQualHere = false;
7751 found_row_compare = false;
7752 found_array = false;
7753 found_is_null_op = false;
7754 num_sa_scans = 1;
7755 foreach(lc, path->indexclauses)
7756 {
7758 ListCell *lc2;
7759
7760 if (indexcol < iclause->indexcol)
7761 {
7762 double num_sa_scans_prev_cols = num_sa_scans;
7763
7764 /*
7765 * Beginning of a new column's quals.
7766 *
7767 * Skip scans use skip arrays, which are ScalarArrayOp style
7768 * arrays that generate their elements procedurally and on demand.
7769 * Given a multi-column index on "(a, b)", and an SQL WHERE clause
7770 * "WHERE b = 42", a skip scan will effectively use an indexqual
7771 * "WHERE a = ANY('{every col a value}') AND b = 42". (Obviously,
7772 * the array on "a" must also return "IS NULL" matches, since our
7773 * WHERE clause used no strict operator on "a").
7774 *
7775 * Here we consider how nbtree will backfill skip arrays for any
7776 * index columns that lacked an '=' qual. This maintains our
7777 * num_sa_scans estimate, and determines if this new column (the
7778 * "iclause->indexcol" column, not the prior "indexcol" column)
7779 * can have its RestrictInfos/quals added to indexBoundQuals.
7780 *
7781 * We'll need to handle columns that have inequality quals, where
7782 * the skip array generates values from a range constrained by the
7783 * quals (not every possible value). We've been maintaining
7784 * indexSkipQuals to help with this; it will now contain all of
7785 * the prior column's quals (that is, indexcol's quals) when they
7786 * might be used for this.
7787 */
7789 {
7790 /*
7791 * Skip arrays can't be added after a RowCompare input qual
7792 * due to limitations in nbtree
7793 */
7794 break;
7795 }
7796 if (eqQualHere)
7797 {
7798 /*
7799 * Don't need to add a skip array for an indexcol that already
7800 * has an '=' qual/equality constraint
7801 */
7802 indexcol++;
7804 }
7805 eqQualHere = false;
7806
7807 while (indexcol < iclause->indexcol)
7808 {
7809 double ndistinct;
7810 bool isdefault = true;
7811
7812 found_array = true;
7813
7814 /*
7815 * A skipped attribute's ndistinct forms the basis of our
7816 * estimate of the total number of "array elements" used by
7817 * its skip array at runtime. Look that up first.
7818 */
7820 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
7821
7822 if (indexcol == 0)
7823 {
7824 /*
7825 * Get an estimate of the leading column's correlation in
7826 * passing (avoids rereading variable stats below)
7827 */
7828 if (HeapTupleIsValid(vardata.statsTuple))
7830 have_correlation = true;
7831 }
7832
7834
7835 /*
7836 * If ndistinct is a default estimate, conservatively assume
7837 * that no skipping will happen at runtime
7838 */
7839 if (isdefault)
7840 {
7841 num_sa_scans = num_sa_scans_prev_cols;
7842 break; /* done building indexBoundQuals */
7843 }
7844
7845 /*
7846 * Apply indexcol's indexSkipQuals selectivity to ndistinct
7847 */
7848 if (indexSkipQuals != NIL)
7849 {
7852
7853 /*
7854 * If the index is partial, AND the index predicate with
7855 * the index-bound quals to produce a more accurate idea
7856 * of the number of distinct values for prior indexcol
7857 */
7860
7862 index->rel->relid,
7863 JOIN_INNER,
7864 NULL);
7865
7866 /*
7867 * If ndistinctfrac is selective (on its own), the scan is
7868 * unlikely to benefit from repositioning itself using
7869 * later quals. Do not allow iclause->indexcol's quals to
7870 * be added to indexBoundQuals (it would increase descent
7871 * costs, without lowering numIndexTuples costs by much).
7872 */
7874 {
7875 num_sa_scans = num_sa_scans_prev_cols;
7876 break; /* done building indexBoundQuals */
7877 }
7878
7879 /* Adjust ndistinct downward */
7880 ndistinct = rint(ndistinct * ndistinctfrac);
7881 ndistinct = Max(ndistinct, 1);
7882 }
7883
7884 /*
7885 * When there's no inequality quals, account for the need to
7886 * find an initial value by counting -inf/+inf as a value.
7887 *
7888 * We don't charge anything extra for possible next/prior key
7889 * index probes, which are sometimes used to find the next
7890 * valid skip array element (ahead of using the located
7891 * element value to relocate the scan to the next position
7892 * that might contain matching tuples). It seems hard to do
7893 * better here. Use of the skip support infrastructure often
7894 * avoids most next/prior key probes. But even when it can't,
7895 * there's a decent chance that most individual next/prior key
7896 * probes will locate a leaf page whose key space overlaps all
7897 * of the scan's keys (even the lower-order keys) -- which
7898 * also avoids the need for a separate, extra index descent.
7899 * Note also that these probes are much cheaper than non-probe
7900 * primitive index scans: they're reliably very selective.
7901 */
7902 if (indexSkipQuals == NIL)
7903 ndistinct += 1;
7904
7905 /*
7906 * Update num_sa_scans estimate by multiplying by ndistinct.
7907 *
7908 * We make the pessimistic assumption that there is no
7909 * naturally occurring cross-column correlation. This is
7910 * often wrong, but it seems best to err on the side of not
7911 * expecting skipping to be helpful...
7912 */
7913 num_sa_scans *= ndistinct;
7914
7915 /*
7916 * ...but back out of adding this latest group of 1 or more
7917 * skip arrays when num_sa_scans exceeds the total number of
7918 * index pages (revert to num_sa_scans from before indexcol).
7919 * This causes a sharp discontinuity in cost (as a function of
7920 * the indexcol's ndistinct), but that is representative of
7921 * actual runtime costs.
7922 *
7923 * Note that skipping is helpful when each primitive index
7924 * scan only manages to skip over 1 or 2 irrelevant leaf pages
7925 * on average. Skip arrays bring savings in CPU costs due to
7926 * the scan not needing to evaluate indexquals against every
7927 * tuple, which can greatly exceed any savings in I/O costs.
7928 * This test is a test of whether num_sa_scans implies that
7929 * we're past the point where the ability to skip ceases to
7930 * lower the scan's costs (even qual evaluation CPU costs).
7931 */
7932 if (index->pages < num_sa_scans)
7933 {
7934 num_sa_scans = num_sa_scans_prev_cols;
7935 break; /* done building indexBoundQuals */
7936 }
7937
7938 indexcol++;
7940 }
7941
7942 /*
7943 * Finished considering the need to add skip arrays to bridge an
7944 * initial eqQualHere gap between the old and new index columns
7945 * (or there was no initial eqQualHere gap in the first place).
7946 *
7947 * If an initial gap could not be bridged, then new column's quals
7948 * (i.e. iclause->indexcol's quals) won't go into indexBoundQuals,
7949 * and so won't affect our final numIndexTuples estimate.
7950 */
7951 if (indexcol != iclause->indexcol)
7952 break; /* done building indexBoundQuals */
7953 }
7954
7955 Assert(indexcol == iclause->indexcol);
7956
7957 /* Examine each indexqual associated with this index clause */
7958 foreach(lc2, iclause->indexquals)
7959 {
7961 Expr *clause = rinfo->clause;
7962 Oid clause_op = InvalidOid;
7963 int op_strategy;
7964
7965 if (IsA(clause, OpExpr))
7966 {
7967 OpExpr *op = (OpExpr *) clause;
7968
7969 clause_op = op->opno;
7970 }
7971 else if (IsA(clause, RowCompareExpr))
7972 {
7973 RowCompareExpr *rc = (RowCompareExpr *) clause;
7974
7975 clause_op = linitial_oid(rc->opnos);
7976 found_row_compare = true;
7977 }
7978 else if (IsA(clause, ScalarArrayOpExpr))
7979 {
7980 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
7981 Node *other_operand = (Node *) lsecond(saop->args);
7983
7984 clause_op = saop->opno;
7985 found_array = true;
7986 /* estimate SA descents by indexBoundQuals only */
7987 if (alength > 1)
7988 num_sa_scans *= alength;
7989 }
7990 else if (IsA(clause, NullTest))
7991 {
7992 NullTest *nt = (NullTest *) clause;
7993
7994 if (nt->nulltesttype == IS_NULL)
7995 {
7996 found_is_null_op = true;
7997 /* IS NULL is like = for selectivity/skip scan purposes */
7998 eqQualHere = true;
7999 }
8000 }
8001 else
8002 elog(ERROR, "unsupported indexqual type: %d",
8003 (int) nodeTag(clause));
8004
8005 /* check for equality operator */
8006 if (OidIsValid(clause_op))
8007 {
8008 op_strategy = get_op_opfamily_strategy(clause_op,
8009 index->opfamily[indexcol]);
8010 Assert(op_strategy != 0); /* not a member of opfamily?? */
8011 if (op_strategy == BTEqualStrategyNumber)
8012 eqQualHere = true;
8013 }
8014
8016
8017 /*
8018 * We apply inequality selectivities to estimate index descent
8019 * costs with scans that use skip arrays. Save this indexcol's
8020 * RestrictInfos if it looks like they'll be needed for that.
8021 */
8022 if (!eqQualHere && !found_row_compare &&
8023 indexcol < index->nkeycolumns - 1)
8025 }
8026 }
8027
8028 /*
8029 * If index is unique and we found an '=' clause for each column, we can
8030 * just assume numIndexTuples = 1 and skip the expensive
8031 * clauselist_selectivity calculations. However, an array or NullTest
8032 * always invalidates that theory (even when eqQualHere has been set).
8033 */
8034 if (index->unique &&
8035 indexcol == index->nkeycolumns - 1 &&
8036 eqQualHere &&
8037 !found_array &&
8039 numIndexTuples = 1.0;
8040 else
8041 {
8044
8045 /*
8046 * If the index is partial, AND the index predicate with the
8047 * index-bound quals to produce a more accurate idea of the number of
8048 * rows covered by the bound conditions.
8049 */
8051
8053 index->rel->relid,
8054 JOIN_INNER,
8055 NULL);
8056 numIndexTuples = btreeSelectivity * index->rel->tuples;
8057
8058 /*
8059 * btree automatically combines individual array element primitive
8060 * index scans whenever the tuples covered by the next set of array
8061 * keys are close to tuples covered by the current set. That puts a
8062 * natural ceiling on the worst case number of descents -- there
8063 * cannot possibly be more than one descent per leaf page scanned.
8064 *
8065 * Clamp the number of descents to at most 1/3 the number of index
8066 * pages. This avoids implausibly high estimates with low selectivity
8067 * paths, where scans usually require only one or two descents. This
8068 * is most likely to help when there are several SAOP clauses, where
8069 * naively accepting the total number of distinct combinations of
8070 * array elements as the number of descents would frequently lead to
8071 * wild overestimates.
8072 *
8073 * We somewhat arbitrarily don't just make the cutoff the total number
8074 * of leaf pages (we make it 1/3 the total number of pages instead) to
8075 * give the btree code credit for its ability to continue on the leaf
8076 * level with low selectivity scans.
8077 *
8078 * Note: num_sa_scans includes both ScalarArrayOp array elements and
8079 * skip array elements whose qual affects our numIndexTuples estimate.
8080 */
8081 num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
8082 num_sa_scans = Max(num_sa_scans, 1);
8083
8084 /*
8085 * As in genericcostestimate(), we have to adjust for any array quals
8086 * included in indexBoundQuals, and then round to integer.
8087 *
8088 * It is tempting to make genericcostestimate behave as if array
8089 * clauses work in almost the same way as scalar operators during
8090 * btree scans, making the top-level scan look like a continuous scan
8091 * (as opposed to num_sa_scans-many primitive index scans). After
8092 * all, btree scans mostly work like that at runtime. However, such a
8093 * scheme would badly bias genericcostestimate's simplistic approach
8094 * to calculating numIndexPages through prorating.
8095 *
8096 * Stick with the approach taken by non-native SAOP scans for now.
8097 * genericcostestimate will use the Mackert-Lohman formula to
8098 * compensate for repeat page fetches, even though that definitely
8099 * won't happen during btree scans (not for leaf pages, at least).
8100 * We're usually very pessimistic about the number of primitive index
8101 * scans that will be required, but it's not clear how to do better.
8102 */
8103 numIndexTuples = rint(numIndexTuples / num_sa_scans);
8104 }
8105
8106 /*
8107 * Now do generic index cost estimation.
8108 *
8109 * While we expended effort to make realistic estimates of numIndexTuples
8110 * and num_sa_scans, we are content to count only the btree metapage as
8111 * non-leaf. btree fanout is typically high enough that upper pages are
8112 * few relative to leaf pages, so accounting for them would move the
8113 * estimates at most a percent or two. Given the uncertainty in just how
8114 * many upper pages exist in a particular index, we'll skip trying to
8115 * handle that.
8116 */
8117 costs.numIndexTuples = numIndexTuples;
8118 costs.num_sa_scans = num_sa_scans;
8119 costs.numNonLeafPages = 1;
8120
8121 genericcostestimate(root, path, loop_count, &costs);
8122
8123 /*
8124 * Add a CPU-cost component to represent the costs of initial btree
8125 * descent. We don't charge any I/O cost for touching upper btree levels,
8126 * since they tend to stay in cache, but we still have to do about log2(N)
8127 * comparisons to descend a btree of N leaf tuples. We charge one
8128 * cpu_operator_cost per comparison.
8129 *
8130 * If there are SAOP or skip array keys, charge this once per estimated
8131 * index descent. The ones after the first one are not startup cost so
8132 * far as the overall plan goes, so just add them to "total" cost.
8133 */
8134 if (index->tuples > 1) /* avoid computing log(0) */
8135 {
8136 descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
8138 costs.indexTotalCost += costs.num_sa_scans * descentCost;
8139 }
8140
8141 /*
8142 * Even though we're not charging I/O cost for touching upper btree pages,
8143 * it's still reasonable to charge some CPU cost per page descended
8144 * through. Moreover, if we had no such charge at all, bloated indexes
8145 * would appear to have the same search cost as unbloated ones, at least
8146 * in cases where only a single leaf page is expected to be visited. This
8147 * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
8148 * touched. The number of such pages is btree tree height plus one (ie,
8149 * we charge for the leaf page too). As above, charge once per estimated
8150 * SAOP/skip array descent.
8151 */
8154 costs.indexTotalCost += costs.num_sa_scans * descentCost;
8155
8156 if (!have_correlation)
8157 {
8159 if (HeapTupleIsValid(vardata.statsTuple))
8162 }
8163 else
8164 {
8165 /* btcost_correlation already called earlier on */
8167 }
8168
8169 *indexStartupCost = costs.indexStartupCost;
8170 *indexTotalCost = costs.indexTotalCost;
8171 *indexSelectivity = costs.indexSelectivity;
8172 *indexCorrelation = costs.indexCorrelation;
8173 *indexPages = costs.numIndexPages;
8174}
#define OidIsValid(objectId)
Definition c.h:858
List * lappend(List *list, void *datum)
Definition list.c:339
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition lsyscache.c:87
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define nodeTag(nodeptr)
Definition nodes.h:139
double Selectivity
Definition nodes.h:260
#define NIL
Definition pg_list.h:68
#define lsecond(l)
Definition pg_list.h:183
#define linitial_oid(l)
Definition pg_list.h:180
unsigned int Oid
@ IS_NULL
Definition primnodes.h:1992
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition selfuncs.c:7637
#define DEFAULT_PAGE_CPU_MULTIPLIER
Definition selfuncs.c:144
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition selfuncs.c:2240
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition selfuncs.c:7412
static void examine_indexcol_variable(PlannerInfo *root, IndexOptInfo *index, int indexcol, VariableStatData *vardata)
Definition selfuncs.c:6510
static double btcost_correlation(IndexOptInfo *index, VariableStatData *vardata)
Definition selfuncs.c:7668
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition selfuncs.c:6613
#define DEFAULT_RANGE_INEQ_SEL
Definition selfuncs.h:40
#define BTEqualStrategyNumber
Definition stratnum.h:31
Selectivity indexSelectivity
Definition selfuncs.h:135
BlockNumber numNonLeafPages
Definition selfuncs.h:143
Cost indexStartupCost
Definition selfuncs.h:133
double indexCorrelation
Definition selfuncs.h:136
double num_sa_scans
Definition selfuncs.h:142
Cost indexTotalCost
Definition selfuncs.h:134
double numIndexPages
Definition selfuncs.h:139
double numIndexTuples
Definition selfuncs.h:140
Definition nodes.h:135
Oid opno
Definition primnodes.h:851
Expr * clause
Definition pathnodes.h:2901

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, Assert, btcost_correlation(), BTEqualStrategyNumber, RestrictInfo::clause, clauselist_selectivity(), cpu_operator_cost, DEFAULT_PAGE_CPU_MULTIPLIER, DEFAULT_RANGE_INEQ_SEL, elog, ERROR, estimate_array_length(), examine_indexcol_variable(), fb(), genericcostestimate(), get_op_opfamily_strategy(), get_variable_numdistinct(), HeapTupleIsValid, IndexPath::indexclauses, GenericCosts::indexCorrelation, IndexPath::indexinfo, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst_node, linitial_oid, lsecond, Max, Min, NIL, nodeTag, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, GenericCosts::numNonLeafPages, OidIsValid, OpExpr::opno, ScalarArrayOpExpr::opno, ReleaseVariableStats, and root.

Referenced by bthandler().

◆ gincostestimate()

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

Definition at line 8637 of file selfuncs.c.

8641{
8642 IndexOptInfo *index = path->indexinfo;
8645 double numPages = index->pages,
8646 numTuples = index->tuples;
8647 double numEntryPages,
8650 numEntries;
8651 GinQualCounts counts;
8652 bool matchPossible;
8653 bool fullIndexScan;
8654 double partialScale;
8655 double entryPagesFetched,
8658 double qual_op_cost,
8660 spc_random_page_cost,
8663 Relation indexRel;
8665 ListCell *lc;
8666 int i;
8667
8668 /*
8669 * Obtain statistical information from the meta page, if possible. Else
8670 * set ginStats to zeroes, and we'll cope below.
8671 */
8672 if (!index->hypothetical)
8673 {
8674 /* Lock should have already been obtained in plancat.c */
8675 indexRel = index_open(index->indexoid, NoLock);
8676 ginGetStats(indexRel, &ginStats);
8677 index_close(indexRel, NoLock);
8678 }
8679 else
8680 {
8681 memset(&ginStats, 0, sizeof(ginStats));
8682 }
8683
8684 /*
8685 * Assuming we got valid (nonzero) stats at all, nPendingPages can be
8686 * trusted, but the other fields are data as of the last VACUUM. We can
8687 * scale them up to account for growth since then, but that method only
8688 * goes so far; in the worst case, the stats might be for a completely
8689 * empty index, and scaling them will produce pretty bogus numbers.
8690 * Somewhat arbitrarily, set the cutoff for doing scaling at 4X growth; if
8691 * it's grown more than that, fall back to estimating things only from the
8692 * assumed-accurate index size. But we'll trust nPendingPages in any case
8693 * so long as it's not clearly insane, ie, more than the index size.
8694 */
8695 if (ginStats.nPendingPages < numPages)
8696 numPendingPages = ginStats.nPendingPages;
8697 else
8698 numPendingPages = 0;
8699
8700 if (numPages > 0 && ginStats.nTotalPages <= numPages &&
8701 ginStats.nTotalPages > numPages / 4 &&
8702 ginStats.nEntryPages > 0 && ginStats.nEntries > 0)
8703 {
8704 /*
8705 * OK, the stats seem close enough to sane to be trusted. But we
8706 * still need to scale them by the ratio numPages / nTotalPages to
8707 * account for growth since the last VACUUM.
8708 */
8709 double scale = numPages / ginStats.nTotalPages;
8710
8711 numEntryPages = ceil(ginStats.nEntryPages * scale);
8712 numDataPages = ceil(ginStats.nDataPages * scale);
8713 numEntries = ceil(ginStats.nEntries * scale);
8714 /* ensure we didn't round up too much */
8718 }
8719 else
8720 {
8721 /*
8722 * We might get here because it's a hypothetical index, or an index
8723 * created pre-9.1 and never vacuumed since upgrading (in which case
8724 * its stats would read as zeroes), or just because it's grown too
8725 * much since the last VACUUM for us to put our faith in scaling.
8726 *
8727 * Invent some plausible internal statistics based on the index page
8728 * count (and clamp that to at least 10 pages, just in case). We
8729 * estimate that 90% of the index is entry pages, and the rest is data
8730 * pages. Estimate 100 entries per entry page; this is rather bogus
8731 * since it'll depend on the size of the keys, but it's more robust
8732 * than trying to predict the number of entries per heap tuple.
8733 */
8734 numPages = Max(numPages, 10);
8738 }
8739
8740 /* In an empty index, numEntries could be zero. Avoid divide-by-zero */
8741 if (numEntries < 1)
8742 numEntries = 1;
8743
8744 /*
8745 * If the index is partial, AND the index predicate with the index-bound
8746 * quals to produce a more accurate idea of the number of rows covered by
8747 * the bound conditions.
8748 */
8750
8751 /* Estimate the fraction of main-table tuples that will be visited */
8752 *indexSelectivity = clauselist_selectivity(root, selectivityQuals,
8753 index->rel->relid,
8754 JOIN_INNER,
8755 NULL);
8756
8757 /* fetch estimated page cost for tablespace containing index */
8758 get_tablespace_page_costs(index->reltablespace,
8759 &spc_random_page_cost,
8760 NULL);
8761
8762 /*
8763 * Generic assumption about index correlation: there isn't any.
8764 */
8765 *indexCorrelation = 0.0;
8766
8767 /*
8768 * Examine quals to estimate number of search entries & partial matches
8769 */
8770 memset(&counts, 0, sizeof(counts));
8771 counts.arrayScans = 1;
8772 matchPossible = true;
8773
8774 foreach(lc, path->indexclauses)
8775 {
8777 ListCell *lc2;
8778
8779 foreach(lc2, iclause->indexquals)
8780 {
8782 Expr *clause = rinfo->clause;
8783
8784 if (IsA(clause, OpExpr))
8785 {
8787 index,
8788 iclause->indexcol,
8789 (OpExpr *) clause,
8790 &counts);
8791 if (!matchPossible)
8792 break;
8793 }
8794 else if (IsA(clause, ScalarArrayOpExpr))
8795 {
8797 index,
8798 iclause->indexcol,
8799 (ScalarArrayOpExpr *) clause,
8800 numEntries,
8801 &counts);
8802 if (!matchPossible)
8803 break;
8804 }
8805 else
8806 {
8807 /* shouldn't be anything else for a GIN index */
8808 elog(ERROR, "unsupported GIN indexqual type: %d",
8809 (int) nodeTag(clause));
8810 }
8811 }
8812 }
8813
8814 /* Fall out if there were any provably-unsatisfiable quals */
8815 if (!matchPossible)
8816 {
8817 *indexStartupCost = 0;
8818 *indexTotalCost = 0;
8819 *indexSelectivity = 0;
8820 return;
8821 }
8822
8823 /*
8824 * If attribute has a full scan and at the same time doesn't have normal
8825 * scan, then we'll have to scan all non-null entries of that attribute.
8826 * Currently, we don't have per-attribute statistics for GIN. Thus, we
8827 * must assume the whole GIN index has to be scanned in this case.
8828 */
8829 fullIndexScan = false;
8830 for (i = 0; i < index->nkeycolumns; i++)
8831 {
8832 if (counts.attHasFullScan[i] && !counts.attHasNormalScan[i])
8833 {
8834 fullIndexScan = true;
8835 break;
8836 }
8837 }
8838
8839 if (fullIndexScan || indexQuals == NIL)
8840 {
8841 /*
8842 * Full index scan will be required. We treat this as if every key in
8843 * the index had been listed in the query; is that reasonable?
8844 */
8845 counts.partialEntries = 0;
8846 counts.exactEntries = numEntries;
8847 counts.searchEntries = numEntries;
8848 }
8849
8850 /* Will we have more than one iteration of a nestloop scan? */
8852
8853 /*
8854 * Compute cost to begin scan, first of all, pay attention to pending
8855 * list.
8856 */
8858
8859 /*
8860 * Estimate number of entry pages read. We need to do
8861 * counts.searchEntries searches. Use a power function as it should be,
8862 * but tuples on leaf pages usually is much greater. Here we include all
8863 * searches in entry tree, including search of first entry in partial
8864 * match algorithm
8865 */
8867
8868 /*
8869 * Add an estimate of entry pages read by partial match algorithm. It's a
8870 * scan over leaf pages in entry tree. We haven't any useful stats here,
8871 * so estimate it as proportion. Because counts.partialEntries is really
8872 * pretty bogus (see code above), it's possible that it is more than
8873 * numEntries; clamp the proportion to ensure sanity.
8874 */
8877
8879
8880 /*
8881 * Partial match algorithm reads all data pages before doing actual scan,
8882 * so it's a startup cost. Again, we haven't any useful stats here, so
8883 * estimate it as proportion.
8884 */
8886
8887 *indexStartupCost = 0;
8888 *indexTotalCost = 0;
8889
8890 /*
8891 * Add a CPU-cost component to represent the costs of initial entry btree
8892 * descent. We don't charge any I/O cost for touching upper btree levels,
8893 * since they tend to stay in cache, but we still have to do about log2(N)
8894 * comparisons to descend a btree of N leaf tuples. We charge one
8895 * cpu_operator_cost per comparison.
8896 *
8897 * If there are ScalarArrayOpExprs, charge this once per SA scan. The
8898 * ones after the first one are not startup cost so far as the overall
8899 * plan is concerned, so add them only to "total" cost.
8900 */
8901 if (numEntries > 1) /* avoid computing log(0) */
8902 {
8904 *indexStartupCost += descentCost * counts.searchEntries;
8905 *indexTotalCost += counts.arrayScans * descentCost * counts.searchEntries;
8906 }
8907
8908 /*
8909 * Add a cpu cost per entry-page fetched. This is not amortized over a
8910 * loop.
8911 */
8914
8915 /*
8916 * Add a cpu cost per data-page fetched. This is also not amortized over a
8917 * loop. Since those are the data pages from the partial match algorithm,
8918 * charge them as startup cost.
8919 */
8921
8922 /*
8923 * Since we add the startup cost to the total cost later on, remove the
8924 * initial arrayscan from the total.
8925 */
8926 *indexTotalCost += dataPagesFetched * (counts.arrayScans - 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
8927
8928 /*
8929 * Calculate cache effects if more than one scan due to nestloops or array
8930 * quals. The result is pro-rated per nestloop scan, but the array qual
8931 * factor shouldn't be pro-rated (compare genericcostestimate).
8932 */
8933 if (outer_scans > 1 || counts.arrayScans > 1)
8934 {
8945 }
8946
8947 /*
8948 * Here we use random page cost because logically-close pages could be far
8949 * apart on disk.
8950 */
8951 *indexStartupCost += (entryPagesFetched + dataPagesFetched) * spc_random_page_cost;
8952
8953 /*
8954 * Now compute the number of data pages fetched during the scan.
8955 *
8956 * We assume every entry to have the same number of items, and that there
8957 * is no overlap between them. (XXX: tsvector and array opclasses collect
8958 * statistics on the frequency of individual keys; it would be nice to use
8959 * those here.)
8960 */
8962
8963 /*
8964 * If there is a lot of overlap among the entries, in particular if one of
8965 * the entries is very frequent, the above calculation can grossly
8966 * under-estimate. As a simple cross-check, calculate a lower bound based
8967 * on the overall selectivity of the quals. At a minimum, we must read
8968 * one item pointer for each matching entry.
8969 *
8970 * The width of each item pointer varies, based on the level of
8971 * compression. We don't have statistics on that, but an average of
8972 * around 3 bytes per item is fairly typical.
8973 */
8974 dataPagesFetchedBySel = ceil(*indexSelectivity *
8975 (numTuples / (BLCKSZ / 3)));
8978
8979 /* Add one page cpu-cost to the startup cost */
8980 *indexStartupCost += DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost * counts.searchEntries;
8981
8982 /*
8983 * Add once again a CPU-cost for those data pages, before amortizing for
8984 * cache.
8985 */
8987
8988 /* Account for cache effects, the same as above */
8989 if (outer_scans > 1 || counts.arrayScans > 1)
8990 {
8996 }
8997
8998 /* And apply random_page_cost as the cost per page */
8999 *indexTotalCost += *indexStartupCost +
9000 dataPagesFetched * spc_random_page_cost;
9001
9002 /*
9003 * Add on index qual eval costs, much as in genericcostestimate. We charge
9004 * cpu but we can disregard indexorderbys, since GIN doesn't support
9005 * those.
9006 */
9009
9010 *indexStartupCost += qual_arg_cost;
9011 *indexTotalCost += qual_arg_cost;
9012
9013 /*
9014 * Add a cpu cost per search entry, corresponding to the actual visited
9015 * entries.
9016 */
9017 *indexTotalCost += (counts.searchEntries * counts.arrayScans) * (qual_op_cost);
9018 /* Now add a cpu cost per tuple in the posting lists / trees */
9019 *indexTotalCost += (numTuples * *indexSelectivity) * (cpu_index_tuple_cost);
9021}
uint32 BlockNumber
Definition block.h:31
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition costsize.c:897
double cpu_index_tuple_cost
Definition costsize.c:134
void ginGetStats(Relation index, GinStatsData *stats)
Definition ginutil.c:578
int i
Definition isn.c:77
static int list_length(const List *l)
Definition pg_list.h:152
static int scale
Definition pgbench.c:182
static bool gincost_scalararrayopexpr(PlannerInfo *root, IndexOptInfo *index, int indexcol, ScalarArrayOpExpr *clause, double numIndexEntries, GinQualCounts *counts)
Definition selfuncs.c:8521
static bool gincost_opexpr(PlannerInfo *root, IndexOptInfo *index, int indexcol, OpExpr *clause, GinQualCounts *counts)
Definition selfuncs.c:8471
bool attHasNormalScan[INDEX_MAX_KEYS]
Definition selfuncs.c:8344
double exactEntries
Definition selfuncs.c:8346
double arrayScans
Definition selfuncs.c:8348
double partialEntries
Definition selfuncs.c:8345
bool attHasFullScan[INDEX_MAX_KEYS]
Definition selfuncs.c:8343
double searchEntries
Definition selfuncs.c:8347

References add_predicate_to_index_quals(), GinQualCounts::arrayScans, GinQualCounts::attHasFullScan, GinQualCounts::attHasNormalScan, RestrictInfo::clause, clauselist_selectivity(), cpu_index_tuple_cost, cpu_operator_cost, DEFAULT_PAGE_CPU_MULTIPLIER, elog, ERROR, GinQualCounts::exactEntries, fb(), get_quals_from_indexclauses(), get_tablespace_page_costs(), gincost_opexpr(), gincost_scalararrayopexpr(), ginGetStats(), i, index_close(), index_open(), index_other_operands_eval_cost(), index_pages_fetched(), IndexPath::indexclauses, IndexPath::indexinfo, IsA, JOIN_INNER, lfirst_node, list_length(), Max, Min, NIL, nodeTag, NoLock, GinQualCounts::partialEntries, root, scale, and GinQualCounts::searchEntries.

Referenced by ginhandler().

◆ gistcostestimate()

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

Definition at line 8222 of file selfuncs.c.

8226{
8227 IndexOptInfo *index = path->indexinfo;
8228 GenericCosts costs = {0};
8230
8231 /* GiST has no metapage, so we treat all pages as leaf pages */
8232
8233 genericcostestimate(root, path, loop_count, &costs);
8234
8235 /*
8236 * We model index descent costs similarly to those for btree, but to do
8237 * that we first need an idea of the tree height. We somewhat arbitrarily
8238 * assume that the fanout is 100, meaning the tree height is at most
8239 * log100(index->pages).
8240 *
8241 * Although this computation isn't really expensive enough to require
8242 * caching, we might as well use index->tree_height to cache it.
8243 */
8244 if (index->tree_height < 0) /* unknown? */
8245 {
8246 if (index->pages > 1) /* avoid computing log(0) */
8247 index->tree_height = (int) (log(index->pages) / log(100.0));
8248 else
8249 index->tree_height = 0;
8250 }
8251
8252 /*
8253 * Add a CPU-cost component to represent the costs of initial descent. We
8254 * just use log(N) here not log2(N) since the branching factor isn't
8255 * necessarily two anyway. As for btree, charge once per SA scan.
8256 */
8257 if (index->tuples > 1) /* avoid computing log(0) */
8258 {
8261 costs.indexTotalCost += costs.num_sa_scans * descentCost;
8262 }
8263
8264 /*
8265 * Likewise add a per-page charge, calculated the same as for btrees.
8266 */
8269 costs.indexTotalCost += costs.num_sa_scans * descentCost;
8270
8271 *indexStartupCost = costs.indexStartupCost;
8272 *indexTotalCost = costs.indexTotalCost;
8273 *indexSelectivity = costs.indexSelectivity;
8274 *indexCorrelation = costs.indexCorrelation;
8275 *indexPages = costs.numIndexPages;
8276}

References cpu_operator_cost, DEFAULT_PAGE_CPU_MULTIPLIER, fb(), genericcostestimate(), GenericCosts::indexCorrelation, IndexPath::indexinfo, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, and root.

Referenced by gisthandler().

◆ hashcostestimate()

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

Definition at line 8177 of file selfuncs.c.

8181{
8182 GenericCosts costs = {0};
8183
8184 /* As in btcostestimate, count only the metapage as non-leaf */
8185 costs.numNonLeafPages = 1;
8186
8187 genericcostestimate(root, path, loop_count, &costs);
8188
8189 /*
8190 * A hash index has no descent costs as such, since the index AM can go
8191 * directly to the target bucket after computing the hash value. There
8192 * are a couple of other hash-specific costs that we could conceivably add
8193 * here, though:
8194 *
8195 * Ideally we'd charge spc_random_page_cost for each page in the target
8196 * bucket, not just the numIndexPages pages that genericcostestimate
8197 * thought we'd visit. However in most cases we don't know which bucket
8198 * that will be. There's no point in considering the average bucket size
8199 * because the hash AM makes sure that's always one page.
8200 *
8201 * Likewise, we could consider charging some CPU for each index tuple in
8202 * the bucket, if we knew how many there were. But the per-tuple cost is
8203 * just a hash value comparison, not a general datatype-dependent
8204 * comparison, so any such charge ought to be quite a bit less than
8205 * cpu_operator_cost; which makes it probably not worth worrying about.
8206 *
8207 * A bigger issue is that chance hash-value collisions will result in
8208 * wasted probes into the heap. We don't currently attempt to model this
8209 * cost on the grounds that it's rare, but maybe it's not rare enough.
8210 * (Any fix for this ought to consider the generic lossy-operator problem,
8211 * though; it's not entirely hash-specific.)
8212 */
8213
8214 *indexStartupCost = costs.indexStartupCost;
8215 *indexTotalCost = costs.indexTotalCost;
8216 *indexSelectivity = costs.indexSelectivity;
8217 *indexCorrelation = costs.indexCorrelation;
8218 *indexPages = costs.numIndexPages;
8219}

References fb(), genericcostestimate(), GenericCosts::indexCorrelation, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, GenericCosts::numIndexPages, GenericCosts::numNonLeafPages, and root.

Referenced by hashhandler().

◆ spgcostestimate()

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

Definition at line 8279 of file selfuncs.c.

8283{
8284 IndexOptInfo *index = path->indexinfo;
8285 GenericCosts costs = {0};
8287
8288 /* As in btcostestimate, count only the metapage as non-leaf */
8289 costs.numNonLeafPages = 1;
8290
8291 genericcostestimate(root, path, loop_count, &costs);
8292
8293 /*
8294 * We model index descent costs similarly to those for btree, but to do
8295 * that we first need an idea of the tree height. We somewhat arbitrarily
8296 * assume that the fanout is 100, meaning the tree height is at most
8297 * log100(index->pages).
8298 *
8299 * Although this computation isn't really expensive enough to require
8300 * caching, we might as well use index->tree_height to cache it.
8301 */
8302 if (index->tree_height < 0) /* unknown? */
8303 {
8304 if (index->pages > 1) /* avoid computing log(0) */
8305 index->tree_height = (int) (log(index->pages) / log(100.0));
8306 else
8307 index->tree_height = 0;
8308 }
8309
8310 /*
8311 * Add a CPU-cost component to represent the costs of initial descent. We
8312 * just use log(N) here not log2(N) since the branching factor isn't
8313 * necessarily two anyway. As for btree, charge once per SA scan.
8314 */
8315 if (index->tuples > 1) /* avoid computing log(0) */
8316 {
8319 costs.indexTotalCost += costs.num_sa_scans * descentCost;
8320 }
8321
8322 /*
8323 * Likewise add a per-page charge, calculated the same as for btrees.
8324 */
8327 costs.indexTotalCost += costs.num_sa_scans * descentCost;
8328
8329 *indexStartupCost = costs.indexStartupCost;
8330 *indexTotalCost = costs.indexTotalCost;
8331 *indexSelectivity = costs.indexSelectivity;
8332 *indexCorrelation = costs.indexCorrelation;
8333 *indexPages = costs.numIndexPages;
8334}

References cpu_operator_cost, DEFAULT_PAGE_CPU_MULTIPLIER, fb(), genericcostestimate(), GenericCosts::indexCorrelation, IndexPath::indexinfo, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, GenericCosts::numNonLeafPages, and root.

Referenced by spghandler().