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

9016{
9017 IndexOptInfo *index = path->indexinfo;
9019 double numPages = index->pages;
9020 RelOptInfo *baserel = index->rel;
9023 Cost spc_random_page_cost;
9024 double qual_arg_cost;
9025 double qualSelectivity;
9027 double indexRanges;
9028 double minimalRanges;
9029 double estimatedRanges;
9030 double selec;
9031 Relation indexRel;
9032 ListCell *l;
9034
9035 Assert(rte->rtekind == RTE_RELATION);
9036
9037 /* fetch estimated page cost for the tablespace containing the index */
9038 get_tablespace_page_costs(index->reltablespace,
9039 &spc_random_page_cost,
9041
9042 /*
9043 * Obtain some data from the index itself, if possible. Otherwise invent
9044 * some plausible internal statistics based on the relation page count.
9045 */
9046 if (!index->hypothetical)
9047 {
9048 /*
9049 * A lock should have already been obtained on the index in plancat.c.
9050 */
9051 indexRel = index_open(index->indexoid, NoLock);
9052 brinGetStats(indexRel, &statsData);
9053 index_close(indexRel, NoLock);
9054
9055 /* work out the actual number of ranges in the index */
9056 indexRanges = Max(ceil((double) baserel->pages /
9057 statsData.pagesPerRange), 1.0);
9058 }
9059 else
9060 {
9061 /*
9062 * Assume default number of pages per range, and estimate the number
9063 * of ranges based on that.
9064 */
9065 indexRanges = Max(ceil((double) baserel->pages /
9067
9069 statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
9070 }
9071
9072 /*
9073 * Compute index correlation
9074 *
9075 * Because we can use all index quals equally when scanning, we can use
9076 * the largest correlation (in absolute value) among columns used by the
9077 * query. Start at zero, the worst possible case. If we cannot find any
9078 * correlation statistics, we will keep it as 0.
9079 */
9080 *indexCorrelation = 0;
9081
9082 foreach(l, path->indexclauses)
9083 {
9085 AttrNumber attnum = index->indexkeys[iclause->indexcol];
9086
9087 /* attempt to lookup stats in relation for this index column */
9088 if (attnum != 0)
9089 {
9090 /* Simple variable -- look to stats for the underlying table */
9093 {
9094 /*
9095 * The hook took control of acquiring a stats tuple. If it
9096 * did supply a tuple, it'd better have supplied a freefunc.
9097 */
9098 if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
9099 elog(ERROR,
9100 "no function provided to release variable stats with");
9101 }
9102 else
9103 {
9104 vardata.statsTuple =
9106 ObjectIdGetDatum(rte->relid),
9108 BoolGetDatum(false));
9109 vardata.freefunc = ReleaseSysCache;
9110 }
9111 }
9112 else
9113 {
9114 /*
9115 * Looks like we've found an expression column in the index. Let's
9116 * see if there's any stats for it.
9117 */
9118
9119 /* get the attnum from the 0-based index. */
9120 attnum = iclause->indexcol + 1;
9121
9123 (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
9124 {
9125 /*
9126 * The hook took control of acquiring a stats tuple. If it
9127 * did supply a tuple, it'd better have supplied a freefunc.
9128 */
9129 if (HeapTupleIsValid(vardata.statsTuple) &&
9130 !vardata.freefunc)
9131 elog(ERROR, "no function provided to release variable stats with");
9132 }
9133 else
9134 {
9136 ObjectIdGetDatum(index->indexoid),
9138 BoolGetDatum(false));
9139 vardata.freefunc = ReleaseSysCache;
9140 }
9141 }
9142
9143 if (HeapTupleIsValid(vardata.statsTuple))
9144 {
9146
9147 if (get_attstatsslot(&sslot, vardata.statsTuple,
9150 {
9151 double varCorrelation = 0.0;
9152
9153 if (sslot.nnumbers > 0)
9154 varCorrelation = fabs(sslot.numbers[0]);
9155
9156 if (varCorrelation > *indexCorrelation)
9157 *indexCorrelation = varCorrelation;
9158
9160 }
9161 }
9162
9164 }
9165
9167 baserel->relid,
9168 JOIN_INNER, NULL);
9169
9170 /*
9171 * Now calculate the minimum possible ranges we could match with if all of
9172 * the rows were in the perfect order in the table's heap.
9173 */
9175
9176 /*
9177 * Now estimate the number of ranges that we'll touch by using the
9178 * indexCorrelation from the stats. Careful not to divide by zero (note
9179 * we're using the absolute value of the correlation).
9180 */
9181 if (*indexCorrelation < 1.0e-10)
9183 else
9184 estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
9185
9186 /* we expect to visit this portion of the table */
9188
9190
9191 *indexSelectivity = selec;
9192
9193 /*
9194 * Compute the index qual costs, much as in genericcostestimate, to add to
9195 * the index costs. We can disregard indexorderbys, since BRIN doesn't
9196 * support those.
9197 */
9199
9200 /*
9201 * Compute the startup cost as the cost to read the whole revmap
9202 * sequentially, including the cost to execute the index quals.
9203 */
9204 *indexStartupCost =
9205 spc_seq_page_cost * statsData.revmapNumPages * loop_count;
9206 *indexStartupCost += qual_arg_cost;
9207
9208 /*
9209 * To read a BRIN index there might be a bit of back and forth over
9210 * regular pages, as revmap might point to them out of sequential order;
9211 * calculate the total cost as reading the whole index in random order.
9212 */
9213 *indexTotalCost = *indexStartupCost +
9214 spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
9215
9216 /*
9217 * Charge a small amount per range tuple which we expect to match to. This
9218 * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
9219 * will set a bit for each page in the range when we find a matching
9220 * range, so we must multiply the charge by the number of pages in the
9221 * range.
9222 */
9223 *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
9224 statsData.pagesPerRange;
9225
9226 *indexPages = index->pages;
9227}
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:1093
#define Max(x, y)
Definition c.h:1087
#define Assert(condition)
Definition c.h:945
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:39
#define elog(elevel,...)
Definition elog.h:226
#define HeapTupleIsValid(tuple)
Definition htup.h:78
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:133
#define NoLock
Definition lockdefs.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition lsyscache.c:3566
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition lsyscache.c:3456
#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:692
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:7308
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:7338
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:2045
IndexOptInfo * indexinfo
Definition pathnodes.h:2044
Definition pg_list.h:54
Definition type.h:96
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache3(SysCacheIdentifier cacheId, Datum key1, Datum key2, Datum key3)
Definition syscache.c:240

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

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

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

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

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

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

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

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

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

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

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