PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
selfuncs.h File Reference
#include "access/htup.h"
#include "fmgr.h"
#include "nodes/pathnodes.h"
Include dependency graph for selfuncs.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  EstimationInfo
 
struct  VariableStatData
 
struct  GenericCosts
 

Macros

#define DEFAULT_EQ_SEL   0.005
 
#define DEFAULT_INEQ_SEL   0.3333333333333333
 
#define DEFAULT_RANGE_INEQ_SEL   0.005
 
#define DEFAULT_MULTIRANGE_INEQ_SEL   0.005
 
#define DEFAULT_MATCH_SEL   0.005
 
#define DEFAULT_MATCHING_SEL   0.010
 
#define DEFAULT_NUM_DISTINCT   200
 
#define DEFAULT_UNK_SEL   0.005
 
#define DEFAULT_NOT_UNK_SEL   (1.0 - DEFAULT_UNK_SEL)
 
#define CLAMP_PROBABILITY(p)
 
#define SELFLAG_USED_DEFAULT
 
#define ReleaseVariableStats(vardata)
 

Typedefs

typedef struct EstimationInfo EstimationInfo
 
typedef struct VariableStatData VariableStatData
 
typedef bool(* get_relation_stats_hook_type) (PlannerInfo *root, RangeTblEntry *rte, AttrNumber attnum, VariableStatData *vardata)
 
typedef bool(* get_index_stats_hook_type) (PlannerInfo *root, Oid indexOid, AttrNumber indexattnum, VariableStatData *vardata)
 

Functions

void examine_variable (PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
 
bool statistic_proc_security_check (VariableStatData *vardata, Oid func_oid)
 
bool get_restriction_variable (PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
 
void get_join_variables (PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
 
double get_variable_numdistinct (VariableStatData *vardata, bool *isdefault)
 
double mcv_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
 
double histogram_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
 
double generic_restriction_selectivity (PlannerInfo *root, Oid oproid, Oid collation, List *args, int varRelid, double default_selectivity)
 
double ineq_histogram_selectivity (PlannerInfo *root, VariableStatData *vardata, Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq, Oid collation, Datum constval, Oid consttype)
 
double var_eq_const (VariableStatData *vardata, Oid oproid, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
 
double var_eq_non_const (VariableStatData *vardata, Oid oproid, Oid collation, Node *other, bool varonleft, bool negate)
 
Selectivity boolvarsel (PlannerInfo *root, Node *arg, int varRelid)
 
Selectivity booltestsel (PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity nulltestsel (PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity scalararraysel (PlannerInfo *root, ScalarArrayOpExpr *clause, bool is_join_clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
double estimate_array_length (PlannerInfo *root, Node *arrayexpr)
 
Selectivity rowcomparesel (PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, CompareType cmptype, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
 
Listestimate_multivariate_bucketsize (PlannerInfo *root, RelOptInfo *inner, List *hashclauses, Selectivity *innerbucketsize)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
double estimate_hashagg_tablesize (PlannerInfo *root, Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
 
Listget_quals_from_indexclauses (List *indexclauses)
 
Cost index_other_operands_eval_cost (PlannerInfo *root, List *indexquals)
 
Listadd_predicate_to_index_quals (IndexOptInfo *index, List *indexQuals)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
 
Selectivity scalararraysel_containment (PlannerInfo *root, Node *leftop, Node *rightop, Oid elemtype, bool isEquality, bool useOr, int varRelid)
 

Variables

PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook
 
PGDLLIMPORT get_index_stats_hook_type get_index_stats_hook
 

Macro Definition Documentation

◆ CLAMP_PROBABILITY

#define CLAMP_PROBABILITY (   p)
Value:
do { \
if (p < 0.0) \
p = 0.0; \
else if (p > 1.0) \
p = 1.0; \
} while (0)

Definition at line 63 of file selfuncs.h.

◆ DEFAULT_EQ_SEL

#define DEFAULT_EQ_SEL   0.005

Definition at line 34 of file selfuncs.h.

◆ DEFAULT_INEQ_SEL

#define DEFAULT_INEQ_SEL   0.3333333333333333

Definition at line 37 of file selfuncs.h.

◆ DEFAULT_MATCH_SEL

#define DEFAULT_MATCH_SEL   0.005

Definition at line 46 of file selfuncs.h.

◆ DEFAULT_MATCHING_SEL

#define DEFAULT_MATCHING_SEL   0.010

Definition at line 49 of file selfuncs.h.

◆ DEFAULT_MULTIRANGE_INEQ_SEL

#define DEFAULT_MULTIRANGE_INEQ_SEL   0.005

Definition at line 43 of file selfuncs.h.

◆ DEFAULT_NOT_UNK_SEL

#define DEFAULT_NOT_UNK_SEL   (1.0 - DEFAULT_UNK_SEL)

Definition at line 56 of file selfuncs.h.

◆ DEFAULT_NUM_DISTINCT

#define DEFAULT_NUM_DISTINCT   200

Definition at line 52 of file selfuncs.h.

◆ DEFAULT_RANGE_INEQ_SEL

#define DEFAULT_RANGE_INEQ_SEL   0.005

Definition at line 40 of file selfuncs.h.

◆ DEFAULT_UNK_SEL

#define DEFAULT_UNK_SEL   0.005

Definition at line 55 of file selfuncs.h.

◆ ReleaseVariableStats

#define ReleaseVariableStats (   vardata)
Value:
do { \
if (HeapTupleIsValid((vardata).statsTuple)) \
(vardata).freefunc((vardata).statsTuple); \
} while(0)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

Definition at line 100 of file selfuncs.h.

◆ SELFLAG_USED_DEFAULT

#define SELFLAG_USED_DEFAULT
Value:
(1 << 0) /* Estimation fell back on one
* of the DEFAULTs as defined
* above. */

Definition at line 76 of file selfuncs.h.

Typedef Documentation

◆ EstimationInfo

◆ get_index_stats_hook_type

typedef bool(* get_index_stats_hook_type) (PlannerInfo *root, Oid indexOid, AttrNumber indexattnum, VariableStatData *vardata)

Definition at line 144 of file selfuncs.h.

◆ get_relation_stats_hook_type

typedef bool(* get_relation_stats_hook_type) (PlannerInfo *root, RangeTblEntry *rte, AttrNumber attnum, VariableStatData *vardata)

Definition at line 139 of file selfuncs.h.

◆ VariableStatData

Function Documentation

◆ add_predicate_to_index_quals()

List * add_predicate_to_index_quals ( IndexOptInfo index,
List indexQuals 
)

Definition at line 7093 of file selfuncs.c.

7094{
7095 List *predExtraQuals = NIL;
7096 ListCell *lc;
7097
7098 if (index->indpred == NIL)
7099 return indexQuals;
7100
7101 foreach(lc, index->indpred)
7102 {
7103 Node *predQual = (Node *) lfirst(lc);
7104 List *oneQual = list_make1(predQual);
7105
7106 if (!predicate_implied_by(oneQual, indexQuals, false))
7107 predExtraQuals = list_concat(predExtraQuals, oneQual);
7108 }
7109 return list_concat(predExtraQuals, indexQuals);
7110}
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:152
Definition: pg_list.h:54
Definition: nodes.h:135
Definition: type.h:96

References lfirst, list_concat(), list_make1, NIL, and predicate_implied_by().

Referenced by btcostestimate(), genericcostestimate(), and gincostestimate().

◆ booltestsel()

Selectivity booltestsel ( PlannerInfo root,
BoolTestType  booltesttype,
Node arg,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1545 of file selfuncs.c.

1547{
1548 VariableStatData vardata;
1549 double selec;
1550
1551 examine_variable(root, arg, varRelid, &vardata);
1552
1553 if (HeapTupleIsValid(vardata.statsTuple))
1554 {
1555 Form_pg_statistic stats;
1556 double freq_null;
1557 AttStatsSlot sslot;
1558
1559 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1560 freq_null = stats->stanullfrac;
1561
1562 if (get_attstatsslot(&sslot, vardata.statsTuple,
1563 STATISTIC_KIND_MCV, InvalidOid,
1565 && sslot.nnumbers > 0)
1566 {
1567 double freq_true;
1568 double freq_false;
1569
1570 /*
1571 * Get first MCV frequency and derive frequency for true.
1572 */
1573 if (DatumGetBool(sslot.values[0]))
1574 freq_true = sslot.numbers[0];
1575 else
1576 freq_true = 1.0 - sslot.numbers[0] - freq_null;
1577
1578 /*
1579 * Next derive frequency for false. Then use these as appropriate
1580 * to derive frequency for each case.
1581 */
1582 freq_false = 1.0 - freq_true - freq_null;
1583
1584 switch (booltesttype)
1585 {
1586 case IS_UNKNOWN:
1587 /* select only NULL values */
1588 selec = freq_null;
1589 break;
1590 case IS_NOT_UNKNOWN:
1591 /* select non-NULL values */
1592 selec = 1.0 - freq_null;
1593 break;
1594 case IS_TRUE:
1595 /* select only TRUE values */
1596 selec = freq_true;
1597 break;
1598 case IS_NOT_TRUE:
1599 /* select non-TRUE values */
1600 selec = 1.0 - freq_true;
1601 break;
1602 case IS_FALSE:
1603 /* select only FALSE values */
1604 selec = freq_false;
1605 break;
1606 case IS_NOT_FALSE:
1607 /* select non-FALSE values */
1608 selec = 1.0 - freq_false;
1609 break;
1610 default:
1611 elog(ERROR, "unrecognized booltesttype: %d",
1612 (int) booltesttype);
1613 selec = 0.0; /* Keep compiler quiet */
1614 break;
1615 }
1616
1617 free_attstatsslot(&sslot);
1618 }
1619 else
1620 {
1621 /*
1622 * No most-common-value info available. Still have null fraction
1623 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1624 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1625 */
1626 switch (booltesttype)
1627 {
1628 case IS_UNKNOWN:
1629 /* select only NULL values */
1630 selec = freq_null;
1631 break;
1632 case IS_NOT_UNKNOWN:
1633 /* select non-NULL values */
1634 selec = 1.0 - freq_null;
1635 break;
1636 case IS_TRUE:
1637 case IS_FALSE:
1638 /* Assume we select half of the non-NULL values */
1639 selec = (1.0 - freq_null) / 2.0;
1640 break;
1641 case IS_NOT_TRUE:
1642 case IS_NOT_FALSE:
1643 /* Assume we select NULLs plus half of the non-NULLs */
1644 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1645 selec = (freq_null + 1.0) / 2.0;
1646 break;
1647 default:
1648 elog(ERROR, "unrecognized booltesttype: %d",
1649 (int) booltesttype);
1650 selec = 0.0; /* Keep compiler quiet */
1651 break;
1652 }
1653 }
1654 }
1655 else
1656 {
1657 /*
1658 * If we can't get variable statistics for the argument, perhaps
1659 * clause_selectivity can do something with it. We ignore the
1660 * possibility of a NULL value when using clause_selectivity, and just
1661 * assume the value is either TRUE or FALSE.
1662 */
1663 switch (booltesttype)
1664 {
1665 case IS_UNKNOWN:
1666 selec = DEFAULT_UNK_SEL;
1667 break;
1668 case IS_NOT_UNKNOWN:
1669 selec = DEFAULT_NOT_UNK_SEL;
1670 break;
1671 case IS_TRUE:
1672 case IS_NOT_FALSE:
1673 selec = (double) clause_selectivity(root, arg,
1674 varRelid,
1675 jointype, sjinfo);
1676 break;
1677 case IS_FALSE:
1678 case IS_NOT_TRUE:
1679 selec = 1.0 - (double) clause_selectivity(root, arg,
1680 varRelid,
1681 jointype, sjinfo);
1682 break;
1683 default:
1684 elog(ERROR, "unrecognized booltesttype: %d",
1685 (int) booltesttype);
1686 selec = 0.0; /* Keep compiler quiet */
1687 break;
1688 }
1689 }
1690
1691 ReleaseVariableStats(vardata);
1692
1693 /* result should be in range, but make sure... */
1694 CLAMP_PROBABILITY(selec);
1695
1696 return (Selectivity) selec;
1697}
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:667
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3484
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3374
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:44
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:43
double Selectivity
Definition: nodes.h:256
void * arg
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:135
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
#define InvalidOid
Definition: postgres_ext.h:35
@ IS_NOT_TRUE
Definition: primnodes.h:1981
@ IS_NOT_FALSE
Definition: primnodes.h:1981
@ IS_NOT_UNKNOWN
Definition: primnodes.h:1981
@ IS_TRUE
Definition: primnodes.h:1981
@ IS_UNKNOWN
Definition: primnodes.h:1981
@ IS_FALSE
Definition: primnodes.h:1981
tree ctl root
Definition: radixtree.h:1857
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:5224
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:56
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:100
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:55
Datum * values
Definition: lsyscache.h:54
float4 * numbers
Definition: lsyscache.h:57
int nnumbers
Definition: lsyscache.h:58
HeapTuple statsTuple
Definition: selfuncs.h:89

References arg, ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, clause_selectivity(), DatumGetBool(), DEFAULT_NOT_UNK_SEL, DEFAULT_UNK_SEL, elog, ERROR, examine_variable(), free_attstatsslot(), get_attstatsslot(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_TRUE, IS_UNKNOWN, AttStatsSlot::nnumbers, AttStatsSlot::numbers, ReleaseVariableStats, root, VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by clause_selectivity_ext().

◆ boolvarsel()

Selectivity boolvarsel ( PlannerInfo root,
Node arg,
int  varRelid 
)

Definition at line 1517 of file selfuncs.c.

1518{
1519 VariableStatData vardata;
1520 double selec;
1521
1522 examine_variable(root, arg, varRelid, &vardata);
1523 if (HeapTupleIsValid(vardata.statsTuple))
1524 {
1525 /*
1526 * A boolean variable V is equivalent to the clause V = 't', so we
1527 * compute the selectivity as if that is what we have.
1528 */
1529 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1530 BoolGetDatum(true), false, true, false);
1531 }
1532 else
1533 {
1534 /* Otherwise, the default estimate is 0.5 */
1535 selec = 0.5;
1536 }
1537 ReleaseVariableStats(vardata);
1538 return selec;
1539}
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
double var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:300

References arg, BoolGetDatum(), examine_variable(), HeapTupleIsValid, InvalidOid, ReleaseVariableStats, root, VariableStatData::statsTuple, and var_eq_const().

Referenced by clause_selectivity_ext().

◆ estimate_array_length()

double estimate_array_length ( PlannerInfo root,
Node arrayexpr 
)

Definition at line 2144 of file selfuncs.c.

2145{
2146 /* look through any binary-compatible relabeling of arrayexpr */
2147 arrayexpr = strip_array_coercion(arrayexpr);
2148
2149 if (arrayexpr && IsA(arrayexpr, Const))
2150 {
2151 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2152 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2153 ArrayType *arrayval;
2154
2155 if (arrayisnull)
2156 return 0;
2157 arrayval = DatumGetArrayTypeP(arraydatum);
2158 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2159 }
2160 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2161 !((ArrayExpr *) arrayexpr)->multidims)
2162 {
2163 return list_length(((ArrayExpr *) arrayexpr)->elements);
2164 }
2165 else if (arrayexpr && root)
2166 {
2167 /* See if we can find any statistics about it */
2168 VariableStatData vardata;
2169 AttStatsSlot sslot;
2170 double nelem = 0;
2171
2172 examine_variable(root, arrayexpr, 0, &vardata);
2173 if (HeapTupleIsValid(vardata.statsTuple))
2174 {
2175 /*
2176 * Found stats, so use the average element count, which is stored
2177 * in the last stanumbers element of the DECHIST statistics.
2178 * Actually that is the average count of *distinct* elements;
2179 * perhaps we should scale it up somewhat?
2180 */
2181 if (get_attstatsslot(&sslot, vardata.statsTuple,
2182 STATISTIC_KIND_DECHIST, InvalidOid,
2184 {
2185 if (sslot.nnumbers > 0)
2186 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2187 free_attstatsslot(&sslot);
2188 }
2189 }
2190 ReleaseVariableStats(vardata);
2191
2192 if (nelem > 0)
2193 return nelem;
2194 }
2195
2196 /* Else use a default guess --- this should match scalararraysel */
2197 return 10;
2198}
#define ARR_NDIM(a)
Definition: array.h:290
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_DIMS(a)
Definition: array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
double clamp_row_est(double nrows)
Definition: costsize.c:213
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
static int list_length(const List *l)
Definition: pg_list.h:152
uintptr_t Datum
Definition: postgres.h:69
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1788

References ARR_DIMS, ARR_NDIM, ArrayGetNItems(), ATTSTATSSLOT_NUMBERS, clamp_row_est(), DatumGetArrayTypeP, examine_variable(), free_attstatsslot(), get_attstatsslot(), HeapTupleIsValid, InvalidOid, IsA, list_length(), AttStatsSlot::nnumbers, AttStatsSlot::numbers, ReleaseVariableStats, root, VariableStatData::statsTuple, and strip_array_coercion().

Referenced by array_unnest_support(), btcostestimate(), cost_qual_eval_walker(), cost_tidscan(), genericcostestimate(), and gincost_scalararrayopexpr().

◆ estimate_hash_bucket_stats()

void estimate_hash_bucket_stats ( PlannerInfo root,
Node hashkey,
double  nbuckets,
Selectivity mcv_freq,
Selectivity bucketsize_frac 
)

Definition at line 4003 of file selfuncs.c.

4006{
4007 VariableStatData vardata;
4008 double estfract,
4009 ndistinct,
4010 stanullfrac,
4011 avgfreq;
4012 bool isdefault;
4013 AttStatsSlot sslot;
4014
4015 examine_variable(root, hashkey, 0, &vardata);
4016
4017 /* Look up the frequency of the most common value, if available */
4018 *mcv_freq = 0.0;
4019
4020 if (HeapTupleIsValid(vardata.statsTuple))
4021 {
4022 if (get_attstatsslot(&sslot, vardata.statsTuple,
4023 STATISTIC_KIND_MCV, InvalidOid,
4025 {
4026 /*
4027 * The first MCV stat is for the most common value.
4028 */
4029 if (sslot.nnumbers > 0)
4030 *mcv_freq = sslot.numbers[0];
4031 free_attstatsslot(&sslot);
4032 }
4033 }
4034
4035 /* Get number of distinct values */
4036 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
4037
4038 /*
4039 * If ndistinct isn't real, punt. We normally return 0.1, but if the
4040 * mcv_freq is known to be even higher than that, use it instead.
4041 */
4042 if (isdefault)
4043 {
4044 *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
4045 ReleaseVariableStats(vardata);
4046 return;
4047 }
4048
4049 /* Get fraction that are null */
4050 if (HeapTupleIsValid(vardata.statsTuple))
4051 {
4052 Form_pg_statistic stats;
4053
4054 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
4055 stanullfrac = stats->stanullfrac;
4056 }
4057 else
4058 stanullfrac = 0.0;
4059
4060 /* Compute avg freq of all distinct data values in raw relation */
4061 avgfreq = (1.0 - stanullfrac) / ndistinct;
4062
4063 /*
4064 * Adjust ndistinct to account for restriction clauses. Observe we are
4065 * assuming that the data distribution is affected uniformly by the
4066 * restriction clauses!
4067 *
4068 * XXX Possibly better way, but much more expensive: multiply by
4069 * selectivity of rel's restriction clauses that mention the target Var.
4070 */
4071 if (vardata.rel && vardata.rel->tuples > 0)
4072 {
4073 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
4074 ndistinct = clamp_row_est(ndistinct);
4075 }
4076
4077 /*
4078 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
4079 * number of buckets is less than the expected number of distinct values;
4080 * otherwise it is 1/ndistinct.
4081 */
4082 if (ndistinct > nbuckets)
4083 estfract = 1.0 / nbuckets;
4084 else
4085 estfract = 1.0 / ndistinct;
4086
4087 /*
4088 * Adjust estimated bucketsize upward to account for skewed distribution.
4089 */
4090 if (avgfreq > 0.0 && *mcv_freq > avgfreq)
4091 estfract *= *mcv_freq / avgfreq;
4092
4093 /*
4094 * Clamp bucketsize to sane range (the above adjustment could easily
4095 * produce an out-of-range result). We set the lower bound a little above
4096 * zero, since zero isn't a very sane result.
4097 */
4098 if (estfract < 1.0e-6)
4099 estfract = 1.0e-6;
4100 else if (estfract > 1.0)
4101 estfract = 1.0;
4102
4103 *bucketsize_frac = (Selectivity) estfract;
4104
4105 ReleaseVariableStats(vardata);
4106}
#define Max(x, y)
Definition: c.h:969
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:6084
Cardinality tuples
Definition: pathnodes.h:976
Cardinality rows
Definition: pathnodes.h:904
RelOptInfo * rel
Definition: selfuncs.h:88

References ATTSTATSSLOT_NUMBERS, clamp_row_est(), examine_variable(), free_attstatsslot(), get_attstatsslot(), get_variable_numdistinct(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, Max, AttStatsSlot::nnumbers, AttStatsSlot::numbers, VariableStatData::rel, ReleaseVariableStats, root, RelOptInfo::rows, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by final_cost_hashjoin().

◆ estimate_hashagg_tablesize()

double estimate_hashagg_tablesize ( PlannerInfo root,
Path path,
const AggClauseCosts agg_costs,
double  dNumGroups 
)

Definition at line 4122 of file selfuncs.c.

4124{
4125 Size hashentrysize;
4126
4127 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4128 path->pathtarget->width,
4129 agg_costs->transitionSpace);
4130
4131 /*
4132 * Note that this disregards the effect of fill-factor and growth policy
4133 * of the hash table. That's probably ok, given that the default
4134 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4135 * "double-in-size" growth policies here.
4136 */
4137 return hashentrysize * dNumGroups;
4138}
size_t Size
Definition: c.h:576
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1701
Size transitionSpace
Definition: pathnodes.h:62

References hash_agg_entry_size(), list_length(), root, and AggClauseCosts::transitionSpace.

Referenced by consider_groupingsets_paths().

◆ estimate_multivariate_bucketsize()

List * estimate_multivariate_bucketsize ( PlannerInfo root,
RelOptInfo inner,
List hashclauses,
Selectivity innerbucketsize 
)

Definition at line 3798 of file selfuncs.c.

3801{
3802 List *clauses = list_copy(hashclauses);
3803 List *otherclauses = NIL;
3804 double ndistinct = 1.0;
3805
3806 if (list_length(hashclauses) <= 1)
3807
3808 /*
3809 * Nothing to do for a single clause. Could we employ univariate
3810 * extended stat here?
3811 */
3812 return hashclauses;
3813
3814 while (clauses != NIL)
3815 {
3816 ListCell *lc;
3817 int relid = -1;
3818 List *varinfos = NIL;
3819 List *origin_rinfos = NIL;
3820 double mvndistinct;
3821 List *origin_varinfos;
3822 int group_relid = -1;
3823 RelOptInfo *group_rel = NULL;
3824 ListCell *lc1,
3825 *lc2;
3826
3827 /*
3828 * Find clauses, referencing the same single base relation and try to
3829 * estimate such a group with extended statistics. Create varinfo for
3830 * an approved clause, push it to otherclauses, if it can't be
3831 * estimated here or ignore to process at the next iteration.
3832 */
3833 foreach(lc, clauses)
3834 {
3836 Node *expr;
3837 Relids relids;
3838 GroupVarInfo *varinfo;
3839
3840 /*
3841 * Find the inner side of the join, which we need to estimate the
3842 * number of buckets. Use outer_is_left because the
3843 * clause_sides_match_join routine has called on hash clauses.
3844 */
3845 relids = rinfo->outer_is_left ?
3846 rinfo->right_relids : rinfo->left_relids;
3847 expr = rinfo->outer_is_left ?
3848 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
3849
3850 if (bms_get_singleton_member(relids, &relid) &&
3851 root->simple_rel_array[relid]->statlist != NIL)
3852 {
3853 /*
3854 * This inner-side expression references only one relation.
3855 * Extended statistics on this clause can exist.
3856 */
3857 if (group_relid < 0)
3858 {
3859 RangeTblEntry *rte = root->simple_rte_array[relid];
3860
3861 if (!rte || (rte->relkind != RELKIND_RELATION &&
3862 rte->relkind != RELKIND_MATVIEW &&
3863 rte->relkind != RELKIND_FOREIGN_TABLE &&
3864 rte->relkind != RELKIND_PARTITIONED_TABLE))
3865 {
3866 /* Extended statistics can't exist in principle */
3867 otherclauses = lappend(otherclauses, rinfo);
3868 clauses = foreach_delete_current(clauses, lc);
3869 continue;
3870 }
3871
3872 group_relid = relid;
3873 group_rel = root->simple_rel_array[relid];
3874 }
3875 else if (group_relid != relid)
3876
3877 /*
3878 * Being in the group forming state we don't need other
3879 * clauses.
3880 */
3881 continue;
3882
3883 varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3884 varinfo->var = expr;
3885 varinfo->rel = root->simple_rel_array[relid];
3886 varinfo->ndistinct = 0.0;
3887 varinfo->isdefault = false;
3888 varinfos = lappend(varinfos, varinfo);
3889
3890 /*
3891 * Remember the link to RestrictInfo for the case the clause
3892 * is failed to be estimated.
3893 */
3894 origin_rinfos = lappend(origin_rinfos, rinfo);
3895 }
3896 else
3897 /* This clause can't be estimated with extended statistics */
3898 otherclauses = lappend(otherclauses, rinfo);
3899
3900 clauses = foreach_delete_current(clauses, lc);
3901 }
3902
3903 if (list_length(varinfos) < 2)
3904 {
3905 /*
3906 * Multivariate statistics doesn't apply to single columns except
3907 * for expressions, but it has not been implemented yet.
3908 */
3909 otherclauses = list_concat(otherclauses, origin_rinfos);
3910 list_free_deep(varinfos);
3911 list_free(origin_rinfos);
3912 continue;
3913 }
3914
3915 Assert(group_rel != NULL);
3916
3917 /* Employ the extended statistics. */
3918 origin_varinfos = varinfos;
3919 for (;;)
3920 {
3921 bool estimated = estimate_multivariate_ndistinct(root,
3922 group_rel,
3923 &varinfos,
3924 &mvndistinct);
3925
3926 if (!estimated)
3927 break;
3928
3929 /*
3930 * We've got an estimation. Use ndistinct value in a consistent
3931 * way - according to the caller's logic (see
3932 * final_cost_hashjoin).
3933 */
3934 if (ndistinct < mvndistinct)
3935 ndistinct = mvndistinct;
3936 Assert(ndistinct >= 1.0);
3937 }
3938
3939 Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
3940
3941 /* Collect unmatched clauses as otherclauses. */
3942 forboth(lc1, origin_varinfos, lc2, origin_rinfos)
3943 {
3944 GroupVarInfo *vinfo = lfirst(lc1);
3945
3946 if (!list_member_ptr(varinfos, vinfo))
3947 /* Already estimated */
3948 continue;
3949
3950 /* Can't be estimated here - push to the returning list */
3951 otherclauses = lappend(otherclauses, lfirst(lc2));
3952 }
3953 }
3954
3955 *innerbucketsize = 1.0 / ndistinct;
3956 return otherclauses;
3957}
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:715
Assert(PointerIsAligned(start, uint64))
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_copy(const List *oldlist)
Definition: list.c:1573
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:682
void list_free(List *list)
Definition: list.c:1546
void list_free_deep(List *list)
Definition: list.c:1560
void * palloc(Size size)
Definition: mcxt.c:1940
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:95
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:83
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
static bool estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
Definition: selfuncs.c:4159
RelOptInfo * rel
Definition: selfuncs.c:3310
double ndistinct
Definition: selfuncs.c:3311
bool isdefault
Definition: selfuncs.c:3312
Node * var
Definition: selfuncs.c:3309
Expr * clause
Definition: pathnodes.h:2700

References Assert(), bms_get_singleton_member(), RestrictInfo::clause, estimate_multivariate_ndistinct(), forboth, foreach_delete_current, get_leftop(), get_rightop(), GroupVarInfo::isdefault, lappend(), lfirst, lfirst_node, list_concat(), list_copy(), list_free(), list_free_deep(), list_length(), list_member_ptr(), GroupVarInfo::ndistinct, NIL, palloc(), GroupVarInfo::rel, root, and GroupVarInfo::var.

Referenced by final_cost_hashjoin().

◆ estimate_num_groups()

double estimate_num_groups ( PlannerInfo root,
List groupExprs,
double  input_rows,
List **  pgset,
EstimationInfo estinfo 
)

Definition at line 3446 of file selfuncs.c.

3448{
3449 List *varinfos = NIL;
3450 double srf_multiplier = 1.0;
3451 double numdistinct;
3452 ListCell *l;
3453 int i;
3454
3455 /* Zero the estinfo output parameter, if non-NULL */
3456 if (estinfo != NULL)
3457 memset(estinfo, 0, sizeof(EstimationInfo));
3458
3459 /*
3460 * We don't ever want to return an estimate of zero groups, as that tends
3461 * to lead to division-by-zero and other unpleasantness. The input_rows
3462 * estimate is usually already at least 1, but clamp it just in case it
3463 * isn't.
3464 */
3465 input_rows = clamp_row_est(input_rows);
3466
3467 /*
3468 * If no grouping columns, there's exactly one group. (This can't happen
3469 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3470 * corner cases with set operations.)
3471 */
3472 if (groupExprs == NIL || (pgset && *pgset == NIL))
3473 return 1.0;
3474
3475 /*
3476 * Count groups derived from boolean grouping expressions. For other
3477 * expressions, find the unique Vars used, treating an expression as a Var
3478 * if we can find stats for it. For each one, record the statistical
3479 * estimate of number of distinct values (total in its table, without
3480 * regard for filtering).
3481 */
3482 numdistinct = 1.0;
3483
3484 i = 0;
3485 foreach(l, groupExprs)
3486 {
3487 Node *groupexpr = (Node *) lfirst(l);
3488 double this_srf_multiplier;
3489 VariableStatData vardata;
3490 List *varshere;
3491 ListCell *l2;
3492
3493 /* is expression in this grouping set? */
3494 if (pgset && !list_member_int(*pgset, i++))
3495 continue;
3496
3497 /*
3498 * Set-returning functions in grouping columns are a bit problematic.
3499 * The code below will effectively ignore their SRF nature and come up
3500 * with a numdistinct estimate as though they were scalar functions.
3501 * We compensate by scaling up the end result by the largest SRF
3502 * rowcount estimate. (This will be an overestimate if the SRF
3503 * produces multiple copies of any output value, but it seems best to
3504 * assume the SRF's outputs are distinct. In any case, it's probably
3505 * pointless to worry too much about this without much better
3506 * estimates for SRF output rowcounts than we have today.)
3507 */
3508 this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3509 if (srf_multiplier < this_srf_multiplier)
3510 srf_multiplier = this_srf_multiplier;
3511
3512 /* Short-circuit for expressions returning boolean */
3513 if (exprType(groupexpr) == BOOLOID)
3514 {
3515 numdistinct *= 2.0;
3516 continue;
3517 }
3518
3519 /*
3520 * If examine_variable is able to deduce anything about the GROUP BY
3521 * expression, treat it as a single variable even if it's really more
3522 * complicated.
3523 *
3524 * XXX This has the consequence that if there's a statistics object on
3525 * the expression, we don't split it into individual Vars. This
3526 * affects our selection of statistics in
3527 * estimate_multivariate_ndistinct, because it's probably better to
3528 * use more accurate estimate for each expression and treat them as
3529 * independent, than to combine estimates for the extracted variables
3530 * when we don't know how that relates to the expressions.
3531 */
3532 examine_variable(root, groupexpr, 0, &vardata);
3533 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3534 {
3535 varinfos = add_unique_group_var(root, varinfos,
3536 groupexpr, &vardata);
3537 ReleaseVariableStats(vardata);
3538 continue;
3539 }
3540 ReleaseVariableStats(vardata);
3541
3542 /*
3543 * Else pull out the component Vars. Handle PlaceHolderVars by
3544 * recursing into their arguments (effectively assuming that the
3545 * PlaceHolderVar doesn't change the number of groups, which boils
3546 * down to ignoring the possible addition of nulls to the result set).
3547 */
3548 varshere = pull_var_clause(groupexpr,
3552
3553 /*
3554 * If we find any variable-free GROUP BY item, then either it is a
3555 * constant (and we can ignore it) or it contains a volatile function;
3556 * in the latter case we punt and assume that each input row will
3557 * yield a distinct group.
3558 */
3559 if (varshere == NIL)
3560 {
3561 if (contain_volatile_functions(groupexpr))
3562 return input_rows;
3563 continue;
3564 }
3565
3566 /*
3567 * Else add variables to varinfos list
3568 */
3569 foreach(l2, varshere)
3570 {
3571 Node *var = (Node *) lfirst(l2);
3572
3573 examine_variable(root, var, 0, &vardata);
3574 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3575 ReleaseVariableStats(vardata);
3576 }
3577 }
3578
3579 /*
3580 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3581 * list.
3582 */
3583 if (varinfos == NIL)
3584 {
3585 /* Apply SRF multiplier as we would do in the long path */
3586 numdistinct *= srf_multiplier;
3587 /* Round off */
3588 numdistinct = ceil(numdistinct);
3589 /* Guard against out-of-range answers */
3590 if (numdistinct > input_rows)
3591 numdistinct = input_rows;
3592 if (numdistinct < 1.0)
3593 numdistinct = 1.0;
3594 return numdistinct;
3595 }
3596
3597 /*
3598 * Group Vars by relation and estimate total numdistinct.
3599 *
3600 * For each iteration of the outer loop, we process the frontmost Var in
3601 * varinfos, plus all other Vars in the same relation. We remove these
3602 * Vars from the newvarinfos list for the next iteration. This is the
3603 * easiest way to group Vars of same rel together.
3604 */
3605 do
3606 {
3607 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3608 RelOptInfo *rel = varinfo1->rel;
3609 double reldistinct = 1;
3610 double relmaxndistinct = reldistinct;
3611 int relvarcount = 0;
3612 List *newvarinfos = NIL;
3613 List *relvarinfos = NIL;
3614
3615 /*
3616 * Split the list of varinfos in two - one for the current rel, one
3617 * for remaining Vars on other rels.
3618 */
3619 relvarinfos = lappend(relvarinfos, varinfo1);
3620 for_each_from(l, varinfos, 1)
3621 {
3622 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3623
3624 if (varinfo2->rel == varinfo1->rel)
3625 {
3626 /* varinfos on current rel */
3627 relvarinfos = lappend(relvarinfos, varinfo2);
3628 }
3629 else
3630 {
3631 /* not time to process varinfo2 yet */
3632 newvarinfos = lappend(newvarinfos, varinfo2);
3633 }
3634 }
3635
3636 /*
3637 * Get the numdistinct estimate for the Vars of this rel. We
3638 * iteratively search for multivariate n-distinct with maximum number
3639 * of vars; assuming that each var group is independent of the others,
3640 * we multiply them together. Any remaining relvarinfos after no more
3641 * multivariate matches are found are assumed independent too, so
3642 * their individual ndistinct estimates are multiplied also.
3643 *
3644 * While iterating, count how many separate numdistinct values we
3645 * apply. We apply a fudge factor below, but only if we multiplied
3646 * more than one such values.
3647 */
3648 while (relvarinfos)
3649 {
3650 double mvndistinct;
3651
3652 if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3653 &mvndistinct))
3654 {
3655 reldistinct *= mvndistinct;
3656 if (relmaxndistinct < mvndistinct)
3657 relmaxndistinct = mvndistinct;
3658 relvarcount++;
3659 }
3660 else
3661 {
3662 foreach(l, relvarinfos)
3663 {
3664 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3665
3666 reldistinct *= varinfo2->ndistinct;
3667 if (relmaxndistinct < varinfo2->ndistinct)
3668 relmaxndistinct = varinfo2->ndistinct;
3669 relvarcount++;
3670
3671 /*
3672 * When varinfo2's isdefault is set then we'd better set
3673 * the SELFLAG_USED_DEFAULT bit in the EstimationInfo.
3674 */
3675 if (estinfo != NULL && varinfo2->isdefault)
3676 estinfo->flags |= SELFLAG_USED_DEFAULT;
3677 }
3678
3679 /* we're done with this relation */
3680 relvarinfos = NIL;
3681 }
3682 }
3683
3684 /*
3685 * Sanity check --- don't divide by zero if empty relation.
3686 */
3687 Assert(IS_SIMPLE_REL(rel));
3688 if (rel->tuples > 0)
3689 {
3690 /*
3691 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3692 * fudge factor is because the Vars are probably correlated but we
3693 * don't know by how much. We should never clamp to less than the
3694 * largest ndistinct value for any of the Vars, though, since
3695 * there will surely be at least that many groups.
3696 */
3697 double clamp = rel->tuples;
3698
3699 if (relvarcount > 1)
3700 {
3701 clamp *= 0.1;
3702 if (clamp < relmaxndistinct)
3703 {
3704 clamp = relmaxndistinct;
3705 /* for sanity in case some ndistinct is too large: */
3706 if (clamp > rel->tuples)
3707 clamp = rel->tuples;
3708 }
3709 }
3710 if (reldistinct > clamp)
3711 reldistinct = clamp;
3712
3713 /*
3714 * Update the estimate based on the restriction selectivity,
3715 * guarding against division by zero when reldistinct is zero.
3716 * Also skip this if we know that we are returning all rows.
3717 */
3718 if (reldistinct > 0 && rel->rows < rel->tuples)
3719 {
3720 /*
3721 * Given a table containing N rows with n distinct values in a
3722 * uniform distribution, if we select p rows at random then
3723 * the expected number of distinct values selected is
3724 *
3725 * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3726 *
3727 * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3728 *
3729 * See "Approximating block accesses in database
3730 * organizations", S. B. Yao, Communications of the ACM,
3731 * Volume 20 Issue 4, April 1977 Pages 260-261.
3732 *
3733 * Alternatively, re-arranging the terms from the factorials,
3734 * this may be written as
3735 *
3736 * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3737 *
3738 * This form of the formula is more efficient to compute in
3739 * the common case where p is larger than N/n. Additionally,
3740 * as pointed out by Dell'Era, if i << N for all terms in the
3741 * product, it can be approximated by
3742 *
3743 * n * (1 - ((N-p)/N)^(N/n))
3744 *
3745 * See "Expected distinct values when selecting from a bag
3746 * without replacement", Alberto Dell'Era,
3747 * http://www.adellera.it/investigations/distinct_balls/.
3748 *
3749 * The condition i << N is equivalent to n >> 1, so this is a
3750 * good approximation when the number of distinct values in
3751 * the table is large. It turns out that this formula also
3752 * works well even when n is small.
3753 */
3754 reldistinct *=
3755 (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3756 rel->tuples / reldistinct));
3757 }
3758 reldistinct = clamp_row_est(reldistinct);
3759
3760 /*
3761 * Update estimate of total distinct groups.
3762 */
3763 numdistinct *= reldistinct;
3764 }
3765
3766 varinfos = newvarinfos;
3767 } while (varinfos != NIL);
3768
3769 /* Now we can account for the effects of any SRFs */
3770 numdistinct *= srf_multiplier;
3771
3772 /* Round off */
3773 numdistinct = ceil(numdistinct);
3774
3775 /* Guard against out-of-range answers */
3776 if (numdistinct > input_rows)
3777 numdistinct = input_rows;
3778 if (numdistinct < 1.0)
3779 numdistinct = 1.0;
3780
3781 return numdistinct;
3782}
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:539
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:290
int i
Definition: isn.c:77
bool list_member_int(const List *list, int datum)
Definition: list.c:702
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:193
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:197
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:195
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:866
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178
static List * add_unique_group_var(PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
Definition: selfuncs.c:3316
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
uint32 flags
Definition: selfuncs.h:80
List * pull_var_clause(Node *node, int flags)
Definition: var.c:653

References add_unique_group_var(), Assert(), clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), expression_returns_set_rows(), exprType(), EstimationInfo::flags, for_each_from, HeapTupleIsValid, i, IS_SIMPLE_REL, GroupVarInfo::isdefault, VariableStatData::isunique, lappend(), lfirst, linitial, list_member_int(), GroupVarInfo::ndistinct, NIL, pull_var_clause(), PVC_RECURSE_AGGREGATES, PVC_RECURSE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, GroupVarInfo::rel, ReleaseVariableStats, root, RelOptInfo::rows, SELFLAG_USED_DEFAULT, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by adjust_rowcount_for_semijoins(), build_setop_child_paths(), cost_incremental_sort(), cost_memoize_rescan(), create_final_distinct_paths(), create_partial_distinct_paths(), create_unique_path(), estimate_path_cost_size(), get_number_of_groups(), and get_windowclause_startup_tuples().

◆ examine_variable()

void examine_variable ( PlannerInfo root,
Node node,
int  varRelid,
VariableStatData vardata 
)

Definition at line 5224 of file selfuncs.c.

5226{
5227 Node *basenode;
5228 Relids varnos;
5229 Relids basevarnos;
5230 RelOptInfo *onerel;
5231
5232 /* Make sure we don't return dangling pointers in vardata */
5233 MemSet(vardata, 0, sizeof(VariableStatData));
5234
5235 /* Save the exposed type of the expression */
5236 vardata->vartype = exprType(node);
5237
5238 /* Look inside any binary-compatible relabeling */
5239
5240 if (IsA(node, RelabelType))
5241 basenode = (Node *) ((RelabelType *) node)->arg;
5242 else
5243 basenode = node;
5244
5245 /* Fast path for a simple Var */
5246
5247 if (IsA(basenode, Var) &&
5248 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5249 {
5250 Var *var = (Var *) basenode;
5251
5252 /* Set up result fields other than the stats tuple */
5253 vardata->var = basenode; /* return Var without relabeling */
5254 vardata->rel = find_base_rel(root, var->varno);
5255 vardata->atttype = var->vartype;
5256 vardata->atttypmod = var->vartypmod;
5257 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5258
5259 /* Try to locate some stats */
5260 examine_simple_variable(root, var, vardata);
5261
5262 return;
5263 }
5264
5265 /*
5266 * Okay, it's a more complicated expression. Determine variable
5267 * membership. Note that when varRelid isn't zero, only vars of that
5268 * relation are considered "real" vars.
5269 */
5270 varnos = pull_varnos(root, basenode);
5271 basevarnos = bms_difference(varnos, root->outer_join_rels);
5272
5273 onerel = NULL;
5274
5275 if (bms_is_empty(basevarnos))
5276 {
5277 /* No Vars at all ... must be pseudo-constant clause */
5278 }
5279 else
5280 {
5281 int relid;
5282
5283 /* Check if the expression is in vars of a single base relation */
5284 if (bms_get_singleton_member(basevarnos, &relid))
5285 {
5286 if (varRelid == 0 || varRelid == relid)
5287 {
5288 onerel = find_base_rel(root, relid);
5289 vardata->rel = onerel;
5290 node = basenode; /* strip any relabeling */
5291 }
5292 /* else treat it as a constant */
5293 }
5294 else
5295 {
5296 /* varnos has multiple relids */
5297 if (varRelid == 0)
5298 {
5299 /* treat it as a variable of a join relation */
5300 vardata->rel = find_join_rel(root, varnos);
5301 node = basenode; /* strip any relabeling */
5302 }
5303 else if (bms_is_member(varRelid, varnos))
5304 {
5305 /* ignore the vars belonging to other relations */
5306 vardata->rel = find_base_rel(root, varRelid);
5307 node = basenode; /* strip any relabeling */
5308 /* note: no point in expressional-index search here */
5309 }
5310 /* else treat it as a constant */
5311 }
5312 }
5313
5314 bms_free(basevarnos);
5315
5316 vardata->var = node;
5317 vardata->atttype = exprType(node);
5318 vardata->atttypmod = exprTypmod(node);
5319
5320 if (onerel)
5321 {
5322 /*
5323 * We have an expression in vars of a single relation. Try to match
5324 * it to expressional index columns, in hopes of finding some
5325 * statistics.
5326 *
5327 * Note that we consider all index columns including INCLUDE columns,
5328 * since there could be stats for such columns. But the test for
5329 * uniqueness needs to be warier.
5330 *
5331 * XXX it's conceivable that there are multiple matches with different
5332 * index opfamilies; if so, we need to pick one that matches the
5333 * operator we are estimating for. FIXME later.
5334 */
5335 ListCell *ilist;
5336 ListCell *slist;
5337 Oid userid;
5338
5339 /*
5340 * The nullingrels bits within the expression could prevent us from
5341 * matching it to expressional index columns or to the expressions in
5342 * extended statistics. So strip them out first.
5343 */
5344 if (bms_overlap(varnos, root->outer_join_rels))
5345 node = remove_nulling_relids(node, root->outer_join_rels, NULL);
5346
5347 /*
5348 * Determine the user ID to use for privilege checks: either
5349 * onerel->userid if it's set (e.g., in case we're accessing the table
5350 * via a view), or the current user otherwise.
5351 *
5352 * If we drill down to child relations, we keep using the same userid:
5353 * it's going to be the same anyway, due to how we set up the relation
5354 * tree (q.v. build_simple_rel).
5355 */
5356 userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5357
5358 foreach(ilist, onerel->indexlist)
5359 {
5360 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5361 ListCell *indexpr_item;
5362 int pos;
5363
5364 indexpr_item = list_head(index->indexprs);
5365 if (indexpr_item == NULL)
5366 continue; /* no expressions here... */
5367
5368 for (pos = 0; pos < index->ncolumns; pos++)
5369 {
5370 if (index->indexkeys[pos] == 0)
5371 {
5372 Node *indexkey;
5373
5374 if (indexpr_item == NULL)
5375 elog(ERROR, "too few entries in indexprs list");
5376 indexkey = (Node *) lfirst(indexpr_item);
5377 if (indexkey && IsA(indexkey, RelabelType))
5378 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5379 if (equal(node, indexkey))
5380 {
5381 /*
5382 * Found a match ... is it a unique index? Tests here
5383 * should match has_unique_index().
5384 */
5385 if (index->unique &&
5386 index->nkeycolumns == 1 &&
5387 pos == 0 &&
5388 (index->indpred == NIL || index->predOK))
5389 vardata->isunique = true;
5390
5391 /*
5392 * Has it got stats? We only consider stats for
5393 * non-partial indexes, since partial indexes probably
5394 * don't reflect whole-relation statistics; the above
5395 * check for uniqueness is the only info we take from
5396 * a partial index.
5397 *
5398 * An index stats hook, however, must make its own
5399 * decisions about what to do with partial indexes.
5400 */
5402 (*get_index_stats_hook) (root, index->indexoid,
5403 pos + 1, vardata))
5404 {
5405 /*
5406 * The hook took control of acquiring a stats
5407 * tuple. If it did supply a tuple, it'd better
5408 * have supplied a freefunc.
5409 */
5410 if (HeapTupleIsValid(vardata->statsTuple) &&
5411 !vardata->freefunc)
5412 elog(ERROR, "no function provided to release variable stats with");
5413 }
5414 else if (index->indpred == NIL)
5415 {
5416 vardata->statsTuple =
5417 SearchSysCache3(STATRELATTINH,
5418 ObjectIdGetDatum(index->indexoid),
5419 Int16GetDatum(pos + 1),
5420 BoolGetDatum(false));
5421 vardata->freefunc = ReleaseSysCache;
5422
5423 if (HeapTupleIsValid(vardata->statsTuple))
5424 {
5425 /* Get index's table for permission check */
5426 RangeTblEntry *rte;
5427
5428 rte = planner_rt_fetch(index->rel->relid, root);
5429 Assert(rte->rtekind == RTE_RELATION);
5430
5431 /*
5432 * For simplicity, we insist on the whole
5433 * table being selectable, rather than trying
5434 * to identify which column(s) the index
5435 * depends on. Also require all rows to be
5436 * selectable --- there must be no
5437 * securityQuals from security barrier views
5438 * or RLS policies.
5439 */
5440 vardata->acl_ok =
5441 rte->securityQuals == NIL &&
5442 (pg_class_aclcheck(rte->relid, userid,
5444
5445 /*
5446 * If the user doesn't have permissions to
5447 * access an inheritance child relation, check
5448 * the permissions of the table actually
5449 * mentioned in the query, since most likely
5450 * the user does have that permission. Note
5451 * that whole-table select privilege on the
5452 * parent doesn't quite guarantee that the
5453 * user could read all columns of the child.
5454 * But in practice it's unlikely that any
5455 * interesting security violation could result
5456 * from allowing access to the expression
5457 * index's stats, so we allow it anyway. See
5458 * similar code in examine_simple_variable()
5459 * for additional comments.
5460 */
5461 if (!vardata->acl_ok &&
5462 root->append_rel_array != NULL)
5463 {
5464 AppendRelInfo *appinfo;
5465 Index varno = index->rel->relid;
5466
5467 appinfo = root->append_rel_array[varno];
5468 while (appinfo &&
5470 root)->rtekind == RTE_RELATION)
5471 {
5472 varno = appinfo->parent_relid;
5473 appinfo = root->append_rel_array[varno];
5474 }
5475 if (varno != index->rel->relid)
5476 {
5477 /* Repeat access check on this rel */
5478 rte = planner_rt_fetch(varno, root);
5479 Assert(rte->rtekind == RTE_RELATION);
5480
5481 vardata->acl_ok =
5482 rte->securityQuals == NIL &&
5483 (pg_class_aclcheck(rte->relid,
5484 userid,
5486 }
5487 }
5488 }
5489 else
5490 {
5491 /* suppress leakproofness checks later */
5492 vardata->acl_ok = true;
5493 }
5494 }
5495 if (vardata->statsTuple)
5496 break;
5497 }
5498 indexpr_item = lnext(index->indexprs, indexpr_item);
5499 }
5500 }
5501 if (vardata->statsTuple)
5502 break;
5503 }
5504
5505 /*
5506 * Search extended statistics for one with a matching expression.
5507 * There might be multiple ones, so just grab the first one. In the
5508 * future, we might consider the statistics target (and pick the most
5509 * accurate statistics) and maybe some other parameters.
5510 */
5511 foreach(slist, onerel->statlist)
5512 {
5513 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5514 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5515 ListCell *expr_item;
5516 int pos;
5517
5518 /*
5519 * Stop once we've found statistics for the expression (either
5520 * from extended stats, or for an index in the preceding loop).
5521 */
5522 if (vardata->statsTuple)
5523 break;
5524
5525 /* skip stats without per-expression stats */
5526 if (info->kind != STATS_EXT_EXPRESSIONS)
5527 continue;
5528
5529 /* skip stats with mismatching stxdinherit value */
5530 if (info->inherit != rte->inh)
5531 continue;
5532
5533 pos = 0;
5534 foreach(expr_item, info->exprs)
5535 {
5536 Node *expr = (Node *) lfirst(expr_item);
5537
5538 Assert(expr);
5539
5540 /* strip RelabelType before comparing it */
5541 if (expr && IsA(expr, RelabelType))
5542 expr = (Node *) ((RelabelType *) expr)->arg;
5543
5544 /* found a match, see if we can extract pg_statistic row */
5545 if (equal(node, expr))
5546 {
5547 /*
5548 * XXX Not sure if we should cache the tuple somewhere.
5549 * Now we just create a new copy every time.
5550 */
5551 vardata->statsTuple =
5552 statext_expressions_load(info->statOid, rte->inh, pos);
5553
5554 vardata->freefunc = ReleaseDummy;
5555
5556 /*
5557 * For simplicity, we insist on the whole table being
5558 * selectable, rather than trying to identify which
5559 * column(s) the statistics object depends on. Also
5560 * require all rows to be selectable --- there must be no
5561 * securityQuals from security barrier views or RLS
5562 * policies.
5563 */
5564 vardata->acl_ok =
5565 rte->securityQuals == NIL &&
5566 (pg_class_aclcheck(rte->relid, userid,
5568
5569 /*
5570 * If the user doesn't have permissions to access an
5571 * inheritance child relation, check the permissions of
5572 * the table actually mentioned in the query, since most
5573 * likely the user does have that permission. Note that
5574 * whole-table select privilege on the parent doesn't
5575 * quite guarantee that the user could read all columns of
5576 * the child. But in practice it's unlikely that any
5577 * interesting security violation could result from
5578 * allowing access to the expression stats, so we allow it
5579 * anyway. See similar code in examine_simple_variable()
5580 * for additional comments.
5581 */
5582 if (!vardata->acl_ok &&
5583 root->append_rel_array != NULL)
5584 {
5585 AppendRelInfo *appinfo;
5586 Index varno = onerel->relid;
5587
5588 appinfo = root->append_rel_array[varno];
5589 while (appinfo &&
5591 root)->rtekind == RTE_RELATION)
5592 {
5593 varno = appinfo->parent_relid;
5594 appinfo = root->append_rel_array[varno];
5595 }
5596 if (varno != onerel->relid)
5597 {
5598 /* Repeat access check on this rel */
5599 rte = planner_rt_fetch(varno, root);
5600 Assert(rte->rtekind == RTE_RELATION);
5601
5602 vardata->acl_ok =
5603 rte->securityQuals == NIL &&
5604 (pg_class_aclcheck(rte->relid,
5605 userid,
5607 }
5608 }
5609
5610 break;
5611 }
5612
5613 pos++;
5614 }
5615 }
5616 }
5617
5618 bms_free(varnos);
5619}
@ ACLCHECK_OK
Definition: acl.h:183
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:346
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
#define bms_is_empty(a)
Definition: bitmapset.h:118
unsigned int Index
Definition: c.h:585
#define MemSet(start, val, len)
Definition: c.h:991
#define OidIsValid(objectId)
Definition: c.h:746
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
HeapTuple statext_expressions_load(Oid stxoid, bool inh, int idx)
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
Oid GetUserId(void)
Definition: miscinit.c:520
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
@ RTE_RELATION
Definition: parsenodes.h:1026
#define ACL_SELECT
Definition: parsenodes.h:77
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:597
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2230
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:177
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
unsigned int Oid
Definition: postgres_ext.h:30
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:414
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:527
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5631
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:149
static void ReleaseDummy(HeapTuple tuple)
Definition: selfuncs.c:5183
Index parent_relid
Definition: pathnodes.h:3105
RTEKind rtekind
Definition: parsenodes.h:1061
Index relid
Definition: pathnodes.h:945
List * statlist
Definition: pathnodes.h:973
List * indexlist
Definition: pathnodes.h:971
Oid userid
Definition: pathnodes.h:993
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274
int varno
Definition: primnodes.h:269
int32 atttypmod
Definition: selfuncs.h:94
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:91
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:243
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:114

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, arg, Assert(), VariableStatData::atttype, VariableStatData::atttypmod, bms_difference(), bms_free(), bms_get_singleton_member(), bms_is_empty, bms_is_member(), bms_overlap(), BoolGetDatum(), elog, equal(), ERROR, examine_simple_variable(), StatisticExtInfo::exprs, exprType(), exprTypmod(), find_base_rel(), find_join_rel(), VariableStatData::freefunc, get_index_stats_hook, GetUserId(), has_unique_index(), HeapTupleIsValid, if(), RelOptInfo::indexlist, RangeTblEntry::inh, StatisticExtInfo::inherit, Int16GetDatum(), IsA, VariableStatData::isunique, StatisticExtInfo::kind, lfirst, list_head(), lnext(), MemSet, NIL, ObjectIdGetDatum(), OidIsValid, AppendRelInfo::parent_relid, pg_class_aclcheck(), planner_rt_fetch, pull_varnos(), VariableStatData::rel, ReleaseDummy(), ReleaseSysCache(), RelOptInfo::relid, remove_nulling_relids(), root, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), statext_expressions_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, VariableStatData::statsTuple, RelOptInfo::userid, VariableStatData::var, Var::varattno, Var::varno, and VariableStatData::vartype.

Referenced by booltestsel(), boolvarsel(), estimate_array_length(), estimate_hash_bucket_stats(), estimate_num_groups(), get_join_variables(), get_restriction_variable(), mergejoinscansel(), nulltestsel(), and scalararraysel_containment().

◆ generic_restriction_selectivity()

double generic_restriction_selectivity ( PlannerInfo root,
Oid  oproid,
Oid  collation,
List args,
int  varRelid,
double  default_selectivity 
)

Definition at line 919 of file selfuncs.c.

922{
923 double selec;
924 VariableStatData vardata;
925 Node *other;
926 bool varonleft;
927
928 /*
929 * If expression is not variable OP something or something OP variable,
930 * then punt and return the default estimate.
931 */
932 if (!get_restriction_variable(root, args, varRelid,
933 &vardata, &other, &varonleft))
934 return default_selectivity;
935
936 /*
937 * If the something is a NULL constant, assume operator is strict and
938 * return zero, ie, operator will never return TRUE.
939 */
940 if (IsA(other, Const) &&
941 ((Const *) other)->constisnull)
942 {
943 ReleaseVariableStats(vardata);
944 return 0.0;
945 }
946
947 if (IsA(other, Const))
948 {
949 /* Variable is being compared to a known non-null constant */
950 Datum constval = ((Const *) other)->constvalue;
951 FmgrInfo opproc;
952 double mcvsum;
953 double mcvsel;
954 double nullfrac;
955 int hist_size;
956
957 fmgr_info(get_opcode(oproid), &opproc);
958
959 /*
960 * Calculate the selectivity for the column's most common values.
961 */
962 mcvsel = mcv_selectivity(&vardata, &opproc, collation,
963 constval, varonleft,
964 &mcvsum);
965
966 /*
967 * If the histogram is large enough, see what fraction of it matches
968 * the query, and assume that's representative of the non-MCV
969 * population. Otherwise use the default selectivity for the non-MCV
970 * population.
971 */
972 selec = histogram_selectivity(&vardata, &opproc, collation,
973 constval, varonleft,
974 10, 1, &hist_size);
975 if (selec < 0)
976 {
977 /* Nope, fall back on default */
978 selec = default_selectivity;
979 }
980 else if (hist_size < 100)
981 {
982 /*
983 * For histogram sizes from 10 to 100, we combine the histogram
984 * and default selectivities, putting increasingly more trust in
985 * the histogram for larger sizes.
986 */
987 double hist_weight = hist_size / 100.0;
988
989 selec = selec * hist_weight +
990 default_selectivity * (1.0 - hist_weight);
991 }
992
993 /* In any case, don't believe extremely small or large estimates. */
994 if (selec < 0.0001)
995 selec = 0.0001;
996 else if (selec > 0.9999)
997 selec = 0.9999;
998
999 /* Don't forget to account for nulls. */
1000 if (HeapTupleIsValid(vardata.statsTuple))
1001 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1002 else
1003 nullfrac = 0.0;
1004
1005 /*
1006 * Now merge the results from the MCV and histogram calculations,
1007 * realizing that the histogram covers only the non-null values that
1008 * are not listed in MCV.
1009 */
1010 selec *= 1.0 - nullfrac - mcvsum;
1011 selec += mcvsel;
1012 }
1013 else
1014 {
1015 /* Comparison value is not constant, so we can't do anything */
1016 selec = default_selectivity;
1017 }
1018
1019 ReleaseVariableStats(vardata);
1020
1021 /* result should be in range, but make sure... */
1022 CLAMP_PROBABILITY(selec);
1023
1024 return selec;
1025}
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1425
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:5095
double mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
Definition: selfuncs.c:737
double histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
Definition: selfuncs.c:828
Definition: fmgr.h:57

References generate_unaccent_rules::args, CLAMP_PROBABILITY, fmgr_info(), get_opcode(), get_restriction_variable(), GETSTRUCT(), HeapTupleIsValid, histogram_selectivity(), IsA, mcv_selectivity(), ReleaseVariableStats, root, and VariableStatData::statsTuple.

Referenced by ltreeparentsel(), and matchingsel().

◆ genericcostestimate()

void genericcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
GenericCosts costs 
)

Definition at line 6870 of file selfuncs.c.

6874{
6875 IndexOptInfo *index = path->indexinfo;
6876 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6877 List *indexOrderBys = path->indexorderbys;
6878 Cost indexStartupCost;
6879 Cost indexTotalCost;
6880 Selectivity indexSelectivity;
6881 double indexCorrelation;
6882 double numIndexPages;
6883 double numIndexTuples;
6884 double spc_random_page_cost;
6885 double num_sa_scans;
6886 double num_outer_scans;
6887 double num_scans;
6888 double qual_op_cost;
6889 double qual_arg_cost;
6890 List *selectivityQuals;
6891 ListCell *l;
6892
6893 /*
6894 * If the index is partial, AND the index predicate with the explicitly
6895 * given indexquals to produce a more accurate idea of the index
6896 * selectivity.
6897 */
6898 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6899
6900 /*
6901 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
6902 * just assume that the number of index descents is the number of distinct
6903 * combinations of array elements from all of the scan's SAOP clauses.
6904 */
6905 num_sa_scans = costs->num_sa_scans;
6906 if (num_sa_scans < 1)
6907 {
6908 num_sa_scans = 1;
6909 foreach(l, indexQuals)
6910 {
6911 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6912
6913 if (IsA(rinfo->clause, ScalarArrayOpExpr))
6914 {
6915 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6916 double alength = estimate_array_length(root, lsecond(saop->args));
6917
6918 if (alength > 1)
6919 num_sa_scans *= alength;
6920 }
6921 }
6922 }
6923
6924 /* Estimate the fraction of main-table tuples that will be visited */
6925 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6926 index->rel->relid,
6927 JOIN_INNER,
6928 NULL);
6929
6930 /*
6931 * If caller didn't give us an estimate, estimate the number of index
6932 * tuples that will be visited. We do it in this rather peculiar-looking
6933 * way in order to get the right answer for partial indexes.
6934 */
6935 numIndexTuples = costs->numIndexTuples;
6936 if (numIndexTuples <= 0.0)
6937 {
6938 numIndexTuples = indexSelectivity * index->rel->tuples;
6939
6940 /*
6941 * The above calculation counts all the tuples visited across all
6942 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6943 * average per-indexscan number, so adjust. This is a handy place to
6944 * round to integer, too. (If caller supplied tuple estimate, it's
6945 * responsible for handling these considerations.)
6946 */
6947 numIndexTuples = rint(numIndexTuples / num_sa_scans);
6948 }
6949
6950 /*
6951 * We can bound the number of tuples by the index size in any case. Also,
6952 * always estimate at least one tuple is touched, even when
6953 * indexSelectivity estimate is tiny.
6954 */
6955 if (numIndexTuples > index->tuples)
6956 numIndexTuples = index->tuples;
6957 if (numIndexTuples < 1.0)
6958 numIndexTuples = 1.0;
6959
6960 /*
6961 * Estimate the number of index pages that will be retrieved.
6962 *
6963 * We use the simplistic method of taking a pro-rata fraction of the total
6964 * number of index pages. In effect, this counts only leaf pages and not
6965 * any overhead such as index metapage or upper tree levels.
6966 *
6967 * In practice access to upper index levels is often nearly free because
6968 * those tend to stay in cache under load; moreover, the cost involved is
6969 * highly dependent on index type. We therefore ignore such costs here
6970 * and leave it to the caller to add a suitable charge if needed.
6971 */
6972 if (index->pages > 1 && index->tuples > 1)
6973 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6974 else
6975 numIndexPages = 1.0;
6976
6977 /* fetch estimated page cost for tablespace containing index */
6978 get_tablespace_page_costs(index->reltablespace,
6979 &spc_random_page_cost,
6980 NULL);
6981
6982 /*
6983 * Now compute the disk access costs.
6984 *
6985 * The above calculations are all per-index-scan. However, if we are in a
6986 * nestloop inner scan, we can expect the scan to be repeated (with
6987 * different search keys) for each row of the outer relation. Likewise,
6988 * ScalarArrayOpExpr quals result in multiple index scans. This creates
6989 * the potential for cache effects to reduce the number of disk page
6990 * fetches needed. We want to estimate the average per-scan I/O cost in
6991 * the presence of caching.
6992 *
6993 * We use the Mackert-Lohman formula (see costsize.c for details) to
6994 * estimate the total number of page fetches that occur. While this
6995 * wasn't what it was designed for, it seems a reasonable model anyway.
6996 * Note that we are counting pages not tuples anymore, so we take N = T =
6997 * index size, as if there were one "tuple" per page.
6998 */
6999 num_outer_scans = loop_count;
7000 num_scans = num_sa_scans * num_outer_scans;
7001
7002 if (num_scans > 1)
7003 {
7004 double pages_fetched;
7005
7006 /* total page fetches ignoring cache effects */
7007 pages_fetched = numIndexPages * num_scans;
7008
7009 /* use Mackert and Lohman formula to adjust for cache effects */
7010 pages_fetched = index_pages_fetched(pages_fetched,
7011 index->pages,
7012 (double) index->pages,
7013 root);
7014
7015 /*
7016 * Now compute the total disk access cost, and then report a pro-rated
7017 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7018 * since that's internal to the indexscan.)
7019 */
7020 indexTotalCost = (pages_fetched * spc_random_page_cost)
7021 / num_outer_scans;
7022 }
7023 else
7024 {
7025 /*
7026 * For a single index scan, we just charge spc_random_page_cost per
7027 * page touched.
7028 */
7029 indexTotalCost = numIndexPages * spc_random_page_cost;
7030 }
7031
7032 /*
7033 * CPU cost: any complex expressions in the indexquals will need to be
7034 * evaluated once at the start of the scan to reduce them to runtime keys
7035 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7036 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7037 * indexqual operator. Because we have numIndexTuples as a per-scan
7038 * number, we have to multiply by num_sa_scans to get the correct result
7039 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7040 * ORDER BY expressions.
7041 *
7042 * Note: this neglects the possible costs of rechecking lossy operators.
7043 * Detecting that that might be needed seems more expensive than it's
7044 * worth, though, considering all the other inaccuracies here ...
7045 */
7046 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
7047 index_other_operands_eval_cost(root, indexOrderBys);
7048 qual_op_cost = cpu_operator_cost *
7049 (list_length(indexQuals) + list_length(indexOrderBys));
7050
7051 indexStartupCost = qual_arg_cost;
7052 indexTotalCost += qual_arg_cost;
7053 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7054
7055 /*
7056 * Generic assumption about index correlation: there isn't any.
7057 */
7058 indexCorrelation = 0.0;
7059
7060 /*
7061 * Return everything to caller.
7062 */
7063 costs->indexStartupCost = indexStartupCost;
7064 costs->indexTotalCost = indexTotalCost;
7065 costs->indexSelectivity = indexSelectivity;
7066 costs->indexCorrelation = indexCorrelation;
7067 costs->numIndexPages = numIndexPages;
7068 costs->numIndexTuples = numIndexTuples;
7069 costs->spc_random_page_cost = spc_random_page_cost;
7070 costs->num_sa_scans = num_sa_scans;
7071}
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
double cpu_operator_cost
Definition: costsize.c:134
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:908
double cpu_index_tuple_cost
Definition: costsize.c:133
double Cost
Definition: nodes.h:257
@ JOIN_INNER
Definition: nodes.h:299
#define lsecond(l)
Definition: pg_list.h:183
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:6786
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:7093
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2144
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6816
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Selectivity indexSelectivity
Definition: selfuncs.h:128
Cost indexStartupCost
Definition: selfuncs.h:126
double indexCorrelation
Definition: selfuncs.h:129
double spc_random_page_cost
Definition: selfuncs.h:134
double num_sa_scans
Definition: selfuncs.h:135
Cost indexTotalCost
Definition: selfuncs.h:127
double numIndexPages
Definition: selfuncs.h:132
double numIndexTuples
Definition: selfuncs.h:133
List * indexclauses
Definition: pathnodes.h:1848
List * indexorderbys
Definition: pathnodes.h:1849
IndexOptInfo * indexinfo
Definition: pathnodes.h:1847

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, RestrictInfo::clause, clauselist_selectivity(), cpu_index_tuple_cost, cpu_operator_cost, estimate_array_length(), get_quals_from_indexclauses(), get_tablespace_page_costs(), index_other_operands_eval_cost(), index_pages_fetched(), IndexPath::indexclauses, GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexPath::indexorderbys, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, IsA, JOIN_INNER, lfirst, list_length(), lsecond, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, root, and GenericCosts::spc_random_page_cost.

Referenced by blcostestimate(), btcostestimate(), gistcostestimate(), hashcostestimate(), and spgcostestimate().

◆ get_join_variables()

void get_join_variables ( PlannerInfo root,
List args,
SpecialJoinInfo sjinfo,
VariableStatData vardata1,
VariableStatData vardata2,
bool *  join_is_reversed 
)

Definition at line 5155 of file selfuncs.c.

5158{
5159 Node *left,
5160 *right;
5161
5162 if (list_length(args) != 2)
5163 elog(ERROR, "join operator should take two arguments");
5164
5165 left = (Node *) linitial(args);
5166 right = (Node *) lsecond(args);
5167
5168 examine_variable(root, left, 0, vardata1);
5169 examine_variable(root, right, 0, vardata2);
5170
5171 if (vardata1->rel &&
5172 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5173 *join_is_reversed = true; /* var1 is on RHS */
5174 else if (vardata2->rel &&
5175 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5176 *join_is_reversed = true; /* var2 is on LHS */
5177 else
5178 *join_is_reversed = false;
5179}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Relids relids
Definition: pathnodes.h:898
Relids syn_lefthand
Definition: pathnodes.h:3032
Relids syn_righthand
Definition: pathnodes.h:3033

References generate_unaccent_rules::args, bms_is_subset(), elog, ERROR, examine_variable(), linitial, list_length(), lsecond, VariableStatData::rel, RelOptInfo::relids, root, SpecialJoinInfo::syn_lefthand, and SpecialJoinInfo::syn_righthand.

Referenced by eqjoinsel(), neqjoinsel(), and networkjoinsel().

◆ get_quals_from_indexclauses()

List * get_quals_from_indexclauses ( List indexclauses)

Definition at line 6786 of file selfuncs.c.

6787{
6788 List *result = NIL;
6789 ListCell *lc;
6790
6791 foreach(lc, indexclauses)
6792 {
6793 IndexClause *iclause = lfirst_node(IndexClause, lc);
6794 ListCell *lc2;
6795
6796 foreach(lc2, iclause->indexquals)
6797 {
6798 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6799
6800 result = lappend(result, rinfo);
6801 }
6802 }
6803 return result;
6804}
List * indexquals
Definition: pathnodes.h:1896

References IndexClause::indexquals, lappend(), lfirst_node, and NIL.

Referenced by brincostestimate(), genericcostestimate(), and gincostestimate().

◆ get_restriction_variable()

bool get_restriction_variable ( PlannerInfo root,
List args,
int  varRelid,
VariableStatData vardata,
Node **  other,
bool *  varonleft 
)

Definition at line 5095 of file selfuncs.c.

5098{
5099 Node *left,
5100 *right;
5101 VariableStatData rdata;
5102
5103 /* Fail if not a binary opclause (probably shouldn't happen) */
5104 if (list_length(args) != 2)
5105 return false;
5106
5107 left = (Node *) linitial(args);
5108 right = (Node *) lsecond(args);
5109
5110 /*
5111 * Examine both sides. Note that when varRelid is nonzero, Vars of other
5112 * relations will be treated as pseudoconstants.
5113 */
5114 examine_variable(root, left, varRelid, vardata);
5115 examine_variable(root, right, varRelid, &rdata);
5116
5117 /*
5118 * If one side is a variable and the other not, we win.
5119 */
5120 if (vardata->rel && rdata.rel == NULL)
5121 {
5122 *varonleft = true;
5123 *other = estimate_expression_value(root, rdata.var);
5124 /* Assume we need no ReleaseVariableStats(rdata) here */
5125 return true;
5126 }
5127
5128 if (vardata->rel == NULL && rdata.rel)
5129 {
5130 *varonleft = false;
5131 *other = estimate_expression_value(root, vardata->var);
5132 /* Assume we need no ReleaseVariableStats(*vardata) here */
5133 *vardata = rdata;
5134 return true;
5135 }
5136
5137 /* Oops, clause has wrong structure (probably var op var) */
5138 ReleaseVariableStats(*vardata);
5139 ReleaseVariableStats(rdata);
5140
5141 return false;
5142}
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2397

References generate_unaccent_rules::args, estimate_expression_value(), examine_variable(), linitial, list_length(), lsecond, VariableStatData::rel, ReleaseVariableStats, root, and VariableStatData::var.

Referenced by _int_matchsel(), arraycontsel(), eqsel_internal(), generic_restriction_selectivity(), multirangesel(), networksel(), patternsel_common(), rangesel(), scalarineqsel_wrapper(), and tsmatchsel().

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool *  isdefault 
)

Definition at line 6084 of file selfuncs.c.

6085{
6086 double stadistinct;
6087 double stanullfrac = 0.0;
6088 double ntuples;
6089
6090 *isdefault = false;
6091
6092 /*
6093 * Determine the stadistinct value to use. There are cases where we can
6094 * get an estimate even without a pg_statistic entry, or can get a better
6095 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6096 * (otherwise, assume no nulls, for lack of any better idea).
6097 */
6098 if (HeapTupleIsValid(vardata->statsTuple))
6099 {
6100 /* Use the pg_statistic entry */
6101 Form_pg_statistic stats;
6102
6103 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6104 stadistinct = stats->stadistinct;
6105 stanullfrac = stats->stanullfrac;
6106 }
6107 else if (vardata->vartype == BOOLOID)
6108 {
6109 /*
6110 * Special-case boolean columns: presumably, two distinct values.
6111 *
6112 * Are there any other datatypes we should wire in special estimates
6113 * for?
6114 */
6115 stadistinct = 2.0;
6116 }
6117 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6118 {
6119 /*
6120 * If the Var represents a column of a VALUES RTE, assume it's unique.
6121 * This could of course be very wrong, but it should tend to be true
6122 * in well-written queries. We could consider examining the VALUES'
6123 * contents to get some real statistics; but that only works if the
6124 * entries are all constants, and it would be pretty expensive anyway.
6125 */
6126 stadistinct = -1.0; /* unique (and all non null) */
6127 }
6128 else
6129 {
6130 /*
6131 * We don't keep statistics for system columns, but in some cases we
6132 * can infer distinctness anyway.
6133 */
6134 if (vardata->var && IsA(vardata->var, Var))
6135 {
6136 switch (((Var *) vardata->var)->varattno)
6137 {
6139 stadistinct = -1.0; /* unique (and all non null) */
6140 break;
6142 stadistinct = 1.0; /* only 1 value */
6143 break;
6144 default:
6145 stadistinct = 0.0; /* means "unknown" */
6146 break;
6147 }
6148 }
6149 else
6150 stadistinct = 0.0; /* means "unknown" */
6151
6152 /*
6153 * XXX consider using estimate_num_groups on expressions?
6154 */
6155 }
6156
6157 /*
6158 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6159 * variable, assume it is unique no matter what pg_statistic says; the
6160 * statistics could be out of date, or we might have found a partial
6161 * unique index that proves the var is unique for this query. However,
6162 * we'd better still believe the null-fraction statistic.
6163 */
6164 if (vardata->isunique)
6165 stadistinct = -1.0 * (1.0 - stanullfrac);
6166
6167 /*
6168 * If we had an absolute estimate, use that.
6169 */
6170 if (stadistinct > 0.0)
6171 return clamp_row_est(stadistinct);
6172
6173 /*
6174 * Otherwise we need to get the relation size; punt if not available.
6175 */
6176 if (vardata->rel == NULL)
6177 {
6178 *isdefault = true;
6179 return DEFAULT_NUM_DISTINCT;
6180 }
6181 ntuples = vardata->rel->tuples;
6182 if (ntuples <= 0.0)
6183 {
6184 *isdefault = true;
6185 return DEFAULT_NUM_DISTINCT;
6186 }
6187
6188 /*
6189 * If we had a relative estimate, use that.
6190 */
6191 if (stadistinct < 0.0)
6192 return clamp_row_est(-stadistinct * ntuples);
6193
6194 /*
6195 * With no data, estimate ndistinct = ntuples if the table is small, else
6196 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6197 * that the behavior isn't discontinuous.
6198 */
6199 if (ntuples < DEFAULT_NUM_DISTINCT)
6200 return clamp_row_est(ntuples);
6201
6202 *isdefault = true;
6203 return DEFAULT_NUM_DISTINCT;
6204}
@ RTE_VALUES
Definition: parsenodes.h:1031
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
RTEKind rtekind
Definition: pathnodes.h:949
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21

References clamp_row_est(), DEFAULT_NUM_DISTINCT, GETSTRUCT(), HeapTupleIsValid, IsA, VariableStatData::isunique, VariableStatData::rel, RTE_VALUES, RelOptInfo::rtekind, SelfItemPointerAttributeNumber, VariableStatData::statsTuple, TableOidAttributeNumber, RelOptInfo::tuples, VariableStatData::var, and VariableStatData::vartype.

Referenced by add_unique_group_var(), btcostestimate(), eqjoinsel(), estimate_hash_bucket_stats(), ineq_histogram_selectivity(), var_eq_const(), and var_eq_non_const().

◆ histogram_selectivity()

double histogram_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Oid  collation,
Datum  constval,
bool  varonleft,
int  min_hist_size,
int  n_skip,
int *  hist_size 
)

Definition at line 828 of file selfuncs.c.

833{
834 double result;
835 AttStatsSlot sslot;
836
837 /* check sanity of parameters */
838 Assert(n_skip >= 0);
839 Assert(min_hist_size > 2 * n_skip);
840
841 if (HeapTupleIsValid(vardata->statsTuple) &&
842 statistic_proc_security_check(vardata, opproc->fn_oid) &&
843 get_attstatsslot(&sslot, vardata->statsTuple,
844 STATISTIC_KIND_HISTOGRAM, InvalidOid,
846 {
847 *hist_size = sslot.nvalues;
848 if (sslot.nvalues >= min_hist_size)
849 {
850 LOCAL_FCINFO(fcinfo, 2);
851 int nmatch = 0;
852 int i;
853
854 /*
855 * We invoke the opproc "by hand" so that we won't fail on NULL
856 * results. Such cases won't arise for normal comparison
857 * functions, but generic_restriction_selectivity could perhaps be
858 * used with operators that can return NULL. A small side benefit
859 * is to not need to re-initialize the fcinfo struct from scratch
860 * each time.
861 */
862 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
863 NULL, NULL);
864 fcinfo->args[0].isnull = false;
865 fcinfo->args[1].isnull = false;
866 /* be careful to apply operator right way 'round */
867 if (varonleft)
868 fcinfo->args[1].value = constval;
869 else
870 fcinfo->args[0].value = constval;
871
872 for (i = n_skip; i < sslot.nvalues - n_skip; i++)
873 {
874 Datum fresult;
875
876 if (varonleft)
877 fcinfo->args[0].value = sslot.values[i];
878 else
879 fcinfo->args[1].value = sslot.values[i];
880 fcinfo->isnull = false;
881 fresult = FunctionCallInvoke(fcinfo);
882 if (!fcinfo->isnull && DatumGetBool(fresult))
883 nmatch++;
884 }
885 result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
886 }
887 else
888 result = -1;
889 free_attstatsslot(&sslot);
890 }
891 else
892 {
893 *hist_size = 0;
894 result = -1;
895 }
896
897 return result;
898}
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:6055
Oid fn_oid
Definition: fmgr.h:59

References Assert(), ATTSTATSSLOT_VALUES, DatumGetBool(), FmgrInfo::fn_oid, free_attstatsslot(), FunctionCallInvoke, get_attstatsslot(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, AttStatsSlot::nvalues, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by generic_restriction_selectivity(), and patternsel_common().

◆ index_other_operands_eval_cost()

Cost index_other_operands_eval_cost ( PlannerInfo root,
List indexquals 
)

Definition at line 6816 of file selfuncs.c.

6817{
6818 Cost qual_arg_cost = 0;
6819 ListCell *lc;
6820
6821 foreach(lc, indexquals)
6822 {
6823 Expr *clause = (Expr *) lfirst(lc);
6824 Node *other_operand;
6825 QualCost index_qual_cost;
6826
6827 /*
6828 * Index quals will have RestrictInfos, indexorderbys won't. Look
6829 * through RestrictInfo if present.
6830 */
6831 if (IsA(clause, RestrictInfo))
6832 clause = ((RestrictInfo *) clause)->clause;
6833
6834 if (IsA(clause, OpExpr))
6835 {
6836 OpExpr *op = (OpExpr *) clause;
6837
6838 other_operand = (Node *) lsecond(op->args);
6839 }
6840 else if (IsA(clause, RowCompareExpr))
6841 {
6842 RowCompareExpr *rc = (RowCompareExpr *) clause;
6843
6844 other_operand = (Node *) rc->rargs;
6845 }
6846 else if (IsA(clause, ScalarArrayOpExpr))
6847 {
6848 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6849
6850 other_operand = (Node *) lsecond(saop->args);
6851 }
6852 else if (IsA(clause, NullTest))
6853 {
6854 other_operand = NULL;
6855 }
6856 else
6857 {
6858 elog(ERROR, "unsupported indexqual type: %d",
6859 (int) nodeTag(clause));
6860 other_operand = NULL; /* keep compiler quiet */
6861 }
6862
6863 cost_qual_eval_node(&index_qual_cost, other_operand, root);
6864 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6865 }
6866 return qual_arg_cost;
6867}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4767
#define nodeTag(nodeptr)
Definition: nodes.h:139
List * args
Definition: primnodes.h:853
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

References OpExpr::args, ScalarArrayOpExpr::args, cost_qual_eval_node(), elog, ERROR, IsA, lfirst, lsecond, nodeTag, QualCost::per_tuple, RowCompareExpr::rargs, root, and QualCost::startup.

Referenced by brincostestimate(), genericcostestimate(), and gincostestimate().

◆ ineq_histogram_selectivity()

double ineq_histogram_selectivity ( PlannerInfo root,
VariableStatData vardata,
Oid  opoid,
FmgrInfo opproc,
bool  isgt,
bool  iseq,
Oid  collation,
Datum  constval,
Oid  consttype 
)

Definition at line 1046 of file selfuncs.c.

1051{
1052 double hist_selec;
1053 AttStatsSlot sslot;
1054
1055 hist_selec = -1.0;
1056
1057 /*
1058 * Someday, ANALYZE might store more than one histogram per rel/att,
1059 * corresponding to more than one possible sort ordering defined for the
1060 * column type. Right now, we know there is only one, so just grab it and
1061 * see if it matches the query.
1062 *
1063 * Note that we can't use opoid as search argument; the staop appearing in
1064 * pg_statistic will be for the relevant '<' operator, but what we have
1065 * might be some other inequality operator such as '>='. (Even if opoid
1066 * is a '<' operator, it could be cross-type.) Hence we must use
1067 * comparison_ops_are_compatible() to see if the operators match.
1068 */
1069 if (HeapTupleIsValid(vardata->statsTuple) &&
1070 statistic_proc_security_check(vardata, opproc->fn_oid) &&
1071 get_attstatsslot(&sslot, vardata->statsTuple,
1072 STATISTIC_KIND_HISTOGRAM, InvalidOid,
1074 {
1075 if (sslot.nvalues > 1 &&
1076 sslot.stacoll == collation &&
1078 {
1079 /*
1080 * Use binary search to find the desired location, namely the
1081 * right end of the histogram bin containing the comparison value,
1082 * which is the leftmost entry for which the comparison operator
1083 * succeeds (if isgt) or fails (if !isgt).
1084 *
1085 * In this loop, we pay no attention to whether the operator iseq
1086 * or not; that detail will be mopped up below. (We cannot tell,
1087 * anyway, whether the operator thinks the values are equal.)
1088 *
1089 * If the binary search accesses the first or last histogram
1090 * entry, we try to replace that endpoint with the true column min
1091 * or max as found by get_actual_variable_range(). This
1092 * ameliorates misestimates when the min or max is moving as a
1093 * result of changes since the last ANALYZE. Note that this could
1094 * result in effectively including MCVs into the histogram that
1095 * weren't there before, but we don't try to correct for that.
1096 */
1097 double histfrac;
1098 int lobound = 0; /* first possible slot to search */
1099 int hibound = sslot.nvalues; /* last+1 slot to search */
1100 bool have_end = false;
1101
1102 /*
1103 * If there are only two histogram entries, we'll want up-to-date
1104 * values for both. (If there are more than two, we need at most
1105 * one of them to be updated, so we deal with that within the
1106 * loop.)
1107 */
1108 if (sslot.nvalues == 2)
1110 vardata,
1111 sslot.staop,
1112 collation,
1113 &sslot.values[0],
1114 &sslot.values[1]);
1115
1116 while (lobound < hibound)
1117 {
1118 int probe = (lobound + hibound) / 2;
1119 bool ltcmp;
1120
1121 /*
1122 * If we find ourselves about to compare to the first or last
1123 * histogram entry, first try to replace it with the actual
1124 * current min or max (unless we already did so above).
1125 */
1126 if (probe == 0 && sslot.nvalues > 2)
1128 vardata,
1129 sslot.staop,
1130 collation,
1131 &sslot.values[0],
1132 NULL);
1133 else if (probe == sslot.nvalues - 1 && sslot.nvalues > 2)
1135 vardata,
1136 sslot.staop,
1137 collation,
1138 NULL,
1139 &sslot.values[probe]);
1140
1141 ltcmp = DatumGetBool(FunctionCall2Coll(opproc,
1142 collation,
1143 sslot.values[probe],
1144 constval));
1145 if (isgt)
1146 ltcmp = !ltcmp;
1147 if (ltcmp)
1148 lobound = probe + 1;
1149 else
1150 hibound = probe;
1151 }
1152
1153 if (lobound <= 0)
1154 {
1155 /*
1156 * Constant is below lower histogram boundary. More
1157 * precisely, we have found that no entry in the histogram
1158 * satisfies the inequality clause (if !isgt) or they all do
1159 * (if isgt). We estimate that that's true of the entire
1160 * table, so set histfrac to 0.0 (which we'll flip to 1.0
1161 * below, if isgt).
1162 */
1163 histfrac = 0.0;
1164 }
1165 else if (lobound >= sslot.nvalues)
1166 {
1167 /*
1168 * Inverse case: constant is above upper histogram boundary.
1169 */
1170 histfrac = 1.0;
1171 }
1172 else
1173 {
1174 /* We have values[i-1] <= constant <= values[i]. */
1175 int i = lobound;
1176 double eq_selec = 0;
1177 double val,
1178 high,
1179 low;
1180 double binfrac;
1181
1182 /*
1183 * In the cases where we'll need it below, obtain an estimate
1184 * of the selectivity of "x = constval". We use a calculation
1185 * similar to what var_eq_const() does for a non-MCV constant,
1186 * ie, estimate that all distinct non-MCV values occur equally
1187 * often. But multiplication by "1.0 - sumcommon - nullfrac"
1188 * will be done by our caller, so we shouldn't do that here.
1189 * Therefore we can't try to clamp the estimate by reference
1190 * to the least common MCV; the result would be too small.
1191 *
1192 * Note: since this is effectively assuming that constval
1193 * isn't an MCV, it's logically dubious if constval in fact is
1194 * one. But we have to apply *some* correction for equality,
1195 * and anyway we cannot tell if constval is an MCV, since we
1196 * don't have a suitable equality operator at hand.
1197 */
1198 if (i == 1 || isgt == iseq)
1199 {
1200 double otherdistinct;
1201 bool isdefault;
1202 AttStatsSlot mcvslot;
1203
1204 /* Get estimated number of distinct values */
1205 otherdistinct = get_variable_numdistinct(vardata,
1206 &isdefault);
1207
1208 /* Subtract off the number of known MCVs */
1209 if (get_attstatsslot(&mcvslot, vardata->statsTuple,
1210 STATISTIC_KIND_MCV, InvalidOid,
1212 {
1213 otherdistinct -= mcvslot.nnumbers;
1214 free_attstatsslot(&mcvslot);
1215 }
1216
1217 /* If result doesn't seem sane, leave eq_selec at 0 */
1218 if (otherdistinct > 1)
1219 eq_selec = 1.0 / otherdistinct;
1220 }
1221
1222 /*
1223 * Convert the constant and the two nearest bin boundary
1224 * values to a uniform comparison scale, and do a linear
1225 * interpolation within this bin.
1226 */
1227 if (convert_to_scalar(constval, consttype, collation,
1228 &val,
1229 sslot.values[i - 1], sslot.values[i],
1230 vardata->vartype,
1231 &low, &high))
1232 {
1233 if (high <= low)
1234 {
1235 /* cope if bin boundaries appear identical */
1236 binfrac = 0.5;
1237 }
1238 else if (val <= low)
1239 binfrac = 0.0;
1240 else if (val >= high)
1241 binfrac = 1.0;
1242 else
1243 {
1244 binfrac = (val - low) / (high - low);
1245
1246 /*
1247 * Watch out for the possibility that we got a NaN or
1248 * Infinity from the division. This can happen
1249 * despite the previous checks, if for example "low"
1250 * is -Infinity.
1251 */
1252 if (isnan(binfrac) ||
1253 binfrac < 0.0 || binfrac > 1.0)
1254 binfrac = 0.5;
1255 }
1256 }
1257 else
1258 {
1259 /*
1260 * Ideally we'd produce an error here, on the grounds that
1261 * the given operator shouldn't have scalarXXsel
1262 * registered as its selectivity func unless we can deal
1263 * with its operand types. But currently, all manner of
1264 * stuff is invoking scalarXXsel, so give a default
1265 * estimate until that can be fixed.
1266 */
1267 binfrac = 0.5;
1268 }
1269
1270 /*
1271 * Now, compute the overall selectivity across the values
1272 * represented by the histogram. We have i-1 full bins and
1273 * binfrac partial bin below the constant.
1274 */
1275 histfrac = (double) (i - 1) + binfrac;
1276 histfrac /= (double) (sslot.nvalues - 1);
1277
1278 /*
1279 * At this point, histfrac is an estimate of the fraction of
1280 * the population represented by the histogram that satisfies
1281 * "x <= constval". Somewhat remarkably, this statement is
1282 * true regardless of which operator we were doing the probes
1283 * with, so long as convert_to_scalar() delivers reasonable
1284 * results. If the probe constant is equal to some histogram
1285 * entry, we would have considered the bin to the left of that
1286 * entry if probing with "<" or ">=", or the bin to the right
1287 * if probing with "<=" or ">"; but binfrac would have come
1288 * out as 1.0 in the first case and 0.0 in the second, leading
1289 * to the same histfrac in either case. For probe constants
1290 * between histogram entries, we find the same bin and get the
1291 * same estimate with any operator.
1292 *
1293 * The fact that the estimate corresponds to "x <= constval"
1294 * and not "x < constval" is because of the way that ANALYZE
1295 * constructs the histogram: each entry is, effectively, the
1296 * rightmost value in its sample bucket. So selectivity
1297 * values that are exact multiples of 1/(histogram_size-1)
1298 * should be understood as estimates including a histogram
1299 * entry plus everything to its left.
1300 *
1301 * However, that breaks down for the first histogram entry,
1302 * which necessarily is the leftmost value in its sample
1303 * bucket. That means the first histogram bin is slightly
1304 * narrower than the rest, by an amount equal to eq_selec.
1305 * Another way to say that is that we want "x <= leftmost" to
1306 * be estimated as eq_selec not zero. So, if we're dealing
1307 * with the first bin (i==1), rescale to make that true while
1308 * adjusting the rest of that bin linearly.
1309 */
1310 if (i == 1)
1311 histfrac += eq_selec * (1.0 - binfrac);
1312
1313 /*
1314 * "x <= constval" is good if we want an estimate for "<=" or
1315 * ">", but if we are estimating for "<" or ">=", we now need
1316 * to decrease the estimate by eq_selec.
1317 */
1318 if (isgt == iseq)
1319 histfrac -= eq_selec;
1320 }
1321
1322 /*
1323 * Now the estimate is finished for "<" and "<=" cases. If we are
1324 * estimating for ">" or ">=", flip it.
1325 */
1326 hist_selec = isgt ? (1.0 - histfrac) : histfrac;
1327
1328 /*
1329 * The histogram boundaries are only approximate to begin with,
1330 * and may well be out of date anyway. Therefore, don't believe
1331 * extremely small or large selectivity estimates --- unless we
1332 * got actual current endpoint values from the table, in which
1333 * case just do the usual sanity clamp. Somewhat arbitrarily, we
1334 * set the cutoff for other cases at a hundredth of the histogram
1335 * resolution.
1336 */
1337 if (have_end)
1338 CLAMP_PROBABILITY(hist_selec);
1339 else
1340 {
1341 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1342
1343 if (hist_selec < cutoff)
1344 hist_selec = cutoff;
1345 else if (hist_selec > 1.0 - cutoff)
1346 hist_selec = 1.0 - cutoff;
1347 }
1348 }
1349 else if (sslot.nvalues > 1)
1350 {
1351 /*
1352 * If we get here, we have a histogram but it's not sorted the way
1353 * we want. Do a brute-force search to see how many of the
1354 * entries satisfy the comparison condition, and take that
1355 * fraction as our estimate. (This is identical to the inner loop
1356 * of histogram_selectivity; maybe share code?)
1357 */
1358 LOCAL_FCINFO(fcinfo, 2);
1359 int nmatch = 0;
1360
1361 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
1362 NULL, NULL);
1363 fcinfo->args[0].isnull = false;
1364 fcinfo->args[1].isnull = false;
1365 fcinfo->args[1].value = constval;
1366 for (int i = 0; i < sslot.nvalues; i++)
1367 {
1368 Datum fresult;
1369
1370 fcinfo->args[0].value = sslot.values[i];
1371 fcinfo->isnull = false;
1372 fresult = FunctionCallInvoke(fcinfo);
1373 if (!fcinfo->isnull && DatumGetBool(fresult))
1374 nmatch++;
1375 }
1376 hist_selec = ((double) nmatch) / ((double) sslot.nvalues);
1377
1378 /*
1379 * As above, clamp to a hundredth of the histogram resolution.
1380 * This case is surely even less trustworthy than the normal one,
1381 * so we shouldn't believe exact 0 or 1 selectivity. (Maybe the
1382 * clamp should be more restrictive in this case?)
1383 */
1384 {
1385 double cutoff = 0.01 / (double) (sslot.nvalues - 1);
1386
1387 if (hist_selec < cutoff)
1388 hist_selec = cutoff;
1389 else if (hist_selec > 1.0 - cutoff)
1390 hist_selec = 1.0 - cutoff;
1391 }
1392 }
1393
1394 free_attstatsslot(&sslot);
1395 }
1396
1397 return hist_selec;
1398}
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
long val
Definition: informix.c:689
bool comparison_ops_are_compatible(Oid opno1, Oid opno2)
Definition: lsyscache.c:835
static bool convert_to_scalar(Datum value, Oid valuetypid, Oid collid, double *scaledvalue, Datum lobound, Datum hibound, Oid boundstypid, double *scaledlobound, double *scaledhibound)
Definition: selfuncs.c:4510
static bool get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
Definition: selfuncs.c:6407

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, comparison_ops_are_compatible(), convert_to_scalar(), DatumGetBool(), FmgrInfo::fn_oid, free_attstatsslot(), FunctionCall2Coll(), FunctionCallInvoke, get_actual_variable_range(), get_attstatsslot(), get_variable_numdistinct(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, AttStatsSlot::nnumbers, AttStatsSlot::nvalues, root, AttStatsSlot::stacoll, AttStatsSlot::staop, statistic_proc_security_check(), VariableStatData::statsTuple, val, AttStatsSlot::values, and VariableStatData::vartype.

Referenced by prefix_selectivity(), and scalarineqsel().

◆ mcv_selectivity()

double mcv_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Oid  collation,
Datum  constval,
bool  varonleft,
double *  sumcommonp 
)

Definition at line 737 of file selfuncs.c.

740{
741 double mcv_selec,
742 sumcommon;
743 AttStatsSlot sslot;
744 int i;
745
746 mcv_selec = 0.0;
747 sumcommon = 0.0;
748
749 if (HeapTupleIsValid(vardata->statsTuple) &&
750 statistic_proc_security_check(vardata, opproc->fn_oid) &&
751 get_attstatsslot(&sslot, vardata->statsTuple,
752 STATISTIC_KIND_MCV, InvalidOid,
754 {
755 LOCAL_FCINFO(fcinfo, 2);
756
757 /*
758 * We invoke the opproc "by hand" so that we won't fail on NULL
759 * results. Such cases won't arise for normal comparison functions,
760 * but generic_restriction_selectivity could perhaps be used with
761 * operators that can return NULL. A small side benefit is to not
762 * need to re-initialize the fcinfo struct from scratch each time.
763 */
764 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
765 NULL, NULL);
766 fcinfo->args[0].isnull = false;
767 fcinfo->args[1].isnull = false;
768 /* be careful to apply operator right way 'round */
769 if (varonleft)
770 fcinfo->args[1].value = constval;
771 else
772 fcinfo->args[0].value = constval;
773
774 for (i = 0; i < sslot.nvalues; i++)
775 {
776 Datum fresult;
777
778 if (varonleft)
779 fcinfo->args[0].value = sslot.values[i];
780 else
781 fcinfo->args[1].value = sslot.values[i];
782 fcinfo->isnull = false;
783 fresult = FunctionCallInvoke(fcinfo);
784 if (!fcinfo->isnull && DatumGetBool(fresult))
785 mcv_selec += sslot.numbers[i];
786 sumcommon += sslot.numbers[i];
787 }
788 free_attstatsslot(&sslot);
789 }
790
791 *sumcommonp = sumcommon;
792 return mcv_selec;
793}

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, DatumGetBool(), FmgrInfo::fn_oid, free_attstatsslot(), FunctionCallInvoke, get_attstatsslot(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, AttStatsSlot::numbers, AttStatsSlot::nvalues, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by generic_restriction_selectivity(), networksel(), patternsel_common(), and scalarineqsel().

◆ mergejoinscansel()

void mergejoinscansel ( PlannerInfo root,
Node clause,
Oid  opfamily,
CompareType  cmptype,
bool  nulls_first,
Selectivity leftstart,
Selectivity leftend,
Selectivity rightstart,
Selectivity rightend 
)

Definition at line 2960 of file selfuncs.c.

2964{
2965 Node *left,
2966 *right;
2967 VariableStatData leftvar,
2968 rightvar;
2969 Oid opmethod;
2970 int op_strategy;
2971 Oid op_lefttype;
2972 Oid op_righttype;
2973 Oid opno,
2974 collation,
2975 lsortop,
2976 rsortop,
2977 lstatop,
2978 rstatop,
2979 ltop,
2980 leop,
2981 revltop,
2982 revleop;
2983 StrategyNumber ltstrat,
2984 lestrat,
2985 gtstrat,
2986 gestrat;
2987 bool isgt;
2988 Datum leftmin,
2989 leftmax,
2990 rightmin,
2991 rightmax;
2992 double selec;
2993
2994 /* Set default results if we can't figure anything out. */
2995 /* XXX should default "start" fraction be a bit more than 0? */
2996 *leftstart = *rightstart = 0.0;
2997 *leftend = *rightend = 1.0;
2998
2999 /* Deconstruct the merge clause */
3000 if (!is_opclause(clause))
3001 return; /* shouldn't happen */
3002 opno = ((OpExpr *) clause)->opno;
3003 collation = ((OpExpr *) clause)->inputcollid;
3004 left = get_leftop((Expr *) clause);
3005 right = get_rightop((Expr *) clause);
3006 if (!right)
3007 return; /* shouldn't happen */
3008
3009 /* Look for stats for the inputs */
3010 examine_variable(root, left, 0, &leftvar);
3011 examine_variable(root, right, 0, &rightvar);
3012
3013 opmethod = get_opfamily_method(opfamily);
3014
3015 /* Extract the operator's declared left/right datatypes */
3016 get_op_opfamily_properties(opno, opfamily, false,
3017 &op_strategy,
3018 &op_lefttype,
3019 &op_righttype);
3020 Assert(IndexAmTranslateStrategy(op_strategy, opmethod, opfamily, true) == COMPARE_EQ);
3021
3022 /*
3023 * Look up the various operators we need. If we don't find them all, it
3024 * probably means the opfamily is broken, but we just fail silently.
3025 *
3026 * Note: we expect that pg_statistic histograms will be sorted by the '<'
3027 * operator, regardless of which sort direction we are considering.
3028 */
3029 switch (cmptype)
3030 {
3031 case COMPARE_LT:
3032 isgt = false;
3033 ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
3034 lestrat = IndexAmTranslateCompareType(COMPARE_LE, opmethod, opfamily, true);
3035 if (op_lefttype == op_righttype)
3036 {
3037 /* easy case */
3038 ltop = get_opfamily_member(opfamily,
3039 op_lefttype, op_righttype,
3040 ltstrat);
3041 leop = get_opfamily_member(opfamily,
3042 op_lefttype, op_righttype,
3043 lestrat);
3044 lsortop = ltop;
3045 rsortop = ltop;
3046 lstatop = lsortop;
3047 rstatop = rsortop;
3048 revltop = ltop;
3049 revleop = leop;
3050 }
3051 else
3052 {
3053 ltop = get_opfamily_member(opfamily,
3054 op_lefttype, op_righttype,
3055 ltstrat);
3056 leop = get_opfamily_member(opfamily,
3057 op_lefttype, op_righttype,
3058 lestrat);
3059 lsortop = get_opfamily_member(opfamily,
3060 op_lefttype, op_lefttype,
3061 ltstrat);
3062 rsortop = get_opfamily_member(opfamily,
3063 op_righttype, op_righttype,
3064 ltstrat);
3065 lstatop = lsortop;
3066 rstatop = rsortop;
3067 revltop = get_opfamily_member(opfamily,
3068 op_righttype, op_lefttype,
3069 ltstrat);
3070 revleop = get_opfamily_member(opfamily,
3071 op_righttype, op_lefttype,
3072 lestrat);
3073 }
3074 break;
3075 case COMPARE_GT:
3076 /* descending-order case */
3077 isgt = true;
3078 ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
3079 gtstrat = IndexAmTranslateCompareType(COMPARE_GT, opmethod, opfamily, true);
3080 gestrat = IndexAmTranslateCompareType(COMPARE_GE, opmethod, opfamily, true);
3081 if (op_lefttype == op_righttype)
3082 {
3083 /* easy case */
3084 ltop = get_opfamily_member(opfamily,
3085 op_lefttype, op_righttype,
3086 gtstrat);
3087 leop = get_opfamily_member(opfamily,
3088 op_lefttype, op_righttype,
3089 gestrat);
3090 lsortop = ltop;
3091 rsortop = ltop;
3092 lstatop = get_opfamily_member(opfamily,
3093 op_lefttype, op_lefttype,
3094 ltstrat);
3095 rstatop = lstatop;
3096 revltop = ltop;
3097 revleop = leop;
3098 }
3099 else
3100 {
3101 ltop = get_opfamily_member(opfamily,
3102 op_lefttype, op_righttype,
3103 gtstrat);
3104 leop = get_opfamily_member(opfamily,
3105 op_lefttype, op_righttype,
3106 gestrat);
3107 lsortop = get_opfamily_member(opfamily,
3108 op_lefttype, op_lefttype,
3109 gtstrat);
3110 rsortop = get_opfamily_member(opfamily,
3111 op_righttype, op_righttype,
3112 gtstrat);
3113 lstatop = get_opfamily_member(opfamily,
3114 op_lefttype, op_lefttype,
3115 ltstrat);
3116 rstatop = get_opfamily_member(opfamily,
3117 op_righttype, op_righttype,
3118 ltstrat);
3119 revltop = get_opfamily_member(opfamily,
3120 op_righttype, op_lefttype,
3121 gtstrat);
3122 revleop = get_opfamily_member(opfamily,
3123 op_righttype, op_lefttype,
3124 gestrat);
3125 }
3126 break;
3127 default:
3128 goto fail; /* shouldn't get here */
3129 }
3130
3131 if (!OidIsValid(lsortop) ||
3132 !OidIsValid(rsortop) ||
3133 !OidIsValid(lstatop) ||
3134 !OidIsValid(rstatop) ||
3135 !OidIsValid(ltop) ||
3136 !OidIsValid(leop) ||
3137 !OidIsValid(revltop) ||
3138 !OidIsValid(revleop))
3139 goto fail; /* insufficient info in catalogs */
3140
3141 /* Try to get ranges of both inputs */
3142 if (!isgt)
3143 {
3144 if (!get_variable_range(root, &leftvar, lstatop, collation,
3145 &leftmin, &leftmax))
3146 goto fail; /* no range available from stats */
3147 if (!get_variable_range(root, &rightvar, rstatop, collation,
3148 &rightmin, &rightmax))
3149 goto fail; /* no range available from stats */
3150 }
3151 else
3152 {
3153 /* need to swap the max and min */
3154 if (!get_variable_range(root, &leftvar, lstatop, collation,
3155 &leftmax, &leftmin))
3156 goto fail; /* no range available from stats */
3157 if (!get_variable_range(root, &rightvar, rstatop, collation,
3158 &rightmax, &rightmin))
3159 goto fail; /* no range available from stats */
3160 }
3161
3162 /*
3163 * Now, the fraction of the left variable that will be scanned is the
3164 * fraction that's <= the right-side maximum value. But only believe
3165 * non-default estimates, else stick with our 1.0.
3166 */
3167 selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3168 rightmax, op_righttype);
3169 if (selec != DEFAULT_INEQ_SEL)
3170 *leftend = selec;
3171
3172 /* And similarly for the right variable. */
3173 selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3174 leftmax, op_lefttype);
3175 if (selec != DEFAULT_INEQ_SEL)
3176 *rightend = selec;
3177
3178 /*
3179 * Only one of the two "end" fractions can really be less than 1.0;
3180 * believe the smaller estimate and reset the other one to exactly 1.0. If
3181 * we get exactly equal estimates (as can easily happen with self-joins),
3182 * believe neither.
3183 */
3184 if (*leftend > *rightend)
3185 *leftend = 1.0;
3186 else if (*leftend < *rightend)
3187 *rightend = 1.0;
3188 else
3189 *leftend = *rightend = 1.0;
3190
3191 /*
3192 * Also, the fraction of the left variable that will be scanned before the
3193 * first join pair is found is the fraction that's < the right-side
3194 * minimum value. But only believe non-default estimates, else stick with
3195 * our own default.
3196 */
3197 selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3198 rightmin, op_righttype);
3199 if (selec != DEFAULT_INEQ_SEL)
3200 *leftstart = selec;
3201
3202 /* And similarly for the right variable. */
3203 selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3204 leftmin, op_lefttype);
3205 if (selec != DEFAULT_INEQ_SEL)
3206 *rightstart = selec;
3207
3208 /*
3209 * Only one of the two "start" fractions can really be more than zero;
3210 * believe the larger estimate and reset the other one to exactly 0.0. If
3211 * we get exactly equal estimates (as can easily happen with self-joins),
3212 * believe neither.
3213 */
3214 if (*leftstart < *rightstart)
3215 *leftstart = 0.0;
3216 else if (*leftstart > *rightstart)
3217 *rightstart = 0.0;
3218 else
3219 *leftstart = *rightstart = 0.0;
3220
3221 /*
3222 * If the sort order is nulls-first, we're going to have to skip over any
3223 * nulls too. These would not have been counted by scalarineqsel, and we
3224 * can safely add in this fraction regardless of whether we believe
3225 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3226 */
3227 if (nulls_first)
3228 {
3229 Form_pg_statistic stats;
3230
3231 if (HeapTupleIsValid(leftvar.statsTuple))
3232 {
3233 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3234 *leftstart += stats->stanullfrac;
3235 CLAMP_PROBABILITY(*leftstart);
3236 *leftend += stats->stanullfrac;
3237 CLAMP_PROBABILITY(*leftend);
3238 }
3239 if (HeapTupleIsValid(rightvar.statsTuple))
3240 {
3241 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3242 *rightstart += stats->stanullfrac;
3243 CLAMP_PROBABILITY(*rightstart);
3244 *rightend += stats->stanullfrac;
3245 CLAMP_PROBABILITY(*rightend);
3246 }
3247 }
3248
3249 /* Disbelieve start >= end, just in case that can happen */
3250 if (*leftstart >= *leftend)
3251 {
3252 *leftstart = 0.0;
3253 *leftend = 1.0;
3254 }
3255 if (*rightstart >= *rightend)
3256 {
3257 *rightstart = 0.0;
3258 *rightend = 1.0;
3259 }
3260
3261fail:
3262 ReleaseVariableStats(leftvar);
3263 ReleaseVariableStats(rightvar);
3264}
StrategyNumber IndexAmTranslateCompareType(CompareType cmptype, Oid amoid, Oid opfamily, bool missing_ok)
Definition: amapi.c:148
CompareType IndexAmTranslateStrategy(StrategyNumber strategy, Oid amoid, Oid opfamily, bool missing_ok)
Definition: amapi.c:118
@ COMPARE_LE
Definition: cmptype.h:35
@ COMPARE_GT
Definition: cmptype.h:38
@ COMPARE_EQ
Definition: cmptype.h:36
@ COMPARE_GE
Definition: cmptype.h:37
@ COMPARE_LT
Definition: cmptype.h:34
void get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op, int *strategy, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:137
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:167
Oid get_opfamily_method(Oid opfid)
Definition: lsyscache.c:1376
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:76
static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
Definition: selfuncs.c:6217
static double scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq, Oid collation, VariableStatData *vardata, Datum constval, Oid consttype)
Definition: selfuncs.c:585
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
uint16 StrategyNumber
Definition: stratnum.h:22

References Assert(), CLAMP_PROBABILITY, COMPARE_EQ, COMPARE_GE, COMPARE_GT, COMPARE_LE, COMPARE_LT, DEFAULT_INEQ_SEL, examine_variable(), get_leftop(), get_op_opfamily_properties(), get_opfamily_member(), get_opfamily_method(), get_rightop(), get_variable_range(), GETSTRUCT(), HeapTupleIsValid, IndexAmTranslateCompareType(), IndexAmTranslateStrategy(), is_opclause(), OidIsValid, ReleaseVariableStats, root, scalarineqsel(), and VariableStatData::statsTuple.

Referenced by cached_scansel().

◆ nulltestsel()

Selectivity nulltestsel ( PlannerInfo root,
NullTestType  nulltesttype,
Node arg,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1703 of file selfuncs.c.

1705{
1706 VariableStatData vardata;
1707 double selec;
1708
1709 examine_variable(root, arg, varRelid, &vardata);
1710
1711 if (HeapTupleIsValid(vardata.statsTuple))
1712 {
1713 Form_pg_statistic stats;
1714 double freq_null;
1715
1716 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1717 freq_null = stats->stanullfrac;
1718
1719 switch (nulltesttype)
1720 {
1721 case IS_NULL:
1722
1723 /*
1724 * Use freq_null directly.
1725 */
1726 selec = freq_null;
1727 break;
1728 case IS_NOT_NULL:
1729
1730 /*
1731 * Select not unknown (not null) values. Calculate from
1732 * freq_null.
1733 */
1734 selec = 1.0 - freq_null;
1735 break;
1736 default:
1737 elog(ERROR, "unrecognized nulltesttype: %d",
1738 (int) nulltesttype);
1739 return (Selectivity) 0; /* keep compiler quiet */
1740 }
1741 }
1742 else if (vardata.var && IsA(vardata.var, Var) &&
1743 ((Var *) vardata.var)->varattno < 0)
1744 {
1745 /*
1746 * There are no stats for system columns, but we know they are never
1747 * NULL.
1748 */
1749 selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1750 }
1751 else
1752 {
1753 /*
1754 * No ANALYZE stats available, so make a guess
1755 */
1756 switch (nulltesttype)
1757 {
1758 case IS_NULL:
1759 selec = DEFAULT_UNK_SEL;
1760 break;
1761 case IS_NOT_NULL:
1762 selec = DEFAULT_NOT_UNK_SEL;
1763 break;
1764 default:
1765 elog(ERROR, "unrecognized nulltesttype: %d",
1766 (int) nulltesttype);
1767 return (Selectivity) 0; /* keep compiler quiet */
1768 }
1769 }
1770
1771 ReleaseVariableStats(vardata);
1772
1773 /* result should be in range, but make sure... */
1774 CLAMP_PROBABILITY(selec);
1775
1776 return (Selectivity) selec;
1777}
@ IS_NULL
Definition: primnodes.h:1957
@ IS_NOT_NULL
Definition: primnodes.h:1957

References arg, CLAMP_PROBABILITY, DEFAULT_NOT_UNK_SEL, DEFAULT_UNK_SEL, elog, ERROR, examine_variable(), GETSTRUCT(), HeapTupleIsValid, IS_NOT_NULL, IS_NULL, IsA, ReleaseVariableStats, root, VariableStatData::statsTuple, and VariableStatData::var.

Referenced by clause_selectivity_ext(), and clauselist_selectivity_ext().

◆ rowcomparesel()

Selectivity rowcomparesel ( PlannerInfo root,
RowCompareExpr clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 2210 of file selfuncs.c.

2213{
2215 Oid opno = linitial_oid(clause->opnos);
2216 Oid inputcollid = linitial_oid(clause->inputcollids);
2217 List *opargs;
2218 bool is_join_clause;
2219
2220 /* Build equivalent arg list for single operator */
2221 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2222
2223 /*
2224 * Decide if it's a join clause. This should match clausesel.c's
2225 * treat_as_join_clause(), except that we intentionally consider only the
2226 * leading columns and not the rest of the clause.
2227 */
2228 if (varRelid != 0)
2229 {
2230 /*
2231 * Caller is forcing restriction mode (eg, because we are examining an
2232 * inner indexscan qual).
2233 */
2234 is_join_clause = false;
2235 }
2236 else if (sjinfo == NULL)
2237 {
2238 /*
2239 * It must be a restriction clause, since it's being evaluated at a
2240 * scan node.
2241 */
2242 is_join_clause = false;
2243 }
2244 else
2245 {
2246 /*
2247 * Otherwise, it's a join if there's more than one base relation used.
2248 */
2249 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2250 }
2251
2252 if (is_join_clause)
2253 {
2254 /* Estimate selectivity for a join clause. */
2255 s1 = join_selectivity(root, opno,
2256 opargs,
2257 inputcollid,
2258 jointype,
2259 sjinfo);
2260 }
2261 else
2262 {
2263 /* Estimate selectivity for a restriction clause. */
2265 opargs,
2266 inputcollid,
2267 varRelid);
2268 }
2269
2270 return s1;
2271}
int NumRelids(PlannerInfo *root, Node *clause)
Definition: clauses.c:2132
#define linitial_oid(l)
Definition: pg_list.h:180
#define list_make2(x1, x2)
Definition: pg_list.h:214
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1969
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:2008
char * s1

References join_selectivity(), RowCompareExpr::largs, linitial, linitial_oid, list_make2, NumRelids(), RowCompareExpr::rargs, restriction_selectivity(), root, and s1.

Referenced by clause_selectivity_ext().

◆ scalararraysel()

Selectivity scalararraysel ( PlannerInfo root,
ScalarArrayOpExpr clause,
bool  is_join_clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1821 of file selfuncs.c.

1827{
1828 Oid operator = clause->opno;
1829 bool useOr = clause->useOr;
1830 bool isEquality = false;
1831 bool isInequality = false;
1832 Node *leftop;
1833 Node *rightop;
1834 Oid nominal_element_type;
1835 Oid nominal_element_collation;
1836 TypeCacheEntry *typentry;
1837 RegProcedure oprsel;
1838 FmgrInfo oprselproc;
1840 Selectivity s1disjoint;
1841
1842 /* First, deconstruct the expression */
1843 Assert(list_length(clause->args) == 2);
1844 leftop = (Node *) linitial(clause->args);
1845 rightop = (Node *) lsecond(clause->args);
1846
1847 /* aggressively reduce both sides to constants */
1848 leftop = estimate_expression_value(root, leftop);
1849 rightop = estimate_expression_value(root, rightop);
1850
1851 /* get nominal (after relabeling) element type of rightop */
1852 nominal_element_type = get_base_element_type(exprType(rightop));
1853 if (!OidIsValid(nominal_element_type))
1854 return (Selectivity) 0.5; /* probably shouldn't happen */
1855 /* get nominal collation, too, for generating constants */
1856 nominal_element_collation = exprCollation(rightop);
1857
1858 /* look through any binary-compatible relabeling of rightop */
1859 rightop = strip_array_coercion(rightop);
1860
1861 /*
1862 * Detect whether the operator is the default equality or inequality
1863 * operator of the array element type.
1864 */
1865 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1866 if (OidIsValid(typentry->eq_opr))
1867 {
1868 if (operator == typentry->eq_opr)
1869 isEquality = true;
1870 else if (get_negator(operator) == typentry->eq_opr)
1871 isInequality = true;
1872 }
1873
1874 /*
1875 * If it is equality or inequality, we might be able to estimate this as a
1876 * form of array containment; for instance "const = ANY(column)" can be
1877 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1878 * that, and returns the selectivity estimate if successful, or -1 if not.
1879 */
1880 if ((isEquality || isInequality) && !is_join_clause)
1881 {
1882 s1 = scalararraysel_containment(root, leftop, rightop,
1883 nominal_element_type,
1884 isEquality, useOr, varRelid);
1885 if (s1 >= 0.0)
1886 return s1;
1887 }
1888
1889 /*
1890 * Look up the underlying operator's selectivity estimator. Punt if it
1891 * hasn't got one.
1892 */
1893 if (is_join_clause)
1894 oprsel = get_oprjoin(operator);
1895 else
1896 oprsel = get_oprrest(operator);
1897 if (!oprsel)
1898 return (Selectivity) 0.5;
1899 fmgr_info(oprsel, &oprselproc);
1900
1901 /*
1902 * In the array-containment check above, we must only believe that an
1903 * operator is equality or inequality if it is the default btree equality
1904 * operator (or its negator) for the element type, since those are the
1905 * operators that array containment will use. But in what follows, we can
1906 * be a little laxer, and also believe that any operators using eqsel() or
1907 * neqsel() as selectivity estimator act like equality or inequality.
1908 */
1909 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1910 isEquality = true;
1911 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1912 isInequality = true;
1913
1914 /*
1915 * We consider three cases:
1916 *
1917 * 1. rightop is an Array constant: deconstruct the array, apply the
1918 * operator's selectivity function for each array element, and merge the
1919 * results in the same way that clausesel.c does for AND/OR combinations.
1920 *
1921 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1922 * function for each element of the ARRAY[] construct, and merge.
1923 *
1924 * 3. otherwise, make a guess ...
1925 */
1926 if (rightop && IsA(rightop, Const))
1927 {
1928 Datum arraydatum = ((Const *) rightop)->constvalue;
1929 bool arrayisnull = ((Const *) rightop)->constisnull;
1930 ArrayType *arrayval;
1931 int16 elmlen;
1932 bool elmbyval;
1933 char elmalign;
1934 int num_elems;
1935 Datum *elem_values;
1936 bool *elem_nulls;
1937 int i;
1938
1939 if (arrayisnull) /* qual can't succeed if null array */
1940 return (Selectivity) 0.0;
1941 arrayval = DatumGetArrayTypeP(arraydatum);
1943 &elmlen, &elmbyval, &elmalign);
1944 deconstruct_array(arrayval,
1945 ARR_ELEMTYPE(arrayval),
1946 elmlen, elmbyval, elmalign,
1947 &elem_values, &elem_nulls, &num_elems);
1948
1949 /*
1950 * For generic operators, we assume the probability of success is
1951 * independent for each array element. But for "= ANY" or "<> ALL",
1952 * if the array elements are distinct (which'd typically be the case)
1953 * then the probabilities are disjoint, and we should just sum them.
1954 *
1955 * If we were being really tense we would try to confirm that the
1956 * elements are all distinct, but that would be expensive and it
1957 * doesn't seem to be worth the cycles; it would amount to penalizing
1958 * well-written queries in favor of poorly-written ones. However, we
1959 * do protect ourselves a little bit by checking whether the
1960 * disjointness assumption leads to an impossible (out of range)
1961 * probability; if so, we fall back to the normal calculation.
1962 */
1963 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1964
1965 for (i = 0; i < num_elems; i++)
1966 {
1967 List *args;
1969
1970 args = list_make2(leftop,
1971 makeConst(nominal_element_type,
1972 -1,
1973 nominal_element_collation,
1974 elmlen,
1975 elem_values[i],
1976 elem_nulls[i],
1977 elmbyval));
1978 if (is_join_clause)
1979 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1980 clause->inputcollid,
1982 ObjectIdGetDatum(operator),
1984 Int16GetDatum(jointype),
1985 PointerGetDatum(sjinfo)));
1986 else
1987 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1988 clause->inputcollid,
1990 ObjectIdGetDatum(operator),
1992 Int32GetDatum(varRelid)));
1993
1994 if (useOr)
1995 {
1996 s1 = s1 + s2 - s1 * s2;
1997 if (isEquality)
1998 s1disjoint += s2;
1999 }
2000 else
2001 {
2002 s1 = s1 * s2;
2003 if (isInequality)
2004 s1disjoint += s2 - 1.0;
2005 }
2006 }
2007
2008 /* accept disjoint-probability estimate if in range */
2009 if ((useOr ? isEquality : isInequality) &&
2010 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2011 s1 = s1disjoint;
2012 }
2013 else if (rightop && IsA(rightop, ArrayExpr) &&
2014 !((ArrayExpr *) rightop)->multidims)
2015 {
2016 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2017 int16 elmlen;
2018 bool elmbyval;
2019 ListCell *l;
2020
2021 get_typlenbyval(arrayexpr->element_typeid,
2022 &elmlen, &elmbyval);
2023
2024 /*
2025 * We use the assumption of disjoint probabilities here too, although
2026 * the odds of equal array elements are rather higher if the elements
2027 * are not all constants (which they won't be, else constant folding
2028 * would have reduced the ArrayExpr to a Const). In this path it's
2029 * critical to have the sanity check on the s1disjoint estimate.
2030 */
2031 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2032
2033 foreach(l, arrayexpr->elements)
2034 {
2035 Node *elem = (Node *) lfirst(l);
2036 List *args;
2038
2039 /*
2040 * Theoretically, if elem isn't of nominal_element_type we should
2041 * insert a RelabelType, but it seems unlikely that any operator
2042 * estimation function would really care ...
2043 */
2044 args = list_make2(leftop, elem);
2045 if (is_join_clause)
2046 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2047 clause->inputcollid,
2049 ObjectIdGetDatum(operator),
2051 Int16GetDatum(jointype),
2052 PointerGetDatum(sjinfo)));
2053 else
2054 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2055 clause->inputcollid,
2057 ObjectIdGetDatum(operator),
2059 Int32GetDatum(varRelid)));
2060
2061 if (useOr)
2062 {
2063 s1 = s1 + s2 - s1 * s2;
2064 if (isEquality)
2065 s1disjoint += s2;
2066 }
2067 else
2068 {
2069 s1 = s1 * s2;
2070 if (isInequality)
2071 s1disjoint += s2 - 1.0;
2072 }
2073 }
2074
2075 /* accept disjoint-probability estimate if in range */
2076 if ((useOr ? isEquality : isInequality) &&
2077 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2078 s1 = s1disjoint;
2079 }
2080 else
2081 {
2082 CaseTestExpr *dummyexpr;
2083 List *args;
2085 int i;
2086
2087 /*
2088 * We need a dummy rightop to pass to the operator selectivity
2089 * routine. It can be pretty much anything that doesn't look like a
2090 * constant; CaseTestExpr is a convenient choice.
2091 */
2092 dummyexpr = makeNode(CaseTestExpr);
2093 dummyexpr->typeId = nominal_element_type;
2094 dummyexpr->typeMod = -1;
2095 dummyexpr->collation = clause->inputcollid;
2096 args = list_make2(leftop, dummyexpr);
2097 if (is_join_clause)
2098 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2099 clause->inputcollid,
2101 ObjectIdGetDatum(operator),
2103 Int16GetDatum(jointype),
2104 PointerGetDatum(sjinfo)));
2105 else
2106 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2107 clause->inputcollid,
2109 ObjectIdGetDatum(operator),
2111 Int32GetDatum(varRelid)));
2112 s1 = useOr ? 0.0 : 1.0;
2113
2114 /*
2115 * Arbitrarily assume 10 elements in the eventual array value (see
2116 * also estimate_array_length). We don't risk an assumption of
2117 * disjoint probabilities here.
2118 */
2119 for (i = 0; i < 10; i++)
2120 {
2121 if (useOr)
2122 s1 = s1 + s2 - s1 * s2;
2123 else
2124 s1 = s1 * s2;
2125 }
2126 }
2127
2128 /* result should be in range, but make sure... */
2130
2131 return s1;
2132}
#define ARR_ELEMTYPE(a)
Definition: array.h:292
Selectivity scalararraysel_containment(PlannerInfo *root, Node *leftop, Node *rightop, Oid elemtype, bool isEquality, bool useOr, int varRelid)
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3631
int16_t int16
Definition: c.h:497
regproc RegProcedure
Definition: c.h:621
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1196
Datum FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1223
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1697
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2411
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1721
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2391
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2972
Oid get_negator(Oid opno)
Definition: lsyscache.c:1673
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:350
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
#define makeNode(_type_)
Definition: nodes.h:161
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:499
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
char * s2
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
#define TYPECACHE_EQ_OPR
Definition: typcache.h:138

References generate_unaccent_rules::args, ScalarArrayOpExpr::args, ARR_ELEMTYPE, Assert(), CLAMP_PROBABILITY, DatumGetArrayTypeP, DatumGetFloat8(), deconstruct_array(), TypeCacheEntry::eq_opr, estimate_expression_value(), exprCollation(), exprType(), fmgr_info(), FunctionCall4Coll(), FunctionCall5Coll(), get_base_element_type(), get_negator(), get_oprjoin(), get_oprrest(), get_typlenbyval(), get_typlenbyvalalign(), i, Int16GetDatum(), Int32GetDatum(), IsA, lfirst, linitial, list_length(), list_make2, lookup_type_cache(), lsecond, makeConst(), makeNode, ObjectIdGetDatum(), OidIsValid, ScalarArrayOpExpr::opno, PointerGetDatum(), root, s1, s2, scalararraysel_containment(), strip_array_coercion(), TYPECACHE_EQ_OPR, CaseTestExpr::typeId, and ScalarArrayOpExpr::useOr.

Referenced by clause_selectivity_ext().

◆ scalararraysel_containment()

Selectivity scalararraysel_containment ( PlannerInfo root,
Node leftop,
Node rightop,
Oid  elemtype,
bool  isEquality,
bool  useOr,
int  varRelid 
)

Definition at line 81 of file array_selfuncs.c.

85{
86 Selectivity selec;
87 VariableStatData vardata;
88 Datum constval;
89 TypeCacheEntry *typentry;
90 FmgrInfo *cmpfunc;
91
92 /*
93 * rightop must be a variable, else punt.
94 */
95 examine_variable(root, rightop, varRelid, &vardata);
96 if (!vardata.rel)
97 {
98 ReleaseVariableStats(vardata);
99 return -1.0;
100 }
101
102 /*
103 * leftop must be a constant, else punt.
104 */
105 if (!IsA(leftop, Const))
106 {
107 ReleaseVariableStats(vardata);
108 return -1.0;
109 }
110 if (((Const *) leftop)->constisnull)
111 {
112 /* qual can't succeed if null on left */
113 ReleaseVariableStats(vardata);
114 return (Selectivity) 0.0;
115 }
116 constval = ((Const *) leftop)->constvalue;
117
118 /* Get element type's default comparison function */
119 typentry = lookup_type_cache(elemtype, TYPECACHE_CMP_PROC_FINFO);
120 if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
121 {
122 ReleaseVariableStats(vardata);
123 return -1.0;
124 }
125 cmpfunc = &typentry->cmp_proc_finfo;
126
127 /*
128 * If the operator is <>, swap ANY/ALL, then invert the result later.
129 */
130 if (!isEquality)
131 useOr = !useOr;
132
133 /* Get array element stats for var, if available */
134 if (HeapTupleIsValid(vardata.statsTuple) &&
135 statistic_proc_security_check(&vardata, cmpfunc->fn_oid))
136 {
137 Form_pg_statistic stats;
138 AttStatsSlot sslot;
139 AttStatsSlot hslot;
140
141 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
142
143 /* MCELEM will be an array of same type as element */
144 if (get_attstatsslot(&sslot, vardata.statsTuple,
145 STATISTIC_KIND_MCELEM, InvalidOid,
147 {
148 /* For ALL case, also get histogram of distinct-element counts */
149 if (useOr ||
150 !get_attstatsslot(&hslot, vardata.statsTuple,
151 STATISTIC_KIND_DECHIST, InvalidOid,
153 memset(&hslot, 0, sizeof(hslot));
154
155 /*
156 * For = ANY, estimate as var @> ARRAY[const].
157 *
158 * For = ALL, estimate as var <@ ARRAY[const].
159 */
160 if (useOr)
162 sslot.nvalues,
163 sslot.numbers,
164 sslot.nnumbers,
165 &constval, 1,
166 OID_ARRAY_CONTAINS_OP,
167 typentry);
168 else
170 sslot.nvalues,
171 sslot.numbers,
172 sslot.nnumbers,
173 &constval, 1,
174 hslot.numbers,
175 hslot.nnumbers,
176 OID_ARRAY_CONTAINED_OP,
177 typentry);
178
179 free_attstatsslot(&hslot);
180 free_attstatsslot(&sslot);
181 }
182 else
183 {
184 /* No most-common-elements info, so do without */
185 if (useOr)
187 NULL, 0,
188 &constval, 1,
189 OID_ARRAY_CONTAINS_OP,
190 typentry);
191 else
192 selec = mcelem_array_contained_selec(NULL, 0,
193 NULL, 0,
194 &constval, 1,
195 NULL, 0,
196 OID_ARRAY_CONTAINED_OP,
197 typentry);
198 }
199
200 /*
201 * MCE stats count only non-null rows, so adjust for null rows.
202 */
203 selec *= (1.0 - stats->stanullfrac);
204 }
205 else
206 {
207 /* No stats at all, so do without */
208 if (useOr)
210 NULL, 0,
211 &constval, 1,
212 OID_ARRAY_CONTAINS_OP,
213 typentry);
214 else
215 selec = mcelem_array_contained_selec(NULL, 0,
216 NULL, 0,
217 &constval, 1,
218 NULL, 0,
219 OID_ARRAY_CONTAINED_OP,
220 typentry);
221 /* we assume no nulls here, so no stanullfrac correction */
222 }
223
224 ReleaseVariableStats(vardata);
225
226 /*
227 * If the operator is <>, invert the results.
228 */
229 if (!isEquality)
230 selec = 1.0 - selec;
231
232 CLAMP_PROBABILITY(selec);
233
234 return selec;
235}
static Selectivity mcelem_array_contained_selec(Datum *mcelem, int nmcelem, float4 *numbers, int nnumbers, Datum *array_data, int nitems, float4 *hist, int nhist, Oid operator, TypeCacheEntry *typentry)
static Selectivity mcelem_array_contain_overlap_selec(Datum *mcelem, int nmcelem, float4 *numbers, int nnumbers, Datum *array_data, int nitems, Oid operator, TypeCacheEntry *typentry)
FmgrInfo cmp_proc_finfo
Definition: typcache.h:77
#define TYPECACHE_CMP_PROC_FINFO
Definition: typcache.h:144

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, TypeCacheEntry::cmp_proc_finfo, examine_variable(), FmgrInfo::fn_oid, free_attstatsslot(), get_attstatsslot(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, IsA, lookup_type_cache(), mcelem_array_contain_overlap_selec(), mcelem_array_contained_selec(), AttStatsSlot::nnumbers, AttStatsSlot::numbers, AttStatsSlot::nvalues, OidIsValid, VariableStatData::rel, ReleaseVariableStats, root, statistic_proc_security_check(), VariableStatData::statsTuple, TYPECACHE_CMP_PROC_FINFO, and AttStatsSlot::values.

Referenced by scalararraysel().

◆ statistic_proc_security_check()

bool statistic_proc_security_check ( VariableStatData vardata,
Oid  func_oid 
)

Definition at line 6055 of file selfuncs.c.

6056{
6057 if (vardata->acl_ok)
6058 return true;
6059
6060 if (!OidIsValid(func_oid))
6061 return false;
6062
6063 if (get_func_leakproof(func_oid))
6064 return true;
6065
6067 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6068 get_func_name(func_oid))));
6069 return false;
6070}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:149
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1977
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1748

References VariableStatData::acl_ok, DEBUG2, ereport, errmsg_internal(), get_func_leakproof(), get_func_name(), and OidIsValid.

Referenced by calc_arraycontsel(), calc_hist_selectivity(), eqjoinsel(), get_variable_range(), histogram_selectivity(), ineq_histogram_selectivity(), mcv_selectivity(), scalararraysel_containment(), and var_eq_const().

◆ var_eq_const()

double var_eq_const ( VariableStatData vardata,
Oid  oproid,
Oid  collation,
Datum  constval,
bool  constisnull,
bool  varonleft,
bool  negate 
)

Definition at line 300 of file selfuncs.c.

303{
304 double selec;
305 double nullfrac = 0.0;
306 bool isdefault;
307 Oid opfuncoid;
308
309 /*
310 * If the constant is NULL, assume operator is strict and return zero, ie,
311 * operator will never return TRUE. (It's zero even for a negator op.)
312 */
313 if (constisnull)
314 return 0.0;
315
316 /*
317 * Grab the nullfrac for use below. Note we allow use of nullfrac
318 * regardless of security check.
319 */
320 if (HeapTupleIsValid(vardata->statsTuple))
321 {
322 Form_pg_statistic stats;
323
324 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
325 nullfrac = stats->stanullfrac;
326 }
327
328 /*
329 * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
330 * assume there is exactly one match regardless of anything else. (This
331 * is slightly bogus, since the index or clause's equality operator might
332 * be different from ours, but it's much more likely to be right than
333 * ignoring the information.)
334 */
335 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
336 {
337 selec = 1.0 / vardata->rel->tuples;
338 }
339 else if (HeapTupleIsValid(vardata->statsTuple) &&
341 (opfuncoid = get_opcode(oproid))))
342 {
343 AttStatsSlot sslot;
344 bool match = false;
345 int i;
346
347 /*
348 * Is the constant "=" to any of the column's most common values?
349 * (Although the given operator may not really be "=", we will assume
350 * that seeing whether it returns TRUE is an appropriate test. If you
351 * don't like this, maybe you shouldn't be using eqsel for your
352 * operator...)
353 */
354 if (get_attstatsslot(&sslot, vardata->statsTuple,
355 STATISTIC_KIND_MCV, InvalidOid,
357 {
358 LOCAL_FCINFO(fcinfo, 2);
359 FmgrInfo eqproc;
360
361 fmgr_info(opfuncoid, &eqproc);
362
363 /*
364 * Save a few cycles by setting up the fcinfo struct just once.
365 * Using FunctionCallInvoke directly also avoids failure if the
366 * eqproc returns NULL, though really equality functions should
367 * never do that.
368 */
369 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
370 NULL, NULL);
371 fcinfo->args[0].isnull = false;
372 fcinfo->args[1].isnull = false;
373 /* be careful to apply operator right way 'round */
374 if (varonleft)
375 fcinfo->args[1].value = constval;
376 else
377 fcinfo->args[0].value = constval;
378
379 for (i = 0; i < sslot.nvalues; i++)
380 {
381 Datum fresult;
382
383 if (varonleft)
384 fcinfo->args[0].value = sslot.values[i];
385 else
386 fcinfo->args[1].value = sslot.values[i];
387 fcinfo->isnull = false;
388 fresult = FunctionCallInvoke(fcinfo);
389 if (!fcinfo->isnull && DatumGetBool(fresult))
390 {
391 match = true;
392 break;
393 }
394 }
395 }
396 else
397 {
398 /* no most-common-value info available */
399 i = 0; /* keep compiler quiet */
400 }
401
402 if (match)
403 {
404 /*
405 * Constant is "=" to this common value. We know selectivity
406 * exactly (or as exactly as ANALYZE could calculate it, anyway).
407 */
408 selec = sslot.numbers[i];
409 }
410 else
411 {
412 /*
413 * Comparison is against a constant that is neither NULL nor any
414 * of the common values. Its selectivity cannot be more than
415 * this:
416 */
417 double sumcommon = 0.0;
418 double otherdistinct;
419
420 for (i = 0; i < sslot.nnumbers; i++)
421 sumcommon += sslot.numbers[i];
422 selec = 1.0 - sumcommon - nullfrac;
423 CLAMP_PROBABILITY(selec);
424
425 /*
426 * and in fact it's probably a good deal less. We approximate that
427 * all the not-common values share this remaining fraction
428 * equally, so we divide by the number of other distinct values.
429 */
430 otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
431 sslot.nnumbers;
432 if (otherdistinct > 1)
433 selec /= otherdistinct;
434
435 /*
436 * Another cross-check: selectivity shouldn't be estimated as more
437 * than the least common "most common value".
438 */
439 if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
440 selec = sslot.numbers[sslot.nnumbers - 1];
441 }
442
443 free_attstatsslot(&sslot);
444 }
445 else
446 {
447 /*
448 * No ANALYZE stats available, so make a guess using estimated number
449 * of distinct values and assuming they are equally common. (The guess
450 * is unlikely to be very good, but we do know a few special cases.)
451 */
452 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
453 }
454
455 /* now adjust if we wanted <> rather than = */
456 if (negate)
457 selec = 1.0 - selec - nullfrac;
458
459 /* result should be in range, but make sure... */
460 CLAMP_PROBABILITY(selec);
461
462 return selec;
463}

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool(), fmgr_info(), free_attstatsslot(), FunctionCallInvoke, get_attstatsslot(), get_opcode(), get_variable_numdistinct(), GETSTRUCT(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, VariableStatData::isunique, LOCAL_FCINFO, AttStatsSlot::nnumbers, AttStatsSlot::numbers, AttStatsSlot::nvalues, VariableStatData::rel, statistic_proc_security_check(), VariableStatData::statsTuple, RelOptInfo::tuples, and AttStatsSlot::values.

Referenced by boolvarsel(), eqsel_internal(), patternsel_common(), and prefix_selectivity().

◆ var_eq_non_const()

double var_eq_non_const ( VariableStatData vardata,
Oid  oproid,
Oid  collation,
Node other,
bool  varonleft,
bool  negate 
)

Definition at line 471 of file selfuncs.c.

474{
475 double selec;
476 double nullfrac = 0.0;
477 bool isdefault;
478
479 /*
480 * Grab the nullfrac for use below.
481 */
482 if (HeapTupleIsValid(vardata->statsTuple))
483 {
484 Form_pg_statistic stats;
485
486 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
487 nullfrac = stats->stanullfrac;
488 }
489
490 /*
491 * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
492 * assume there is exactly one match regardless of anything else. (This
493 * is slightly bogus, since the index or clause's equality operator might
494 * be different from ours, but it's much more likely to be right than
495 * ignoring the information.)
496 */
497 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
498 {
499 selec = 1.0 / vardata->rel->tuples;
500 }
501 else if (HeapTupleIsValid(vardata->statsTuple))
502 {
503 double ndistinct;
504 AttStatsSlot sslot;
505
506 /*
507 * Search is for a value that we do not know a priori, but we will
508 * assume it is not NULL. Estimate the selectivity as non-null
509 * fraction divided by number of distinct values, so that we get a
510 * result averaged over all possible values whether common or
511 * uncommon. (Essentially, we are assuming that the not-yet-known
512 * comparison value is equally likely to be any of the possible
513 * values, regardless of their frequency in the table. Is that a good
514 * idea?)
515 */
516 selec = 1.0 - nullfrac;
517 ndistinct = get_variable_numdistinct(vardata, &isdefault);
518 if (ndistinct > 1)
519 selec /= ndistinct;
520
521 /*
522 * Cross-check: selectivity should never be estimated as more than the
523 * most common value's.
524 */
525 if (get_attstatsslot(&sslot, vardata->statsTuple,
526 STATISTIC_KIND_MCV, InvalidOid,
528 {
529 if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
530 selec = sslot.numbers[0];
531 free_attstatsslot(&sslot);
532 }
533 }
534 else
535 {
536 /*
537 * No ANALYZE stats available, so make a guess using estimated number
538 * of distinct values and assuming they are equally common. (The guess
539 * is unlikely to be very good, but we do know a few special cases.)
540 */
541 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
542 }
543
544 /* now adjust if we wanted <> rather than = */
545 if (negate)
546 selec = 1.0 - selec - nullfrac;
547
548 /* result should be in range, but make sure... */
549 CLAMP_PROBABILITY(selec);
550
551 return selec;
552}

References ATTSTATSSLOT_NUMBERS, CLAMP_PROBABILITY, free_attstatsslot(), get_attstatsslot(), get_variable_numdistinct(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, VariableStatData::isunique, AttStatsSlot::nnumbers, AttStatsSlot::numbers, VariableStatData::rel, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by eqsel_internal().

Variable Documentation

◆ get_index_stats_hook

PGDLLIMPORT get_index_stats_hook_type get_index_stats_hook
extern

Definition at line 149 of file selfuncs.c.

Referenced by brincostestimate(), examine_indexcol_variable(), and examine_variable().

◆ get_relation_stats_hook

PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook
extern