PostgreSQL Source Code git master
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 7158 of file selfuncs.c.

7159{
7160 List *predExtraQuals = NIL;
7161 ListCell *lc;
7162
7163 if (index->indpred == NIL)
7164 return indexQuals;
7165
7166 foreach(lc, index->indpred)
7167 {
7168 Node *predQual = (Node *) lfirst(lc);
7169 List *oneQual = list_make1(predQual);
7170
7171 if (!predicate_implied_by(oneQual, indexQuals, false))
7172 predExtraQuals = list_concat(predExtraQuals, oneQual);
7173 }
7174 return list_concat(predExtraQuals, indexQuals);
7175}
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:225
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:5289
#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 4057 of file selfuncs.c.

4060{
4061 VariableStatData vardata;
4062 double estfract,
4063 ndistinct,
4064 stanullfrac,
4065 avgfreq;
4066 bool isdefault;
4067 AttStatsSlot sslot;
4068
4069 examine_variable(root, hashkey, 0, &vardata);
4070
4071 /* Look up the frequency of the most common value, if available */
4072 *mcv_freq = 0.0;
4073
4074 if (HeapTupleIsValid(vardata.statsTuple))
4075 {
4076 if (get_attstatsslot(&sslot, vardata.statsTuple,
4077 STATISTIC_KIND_MCV, InvalidOid,
4079 {
4080 /*
4081 * The first MCV stat is for the most common value.
4082 */
4083 if (sslot.nnumbers > 0)
4084 *mcv_freq = sslot.numbers[0];
4085 free_attstatsslot(&sslot);
4086 }
4087 }
4088
4089 /* Get number of distinct values */
4090 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
4091
4092 /*
4093 * If ndistinct isn't real, punt. We normally return 0.1, but if the
4094 * mcv_freq is known to be even higher than that, use it instead.
4095 */
4096 if (isdefault)
4097 {
4098 *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
4099 ReleaseVariableStats(vardata);
4100 return;
4101 }
4102
4103 /* Get fraction that are null */
4104 if (HeapTupleIsValid(vardata.statsTuple))
4105 {
4106 Form_pg_statistic stats;
4107
4108 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
4109 stanullfrac = stats->stanullfrac;
4110 }
4111 else
4112 stanullfrac = 0.0;
4113
4114 /* Compute avg freq of all distinct data values in raw relation */
4115 avgfreq = (1.0 - stanullfrac) / ndistinct;
4116
4117 /*
4118 * Adjust ndistinct to account for restriction clauses. Observe we are
4119 * assuming that the data distribution is affected uniformly by the
4120 * restriction clauses!
4121 *
4122 * XXX Possibly better way, but much more expensive: multiply by
4123 * selectivity of rel's restriction clauses that mention the target Var.
4124 */
4125 if (vardata.rel && vardata.rel->tuples > 0)
4126 {
4127 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
4128 ndistinct = clamp_row_est(ndistinct);
4129 }
4130
4131 /*
4132 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
4133 * number of buckets is less than the expected number of distinct values;
4134 * otherwise it is 1/ndistinct.
4135 */
4136 if (ndistinct > nbuckets)
4137 estfract = 1.0 / nbuckets;
4138 else
4139 estfract = 1.0 / ndistinct;
4140
4141 /*
4142 * Adjust estimated bucketsize upward to account for skewed distribution.
4143 */
4144 if (avgfreq > 0.0 && *mcv_freq > avgfreq)
4145 estfract *= *mcv_freq / avgfreq;
4146
4147 /*
4148 * Clamp bucketsize to sane range (the above adjustment could easily
4149 * produce an out-of-range result). We set the lower bound a little above
4150 * zero, since zero isn't a very sane result.
4151 */
4152 if (estfract < 1.0e-6)
4153 estfract = 1.0e-6;
4154 else if (estfract > 1.0)
4155 estfract = 1.0;
4156
4157 *bucketsize_frac = (Selectivity) estfract;
4158
4159 ReleaseVariableStats(vardata);
4160}
#define Max(x, y)
Definition: c.h:969
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:6149
Cardinality tuples
Definition: pathnodes.h:973
Cardinality rows
Definition: pathnodes.h:901
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 4176 of file selfuncs.c.

4178{
4179 Size hashentrysize;
4180
4181 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4182 path->pathtarget->width,
4183 agg_costs->transitionSpace);
4184
4185 /*
4186 * Note that this disregards the effect of fill-factor and growth policy
4187 * of the hash table. That's probably ok, given that the default
4188 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4189 * "double-in-size" growth policies here.
4190 */
4191 return hashentrysize * dNumGroups;
4192}
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 bool is_duplicate = false;
3854
3855 /*
3856 * This inner-side expression references only one relation.
3857 * Extended statistics on this clause can exist.
3858 */
3859 if (group_relid < 0)
3860 {
3861 RangeTblEntry *rte = root->simple_rte_array[relid];
3862
3863 if (!rte || (rte->relkind != RELKIND_RELATION &&
3864 rte->relkind != RELKIND_MATVIEW &&
3865 rte->relkind != RELKIND_FOREIGN_TABLE &&
3866 rte->relkind != RELKIND_PARTITIONED_TABLE))
3867 {
3868 /* Extended statistics can't exist in principle */
3869 otherclauses = lappend(otherclauses, rinfo);
3870 clauses = foreach_delete_current(clauses, lc);
3871 continue;
3872 }
3873
3874 group_relid = relid;
3875 group_rel = root->simple_rel_array[relid];
3876 }
3877 else if (group_relid != relid)
3878
3879 /*
3880 * Being in the group forming state we don't need other
3881 * clauses.
3882 */
3883 continue;
3884
3885 /*
3886 * We're going to add the new clause to the varinfos list. We
3887 * might re-use add_unique_group_var(), but we don't do so for
3888 * two reasons.
3889 *
3890 * 1) We must keep the origin_rinfos list ordered exactly the
3891 * same way as varinfos.
3892 *
3893 * 2) add_unique_group_var() is designed for
3894 * estimate_num_groups(), where a larger number of groups is
3895 * worse. While estimating the number of hash buckets, we
3896 * have the opposite: a lesser number of groups is worse.
3897 * Therefore, we don't have to remove "known equal" vars: the
3898 * removed var may valuably contribute to the multivariate
3899 * statistics to grow the number of groups.
3900 */
3901
3902 /*
3903 * Clear nullingrels to correctly match hash keys. See
3904 * add_unique_group_var()'s comment for details.
3905 */
3906 expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
3907
3908 /*
3909 * Detect and exclude exact duplicates from the list of hash
3910 * keys (like add_unique_group_var does).
3911 */
3912 foreach(lc1, varinfos)
3913 {
3914 varinfo = (GroupVarInfo *) lfirst(lc1);
3915
3916 if (!equal(expr, varinfo->var))
3917 continue;
3918
3919 is_duplicate = true;
3920 break;
3921 }
3922
3923 if (is_duplicate)
3924 {
3925 /*
3926 * Skip exact duplicates. Adding them to the otherclauses
3927 * list also doesn't make sense.
3928 */
3929 continue;
3930 }
3931
3932 /*
3933 * Initialize GroupVarInfo. We only use it to call
3934 * estimate_multivariate_ndistinct(), which doesn't care about
3935 * ndistinct and isdefault fields. Thus, skip these fields.
3936 */
3937 varinfo = (GroupVarInfo *) palloc0(sizeof(GroupVarInfo));
3938 varinfo->var = expr;
3939 varinfo->rel = root->simple_rel_array[relid];
3940 varinfos = lappend(varinfos, varinfo);
3941
3942 /*
3943 * Remember the link to RestrictInfo for the case the clause
3944 * is failed to be estimated.
3945 */
3946 origin_rinfos = lappend(origin_rinfos, rinfo);
3947 }
3948 else
3949 {
3950 /* This clause can't be estimated with extended statistics */
3951 otherclauses = lappend(otherclauses, rinfo);
3952 }
3953
3954 clauses = foreach_delete_current(clauses, lc);
3955 }
3956
3957 if (list_length(varinfos) < 2)
3958 {
3959 /*
3960 * Multivariate statistics doesn't apply to single columns except
3961 * for expressions, but it has not been implemented yet.
3962 */
3963 otherclauses = list_concat(otherclauses, origin_rinfos);
3964 list_free_deep(varinfos);
3965 list_free(origin_rinfos);
3966 continue;
3967 }
3968
3969 Assert(group_rel != NULL);
3970
3971 /* Employ the extended statistics. */
3972 origin_varinfos = varinfos;
3973 for (;;)
3974 {
3975 bool estimated = estimate_multivariate_ndistinct(root,
3976 group_rel,
3977 &varinfos,
3978 &mvndistinct);
3979
3980 if (!estimated)
3981 break;
3982
3983 /*
3984 * We've got an estimation. Use ndistinct value in a consistent
3985 * way - according to the caller's logic (see
3986 * final_cost_hashjoin).
3987 */
3988 if (ndistinct < mvndistinct)
3989 ndistinct = mvndistinct;
3990 Assert(ndistinct >= 1.0);
3991 }
3992
3993 Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
3994
3995 /* Collect unmatched clauses as otherclauses. */
3996 forboth(lc1, origin_varinfos, lc2, origin_rinfos)
3997 {
3998 GroupVarInfo *vinfo = lfirst(lc1);
3999
4000 if (!list_member_ptr(varinfos, vinfo))
4001 /* Already estimated */
4002 continue;
4003
4004 /* Can't be estimated here - push to the returning list */
4005 otherclauses = lappend(otherclauses, lfirst(lc2));
4006 }
4007 }
4008
4009 *innerbucketsize = 1.0 / ndistinct;
4010 return otherclauses;
4011}
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:715
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
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 * palloc0(Size size)
Definition: mcxt.c:1975
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
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)
static bool estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
Definition: selfuncs.c:4217
RelOptInfo * rel
Definition: selfuncs.c:3310
Node * var
Definition: selfuncs.c:3309
Expr * clause
Definition: pathnodes.h:2705

References Assert(), bms_get_singleton_member(), RestrictInfo::clause, equal(), estimate_multivariate_ndistinct(), forboth, foreach_delete_current, get_leftop(), get_rightop(), lappend(), lfirst, lfirst_node, list_concat(), list_copy(), list_free(), list_free_deep(), list_length(), list_member_ptr(), NIL, palloc0(), GroupVarInfo::rel, remove_nulling_relids(), 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:863
#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
double ndistinct
Definition: selfuncs.c:3311
bool isdefault
Definition: selfuncs.c:3312
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 5289 of file selfuncs.c.

5291{
5292 Node *basenode;
5293 Relids varnos;
5294 Relids basevarnos;
5295 RelOptInfo *onerel;
5296
5297 /* Make sure we don't return dangling pointers in vardata */
5298 MemSet(vardata, 0, sizeof(VariableStatData));
5299
5300 /* Save the exposed type of the expression */
5301 vardata->vartype = exprType(node);
5302
5303 /* Look inside any binary-compatible relabeling */
5304
5305 if (IsA(node, RelabelType))
5306 basenode = (Node *) ((RelabelType *) node)->arg;
5307 else
5308 basenode = node;
5309
5310 /* Fast path for a simple Var */
5311
5312 if (IsA(basenode, Var) &&
5313 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5314 {
5315 Var *var = (Var *) basenode;
5316
5317 /* Set up result fields other than the stats tuple */
5318 vardata->var = basenode; /* return Var without relabeling */
5319 vardata->rel = find_base_rel(root, var->varno);
5320 vardata->atttype = var->vartype;
5321 vardata->atttypmod = var->vartypmod;
5322 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5323
5324 /* Try to locate some stats */
5325 examine_simple_variable(root, var, vardata);
5326
5327 return;
5328 }
5329
5330 /*
5331 * Okay, it's a more complicated expression. Determine variable
5332 * membership. Note that when varRelid isn't zero, only vars of that
5333 * relation are considered "real" vars.
5334 */
5335 varnos = pull_varnos(root, basenode);
5336 basevarnos = bms_difference(varnos, root->outer_join_rels);
5337
5338 onerel = NULL;
5339
5340 if (bms_is_empty(basevarnos))
5341 {
5342 /* No Vars at all ... must be pseudo-constant clause */
5343 }
5344 else
5345 {
5346 int relid;
5347
5348 /* Check if the expression is in vars of a single base relation */
5349 if (bms_get_singleton_member(basevarnos, &relid))
5350 {
5351 if (varRelid == 0 || varRelid == relid)
5352 {
5353 onerel = find_base_rel(root, relid);
5354 vardata->rel = onerel;
5355 node = basenode; /* strip any relabeling */
5356 }
5357 /* else treat it as a constant */
5358 }
5359 else
5360 {
5361 /* varnos has multiple relids */
5362 if (varRelid == 0)
5363 {
5364 /* treat it as a variable of a join relation */
5365 vardata->rel = find_join_rel(root, varnos);
5366 node = basenode; /* strip any relabeling */
5367 }
5368 else if (bms_is_member(varRelid, varnos))
5369 {
5370 /* ignore the vars belonging to other relations */
5371 vardata->rel = find_base_rel(root, varRelid);
5372 node = basenode; /* strip any relabeling */
5373 /* note: no point in expressional-index search here */
5374 }
5375 /* else treat it as a constant */
5376 }
5377 }
5378
5379 bms_free(basevarnos);
5380
5381 vardata->var = node;
5382 vardata->atttype = exprType(node);
5383 vardata->atttypmod = exprTypmod(node);
5384
5385 if (onerel)
5386 {
5387 /*
5388 * We have an expression in vars of a single relation. Try to match
5389 * it to expressional index columns, in hopes of finding some
5390 * statistics.
5391 *
5392 * Note that we consider all index columns including INCLUDE columns,
5393 * since there could be stats for such columns. But the test for
5394 * uniqueness needs to be warier.
5395 *
5396 * XXX it's conceivable that there are multiple matches with different
5397 * index opfamilies; if so, we need to pick one that matches the
5398 * operator we are estimating for. FIXME later.
5399 */
5400 ListCell *ilist;
5401 ListCell *slist;
5402 Oid userid;
5403
5404 /*
5405 * The nullingrels bits within the expression could prevent us from
5406 * matching it to expressional index columns or to the expressions in
5407 * extended statistics. So strip them out first.
5408 */
5409 if (bms_overlap(varnos, root->outer_join_rels))
5410 node = remove_nulling_relids(node, root->outer_join_rels, NULL);
5411
5412 /*
5413 * Determine the user ID to use for privilege checks: either
5414 * onerel->userid if it's set (e.g., in case we're accessing the table
5415 * via a view), or the current user otherwise.
5416 *
5417 * If we drill down to child relations, we keep using the same userid:
5418 * it's going to be the same anyway, due to how we set up the relation
5419 * tree (q.v. build_simple_rel).
5420 */
5421 userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5422
5423 foreach(ilist, onerel->indexlist)
5424 {
5425 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5426 ListCell *indexpr_item;
5427 int pos;
5428
5429 indexpr_item = list_head(index->indexprs);
5430 if (indexpr_item == NULL)
5431 continue; /* no expressions here... */
5432
5433 for (pos = 0; pos < index->ncolumns; pos++)
5434 {
5435 if (index->indexkeys[pos] == 0)
5436 {
5437 Node *indexkey;
5438
5439 if (indexpr_item == NULL)
5440 elog(ERROR, "too few entries in indexprs list");
5441 indexkey = (Node *) lfirst(indexpr_item);
5442 if (indexkey && IsA(indexkey, RelabelType))
5443 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5444 if (equal(node, indexkey))
5445 {
5446 /*
5447 * Found a match ... is it a unique index? Tests here
5448 * should match has_unique_index().
5449 */
5450 if (index->unique &&
5451 index->nkeycolumns == 1 &&
5452 pos == 0 &&
5453 (index->indpred == NIL || index->predOK))
5454 vardata->isunique = true;
5455
5456 /*
5457 * Has it got stats? We only consider stats for
5458 * non-partial indexes, since partial indexes probably
5459 * don't reflect whole-relation statistics; the above
5460 * check for uniqueness is the only info we take from
5461 * a partial index.
5462 *
5463 * An index stats hook, however, must make its own
5464 * decisions about what to do with partial indexes.
5465 */
5467 (*get_index_stats_hook) (root, index->indexoid,
5468 pos + 1, vardata))
5469 {
5470 /*
5471 * The hook took control of acquiring a stats
5472 * tuple. If it did supply a tuple, it'd better
5473 * have supplied a freefunc.
5474 */
5475 if (HeapTupleIsValid(vardata->statsTuple) &&
5476 !vardata->freefunc)
5477 elog(ERROR, "no function provided to release variable stats with");
5478 }
5479 else if (index->indpred == NIL)
5480 {
5481 vardata->statsTuple =
5482 SearchSysCache3(STATRELATTINH,
5483 ObjectIdGetDatum(index->indexoid),
5484 Int16GetDatum(pos + 1),
5485 BoolGetDatum(false));
5486 vardata->freefunc = ReleaseSysCache;
5487
5488 if (HeapTupleIsValid(vardata->statsTuple))
5489 {
5490 /* Get index's table for permission check */
5491 RangeTblEntry *rte;
5492
5493 rte = planner_rt_fetch(index->rel->relid, root);
5494 Assert(rte->rtekind == RTE_RELATION);
5495
5496 /*
5497 * For simplicity, we insist on the whole
5498 * table being selectable, rather than trying
5499 * to identify which column(s) the index
5500 * depends on. Also require all rows to be
5501 * selectable --- there must be no
5502 * securityQuals from security barrier views
5503 * or RLS policies.
5504 */
5505 vardata->acl_ok =
5506 rte->securityQuals == NIL &&
5507 (pg_class_aclcheck(rte->relid, userid,
5509
5510 /*
5511 * If the user doesn't have permissions to
5512 * access an inheritance child relation, check
5513 * the permissions of the table actually
5514 * mentioned in the query, since most likely
5515 * the user does have that permission. Note
5516 * that whole-table select privilege on the
5517 * parent doesn't quite guarantee that the
5518 * user could read all columns of the child.
5519 * But in practice it's unlikely that any
5520 * interesting security violation could result
5521 * from allowing access to the expression
5522 * index's stats, so we allow it anyway. See
5523 * similar code in examine_simple_variable()
5524 * for additional comments.
5525 */
5526 if (!vardata->acl_ok &&
5527 root->append_rel_array != NULL)
5528 {
5529 AppendRelInfo *appinfo;
5530 Index varno = index->rel->relid;
5531
5532 appinfo = root->append_rel_array[varno];
5533 while (appinfo &&
5535 root)->rtekind == RTE_RELATION)
5536 {
5537 varno = appinfo->parent_relid;
5538 appinfo = root->append_rel_array[varno];
5539 }
5540 if (varno != index->rel->relid)
5541 {
5542 /* Repeat access check on this rel */
5543 rte = planner_rt_fetch(varno, root);
5544 Assert(rte->rtekind == RTE_RELATION);
5545
5546 vardata->acl_ok =
5547 rte->securityQuals == NIL &&
5548 (pg_class_aclcheck(rte->relid,
5549 userid,
5551 }
5552 }
5553 }
5554 else
5555 {
5556 /* suppress leakproofness checks later */
5557 vardata->acl_ok = true;
5558 }
5559 }
5560 if (vardata->statsTuple)
5561 break;
5562 }
5563 indexpr_item = lnext(index->indexprs, indexpr_item);
5564 }
5565 }
5566 if (vardata->statsTuple)
5567 break;
5568 }
5569
5570 /*
5571 * Search extended statistics for one with a matching expression.
5572 * There might be multiple ones, so just grab the first one. In the
5573 * future, we might consider the statistics target (and pick the most
5574 * accurate statistics) and maybe some other parameters.
5575 */
5576 foreach(slist, onerel->statlist)
5577 {
5578 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5579 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5580 ListCell *expr_item;
5581 int pos;
5582
5583 /*
5584 * Stop once we've found statistics for the expression (either
5585 * from extended stats, or for an index in the preceding loop).
5586 */
5587 if (vardata->statsTuple)
5588 break;
5589
5590 /* skip stats without per-expression stats */
5591 if (info->kind != STATS_EXT_EXPRESSIONS)
5592 continue;
5593
5594 /* skip stats with mismatching stxdinherit value */
5595 if (info->inherit != rte->inh)
5596 continue;
5597
5598 pos = 0;
5599 foreach(expr_item, info->exprs)
5600 {
5601 Node *expr = (Node *) lfirst(expr_item);
5602
5603 Assert(expr);
5604
5605 /* strip RelabelType before comparing it */
5606 if (expr && IsA(expr, RelabelType))
5607 expr = (Node *) ((RelabelType *) expr)->arg;
5608
5609 /* found a match, see if we can extract pg_statistic row */
5610 if (equal(node, expr))
5611 {
5612 /*
5613 * XXX Not sure if we should cache the tuple somewhere.
5614 * Now we just create a new copy every time.
5615 */
5616 vardata->statsTuple =
5617 statext_expressions_load(info->statOid, rte->inh, pos);
5618
5619 vardata->freefunc = ReleaseDummy;
5620
5621 /*
5622 * For simplicity, we insist on the whole table being
5623 * selectable, rather than trying to identify which
5624 * column(s) the statistics object depends on. Also
5625 * require all rows to be selectable --- there must be no
5626 * securityQuals from security barrier views or RLS
5627 * policies.
5628 */
5629 vardata->acl_ok =
5630 rte->securityQuals == NIL &&
5631 (pg_class_aclcheck(rte->relid, userid,
5633
5634 /*
5635 * If the user doesn't have permissions to access an
5636 * inheritance child relation, check the permissions of
5637 * the table actually mentioned in the query, since most
5638 * likely the user does have that permission. Note that
5639 * whole-table select privilege on the parent doesn't
5640 * quite guarantee that the user could read all columns of
5641 * the child. But in practice it's unlikely that any
5642 * interesting security violation could result from
5643 * allowing access to the expression stats, so we allow it
5644 * anyway. See similar code in examine_simple_variable()
5645 * for additional comments.
5646 */
5647 if (!vardata->acl_ok &&
5648 root->append_rel_array != NULL)
5649 {
5650 AppendRelInfo *appinfo;
5651 Index varno = onerel->relid;
5652
5653 appinfo = root->append_rel_array[varno];
5654 while (appinfo &&
5656 root)->rtekind == RTE_RELATION)
5657 {
5658 varno = appinfo->parent_relid;
5659 appinfo = root->append_rel_array[varno];
5660 }
5661 if (varno != onerel->relid)
5662 {
5663 /* Repeat access check on this rel */
5664 rte = planner_rt_fetch(varno, root);
5665 Assert(rte->rtekind == RTE_RELATION);
5666
5667 vardata->acl_ok =
5668 rte->securityQuals == NIL &&
5669 (pg_class_aclcheck(rte->relid,
5670 userid,
5672 }
5673 }
5674
5675 break;
5676 }
5677
5678 pos++;
5679 }
5680 }
5681 }
5682
5683 bms_free(varnos);
5684}
@ 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
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:594
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
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5696
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:149
static void ReleaseDummy(HeapTuple tuple)
Definition: selfuncs.c:5248
Index parent_relid
Definition: pathnodes.h:3110
RTEKind rtekind
Definition: parsenodes.h:1061
Index relid
Definition: pathnodes.h:942
List * statlist
Definition: pathnodes.h:970
List * indexlist
Definition: pathnodes.h:968
Oid userid
Definition: pathnodes.h:990
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:5160
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 6935 of file selfuncs.c.

6939{
6940 IndexOptInfo *index = path->indexinfo;
6941 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6942 List *indexOrderBys = path->indexorderbys;
6943 Cost indexStartupCost;
6944 Cost indexTotalCost;
6945 Selectivity indexSelectivity;
6946 double indexCorrelation;
6947 double numIndexPages;
6948 double numIndexTuples;
6949 double spc_random_page_cost;
6950 double num_sa_scans;
6951 double num_outer_scans;
6952 double num_scans;
6953 double qual_op_cost;
6954 double qual_arg_cost;
6955 List *selectivityQuals;
6956 ListCell *l;
6957
6958 /*
6959 * If the index is partial, AND the index predicate with the explicitly
6960 * given indexquals to produce a more accurate idea of the index
6961 * selectivity.
6962 */
6963 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6964
6965 /*
6966 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
6967 * just assume that the number of index descents is the number of distinct
6968 * combinations of array elements from all of the scan's SAOP clauses.
6969 */
6970 num_sa_scans = costs->num_sa_scans;
6971 if (num_sa_scans < 1)
6972 {
6973 num_sa_scans = 1;
6974 foreach(l, indexQuals)
6975 {
6976 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6977
6978 if (IsA(rinfo->clause, ScalarArrayOpExpr))
6979 {
6980 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6981 double alength = estimate_array_length(root, lsecond(saop->args));
6982
6983 if (alength > 1)
6984 num_sa_scans *= alength;
6985 }
6986 }
6987 }
6988
6989 /* Estimate the fraction of main-table tuples that will be visited */
6990 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6991 index->rel->relid,
6992 JOIN_INNER,
6993 NULL);
6994
6995 /*
6996 * If caller didn't give us an estimate, estimate the number of index
6997 * tuples that will be visited. We do it in this rather peculiar-looking
6998 * way in order to get the right answer for partial indexes.
6999 */
7000 numIndexTuples = costs->numIndexTuples;
7001 if (numIndexTuples <= 0.0)
7002 {
7003 numIndexTuples = indexSelectivity * index->rel->tuples;
7004
7005 /*
7006 * The above calculation counts all the tuples visited across all
7007 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
7008 * average per-indexscan number, so adjust. This is a handy place to
7009 * round to integer, too. (If caller supplied tuple estimate, it's
7010 * responsible for handling these considerations.)
7011 */
7012 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7013 }
7014
7015 /*
7016 * We can bound the number of tuples by the index size in any case. Also,
7017 * always estimate at least one tuple is touched, even when
7018 * indexSelectivity estimate is tiny.
7019 */
7020 if (numIndexTuples > index->tuples)
7021 numIndexTuples = index->tuples;
7022 if (numIndexTuples < 1.0)
7023 numIndexTuples = 1.0;
7024
7025 /*
7026 * Estimate the number of index pages that will be retrieved.
7027 *
7028 * We use the simplistic method of taking a pro-rata fraction of the total
7029 * number of index pages. In effect, this counts only leaf pages and not
7030 * any overhead such as index metapage or upper tree levels.
7031 *
7032 * In practice access to upper index levels is often nearly free because
7033 * those tend to stay in cache under load; moreover, the cost involved is
7034 * highly dependent on index type. We therefore ignore such costs here
7035 * and leave it to the caller to add a suitable charge if needed.
7036 */
7037 if (index->pages > 1 && index->tuples > 1)
7038 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
7039 else
7040 numIndexPages = 1.0;
7041
7042 /* fetch estimated page cost for tablespace containing index */
7043 get_tablespace_page_costs(index->reltablespace,
7044 &spc_random_page_cost,
7045 NULL);
7046
7047 /*
7048 * Now compute the disk access costs.
7049 *
7050 * The above calculations are all per-index-scan. However, if we are in a
7051 * nestloop inner scan, we can expect the scan to be repeated (with
7052 * different search keys) for each row of the outer relation. Likewise,
7053 * ScalarArrayOpExpr quals result in multiple index scans. This creates
7054 * the potential for cache effects to reduce the number of disk page
7055 * fetches needed. We want to estimate the average per-scan I/O cost in
7056 * the presence of caching.
7057 *
7058 * We use the Mackert-Lohman formula (see costsize.c for details) to
7059 * estimate the total number of page fetches that occur. While this
7060 * wasn't what it was designed for, it seems a reasonable model anyway.
7061 * Note that we are counting pages not tuples anymore, so we take N = T =
7062 * index size, as if there were one "tuple" per page.
7063 */
7064 num_outer_scans = loop_count;
7065 num_scans = num_sa_scans * num_outer_scans;
7066
7067 if (num_scans > 1)
7068 {
7069 double pages_fetched;
7070
7071 /* total page fetches ignoring cache effects */
7072 pages_fetched = numIndexPages * num_scans;
7073
7074 /* use Mackert and Lohman formula to adjust for cache effects */
7075 pages_fetched = index_pages_fetched(pages_fetched,
7076 index->pages,
7077 (double) index->pages,
7078 root);
7079
7080 /*
7081 * Now compute the total disk access cost, and then report a pro-rated
7082 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7083 * since that's internal to the indexscan.)
7084 */
7085 indexTotalCost = (pages_fetched * spc_random_page_cost)
7086 / num_outer_scans;
7087 }
7088 else
7089 {
7090 /*
7091 * For a single index scan, we just charge spc_random_page_cost per
7092 * page touched.
7093 */
7094 indexTotalCost = numIndexPages * spc_random_page_cost;
7095 }
7096
7097 /*
7098 * CPU cost: any complex expressions in the indexquals will need to be
7099 * evaluated once at the start of the scan to reduce them to runtime keys
7100 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7101 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7102 * indexqual operator. Because we have numIndexTuples as a per-scan
7103 * number, we have to multiply by num_sa_scans to get the correct result
7104 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7105 * ORDER BY expressions.
7106 *
7107 * Note: this neglects the possible costs of rechecking lossy operators.
7108 * Detecting that that might be needed seems more expensive than it's
7109 * worth, though, considering all the other inaccuracies here ...
7110 */
7111 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
7112 index_other_operands_eval_cost(root, indexOrderBys);
7113 qual_op_cost = cpu_operator_cost *
7114 (list_length(indexQuals) + list_length(indexOrderBys));
7115
7116 indexStartupCost = qual_arg_cost;
7117 indexTotalCost += qual_arg_cost;
7118 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7119
7120 /*
7121 * Generic assumption about index correlation: there isn't any.
7122 */
7123 indexCorrelation = 0.0;
7124
7125 /*
7126 * Return everything to caller.
7127 */
7128 costs->indexStartupCost = indexStartupCost;
7129 costs->indexTotalCost = indexTotalCost;
7130 costs->indexSelectivity = indexSelectivity;
7131 costs->indexCorrelation = indexCorrelation;
7132 costs->numIndexPages = numIndexPages;
7133 costs->numIndexTuples = numIndexTuples;
7134 costs->spc_random_page_cost = spc_random_page_cost;
7135 costs->num_sa_scans = num_sa_scans;
7136}
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:6851
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:7158
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:6881
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:1845
List * indexorderbys
Definition: pathnodes.h:1846
IndexOptInfo * indexinfo
Definition: pathnodes.h:1844

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

5223{
5224 Node *left,
5225 *right;
5226
5227 if (list_length(args) != 2)
5228 elog(ERROR, "join operator should take two arguments");
5229
5230 left = (Node *) linitial(args);
5231 right = (Node *) lsecond(args);
5232
5233 examine_variable(root, left, 0, vardata1);
5234 examine_variable(root, right, 0, vardata2);
5235
5236 if (vardata1->rel &&
5237 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5238 *join_is_reversed = true; /* var1 is on RHS */
5239 else if (vardata2->rel &&
5240 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5241 *join_is_reversed = true; /* var2 is on LHS */
5242 else
5243 *join_is_reversed = false;
5244}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Relids relids
Definition: pathnodes.h:895
Relids syn_lefthand
Definition: pathnodes.h:3037
Relids syn_righthand
Definition: pathnodes.h:3038

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

6852{
6853 List *result = NIL;
6854 ListCell *lc;
6855
6856 foreach(lc, indexclauses)
6857 {
6858 IndexClause *iclause = lfirst_node(IndexClause, lc);
6859 ListCell *lc2;
6860
6861 foreach(lc2, iclause->indexquals)
6862 {
6863 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6864
6865 result = lappend(result, rinfo);
6866 }
6867 }
6868 return result;
6869}
List * indexquals
Definition: pathnodes.h:1893

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

5163{
5164 Node *left,
5165 *right;
5166 VariableStatData rdata;
5167
5168 /* Fail if not a binary opclause (probably shouldn't happen) */
5169 if (list_length(args) != 2)
5170 return false;
5171
5172 left = (Node *) linitial(args);
5173 right = (Node *) lsecond(args);
5174
5175 /*
5176 * Examine both sides. Note that when varRelid is nonzero, Vars of other
5177 * relations will be treated as pseudoconstants.
5178 */
5179 examine_variable(root, left, varRelid, vardata);
5180 examine_variable(root, right, varRelid, &rdata);
5181
5182 /*
5183 * If one side is a variable and the other not, we win.
5184 */
5185 if (vardata->rel && rdata.rel == NULL)
5186 {
5187 *varonleft = true;
5188 *other = estimate_expression_value(root, rdata.var);
5189 /* Assume we need no ReleaseVariableStats(rdata) here */
5190 return true;
5191 }
5192
5193 if (vardata->rel == NULL && rdata.rel)
5194 {
5195 *varonleft = false;
5196 *other = estimate_expression_value(root, vardata->var);
5197 /* Assume we need no ReleaseVariableStats(*vardata) here */
5198 *vardata = rdata;
5199 return true;
5200 }
5201
5202 /* Oops, clause has wrong structure (probably var op var) */
5203 ReleaseVariableStats(*vardata);
5204 ReleaseVariableStats(rdata);
5205
5206 return false;
5207}
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 6149 of file selfuncs.c.

6150{
6151 double stadistinct;
6152 double stanullfrac = 0.0;
6153 double ntuples;
6154
6155 *isdefault = false;
6156
6157 /*
6158 * Determine the stadistinct value to use. There are cases where we can
6159 * get an estimate even without a pg_statistic entry, or can get a better
6160 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6161 * (otherwise, assume no nulls, for lack of any better idea).
6162 */
6163 if (HeapTupleIsValid(vardata->statsTuple))
6164 {
6165 /* Use the pg_statistic entry */
6166 Form_pg_statistic stats;
6167
6168 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6169 stadistinct = stats->stadistinct;
6170 stanullfrac = stats->stanullfrac;
6171 }
6172 else if (vardata->vartype == BOOLOID)
6173 {
6174 /*
6175 * Special-case boolean columns: presumably, two distinct values.
6176 *
6177 * Are there any other datatypes we should wire in special estimates
6178 * for?
6179 */
6180 stadistinct = 2.0;
6181 }
6182 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6183 {
6184 /*
6185 * If the Var represents a column of a VALUES RTE, assume it's unique.
6186 * This could of course be very wrong, but it should tend to be true
6187 * in well-written queries. We could consider examining the VALUES'
6188 * contents to get some real statistics; but that only works if the
6189 * entries are all constants, and it would be pretty expensive anyway.
6190 */
6191 stadistinct = -1.0; /* unique (and all non null) */
6192 }
6193 else
6194 {
6195 /*
6196 * We don't keep statistics for system columns, but in some cases we
6197 * can infer distinctness anyway.
6198 */
6199 if (vardata->var && IsA(vardata->var, Var))
6200 {
6201 switch (((Var *) vardata->var)->varattno)
6202 {
6204 stadistinct = -1.0; /* unique (and all non null) */
6205 break;
6207 stadistinct = 1.0; /* only 1 value */
6208 break;
6209 default:
6210 stadistinct = 0.0; /* means "unknown" */
6211 break;
6212 }
6213 }
6214 else
6215 stadistinct = 0.0; /* means "unknown" */
6216
6217 /*
6218 * XXX consider using estimate_num_groups on expressions?
6219 */
6220 }
6221
6222 /*
6223 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6224 * variable, assume it is unique no matter what pg_statistic says; the
6225 * statistics could be out of date, or we might have found a partial
6226 * unique index that proves the var is unique for this query. However,
6227 * we'd better still believe the null-fraction statistic.
6228 */
6229 if (vardata->isunique)
6230 stadistinct = -1.0 * (1.0 - stanullfrac);
6231
6232 /*
6233 * If we had an absolute estimate, use that.
6234 */
6235 if (stadistinct > 0.0)
6236 return clamp_row_est(stadistinct);
6237
6238 /*
6239 * Otherwise we need to get the relation size; punt if not available.
6240 */
6241 if (vardata->rel == NULL)
6242 {
6243 *isdefault = true;
6244 return DEFAULT_NUM_DISTINCT;
6245 }
6246 ntuples = vardata->rel->tuples;
6247 if (ntuples <= 0.0)
6248 {
6249 *isdefault = true;
6250 return DEFAULT_NUM_DISTINCT;
6251 }
6252
6253 /*
6254 * If we had a relative estimate, use that.
6255 */
6256 if (stadistinct < 0.0)
6257 return clamp_row_est(-stadistinct * ntuples);
6258
6259 /*
6260 * With no data, estimate ndistinct = ntuples if the table is small, else
6261 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6262 * that the behavior isn't discontinuous.
6263 */
6264 if (ntuples < DEFAULT_NUM_DISTINCT)
6265 return clamp_row_est(ntuples);
6266
6267 *isdefault = true;
6268 return DEFAULT_NUM_DISTINCT;
6269}
@ RTE_VALUES
Definition: parsenodes.h:1031
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
RTEKind rtekind
Definition: pathnodes.h:946
#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:6120
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 6881 of file selfuncs.c.

6882{
6883 Cost qual_arg_cost = 0;
6884 ListCell *lc;
6885
6886 foreach(lc, indexquals)
6887 {
6888 Expr *clause = (Expr *) lfirst(lc);
6889 Node *other_operand;
6890 QualCost index_qual_cost;
6891
6892 /*
6893 * Index quals will have RestrictInfos, indexorderbys won't. Look
6894 * through RestrictInfo if present.
6895 */
6896 if (IsA(clause, RestrictInfo))
6897 clause = ((RestrictInfo *) clause)->clause;
6898
6899 if (IsA(clause, OpExpr))
6900 {
6901 OpExpr *op = (OpExpr *) clause;
6902
6903 other_operand = (Node *) lsecond(op->args);
6904 }
6905 else if (IsA(clause, RowCompareExpr))
6906 {
6907 RowCompareExpr *rc = (RowCompareExpr *) clause;
6908
6909 other_operand = (Node *) rc->rargs;
6910 }
6911 else if (IsA(clause, ScalarArrayOpExpr))
6912 {
6913 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6914
6915 other_operand = (Node *) lsecond(saop->args);
6916 }
6917 else if (IsA(clause, NullTest))
6918 {
6919 other_operand = NULL;
6920 }
6921 else
6922 {
6923 elog(ERROR, "unsupported indexqual type: %d",
6924 (int) nodeTag(clause));
6925 other_operand = NULL; /* keep compiler quiet */
6926 }
6927
6928 cost_qual_eval_node(&index_qual_cost, other_operand, root);
6929 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6930 }
6931 return qual_arg_cost;
6932}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4768
#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:4575
static bool get_actual_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
Definition: selfuncs.c:6472

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:6282
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 6120 of file selfuncs.c.

6121{
6122 if (vardata->acl_ok)
6123 return true;
6124
6125 if (!OidIsValid(func_oid))
6126 return false;
6127
6128 if (get_func_leakproof(func_oid))
6129 return true;
6130
6132 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6133 get_func_name(func_oid))));
6134 return false;
6135}
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