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 all_rows_selectable (PlannerInfo *root, Index varno, Bitmapset *varattnos)
 
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 101 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 145 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 140 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 7537 of file selfuncs.c.

7538{
7539 List *predExtraQuals = NIL;
7540 ListCell *lc;
7541
7542 if (index->indpred == NIL)
7543 return indexQuals;
7544
7545 foreach(lc, index->indpred)
7546 {
7547 Node *predQual = (Node *) lfirst(lc);
7548 List *oneQual = list_make1(predQual);
7549
7550 if (!predicate_implied_by(oneQual, indexQuals, false))
7551 predExtraQuals = list_concat(predExtraQuals, oneQual);
7552 }
7553 return list_concat(predExtraQuals, indexQuals);
7554}
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().

◆ all_rows_selectable()

bool all_rows_selectable ( PlannerInfo root,
Index  varno,
Bitmapset varattnos 
)

Definition at line 6223 of file selfuncs.c.

6224{
6225 RelOptInfo *rel = find_base_rel_noerr(root, varno);
6226 RangeTblEntry *rte = planner_rt_fetch(varno, root);
6227 Oid userid;
6228 int varattno;
6229
6230 Assert(rte->rtekind == RTE_RELATION);
6231
6232 /*
6233 * Determine the user ID to use for privilege checks (either the current
6234 * user or the view owner, if we're accessing the table via a view).
6235 *
6236 * Normally the relation will have an associated RelOptInfo from which we
6237 * can find the userid, but it might not if it's a RETURNING Var for an
6238 * INSERT target relation. In that case use the RTEPermissionInfo
6239 * associated with the RTE.
6240 *
6241 * If we navigate up to a parent relation, we keep using the same userid,
6242 * since it's the same in all relations of a given inheritance tree.
6243 */
6244 if (rel)
6245 userid = rel->userid;
6246 else
6247 {
6248 RTEPermissionInfo *perminfo;
6249
6250 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
6251 userid = perminfo->checkAsUser;
6252 }
6253 if (!OidIsValid(userid))
6254 userid = GetUserId();
6255
6256 /*
6257 * Permissions and securityQuals must be checked on the table actually
6258 * mentioned in the query, so if this is an inheritance child, navigate up
6259 * to the inheritance root parent. If the user can read the whole table
6260 * or the required columns there, then they can read from the child table
6261 * too. For per-column checks, we must find out which of the root
6262 * parent's attributes the child relation's attributes correspond to.
6263 */
6264 if (root->append_rel_array != NULL)
6265 {
6266 AppendRelInfo *appinfo;
6267
6268 appinfo = root->append_rel_array[varno];
6269
6270 /*
6271 * Partitions are mapped to their immediate parent, not the root
6272 * parent, so must be ready to walk up multiple AppendRelInfos. But
6273 * stop if we hit a parent that is not RTE_RELATION --- that's a
6274 * flattened UNION ALL subquery, not an inheritance parent.
6275 */
6276 while (appinfo &&
6278 root)->rtekind == RTE_RELATION)
6279 {
6280 Bitmapset *parent_varattnos = NULL;
6281
6282 /*
6283 * For each child attribute, find the corresponding parent
6284 * attribute. In rare cases, the attribute may be local to the
6285 * child table, in which case, we've got to live with having no
6286 * access to this column.
6287 */
6288 varattno = -1;
6289 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6290 {
6291 AttrNumber attno;
6292 AttrNumber parent_attno;
6293
6294 attno = varattno + FirstLowInvalidHeapAttributeNumber;
6295
6296 if (attno == InvalidAttrNumber)
6297 {
6298 /*
6299 * Whole-row reference, so must map each column of the
6300 * child to the parent table.
6301 */
6302 for (attno = 1; attno <= appinfo->num_child_cols; attno++)
6303 {
6304 parent_attno = appinfo->parent_colnos[attno - 1];
6305 if (parent_attno == 0)
6306 return false; /* attr is local to child */
6307 parent_varattnos =
6308 bms_add_member(parent_varattnos,
6309 parent_attno - FirstLowInvalidHeapAttributeNumber);
6310 }
6311 }
6312 else
6313 {
6314 if (attno < 0)
6315 {
6316 /* System attnos are the same in all tables */
6317 parent_attno = attno;
6318 }
6319 else
6320 {
6321 if (attno > appinfo->num_child_cols)
6322 return false; /* safety check */
6323 parent_attno = appinfo->parent_colnos[attno - 1];
6324 if (parent_attno == 0)
6325 return false; /* attr is local to child */
6326 }
6327 parent_varattnos =
6328 bms_add_member(parent_varattnos,
6329 parent_attno - FirstLowInvalidHeapAttributeNumber);
6330 }
6331 }
6332
6333 /* If the parent is itself a child, continue up */
6334 varno = appinfo->parent_relid;
6335 varattnos = parent_varattnos;
6336 appinfo = root->append_rel_array[varno];
6337 }
6338
6339 /* Perform the access check on this parent rel */
6340 rte = planner_rt_fetch(varno, root);
6341 Assert(rte->rtekind == RTE_RELATION);
6342 }
6343
6344 /*
6345 * For all rows to be accessible, there must be no securityQuals from
6346 * security barrier views or RLS policies.
6347 */
6348 if (rte->securityQuals != NIL)
6349 return false;
6350
6351 /*
6352 * Test for table-level SELECT privilege.
6353 *
6354 * If varattnos is non-NULL, this is sufficient to give access to all
6355 * requested attributes, even for a child table, since we have verified
6356 * that all required child columns have matching parent columns.
6357 *
6358 * If varattnos is NULL (whole-table access requested), this doesn't
6359 * necessarily guarantee that the user can read all columns of a child
6360 * table, but we allow it anyway (see comments in examine_variable()) and
6361 * don't bother checking any column privileges.
6362 */
6363 if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
6364 return true;
6365
6366 if (varattnos == NULL)
6367 return false; /* whole-table access requested */
6368
6369 /*
6370 * Don't have table-level SELECT privilege, so check per-column
6371 * privileges.
6372 */
6373 varattno = -1;
6374 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6375 {
6377
6378 if (attno == InvalidAttrNumber)
6379 {
6380 /* Whole-row reference, so must have access to all columns */
6381 if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
6383 return false;
6384 }
6385 else
6386 {
6387 if (pg_attribute_aclcheck(rte->relid, attno, userid,
6389 return false;
6390 }
6391 }
6392
6393 /* If we reach here, have all required column privileges */
6394 return true;
6395}
@ ACLCHECK_OK
Definition: acl.h:183
@ ACLMASK_ALL
Definition: acl.h:176
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:3908
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3866
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4037
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1305
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
#define OidIsValid(objectId)
Definition: c.h:777
Assert(PointerIsAligned(start, uint64))
Oid GetUserId(void)
Definition: miscinit.c:469
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_RELATION
Definition: parsenodes.h:1043
#define ACL_SELECT
Definition: parsenodes.h:77
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:610
unsigned int Oid
Definition: postgres_ext.h:32
tree ctl root
Definition: radixtree.h:1857
RelOptInfo * find_base_rel_noerr(PlannerInfo *root, int relid)
Definition: relnode.c:551
Index parent_relid
Definition: pathnodes.h:3192
int num_child_cols
Definition: pathnodes.h:3228
RTEKind rtekind
Definition: parsenodes.h:1078
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References ACL_SELECT, ACLCHECK_OK, ACLMASK_ALL, Assert(), bms_add_member(), bms_next_member(), RTEPermissionInfo::checkAsUser, find_base_rel_noerr(), FirstLowInvalidHeapAttributeNumber, getRTEPermissionInfo(), GetUserId(), InvalidAttrNumber, NIL, AppendRelInfo::num_child_cols, OidIsValid, AppendRelInfo::parent_relid, pg_attribute_aclcheck(), pg_attribute_aclcheck_all(), pg_class_aclcheck(), planner_rt_fetch, root, RTE_RELATION, RangeTblEntry::rtekind, and RelOptInfo::userid.

Referenced by examine_simple_variable(), examine_variable(), and statext_is_compatible_clause().

◆ booltestsel()

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

Definition at line 1621 of file selfuncs.c.

1623{
1624 VariableStatData vardata;
1625 double selec;
1626
1627 examine_variable(root, arg, varRelid, &vardata);
1628
1629 if (HeapTupleIsValid(vardata.statsTuple))
1630 {
1631 Form_pg_statistic stats;
1632 double freq_null;
1633 AttStatsSlot sslot;
1634
1635 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1636 freq_null = stats->stanullfrac;
1637
1638 if (get_attstatsslot(&sslot, vardata.statsTuple,
1639 STATISTIC_KIND_MCV, InvalidOid,
1641 && sslot.nnumbers > 0)
1642 {
1643 double freq_true;
1644 double freq_false;
1645
1646 /*
1647 * Get first MCV frequency and derive frequency for true.
1648 */
1649 if (DatumGetBool(sslot.values[0]))
1650 freq_true = sslot.numbers[0];
1651 else
1652 freq_true = 1.0 - sslot.numbers[0] - freq_null;
1653
1654 /*
1655 * Next derive frequency for false. Then use these as appropriate
1656 * to derive frequency for each case.
1657 */
1658 freq_false = 1.0 - freq_true - freq_null;
1659
1660 switch (booltesttype)
1661 {
1662 case IS_UNKNOWN:
1663 /* select only NULL values */
1664 selec = freq_null;
1665 break;
1666 case IS_NOT_UNKNOWN:
1667 /* select non-NULL values */
1668 selec = 1.0 - freq_null;
1669 break;
1670 case IS_TRUE:
1671 /* select only TRUE values */
1672 selec = freq_true;
1673 break;
1674 case IS_NOT_TRUE:
1675 /* select non-TRUE values */
1676 selec = 1.0 - freq_true;
1677 break;
1678 case IS_FALSE:
1679 /* select only FALSE values */
1680 selec = freq_false;
1681 break;
1682 case IS_NOT_FALSE:
1683 /* select non-FALSE values */
1684 selec = 1.0 - freq_false;
1685 break;
1686 default:
1687 elog(ERROR, "unrecognized booltesttype: %d",
1688 (int) booltesttype);
1689 selec = 0.0; /* Keep compiler quiet */
1690 break;
1691 }
1692
1693 free_attstatsslot(&sslot);
1694 }
1695 else
1696 {
1697 /*
1698 * No most-common-value info available. Still have null fraction
1699 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1700 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1701 */
1702 switch (booltesttype)
1703 {
1704 case IS_UNKNOWN:
1705 /* select only NULL values */
1706 selec = freq_null;
1707 break;
1708 case IS_NOT_UNKNOWN:
1709 /* select non-NULL values */
1710 selec = 1.0 - freq_null;
1711 break;
1712 case IS_TRUE:
1713 case IS_FALSE:
1714 /* Assume we select half of the non-NULL values */
1715 selec = (1.0 - freq_null) / 2.0;
1716 break;
1717 case IS_NOT_TRUE:
1718 case IS_NOT_FALSE:
1719 /* Assume we select NULLs plus half of the non-NULLs */
1720 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1721 selec = (freq_null + 1.0) / 2.0;
1722 break;
1723 default:
1724 elog(ERROR, "unrecognized booltesttype: %d",
1725 (int) booltesttype);
1726 selec = 0.0; /* Keep compiler quiet */
1727 break;
1728 }
1729 }
1730 }
1731 else
1732 {
1733 /*
1734 * If we can't get variable statistics for the argument, perhaps
1735 * clause_selectivity can do something with it. We ignore the
1736 * possibility of a NULL value when using clause_selectivity, and just
1737 * assume the value is either TRUE or FALSE.
1738 */
1739 switch (booltesttype)
1740 {
1741 case IS_UNKNOWN:
1742 selec = DEFAULT_UNK_SEL;
1743 break;
1744 case IS_NOT_UNKNOWN:
1745 selec = DEFAULT_NOT_UNK_SEL;
1746 break;
1747 case IS_TRUE:
1748 case IS_NOT_FALSE:
1749 selec = (double) clause_selectivity(root, arg,
1750 varRelid,
1751 jointype, sjinfo);
1752 break;
1753 case IS_FALSE:
1754 case IS_NOT_TRUE:
1755 selec = 1.0 - (double) clause_selectivity(root, arg,
1756 varRelid,
1757 jointype, sjinfo);
1758 break;
1759 default:
1760 elog(ERROR, "unrecognized booltesttype: %d",
1761 (int) booltesttype);
1762 selec = 0.0; /* Keep compiler quiet */
1763 break;
1764 }
1765 }
1766
1767 ReleaseVariableStats(vardata);
1768
1769 /* result should be in range, but make sure... */
1770 CLAMP_PROBABILITY(selec);
1771
1772 return (Selectivity) selec;
1773}
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:667
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3511
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3401
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:44
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:43
double Selectivity
Definition: nodes.h:260
void * arg
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:135
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
#define InvalidOid
Definition: postgres_ext.h:37
@ IS_NOT_TRUE
Definition: primnodes.h:2001
@ IS_NOT_FALSE
Definition: primnodes.h:2001
@ IS_NOT_UNKNOWN
Definition: primnodes.h:2001
@ IS_TRUE
Definition: primnodes.h:2001
@ IS_UNKNOWN
Definition: primnodes.h:2001
@ IS_FALSE
Definition: primnodes.h:2001
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:5621
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:56
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
#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 1582 of file selfuncs.c.

1583{
1584 VariableStatData vardata;
1585 double selec;
1586
1587 examine_variable(root, arg, varRelid, &vardata);
1588 if (HeapTupleIsValid(vardata.statsTuple))
1589 {
1590 /*
1591 * A boolean variable V is equivalent to the clause V = 't', so we
1592 * compute the selectivity as if that is what we have.
1593 */
1594 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1595 BoolGetDatum(true), false, true, false);
1596 }
1597 else if (is_funcclause(arg))
1598 {
1599 /*
1600 * If we have no stats and it's a function call, estimate 0.3333333.
1601 * This seems a pretty unprincipled choice, but Postgres has been
1602 * using that estimate for function calls since 1992. The hoariness
1603 * of this behavior suggests that we should not be in too much hurry
1604 * to use another value.
1605 */
1606 selec = 0.3333333;
1607 }
1608 else
1609 {
1610 /* Otherwise, the default estimate is 0.5 */
1611 selec = 0.5;
1612 }
1613 ReleaseVariableStats(vardata);
1614 return selec;
1615}
static bool is_funcclause(const void *clause)
Definition: nodeFuncs.h:69
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
double var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:365

References arg, BoolGetDatum(), examine_variable(), HeapTupleIsValid, InvalidOid, is_funcclause(), 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 2220 of file selfuncs.c.

2221{
2222 /* look through any binary-compatible relabeling of arrayexpr */
2223 arrayexpr = strip_array_coercion(arrayexpr);
2224
2225 if (arrayexpr && IsA(arrayexpr, Const))
2226 {
2227 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2228 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2229 ArrayType *arrayval;
2230
2231 if (arrayisnull)
2232 return 0;
2233 arrayval = DatumGetArrayTypeP(arraydatum);
2234 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2235 }
2236 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2237 !((ArrayExpr *) arrayexpr)->multidims)
2238 {
2239 return list_length(((ArrayExpr *) arrayexpr)->elements);
2240 }
2241 else if (arrayexpr && root)
2242 {
2243 /* See if we can find any statistics about it */
2244 VariableStatData vardata;
2245 AttStatsSlot sslot;
2246 double nelem = 0;
2247
2248 examine_variable(root, arrayexpr, 0, &vardata);
2249 if (HeapTupleIsValid(vardata.statsTuple))
2250 {
2251 /*
2252 * Found stats, so use the average element count, which is stored
2253 * in the last stanumbers element of the DECHIST statistics.
2254 * Actually that is the average count of *distinct* elements;
2255 * perhaps we should scale it up somewhat?
2256 */
2257 if (get_attstatsslot(&sslot, vardata.statsTuple,
2258 STATISTIC_KIND_DECHIST, InvalidOid,
2260 {
2261 if (sslot.nnumbers > 0)
2262 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2263 free_attstatsslot(&sslot);
2264 }
2265 }
2266 ReleaseVariableStats(vardata);
2267
2268 if (nelem > 0)
2269 return nelem;
2270 }
2271
2272 /* Else use a default guess --- this should match scalararraysel */
2273 return 10;
2274}
#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
uint64_t Datum
Definition: postgres.h:70
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1864

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

4390{
4391 VariableStatData vardata;
4392 double estfract,
4393 ndistinct,
4394 stanullfrac,
4395 avgfreq;
4396 bool isdefault;
4397 AttStatsSlot sslot;
4398
4399 examine_variable(root, hashkey, 0, &vardata);
4400
4401 /* Look up the frequency of the most common value, if available */
4402 *mcv_freq = 0.0;
4403
4404 if (HeapTupleIsValid(vardata.statsTuple))
4405 {
4406 if (get_attstatsslot(&sslot, vardata.statsTuple,
4407 STATISTIC_KIND_MCV, InvalidOid,
4409 {
4410 /*
4411 * The first MCV stat is for the most common value.
4412 */
4413 if (sslot.nnumbers > 0)
4414 *mcv_freq = sslot.numbers[0];
4415 free_attstatsslot(&sslot);
4416 }
4417 }
4418
4419 /* Get number of distinct values */
4420 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
4421
4422 /*
4423 * If ndistinct isn't real, punt. We normally return 0.1, but if the
4424 * mcv_freq is known to be even higher than that, use it instead.
4425 */
4426 if (isdefault)
4427 {
4428 *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
4429 ReleaseVariableStats(vardata);
4430 return;
4431 }
4432
4433 /* Get fraction that are null */
4434 if (HeapTupleIsValid(vardata.statsTuple))
4435 {
4436 Form_pg_statistic stats;
4437
4438 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
4439 stanullfrac = stats->stanullfrac;
4440 }
4441 else
4442 stanullfrac = 0.0;
4443
4444 /* Compute avg freq of all distinct data values in raw relation */
4445 avgfreq = (1.0 - stanullfrac) / ndistinct;
4446
4447 /*
4448 * Adjust ndistinct to account for restriction clauses. Observe we are
4449 * assuming that the data distribution is affected uniformly by the
4450 * restriction clauses!
4451 *
4452 * XXX Possibly better way, but much more expensive: multiply by
4453 * selectivity of rel's restriction clauses that mention the target Var.
4454 */
4455 if (vardata.rel && vardata.rel->tuples > 0)
4456 {
4457 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
4458 ndistinct = clamp_row_est(ndistinct);
4459 }
4460
4461 /*
4462 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
4463 * number of buckets is less than the expected number of distinct values;
4464 * otherwise it is 1/ndistinct.
4465 */
4466 if (ndistinct > nbuckets)
4467 estfract = 1.0 / nbuckets;
4468 else
4469 estfract = 1.0 / ndistinct;
4470
4471 /*
4472 * Adjust estimated bucketsize upward to account for skewed distribution.
4473 */
4474 if (avgfreq > 0.0 && *mcv_freq > avgfreq)
4475 estfract *= *mcv_freq / avgfreq;
4476
4477 /*
4478 * Clamp bucketsize to sane range (the above adjustment could easily
4479 * produce an out-of-range result). We set the lower bound a little above
4480 * zero, since zero isn't a very sane result.
4481 */
4482 if (estfract < 1.0e-6)
4483 estfract = 1.0e-6;
4484 else if (estfract > 1.0)
4485 estfract = 1.0;
4486
4487 *bucketsize_frac = (Selectivity) estfract;
4488
4489 ReleaseVariableStats(vardata);
4490}
#define Max(x, y)
Definition: c.h:1000
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:6521
Cardinality tuples
Definition: pathnodes.h:1000
Cardinality rows
Definition: pathnodes.h:933
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 4506 of file selfuncs.c.

4508{
4509 Size hashentrysize;
4510
4511 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4512 path->pathtarget->width,
4513 agg_costs->transitionSpace);
4514
4515 /*
4516 * Note that this disregards the effect of fill-factor and growth policy
4517 * of the hash table. That's probably ok, given that the default
4518 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4519 * "double-in-size" growth policies here.
4520 */
4521 return hashentrysize * dNumGroups;
4522}
size_t Size
Definition: c.h:613
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1698
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 4120 of file selfuncs.c.

4123{
4124 List *clauses;
4125 List *otherclauses;
4126 double ndistinct;
4127
4128 if (list_length(hashclauses) <= 1)
4129 {
4130 /*
4131 * Nothing to do for a single clause. Could we employ univariate
4132 * extended stat here?
4133 */
4134 return hashclauses;
4135 }
4136
4137 /* "clauses" is the list of hashclauses we've not dealt with yet */
4138 clauses = list_copy(hashclauses);
4139 /* "otherclauses" holds clauses we are going to return to caller */
4140 otherclauses = NIL;
4141 /* current estimate of ndistinct */
4142 ndistinct = 1.0;
4143 while (clauses != NIL)
4144 {
4145 ListCell *lc;
4146 int relid = -1;
4147 List *varinfos = NIL;
4148 List *origin_rinfos = NIL;
4149 double mvndistinct;
4150 List *origin_varinfos;
4151 int group_relid = -1;
4152 RelOptInfo *group_rel = NULL;
4153 ListCell *lc1,
4154 *lc2;
4155
4156 /*
4157 * Find clauses, referencing the same single base relation and try to
4158 * estimate such a group with extended statistics. Create varinfo for
4159 * an approved clause, push it to otherclauses, if it can't be
4160 * estimated here or ignore to process at the next iteration.
4161 */
4162 foreach(lc, clauses)
4163 {
4165 Node *expr;
4166 Relids relids;
4167 GroupVarInfo *varinfo;
4168
4169 /*
4170 * Find the inner side of the join, which we need to estimate the
4171 * number of buckets. Use outer_is_left because the
4172 * clause_sides_match_join routine has called on hash clauses.
4173 */
4174 relids = rinfo->outer_is_left ?
4175 rinfo->right_relids : rinfo->left_relids;
4176 expr = rinfo->outer_is_left ?
4177 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
4178
4179 if (bms_get_singleton_member(relids, &relid) &&
4180 root->simple_rel_array[relid]->statlist != NIL)
4181 {
4182 bool is_duplicate = false;
4183
4184 /*
4185 * This inner-side expression references only one relation.
4186 * Extended statistics on this clause can exist.
4187 */
4188 if (group_relid < 0)
4189 {
4190 RangeTblEntry *rte = root->simple_rte_array[relid];
4191
4192 if (!rte || (rte->relkind != RELKIND_RELATION &&
4193 rte->relkind != RELKIND_MATVIEW &&
4194 rte->relkind != RELKIND_FOREIGN_TABLE &&
4195 rte->relkind != RELKIND_PARTITIONED_TABLE))
4196 {
4197 /* Extended statistics can't exist in principle */
4198 otherclauses = lappend(otherclauses, rinfo);
4199 clauses = foreach_delete_current(clauses, lc);
4200 continue;
4201 }
4202
4203 group_relid = relid;
4204 group_rel = root->simple_rel_array[relid];
4205 }
4206 else if (group_relid != relid)
4207 {
4208 /*
4209 * Being in the group forming state we don't need other
4210 * clauses.
4211 */
4212 continue;
4213 }
4214
4215 /*
4216 * We're going to add the new clause to the varinfos list. We
4217 * might re-use add_unique_group_var(), but we don't do so for
4218 * two reasons.
4219 *
4220 * 1) We must keep the origin_rinfos list ordered exactly the
4221 * same way as varinfos.
4222 *
4223 * 2) add_unique_group_var() is designed for
4224 * estimate_num_groups(), where a larger number of groups is
4225 * worse. While estimating the number of hash buckets, we
4226 * have the opposite: a lesser number of groups is worse.
4227 * Therefore, we don't have to remove "known equal" vars: the
4228 * removed var may valuably contribute to the multivariate
4229 * statistics to grow the number of groups.
4230 */
4231
4232 /*
4233 * Clear nullingrels to correctly match hash keys. See
4234 * add_unique_group_var()'s comment for details.
4235 */
4236 expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
4237
4238 /*
4239 * Detect and exclude exact duplicates from the list of hash
4240 * keys (like add_unique_group_var does).
4241 */
4242 foreach(lc1, varinfos)
4243 {
4244 varinfo = (GroupVarInfo *) lfirst(lc1);
4245
4246 if (!equal(expr, varinfo->var))
4247 continue;
4248
4249 is_duplicate = true;
4250 break;
4251 }
4252
4253 if (is_duplicate)
4254 {
4255 /*
4256 * Skip exact duplicates. Adding them to the otherclauses
4257 * list also doesn't make sense.
4258 */
4259 continue;
4260 }
4261
4262 /*
4263 * Initialize GroupVarInfo. We only use it to call
4264 * estimate_multivariate_ndistinct(), which doesn't care about
4265 * ndistinct and isdefault fields. Thus, skip these fields.
4266 */
4267 varinfo = (GroupVarInfo *) palloc0(sizeof(GroupVarInfo));
4268 varinfo->var = expr;
4269 varinfo->rel = root->simple_rel_array[relid];
4270 varinfos = lappend(varinfos, varinfo);
4271
4272 /*
4273 * Remember the link to RestrictInfo for the case the clause
4274 * is failed to be estimated.
4275 */
4276 origin_rinfos = lappend(origin_rinfos, rinfo);
4277 }
4278 else
4279 {
4280 /* This clause can't be estimated with extended statistics */
4281 otherclauses = lappend(otherclauses, rinfo);
4282 }
4283
4284 clauses = foreach_delete_current(clauses, lc);
4285 }
4286
4287 if (list_length(varinfos) < 2)
4288 {
4289 /*
4290 * Multivariate statistics doesn't apply to single columns except
4291 * for expressions, but it has not been implemented yet.
4292 */
4293 otherclauses = list_concat(otherclauses, origin_rinfos);
4294 list_free_deep(varinfos);
4295 list_free(origin_rinfos);
4296 continue;
4297 }
4298
4299 Assert(group_rel != NULL);
4300
4301 /* Employ the extended statistics. */
4302 origin_varinfos = varinfos;
4303 for (;;)
4304 {
4305 bool estimated = estimate_multivariate_ndistinct(root,
4306 group_rel,
4307 &varinfos,
4308 &mvndistinct);
4309
4310 if (!estimated)
4311 break;
4312
4313 /*
4314 * We've got an estimation. Use ndistinct value in a consistent
4315 * way - according to the caller's logic (see
4316 * final_cost_hashjoin).
4317 */
4318 if (ndistinct < mvndistinct)
4319 ndistinct = mvndistinct;
4320 Assert(ndistinct >= 1.0);
4321 }
4322
4323 Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
4324
4325 /* Collect unmatched clauses as otherclauses. */
4326 forboth(lc1, origin_varinfos, lc2, origin_rinfos)
4327 {
4328 GroupVarInfo *vinfo = lfirst(lc1);
4329
4330 if (!list_member_ptr(varinfos, vinfo))
4331 /* Already estimated */
4332 continue;
4333
4334 /* Can't be estimated here - push to the returning list */
4335 otherclauses = lappend(otherclauses, lfirst(lc2));
4336 }
4337 }
4338
4339 *innerbucketsize = 1.0 / ndistinct;
4340 return otherclauses;
4341}
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:714
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
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:1395
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:4547
RelOptInfo * rel
Definition: selfuncs.c:3632
Node * var
Definition: selfuncs.c:3631
Expr * clause
Definition: pathnodes.h:2792

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

3770{
3771 List *varinfos = NIL;
3772 double srf_multiplier = 1.0;
3773 double numdistinct;
3774 ListCell *l;
3775 int i;
3776
3777 /* Zero the estinfo output parameter, if non-NULL */
3778 if (estinfo != NULL)
3779 memset(estinfo, 0, sizeof(EstimationInfo));
3780
3781 /*
3782 * We don't ever want to return an estimate of zero groups, as that tends
3783 * to lead to division-by-zero and other unpleasantness. The input_rows
3784 * estimate is usually already at least 1, but clamp it just in case it
3785 * isn't.
3786 */
3787 input_rows = clamp_row_est(input_rows);
3788
3789 /*
3790 * If no grouping columns, there's exactly one group. (This can't happen
3791 * for normal cases with GROUP BY or DISTINCT, but it is possible for
3792 * corner cases with set operations.)
3793 */
3794 if (groupExprs == NIL || (pgset && *pgset == NIL))
3795 return 1.0;
3796
3797 /*
3798 * Count groups derived from boolean grouping expressions. For other
3799 * expressions, find the unique Vars used, treating an expression as a Var
3800 * if we can find stats for it. For each one, record the statistical
3801 * estimate of number of distinct values (total in its table, without
3802 * regard for filtering).
3803 */
3804 numdistinct = 1.0;
3805
3806 i = 0;
3807 foreach(l, groupExprs)
3808 {
3809 Node *groupexpr = (Node *) lfirst(l);
3810 double this_srf_multiplier;
3811 VariableStatData vardata;
3812 List *varshere;
3813 ListCell *l2;
3814
3815 /* is expression in this grouping set? */
3816 if (pgset && !list_member_int(*pgset, i++))
3817 continue;
3818
3819 /*
3820 * Set-returning functions in grouping columns are a bit problematic.
3821 * The code below will effectively ignore their SRF nature and come up
3822 * with a numdistinct estimate as though they were scalar functions.
3823 * We compensate by scaling up the end result by the largest SRF
3824 * rowcount estimate. (This will be an overestimate if the SRF
3825 * produces multiple copies of any output value, but it seems best to
3826 * assume the SRF's outputs are distinct. In any case, it's probably
3827 * pointless to worry too much about this without much better
3828 * estimates for SRF output rowcounts than we have today.)
3829 */
3830 this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3831 if (srf_multiplier < this_srf_multiplier)
3832 srf_multiplier = this_srf_multiplier;
3833
3834 /* Short-circuit for expressions returning boolean */
3835 if (exprType(groupexpr) == BOOLOID)
3836 {
3837 numdistinct *= 2.0;
3838 continue;
3839 }
3840
3841 /*
3842 * If examine_variable is able to deduce anything about the GROUP BY
3843 * expression, treat it as a single variable even if it's really more
3844 * complicated.
3845 *
3846 * XXX This has the consequence that if there's a statistics object on
3847 * the expression, we don't split it into individual Vars. This
3848 * affects our selection of statistics in
3849 * estimate_multivariate_ndistinct, because it's probably better to
3850 * use more accurate estimate for each expression and treat them as
3851 * independent, than to combine estimates for the extracted variables
3852 * when we don't know how that relates to the expressions.
3853 */
3854 examine_variable(root, groupexpr, 0, &vardata);
3855 if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3856 {
3857 varinfos = add_unique_group_var(root, varinfos,
3858 groupexpr, &vardata);
3859 ReleaseVariableStats(vardata);
3860 continue;
3861 }
3862 ReleaseVariableStats(vardata);
3863
3864 /*
3865 * Else pull out the component Vars. Handle PlaceHolderVars by
3866 * recursing into their arguments (effectively assuming that the
3867 * PlaceHolderVar doesn't change the number of groups, which boils
3868 * down to ignoring the possible addition of nulls to the result set).
3869 */
3870 varshere = pull_var_clause(groupexpr,
3874
3875 /*
3876 * If we find any variable-free GROUP BY item, then either it is a
3877 * constant (and we can ignore it) or it contains a volatile function;
3878 * in the latter case we punt and assume that each input row will
3879 * yield a distinct group.
3880 */
3881 if (varshere == NIL)
3882 {
3883 if (contain_volatile_functions(groupexpr))
3884 return input_rows;
3885 continue;
3886 }
3887
3888 /*
3889 * Else add variables to varinfos list
3890 */
3891 foreach(l2, varshere)
3892 {
3893 Node *var = (Node *) lfirst(l2);
3894
3895 examine_variable(root, var, 0, &vardata);
3896 varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3897 ReleaseVariableStats(vardata);
3898 }
3899 }
3900
3901 /*
3902 * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3903 * list.
3904 */
3905 if (varinfos == NIL)
3906 {
3907 /* Apply SRF multiplier as we would do in the long path */
3908 numdistinct *= srf_multiplier;
3909 /* Round off */
3910 numdistinct = ceil(numdistinct);
3911 /* Guard against out-of-range answers */
3912 if (numdistinct > input_rows)
3913 numdistinct = input_rows;
3914 if (numdistinct < 1.0)
3915 numdistinct = 1.0;
3916 return numdistinct;
3917 }
3918
3919 /*
3920 * Group Vars by relation and estimate total numdistinct.
3921 *
3922 * For each iteration of the outer loop, we process the frontmost Var in
3923 * varinfos, plus all other Vars in the same relation. We remove these
3924 * Vars from the newvarinfos list for the next iteration. This is the
3925 * easiest way to group Vars of same rel together.
3926 */
3927 do
3928 {
3929 GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3930 RelOptInfo *rel = varinfo1->rel;
3931 double reldistinct = 1;
3932 double relmaxndistinct = reldistinct;
3933 int relvarcount = 0;
3934 List *newvarinfos = NIL;
3935 List *relvarinfos = NIL;
3936
3937 /*
3938 * Split the list of varinfos in two - one for the current rel, one
3939 * for remaining Vars on other rels.
3940 */
3941 relvarinfos = lappend(relvarinfos, varinfo1);
3942 for_each_from(l, varinfos, 1)
3943 {
3944 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3945
3946 if (varinfo2->rel == varinfo1->rel)
3947 {
3948 /* varinfos on current rel */
3949 relvarinfos = lappend(relvarinfos, varinfo2);
3950 }
3951 else
3952 {
3953 /* not time to process varinfo2 yet */
3954 newvarinfos = lappend(newvarinfos, varinfo2);
3955 }
3956 }
3957
3958 /*
3959 * Get the numdistinct estimate for the Vars of this rel. We
3960 * iteratively search for multivariate n-distinct with maximum number
3961 * of vars; assuming that each var group is independent of the others,
3962 * we multiply them together. Any remaining relvarinfos after no more
3963 * multivariate matches are found are assumed independent too, so
3964 * their individual ndistinct estimates are multiplied also.
3965 *
3966 * While iterating, count how many separate numdistinct values we
3967 * apply. We apply a fudge factor below, but only if we multiplied
3968 * more than one such values.
3969 */
3970 while (relvarinfos)
3971 {
3972 double mvndistinct;
3973
3974 if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3975 &mvndistinct))
3976 {
3977 reldistinct *= mvndistinct;
3978 if (relmaxndistinct < mvndistinct)
3979 relmaxndistinct = mvndistinct;
3980 relvarcount++;
3981 }
3982 else
3983 {
3984 foreach(l, relvarinfos)
3985 {
3986 GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3987
3988 reldistinct *= varinfo2->ndistinct;
3989 if (relmaxndistinct < varinfo2->ndistinct)
3990 relmaxndistinct = varinfo2->ndistinct;
3991 relvarcount++;
3992
3993 /*
3994 * When varinfo2's isdefault is set then we'd better set
3995 * the SELFLAG_USED_DEFAULT bit in the EstimationInfo.
3996 */
3997 if (estinfo != NULL && varinfo2->isdefault)
3998 estinfo->flags |= SELFLAG_USED_DEFAULT;
3999 }
4000
4001 /* we're done with this relation */
4002 relvarinfos = NIL;
4003 }
4004 }
4005
4006 /*
4007 * Sanity check --- don't divide by zero if empty relation.
4008 */
4009 Assert(IS_SIMPLE_REL(rel));
4010 if (rel->tuples > 0)
4011 {
4012 /*
4013 * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
4014 * fudge factor is because the Vars are probably correlated but we
4015 * don't know by how much. We should never clamp to less than the
4016 * largest ndistinct value for any of the Vars, though, since
4017 * there will surely be at least that many groups.
4018 */
4019 double clamp = rel->tuples;
4020
4021 if (relvarcount > 1)
4022 {
4023 clamp *= 0.1;
4024 if (clamp < relmaxndistinct)
4025 {
4026 clamp = relmaxndistinct;
4027 /* for sanity in case some ndistinct is too large: */
4028 if (clamp > rel->tuples)
4029 clamp = rel->tuples;
4030 }
4031 }
4032 if (reldistinct > clamp)
4033 reldistinct = clamp;
4034
4035 /*
4036 * Update the estimate based on the restriction selectivity,
4037 * guarding against division by zero when reldistinct is zero.
4038 * Also skip this if we know that we are returning all rows.
4039 */
4040 if (reldistinct > 0 && rel->rows < rel->tuples)
4041 {
4042 /*
4043 * Given a table containing N rows with n distinct values in a
4044 * uniform distribution, if we select p rows at random then
4045 * the expected number of distinct values selected is
4046 *
4047 * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
4048 *
4049 * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
4050 *
4051 * See "Approximating block accesses in database
4052 * organizations", S. B. Yao, Communications of the ACM,
4053 * Volume 20 Issue 4, April 1977 Pages 260-261.
4054 *
4055 * Alternatively, re-arranging the terms from the factorials,
4056 * this may be written as
4057 *
4058 * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
4059 *
4060 * This form of the formula is more efficient to compute in
4061 * the common case where p is larger than N/n. Additionally,
4062 * as pointed out by Dell'Era, if i << N for all terms in the
4063 * product, it can be approximated by
4064 *
4065 * n * (1 - ((N-p)/N)^(N/n))
4066 *
4067 * See "Expected distinct values when selecting from a bag
4068 * without replacement", Alberto Dell'Era,
4069 * http://www.adellera.it/investigations/distinct_balls/.
4070 *
4071 * The condition i << N is equivalent to n >> 1, so this is a
4072 * good approximation when the number of distinct values in
4073 * the table is large. It turns out that this formula also
4074 * works well even when n is small.
4075 */
4076 reldistinct *=
4077 (1 - pow((rel->tuples - rel->rows) / rel->tuples,
4078 rel->tuples / reldistinct));
4079 }
4080 reldistinct = clamp_row_est(reldistinct);
4081
4082 /*
4083 * Update estimate of total distinct groups.
4084 */
4085 numdistinct *= reldistinct;
4086 }
4087
4088 varinfos = newvarinfos;
4089 } while (varinfos != NIL);
4090
4091 /* Now we can account for the effects of any SRFs */
4092 numdistinct *= srf_multiplier;
4093
4094 /* Round off */
4095 numdistinct = ceil(numdistinct);
4096
4097 /* Guard against out-of-range answers */
4098 if (numdistinct > input_rows)
4099 numdistinct = input_rows;
4100 if (numdistinct < 1.0)
4101 numdistinct = 1.0;
4102
4103 return numdistinct;
4104}
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:550
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:301
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:189
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:193
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:191
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:895
#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:3638
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
uint32 flags
Definition: selfuncs.h:80
double ndistinct
Definition: selfuncs.c:3633
bool isdefault
Definition: selfuncs.c:3634
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_final_unique_paths(), create_partial_distinct_paths(), create_partial_unique_paths(), create_rel_agg_info(), estimate_path_cost_size(), generate_grouped_paths(), generate_union_paths(), 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 5621 of file selfuncs.c.

5623{
5624 Node *basenode;
5625 Relids varnos;
5626 Relids basevarnos;
5627 RelOptInfo *onerel;
5628
5629 /* Make sure we don't return dangling pointers in vardata */
5630 MemSet(vardata, 0, sizeof(VariableStatData));
5631
5632 /* Save the exposed type of the expression */
5633 vardata->vartype = exprType(node);
5634
5635 /* Look inside any binary-compatible relabeling */
5636
5637 if (IsA(node, RelabelType))
5638 basenode = (Node *) ((RelabelType *) node)->arg;
5639 else
5640 basenode = node;
5641
5642 /* Fast path for a simple Var */
5643
5644 if (IsA(basenode, Var) &&
5645 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5646 {
5647 Var *var = (Var *) basenode;
5648
5649 /* Set up result fields other than the stats tuple */
5650 vardata->var = basenode; /* return Var without relabeling */
5651 vardata->rel = find_base_rel(root, var->varno);
5652 vardata->atttype = var->vartype;
5653 vardata->atttypmod = var->vartypmod;
5654 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5655
5656 /* Try to locate some stats */
5657 examine_simple_variable(root, var, vardata);
5658
5659 return;
5660 }
5661
5662 /*
5663 * Okay, it's a more complicated expression. Determine variable
5664 * membership. Note that when varRelid isn't zero, only vars of that
5665 * relation are considered "real" vars.
5666 */
5667 varnos = pull_varnos(root, basenode);
5668 basevarnos = bms_difference(varnos, root->outer_join_rels);
5669
5670 onerel = NULL;
5671
5672 if (bms_is_empty(basevarnos))
5673 {
5674 /* No Vars at all ... must be pseudo-constant clause */
5675 }
5676 else
5677 {
5678 int relid;
5679
5680 /* Check if the expression is in vars of a single base relation */
5681 if (bms_get_singleton_member(basevarnos, &relid))
5682 {
5683 if (varRelid == 0 || varRelid == relid)
5684 {
5685 onerel = find_base_rel(root, relid);
5686 vardata->rel = onerel;
5687 node = basenode; /* strip any relabeling */
5688 }
5689 /* else treat it as a constant */
5690 }
5691 else
5692 {
5693 /* varnos has multiple relids */
5694 if (varRelid == 0)
5695 {
5696 /* treat it as a variable of a join relation */
5697 vardata->rel = find_join_rel(root, varnos);
5698 node = basenode; /* strip any relabeling */
5699 }
5700 else if (bms_is_member(varRelid, varnos))
5701 {
5702 /* ignore the vars belonging to other relations */
5703 vardata->rel = find_base_rel(root, varRelid);
5704 node = basenode; /* strip any relabeling */
5705 /* note: no point in expressional-index search here */
5706 }
5707 /* else treat it as a constant */
5708 }
5709 }
5710
5711 bms_free(basevarnos);
5712
5713 vardata->var = node;
5714 vardata->atttype = exprType(node);
5715 vardata->atttypmod = exprTypmod(node);
5716
5717 if (onerel)
5718 {
5719 /*
5720 * We have an expression in vars of a single relation. Try to match
5721 * it to expressional index columns, in hopes of finding some
5722 * statistics.
5723 *
5724 * Note that we consider all index columns including INCLUDE columns,
5725 * since there could be stats for such columns. But the test for
5726 * uniqueness needs to be warier.
5727 *
5728 * XXX it's conceivable that there are multiple matches with different
5729 * index opfamilies; if so, we need to pick one that matches the
5730 * operator we are estimating for. FIXME later.
5731 */
5732 ListCell *ilist;
5733 ListCell *slist;
5734
5735 /*
5736 * The nullingrels bits within the expression could prevent us from
5737 * matching it to expressional index columns or to the expressions in
5738 * extended statistics. So strip them out first.
5739 */
5740 if (bms_overlap(varnos, root->outer_join_rels))
5741 node = remove_nulling_relids(node, root->outer_join_rels, NULL);
5742
5743 foreach(ilist, onerel->indexlist)
5744 {
5745 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5746 ListCell *indexpr_item;
5747 int pos;
5748
5749 indexpr_item = list_head(index->indexprs);
5750 if (indexpr_item == NULL)
5751 continue; /* no expressions here... */
5752
5753 for (pos = 0; pos < index->ncolumns; pos++)
5754 {
5755 if (index->indexkeys[pos] == 0)
5756 {
5757 Node *indexkey;
5758
5759 if (indexpr_item == NULL)
5760 elog(ERROR, "too few entries in indexprs list");
5761 indexkey = (Node *) lfirst(indexpr_item);
5762 if (indexkey && IsA(indexkey, RelabelType))
5763 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5764 if (equal(node, indexkey))
5765 {
5766 /*
5767 * Found a match ... is it a unique index? Tests here
5768 * should match has_unique_index().
5769 */
5770 if (index->unique &&
5771 index->nkeycolumns == 1 &&
5772 pos == 0 &&
5773 (index->indpred == NIL || index->predOK))
5774 vardata->isunique = true;
5775
5776 /*
5777 * Has it got stats? We only consider stats for
5778 * non-partial indexes, since partial indexes probably
5779 * don't reflect whole-relation statistics; the above
5780 * check for uniqueness is the only info we take from
5781 * a partial index.
5782 *
5783 * An index stats hook, however, must make its own
5784 * decisions about what to do with partial indexes.
5785 */
5787 (*get_index_stats_hook) (root, index->indexoid,
5788 pos + 1, vardata))
5789 {
5790 /*
5791 * The hook took control of acquiring a stats
5792 * tuple. If it did supply a tuple, it'd better
5793 * have supplied a freefunc.
5794 */
5795 if (HeapTupleIsValid(vardata->statsTuple) &&
5796 !vardata->freefunc)
5797 elog(ERROR, "no function provided to release variable stats with");
5798 }
5799 else if (index->indpred == NIL)
5800 {
5801 vardata->statsTuple =
5802 SearchSysCache3(STATRELATTINH,
5803 ObjectIdGetDatum(index->indexoid),
5804 Int16GetDatum(pos + 1),
5805 BoolGetDatum(false));
5806 vardata->freefunc = ReleaseSysCache;
5807
5808 if (HeapTupleIsValid(vardata->statsTuple))
5809 {
5810 /*
5811 * Test if user has permission to access all
5812 * rows from the index's table.
5813 *
5814 * For simplicity, we insist on the whole
5815 * table being selectable, rather than trying
5816 * to identify which column(s) the index
5817 * depends on.
5818 *
5819 * Note that for an inheritance child,
5820 * permissions are checked on the inheritance
5821 * root parent, and whole-table select
5822 * privilege on the parent doesn't quite
5823 * guarantee that the user could read all
5824 * columns of the child. But in practice it's
5825 * unlikely that any interesting security
5826 * violation could result from allowing access
5827 * to the expression index's stats, so we
5828 * allow it anyway. See similar code in
5829 * examine_simple_variable() for additional
5830 * comments.
5831 */
5832 vardata->acl_ok =
5834 index->rel->relid,
5835 NULL);
5836 }
5837 else
5838 {
5839 /* suppress leakproofness checks later */
5840 vardata->acl_ok = true;
5841 }
5842 }
5843 if (vardata->statsTuple)
5844 break;
5845 }
5846 indexpr_item = lnext(index->indexprs, indexpr_item);
5847 }
5848 }
5849 if (vardata->statsTuple)
5850 break;
5851 }
5852
5853 /*
5854 * Search extended statistics for one with a matching expression.
5855 * There might be multiple ones, so just grab the first one. In the
5856 * future, we might consider the statistics target (and pick the most
5857 * accurate statistics) and maybe some other parameters.
5858 */
5859 foreach(slist, onerel->statlist)
5860 {
5861 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5862 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5863 ListCell *expr_item;
5864 int pos;
5865
5866 /*
5867 * Stop once we've found statistics for the expression (either
5868 * from extended stats, or for an index in the preceding loop).
5869 */
5870 if (vardata->statsTuple)
5871 break;
5872
5873 /* skip stats without per-expression stats */
5874 if (info->kind != STATS_EXT_EXPRESSIONS)
5875 continue;
5876
5877 /* skip stats with mismatching stxdinherit value */
5878 if (info->inherit != rte->inh)
5879 continue;
5880
5881 pos = 0;
5882 foreach(expr_item, info->exprs)
5883 {
5884 Node *expr = (Node *) lfirst(expr_item);
5885
5886 Assert(expr);
5887
5888 /* strip RelabelType before comparing it */
5889 if (expr && IsA(expr, RelabelType))
5890 expr = (Node *) ((RelabelType *) expr)->arg;
5891
5892 /* found a match, see if we can extract pg_statistic row */
5893 if (equal(node, expr))
5894 {
5895 /*
5896 * XXX Not sure if we should cache the tuple somewhere.
5897 * Now we just create a new copy every time.
5898 */
5899 vardata->statsTuple =
5900 statext_expressions_load(info->statOid, rte->inh, pos);
5901
5902 vardata->freefunc = ReleaseDummy;
5903
5904 /*
5905 * Test if user has permission to access all rows from the
5906 * table.
5907 *
5908 * For simplicity, we insist on the whole table being
5909 * selectable, rather than trying to identify which
5910 * column(s) the statistics object depends on.
5911 *
5912 * Note that for an inheritance child, permissions are
5913 * checked on the inheritance root parent, and whole-table
5914 * select privilege on the parent doesn't quite guarantee
5915 * that the user could read all columns of the child. But
5916 * in practice it's unlikely that any interesting security
5917 * violation could result from allowing access to the
5918 * expression stats, so we allow it anyway. See similar
5919 * code in examine_simple_variable() for additional
5920 * comments.
5921 */
5922 vardata->acl_ok = all_rows_selectable(root,
5923 onerel->relid,
5924 NULL);
5925
5926 break;
5927 }
5928
5929 pos++;
5930 }
5931 }
5932 }
5933
5934 bms_free(varnos);
5935}
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:581
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define MemSet(start, val, len)
Definition: c.h:1022
HeapTuple statext_expressions_load(Oid stxoid, bool inh, int idx)
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
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:2435
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:182
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:529
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:642
bool all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
Definition: selfuncs.c:6223
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5947
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:184
static void ReleaseDummy(HeapTuple tuple)
Definition: selfuncs.c:5580
Index relid
Definition: pathnodes.h:973
List * statlist
Definition: pathnodes.h:997
List * indexlist
Definition: pathnodes.h:995
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:264
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:240
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:114

References VariableStatData::acl_ok, all_rows_selectable(), 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, has_unique_index(), HeapTupleIsValid, if(), RelOptInfo::indexlist, RangeTblEntry::inh, StatisticExtInfo::inherit, Int16GetDatum(), IsA, VariableStatData::isunique, StatisticExtInfo::kind, lfirst, list_head(), lnext(), MemSet, NIL, ObjectIdGetDatum(), planner_rt_fetch, pull_varnos(), VariableStatData::rel, ReleaseDummy(), ReleaseSysCache(), RelOptInfo::relid, remove_nulling_relids(), root, SearchSysCache3(), statext_expressions_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, VariableStatData::statsTuple, 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 984 of file selfuncs.c.

987{
988 double selec;
989 VariableStatData vardata;
990 Node *other;
991 bool varonleft;
992
993 /*
994 * If expression is not variable OP something or something OP variable,
995 * then punt and return the default estimate.
996 */
997 if (!get_restriction_variable(root, args, varRelid,
998 &vardata, &other, &varonleft))
999 return default_selectivity;
1000
1001 /*
1002 * If the something is a NULL constant, assume operator is strict and
1003 * return zero, ie, operator will never return TRUE.
1004 */
1005 if (IsA(other, Const) &&
1006 ((Const *) other)->constisnull)
1007 {
1008 ReleaseVariableStats(vardata);
1009 return 0.0;
1010 }
1011
1012 if (IsA(other, Const))
1013 {
1014 /* Variable is being compared to a known non-null constant */
1015 Datum constval = ((Const *) other)->constvalue;
1016 FmgrInfo opproc;
1017 double mcvsum;
1018 double mcvsel;
1019 double nullfrac;
1020 int hist_size;
1021
1022 fmgr_info(get_opcode(oproid), &opproc);
1023
1024 /*
1025 * Calculate the selectivity for the column's most common values.
1026 */
1027 mcvsel = mcv_selectivity(&vardata, &opproc, collation,
1028 constval, varonleft,
1029 &mcvsum);
1030
1031 /*
1032 * If the histogram is large enough, see what fraction of it matches
1033 * the query, and assume that's representative of the non-MCV
1034 * population. Otherwise use the default selectivity for the non-MCV
1035 * population.
1036 */
1037 selec = histogram_selectivity(&vardata, &opproc, collation,
1038 constval, varonleft,
1039 10, 1, &hist_size);
1040 if (selec < 0)
1041 {
1042 /* Nope, fall back on default */
1043 selec = default_selectivity;
1044 }
1045 else if (hist_size < 100)
1046 {
1047 /*
1048 * For histogram sizes from 10 to 100, we combine the histogram
1049 * and default selectivities, putting increasingly more trust in
1050 * the histogram for larger sizes.
1051 */
1052 double hist_weight = hist_size / 100.0;
1053
1054 selec = selec * hist_weight +
1055 default_selectivity * (1.0 - hist_weight);
1056 }
1057
1058 /* In any case, don't believe extremely small or large estimates. */
1059 if (selec < 0.0001)
1060 selec = 0.0001;
1061 else if (selec > 0.9999)
1062 selec = 0.9999;
1063
1064 /* Don't forget to account for nulls. */
1065 if (HeapTupleIsValid(vardata.statsTuple))
1066 nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
1067 else
1068 nullfrac = 0.0;
1069
1070 /*
1071 * Now merge the results from the MCV and histogram calculations,
1072 * realizing that the histogram covers only the non-null values that
1073 * are not listed in MCV.
1074 */
1075 selec *= 1.0 - nullfrac - mcvsum;
1076 selec += mcvsel;
1077 }
1078 else
1079 {
1080 /* Comparison value is not constant, so we can't do anything */
1081 selec = default_selectivity;
1082 }
1083
1084 ReleaseVariableStats(vardata);
1085
1086 /* result should be in range, but make sure... */
1087 CLAMP_PROBABILITY(selec);
1088
1089 return selec;
1090}
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:128
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1452
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:5492
double mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
Definition: selfuncs.c:802
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:893
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 7314 of file selfuncs.c.

7318{
7319 IndexOptInfo *index = path->indexinfo;
7320 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7321 List *indexOrderBys = path->indexorderbys;
7322 Cost indexStartupCost;
7323 Cost indexTotalCost;
7324 Selectivity indexSelectivity;
7325 double indexCorrelation;
7326 double numIndexPages;
7327 double numIndexTuples;
7328 double spc_random_page_cost;
7329 double num_sa_scans;
7330 double num_outer_scans;
7331 double num_scans;
7332 double qual_op_cost;
7333 double qual_arg_cost;
7334 List *selectivityQuals;
7335 ListCell *l;
7336
7337 /*
7338 * If the index is partial, AND the index predicate with the explicitly
7339 * given indexquals to produce a more accurate idea of the index
7340 * selectivity.
7341 */
7342 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7343
7344 /*
7345 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
7346 * just assume that the number of index descents is the number of distinct
7347 * combinations of array elements from all of the scan's SAOP clauses.
7348 */
7349 num_sa_scans = costs->num_sa_scans;
7350 if (num_sa_scans < 1)
7351 {
7352 num_sa_scans = 1;
7353 foreach(l, indexQuals)
7354 {
7355 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
7356
7357 if (IsA(rinfo->clause, ScalarArrayOpExpr))
7358 {
7359 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
7360 double alength = estimate_array_length(root, lsecond(saop->args));
7361
7362 if (alength > 1)
7363 num_sa_scans *= alength;
7364 }
7365 }
7366 }
7367
7368 /* Estimate the fraction of main-table tuples that will be visited */
7369 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7370 index->rel->relid,
7371 JOIN_INNER,
7372 NULL);
7373
7374 /*
7375 * If caller didn't give us an estimate, estimate the number of index
7376 * tuples that will be visited. We do it in this rather peculiar-looking
7377 * way in order to get the right answer for partial indexes.
7378 */
7379 numIndexTuples = costs->numIndexTuples;
7380 if (numIndexTuples <= 0.0)
7381 {
7382 numIndexTuples = indexSelectivity * index->rel->tuples;
7383
7384 /*
7385 * The above calculation counts all the tuples visited across all
7386 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
7387 * average per-indexscan number, so adjust. This is a handy place to
7388 * round to integer, too. (If caller supplied tuple estimate, it's
7389 * responsible for handling these considerations.)
7390 */
7391 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7392 }
7393
7394 /*
7395 * We can bound the number of tuples by the index size in any case. Also,
7396 * always estimate at least one tuple is touched, even when
7397 * indexSelectivity estimate is tiny.
7398 */
7399 if (numIndexTuples > index->tuples)
7400 numIndexTuples = index->tuples;
7401 if (numIndexTuples < 1.0)
7402 numIndexTuples = 1.0;
7403
7404 /*
7405 * Estimate the number of index pages that will be retrieved.
7406 *
7407 * We use the simplistic method of taking a pro-rata fraction of the total
7408 * number of index pages. In effect, this counts only leaf pages and not
7409 * any overhead such as index metapage or upper tree levels.
7410 *
7411 * In practice access to upper index levels is often nearly free because
7412 * those tend to stay in cache under load; moreover, the cost involved is
7413 * highly dependent on index type. We therefore ignore such costs here
7414 * and leave it to the caller to add a suitable charge if needed.
7415 */
7416 if (index->pages > 1 && index->tuples > 1)
7417 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
7418 else
7419 numIndexPages = 1.0;
7420
7421 /* fetch estimated page cost for tablespace containing index */
7422 get_tablespace_page_costs(index->reltablespace,
7423 &spc_random_page_cost,
7424 NULL);
7425
7426 /*
7427 * Now compute the disk access costs.
7428 *
7429 * The above calculations are all per-index-scan. However, if we are in a
7430 * nestloop inner scan, we can expect the scan to be repeated (with
7431 * different search keys) for each row of the outer relation. Likewise,
7432 * ScalarArrayOpExpr quals result in multiple index scans. This creates
7433 * the potential for cache effects to reduce the number of disk page
7434 * fetches needed. We want to estimate the average per-scan I/O cost in
7435 * the presence of caching.
7436 *
7437 * We use the Mackert-Lohman formula (see costsize.c for details) to
7438 * estimate the total number of page fetches that occur. While this
7439 * wasn't what it was designed for, it seems a reasonable model anyway.
7440 * Note that we are counting pages not tuples anymore, so we take N = T =
7441 * index size, as if there were one "tuple" per page.
7442 */
7443 num_outer_scans = loop_count;
7444 num_scans = num_sa_scans * num_outer_scans;
7445
7446 if (num_scans > 1)
7447 {
7448 double pages_fetched;
7449
7450 /* total page fetches ignoring cache effects */
7451 pages_fetched = numIndexPages * num_scans;
7452
7453 /* use Mackert and Lohman formula to adjust for cache effects */
7454 pages_fetched = index_pages_fetched(pages_fetched,
7455 index->pages,
7456 (double) index->pages,
7457 root);
7458
7459 /*
7460 * Now compute the total disk access cost, and then report a pro-rated
7461 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7462 * since that's internal to the indexscan.)
7463 */
7464 indexTotalCost = (pages_fetched * spc_random_page_cost)
7465 / num_outer_scans;
7466 }
7467 else
7468 {
7469 /*
7470 * For a single index scan, we just charge spc_random_page_cost per
7471 * page touched.
7472 */
7473 indexTotalCost = numIndexPages * spc_random_page_cost;
7474 }
7475
7476 /*
7477 * CPU cost: any complex expressions in the indexquals will need to be
7478 * evaluated once at the start of the scan to reduce them to runtime keys
7479 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7480 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7481 * indexqual operator. Because we have numIndexTuples as a per-scan
7482 * number, we have to multiply by num_sa_scans to get the correct result
7483 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7484 * ORDER BY expressions.
7485 *
7486 * Note: this neglects the possible costs of rechecking lossy operators.
7487 * Detecting that that might be needed seems more expensive than it's
7488 * worth, though, considering all the other inaccuracies here ...
7489 */
7490 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
7491 index_other_operands_eval_cost(root, indexOrderBys);
7492 qual_op_cost = cpu_operator_cost *
7493 (list_length(indexQuals) + list_length(indexOrderBys));
7494
7495 indexStartupCost = qual_arg_cost;
7496 indexTotalCost += qual_arg_cost;
7497 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7498
7499 /*
7500 * Generic assumption about index correlation: there isn't any.
7501 */
7502 indexCorrelation = 0.0;
7503
7504 /*
7505 * Return everything to caller.
7506 */
7507 costs->indexStartupCost = indexStartupCost;
7508 costs->indexTotalCost = indexTotalCost;
7509 costs->indexSelectivity = indexSelectivity;
7510 costs->indexCorrelation = indexCorrelation;
7511 costs->numIndexPages = numIndexPages;
7512 costs->numIndexTuples = numIndexTuples;
7513 costs->spc_random_page_cost = spc_random_page_cost;
7514 costs->num_sa_scans = num_sa_scans;
7515}
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:882
double cpu_index_tuple_cost
Definition: costsize.c:133
double Cost
Definition: nodes.h:261
@ JOIN_INNER
Definition: nodes.h:303
#define lsecond(l)
Definition: pg_list.h:183
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:7230
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:7537
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2220
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:7260
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:129
Cost indexStartupCost
Definition: selfuncs.h:127
double indexCorrelation
Definition: selfuncs.h:130
double spc_random_page_cost
Definition: selfuncs.h:135
double num_sa_scans
Definition: selfuncs.h:136
Cost indexTotalCost
Definition: selfuncs.h:128
double numIndexPages
Definition: selfuncs.h:133
double numIndexTuples
Definition: selfuncs.h:134
List * indexclauses
Definition: pathnodes.h:1959
List * indexorderbys
Definition: pathnodes.h:1960
IndexOptInfo * indexinfo
Definition: pathnodes.h:1958

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

5555{
5556 Node *left,
5557 *right;
5558
5559 if (list_length(args) != 2)
5560 elog(ERROR, "join operator should take two arguments");
5561
5562 left = (Node *) linitial(args);
5563 right = (Node *) lsecond(args);
5564
5565 examine_variable(root, left, 0, vardata1);
5566 examine_variable(root, right, 0, vardata2);
5567
5568 if (vardata1->rel &&
5569 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5570 *join_is_reversed = true; /* var1 is on RHS */
5571 else if (vardata2->rel &&
5572 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5573 *join_is_reversed = true; /* var2 is on LHS */
5574 else
5575 *join_is_reversed = false;
5576}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Relids relids
Definition: pathnodes.h:927
Relids syn_lefthand
Definition: pathnodes.h:3119
Relids syn_righthand
Definition: pathnodes.h:3120

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

7231{
7232 List *result = NIL;
7233 ListCell *lc;
7234
7235 foreach(lc, indexclauses)
7236 {
7237 IndexClause *iclause = lfirst_node(IndexClause, lc);
7238 ListCell *lc2;
7239
7240 foreach(lc2, iclause->indexquals)
7241 {
7242 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7243
7244 result = lappend(result, rinfo);
7245 }
7246 }
7247 return result;
7248}
List * indexquals
Definition: pathnodes.h:2007

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

5495{
5496 Node *left,
5497 *right;
5498 VariableStatData rdata;
5499
5500 /* Fail if not a binary opclause (probably shouldn't happen) */
5501 if (list_length(args) != 2)
5502 return false;
5503
5504 left = (Node *) linitial(args);
5505 right = (Node *) lsecond(args);
5506
5507 /*
5508 * Examine both sides. Note that when varRelid is nonzero, Vars of other
5509 * relations will be treated as pseudoconstants.
5510 */
5511 examine_variable(root, left, varRelid, vardata);
5512 examine_variable(root, right, varRelid, &rdata);
5513
5514 /*
5515 * If one side is a variable and the other not, we win.
5516 */
5517 if (vardata->rel && rdata.rel == NULL)
5518 {
5519 *varonleft = true;
5520 *other = estimate_expression_value(root, rdata.var);
5521 /* Assume we need no ReleaseVariableStats(rdata) here */
5522 return true;
5523 }
5524
5525 if (vardata->rel == NULL && rdata.rel)
5526 {
5527 *varonleft = false;
5528 *other = estimate_expression_value(root, vardata->var);
5529 /* Assume we need no ReleaseVariableStats(*vardata) here */
5530 *vardata = rdata;
5531 return true;
5532 }
5533
5534 /* Oops, clause has wrong structure (probably var op var) */
5535 ReleaseVariableStats(*vardata);
5536 ReleaseVariableStats(rdata);
5537
5538 return false;
5539}
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2411

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

6522{
6523 double stadistinct;
6524 double stanullfrac = 0.0;
6525 double ntuples;
6526
6527 *isdefault = false;
6528
6529 /*
6530 * Determine the stadistinct value to use. There are cases where we can
6531 * get an estimate even without a pg_statistic entry, or can get a better
6532 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6533 * (otherwise, assume no nulls, for lack of any better idea).
6534 */
6535 if (HeapTupleIsValid(vardata->statsTuple))
6536 {
6537 /* Use the pg_statistic entry */
6538 Form_pg_statistic stats;
6539
6540 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6541 stadistinct = stats->stadistinct;
6542 stanullfrac = stats->stanullfrac;
6543 }
6544 else if (vardata->vartype == BOOLOID)
6545 {
6546 /*
6547 * Special-case boolean columns: presumably, two distinct values.
6548 *
6549 * Are there any other datatypes we should wire in special estimates
6550 * for?
6551 */
6552 stadistinct = 2.0;
6553 }
6554 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6555 {
6556 /*
6557 * If the Var represents a column of a VALUES RTE, assume it's unique.
6558 * This could of course be very wrong, but it should tend to be true
6559 * in well-written queries. We could consider examining the VALUES'
6560 * contents to get some real statistics; but that only works if the
6561 * entries are all constants, and it would be pretty expensive anyway.
6562 */
6563 stadistinct = -1.0; /* unique (and all non null) */
6564 }
6565 else
6566 {
6567 /*
6568 * We don't keep statistics for system columns, but in some cases we
6569 * can infer distinctness anyway.
6570 */
6571 if (vardata->var && IsA(vardata->var, Var))
6572 {
6573 switch (((Var *) vardata->var)->varattno)
6574 {
6576 stadistinct = -1.0; /* unique (and all non null) */
6577 break;
6579 stadistinct = 1.0; /* only 1 value */
6580 break;
6581 default:
6582 stadistinct = 0.0; /* means "unknown" */
6583 break;
6584 }
6585 }
6586 else
6587 stadistinct = 0.0; /* means "unknown" */
6588
6589 /*
6590 * XXX consider using estimate_num_groups on expressions?
6591 */
6592 }
6593
6594 /*
6595 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6596 * variable, assume it is unique no matter what pg_statistic says; the
6597 * statistics could be out of date, or we might have found a partial
6598 * unique index that proves the var is unique for this query. However,
6599 * we'd better still believe the null-fraction statistic.
6600 */
6601 if (vardata->isunique)
6602 stadistinct = -1.0 * (1.0 - stanullfrac);
6603
6604 /*
6605 * If we had an absolute estimate, use that.
6606 */
6607 if (stadistinct > 0.0)
6608 return clamp_row_est(stadistinct);
6609
6610 /*
6611 * Otherwise we need to get the relation size; punt if not available.
6612 */
6613 if (vardata->rel == NULL)
6614 {
6615 *isdefault = true;
6616 return DEFAULT_NUM_DISTINCT;
6617 }
6618 ntuples = vardata->rel->tuples;
6619 if (ntuples <= 0.0)
6620 {
6621 *isdefault = true;
6622 return DEFAULT_NUM_DISTINCT;
6623 }
6624
6625 /*
6626 * If we had a relative estimate, use that.
6627 */
6628 if (stadistinct < 0.0)
6629 return clamp_row_est(-stadistinct * ntuples);
6630
6631 /*
6632 * With no data, estimate ndistinct = ntuples if the table is small, else
6633 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6634 * that the behavior isn't discontinuous.
6635 */
6636 if (ntuples < DEFAULT_NUM_DISTINCT)
6637 return clamp_row_est(ntuples);
6638
6639 *isdefault = true;
6640 return DEFAULT_NUM_DISTINCT;
6641}
@ RTE_VALUES
Definition: parsenodes.h:1048
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
RTEKind rtekind
Definition: pathnodes.h:977
#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 893 of file selfuncs.c.

898{
899 double result;
900 AttStatsSlot sslot;
901
902 /* check sanity of parameters */
903 Assert(n_skip >= 0);
904 Assert(min_hist_size > 2 * n_skip);
905
906 if (HeapTupleIsValid(vardata->statsTuple) &&
907 statistic_proc_security_check(vardata, opproc->fn_oid) &&
908 get_attstatsslot(&sslot, vardata->statsTuple,
909 STATISTIC_KIND_HISTOGRAM, InvalidOid,
911 {
912 *hist_size = sslot.nvalues;
913 if (sslot.nvalues >= min_hist_size)
914 {
915 LOCAL_FCINFO(fcinfo, 2);
916 int nmatch = 0;
917 int i;
918
919 /*
920 * We invoke the opproc "by hand" so that we won't fail on NULL
921 * results. Such cases won't arise for normal comparison
922 * functions, but generic_restriction_selectivity could perhaps be
923 * used with operators that can return NULL. A small side benefit
924 * is to not need to re-initialize the fcinfo struct from scratch
925 * each time.
926 */
927 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
928 NULL, NULL);
929 fcinfo->args[0].isnull = false;
930 fcinfo->args[1].isnull = false;
931 /* be careful to apply operator right way 'round */
932 if (varonleft)
933 fcinfo->args[1].value = constval;
934 else
935 fcinfo->args[0].value = constval;
936
937 for (i = n_skip; i < sslot.nvalues - n_skip; i++)
938 {
939 Datum fresult;
940
941 if (varonleft)
942 fcinfo->args[0].value = sslot.values[i];
943 else
944 fcinfo->args[1].value = sslot.values[i];
945 fcinfo->isnull = false;
946 fresult = FunctionCallInvoke(fcinfo);
947 if (!fcinfo->isnull && DatumGetBool(fresult))
948 nmatch++;
949 }
950 result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
951 }
952 else
953 result = -1;
954 free_attstatsslot(&sslot);
955 }
956 else
957 {
958 *hist_size = 0;
959 result = -1;
960 }
961
962 return result;
963}
#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:6492
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 7260 of file selfuncs.c.

7261{
7262 Cost qual_arg_cost = 0;
7263 ListCell *lc;
7264
7265 foreach(lc, indexquals)
7266 {
7267 Expr *clause = (Expr *) lfirst(lc);
7268 Node *other_operand;
7269 QualCost index_qual_cost;
7270
7271 /*
7272 * Index quals will have RestrictInfos, indexorderbys won't. Look
7273 * through RestrictInfo if present.
7274 */
7275 if (IsA(clause, RestrictInfo))
7276 clause = ((RestrictInfo *) clause)->clause;
7277
7278 if (IsA(clause, OpExpr))
7279 {
7280 OpExpr *op = (OpExpr *) clause;
7281
7282 other_operand = (Node *) lsecond(op->args);
7283 }
7284 else if (IsA(clause, RowCompareExpr))
7285 {
7286 RowCompareExpr *rc = (RowCompareExpr *) clause;
7287
7288 other_operand = (Node *) rc->rargs;
7289 }
7290 else if (IsA(clause, ScalarArrayOpExpr))
7291 {
7292 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
7293
7294 other_operand = (Node *) lsecond(saop->args);
7295 }
7296 else if (IsA(clause, NullTest))
7297 {
7298 other_operand = NULL;
7299 }
7300 else
7301 {
7302 elog(ERROR, "unsupported indexqual type: %d",
7303 (int) nodeTag(clause));
7304 other_operand = NULL; /* keep compiler quiet */
7305 }
7306
7307 cost_qual_eval_node(&index_qual_cost, other_operand, root);
7308 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
7309 }
7310 return qual_arg_cost;
7311}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4807
#define nodeTag(nodeptr)
Definition: nodes.h:139
List * args
Definition: primnodes.h:868
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 1111 of file selfuncs.c.

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

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

805{
806 double mcv_selec,
807 sumcommon;
808 AttStatsSlot sslot;
809 int i;
810
811 mcv_selec = 0.0;
812 sumcommon = 0.0;
813
814 if (HeapTupleIsValid(vardata->statsTuple) &&
815 statistic_proc_security_check(vardata, opproc->fn_oid) &&
816 get_attstatsslot(&sslot, vardata->statsTuple,
817 STATISTIC_KIND_MCV, InvalidOid,
819 {
820 LOCAL_FCINFO(fcinfo, 2);
821
822 /*
823 * We invoke the opproc "by hand" so that we won't fail on NULL
824 * results. Such cases won't arise for normal comparison functions,
825 * but generic_restriction_selectivity could perhaps be used with
826 * operators that can return NULL. A small side benefit is to not
827 * need to re-initialize the fcinfo struct from scratch each time.
828 */
829 InitFunctionCallInfoData(*fcinfo, opproc, 2, collation,
830 NULL, NULL);
831 fcinfo->args[0].isnull = false;
832 fcinfo->args[1].isnull = false;
833 /* be careful to apply operator right way 'round */
834 if (varonleft)
835 fcinfo->args[1].value = constval;
836 else
837 fcinfo->args[0].value = constval;
838
839 for (i = 0; i < sslot.nvalues; i++)
840 {
841 Datum fresult;
842
843 if (varonleft)
844 fcinfo->args[0].value = sslot.values[i];
845 else
846 fcinfo->args[1].value = sslot.values[i];
847 fcinfo->isnull = false;
848 fresult = FunctionCallInvoke(fcinfo);
849 if (!fcinfo->isnull && DatumGetBool(fresult))
850 mcv_selec += sslot.numbers[i];
851 sumcommon += sslot.numbers[i];
852 }
853 free_attstatsslot(&sslot);
854 }
855
856 *sumcommonp = sumcommon;
857 return mcv_selec;
858}

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

3286{
3287 Node *left,
3288 *right;
3289 VariableStatData leftvar,
3290 rightvar;
3291 Oid opmethod;
3292 int op_strategy;
3293 Oid op_lefttype;
3294 Oid op_righttype;
3295 Oid opno,
3296 collation,
3297 lsortop,
3298 rsortop,
3299 lstatop,
3300 rstatop,
3301 ltop,
3302 leop,
3303 revltop,
3304 revleop;
3305 StrategyNumber ltstrat,
3306 lestrat,
3307 gtstrat,
3308 gestrat;
3309 bool isgt;
3310 Datum leftmin,
3311 leftmax,
3312 rightmin,
3313 rightmax;
3314 double selec;
3315
3316 /* Set default results if we can't figure anything out. */
3317 /* XXX should default "start" fraction be a bit more than 0? */
3318 *leftstart = *rightstart = 0.0;
3319 *leftend = *rightend = 1.0;
3320
3321 /* Deconstruct the merge clause */
3322 if (!is_opclause(clause))
3323 return; /* shouldn't happen */
3324 opno = ((OpExpr *) clause)->opno;
3325 collation = ((OpExpr *) clause)->inputcollid;
3326 left = get_leftop((Expr *) clause);
3327 right = get_rightop((Expr *) clause);
3328 if (!right)
3329 return; /* shouldn't happen */
3330
3331 /* Look for stats for the inputs */
3332 examine_variable(root, left, 0, &leftvar);
3333 examine_variable(root, right, 0, &rightvar);
3334
3335 opmethod = get_opfamily_method(opfamily);
3336
3337 /* Extract the operator's declared left/right datatypes */
3338 get_op_opfamily_properties(opno, opfamily, false,
3339 &op_strategy,
3340 &op_lefttype,
3341 &op_righttype);
3342 Assert(IndexAmTranslateStrategy(op_strategy, opmethod, opfamily, true) == COMPARE_EQ);
3343
3344 /*
3345 * Look up the various operators we need. If we don't find them all, it
3346 * probably means the opfamily is broken, but we just fail silently.
3347 *
3348 * Note: we expect that pg_statistic histograms will be sorted by the '<'
3349 * operator, regardless of which sort direction we are considering.
3350 */
3351 switch (cmptype)
3352 {
3353 case COMPARE_LT:
3354 isgt = false;
3355 ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
3356 lestrat = IndexAmTranslateCompareType(COMPARE_LE, opmethod, opfamily, true);
3357 if (op_lefttype == op_righttype)
3358 {
3359 /* easy case */
3360 ltop = get_opfamily_member(opfamily,
3361 op_lefttype, op_righttype,
3362 ltstrat);
3363 leop = get_opfamily_member(opfamily,
3364 op_lefttype, op_righttype,
3365 lestrat);
3366 lsortop = ltop;
3367 rsortop = ltop;
3368 lstatop = lsortop;
3369 rstatop = rsortop;
3370 revltop = ltop;
3371 revleop = leop;
3372 }
3373 else
3374 {
3375 ltop = get_opfamily_member(opfamily,
3376 op_lefttype, op_righttype,
3377 ltstrat);
3378 leop = get_opfamily_member(opfamily,
3379 op_lefttype, op_righttype,
3380 lestrat);
3381 lsortop = get_opfamily_member(opfamily,
3382 op_lefttype, op_lefttype,
3383 ltstrat);
3384 rsortop = get_opfamily_member(opfamily,
3385 op_righttype, op_righttype,
3386 ltstrat);
3387 lstatop = lsortop;
3388 rstatop = rsortop;
3389 revltop = get_opfamily_member(opfamily,
3390 op_righttype, op_lefttype,
3391 ltstrat);
3392 revleop = get_opfamily_member(opfamily,
3393 op_righttype, op_lefttype,
3394 lestrat);
3395 }
3396 break;
3397 case COMPARE_GT:
3398 /* descending-order case */
3399 isgt = true;
3400 ltstrat = IndexAmTranslateCompareType(COMPARE_LT, opmethod, opfamily, true);
3401 gtstrat = IndexAmTranslateCompareType(COMPARE_GT, opmethod, opfamily, true);
3402 gestrat = IndexAmTranslateCompareType(COMPARE_GE, opmethod, opfamily, true);
3403 if (op_lefttype == op_righttype)
3404 {
3405 /* easy case */
3406 ltop = get_opfamily_member(opfamily,
3407 op_lefttype, op_righttype,
3408 gtstrat);
3409 leop = get_opfamily_member(opfamily,
3410 op_lefttype, op_righttype,
3411 gestrat);
3412 lsortop = ltop;
3413 rsortop = ltop;
3414 lstatop = get_opfamily_member(opfamily,
3415 op_lefttype, op_lefttype,
3416 ltstrat);
3417 rstatop = lstatop;
3418 revltop = ltop;
3419 revleop = leop;
3420 }
3421 else
3422 {
3423 ltop = get_opfamily_member(opfamily,
3424 op_lefttype, op_righttype,
3425 gtstrat);
3426 leop = get_opfamily_member(opfamily,
3427 op_lefttype, op_righttype,
3428 gestrat);
3429 lsortop = get_opfamily_member(opfamily,
3430 op_lefttype, op_lefttype,
3431 gtstrat);
3432 rsortop = get_opfamily_member(opfamily,
3433 op_righttype, op_righttype,
3434 gtstrat);
3435 lstatop = get_opfamily_member(opfamily,
3436 op_lefttype, op_lefttype,
3437 ltstrat);
3438 rstatop = get_opfamily_member(opfamily,
3439 op_righttype, op_righttype,
3440 ltstrat);
3441 revltop = get_opfamily_member(opfamily,
3442 op_righttype, op_lefttype,
3443 gtstrat);
3444 revleop = get_opfamily_member(opfamily,
3445 op_righttype, op_lefttype,
3446 gestrat);
3447 }
3448 break;
3449 default:
3450 goto fail; /* shouldn't get here */
3451 }
3452
3453 if (!OidIsValid(lsortop) ||
3454 !OidIsValid(rsortop) ||
3455 !OidIsValid(lstatop) ||
3456 !OidIsValid(rstatop) ||
3457 !OidIsValid(ltop) ||
3458 !OidIsValid(leop) ||
3459 !OidIsValid(revltop) ||
3460 !OidIsValid(revleop))
3461 goto fail; /* insufficient info in catalogs */
3462
3463 /* Try to get ranges of both inputs */
3464 if (!isgt)
3465 {
3466 if (!get_variable_range(root, &leftvar, lstatop, collation,
3467 &leftmin, &leftmax))
3468 goto fail; /* no range available from stats */
3469 if (!get_variable_range(root, &rightvar, rstatop, collation,
3470 &rightmin, &rightmax))
3471 goto fail; /* no range available from stats */
3472 }
3473 else
3474 {
3475 /* need to swap the max and min */
3476 if (!get_variable_range(root, &leftvar, lstatop, collation,
3477 &leftmax, &leftmin))
3478 goto fail; /* no range available from stats */
3479 if (!get_variable_range(root, &rightvar, rstatop, collation,
3480 &rightmax, &rightmin))
3481 goto fail; /* no range available from stats */
3482 }
3483
3484 /*
3485 * Now, the fraction of the left variable that will be scanned is the
3486 * fraction that's <= the right-side maximum value. But only believe
3487 * non-default estimates, else stick with our 1.0.
3488 */
3489 selec = scalarineqsel(root, leop, isgt, true, collation, &leftvar,
3490 rightmax, op_righttype);
3491 if (selec != DEFAULT_INEQ_SEL)
3492 *leftend = selec;
3493
3494 /* And similarly for the right variable. */
3495 selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar,
3496 leftmax, op_lefttype);
3497 if (selec != DEFAULT_INEQ_SEL)
3498 *rightend = selec;
3499
3500 /*
3501 * Only one of the two "end" fractions can really be less than 1.0;
3502 * believe the smaller estimate and reset the other one to exactly 1.0. If
3503 * we get exactly equal estimates (as can easily happen with self-joins),
3504 * believe neither.
3505 */
3506 if (*leftend > *rightend)
3507 *leftend = 1.0;
3508 else if (*leftend < *rightend)
3509 *rightend = 1.0;
3510 else
3511 *leftend = *rightend = 1.0;
3512
3513 /*
3514 * Also, the fraction of the left variable that will be scanned before the
3515 * first join pair is found is the fraction that's < the right-side
3516 * minimum value. But only believe non-default estimates, else stick with
3517 * our own default.
3518 */
3519 selec = scalarineqsel(root, ltop, isgt, false, collation, &leftvar,
3520 rightmin, op_righttype);
3521 if (selec != DEFAULT_INEQ_SEL)
3522 *leftstart = selec;
3523
3524 /* And similarly for the right variable. */
3525 selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar,
3526 leftmin, op_lefttype);
3527 if (selec != DEFAULT_INEQ_SEL)
3528 *rightstart = selec;
3529
3530 /*
3531 * Only one of the two "start" fractions can really be more than zero;
3532 * believe the larger estimate and reset the other one to exactly 0.0. If
3533 * we get exactly equal estimates (as can easily happen with self-joins),
3534 * believe neither.
3535 */
3536 if (*leftstart < *rightstart)
3537 *leftstart = 0.0;
3538 else if (*leftstart > *rightstart)
3539 *rightstart = 0.0;
3540 else
3541 *leftstart = *rightstart = 0.0;
3542
3543 /*
3544 * If the sort order is nulls-first, we're going to have to skip over any
3545 * nulls too. These would not have been counted by scalarineqsel, and we
3546 * can safely add in this fraction regardless of whether we believe
3547 * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3548 */
3549 if (nulls_first)
3550 {
3551 Form_pg_statistic stats;
3552
3553 if (HeapTupleIsValid(leftvar.statsTuple))
3554 {
3555 stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3556 *leftstart += stats->stanullfrac;
3557 CLAMP_PROBABILITY(*leftstart);
3558 *leftend += stats->stanullfrac;
3559 CLAMP_PROBABILITY(*leftend);
3560 }
3561 if (HeapTupleIsValid(rightvar.statsTuple))
3562 {
3563 stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3564 *rightstart += stats->stanullfrac;
3565 CLAMP_PROBABILITY(*rightstart);
3566 *rightend += stats->stanullfrac;
3567 CLAMP_PROBABILITY(*rightend);
3568 }
3569 }
3570
3571 /* Disbelieve start >= end, just in case that can happen */
3572 if (*leftstart >= *leftend)
3573 {
3574 *leftstart = 0.0;
3575 *leftend = 1.0;
3576 }
3577 if (*rightstart >= *rightend)
3578 {
3579 *rightstart = 0.0;
3580 *rightend = 1.0;
3581 }
3582
3583fail:
3584 ReleaseVariableStats(leftvar);
3585 ReleaseVariableStats(rightvar);
3586}
StrategyNumber IndexAmTranslateCompareType(CompareType cmptype, Oid amoid, Oid opfamily, bool missing_ok)
Definition: amapi.c:161
CompareType IndexAmTranslateStrategy(StrategyNumber strategy, Oid amoid, Oid opfamily, bool missing_ok)
Definition: amapi.c:131
@ 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:138
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:168
Oid get_opfamily_method(Oid opfid)
Definition: lsyscache.c:1403
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:6654
static double scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq, Oid collation, VariableStatData *vardata, Datum constval, Oid consttype)
Definition: selfuncs.c:650
#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 1779 of file selfuncs.c.

1781{
1782 VariableStatData vardata;
1783 double selec;
1784
1785 examine_variable(root, arg, varRelid, &vardata);
1786
1787 if (HeapTupleIsValid(vardata.statsTuple))
1788 {
1789 Form_pg_statistic stats;
1790 double freq_null;
1791
1792 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1793 freq_null = stats->stanullfrac;
1794
1795 switch (nulltesttype)
1796 {
1797 case IS_NULL:
1798
1799 /*
1800 * Use freq_null directly.
1801 */
1802 selec = freq_null;
1803 break;
1804 case IS_NOT_NULL:
1805
1806 /*
1807 * Select not unknown (not null) values. Calculate from
1808 * freq_null.
1809 */
1810 selec = 1.0 - freq_null;
1811 break;
1812 default:
1813 elog(ERROR, "unrecognized nulltesttype: %d",
1814 (int) nulltesttype);
1815 return (Selectivity) 0; /* keep compiler quiet */
1816 }
1817 }
1818 else if (vardata.var && IsA(vardata.var, Var) &&
1819 ((Var *) vardata.var)->varattno < 0)
1820 {
1821 /*
1822 * There are no stats for system columns, but we know they are never
1823 * NULL.
1824 */
1825 selec = (nulltesttype == IS_NULL) ? 0.0 : 1.0;
1826 }
1827 else
1828 {
1829 /*
1830 * No ANALYZE stats available, so make a guess
1831 */
1832 switch (nulltesttype)
1833 {
1834 case IS_NULL:
1835 selec = DEFAULT_UNK_SEL;
1836 break;
1837 case IS_NOT_NULL:
1838 selec = DEFAULT_NOT_UNK_SEL;
1839 break;
1840 default:
1841 elog(ERROR, "unrecognized nulltesttype: %d",
1842 (int) nulltesttype);
1843 return (Selectivity) 0; /* keep compiler quiet */
1844 }
1845 }
1846
1847 ReleaseVariableStats(vardata);
1848
1849 /* result should be in range, but make sure... */
1850 CLAMP_PROBABILITY(selec);
1851
1852 return (Selectivity) selec;
1853}
@ IS_NULL
Definition: primnodes.h:1977
@ IS_NOT_NULL
Definition: primnodes.h:1977

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

2289{
2291 Oid opno = linitial_oid(clause->opnos);
2292 Oid inputcollid = linitial_oid(clause->inputcollids);
2293 List *opargs;
2294 bool is_join_clause;
2295
2296 /* Build equivalent arg list for single operator */
2297 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2298
2299 /*
2300 * Decide if it's a join clause. This should match clausesel.c's
2301 * treat_as_join_clause(), except that we intentionally consider only the
2302 * leading columns and not the rest of the clause.
2303 */
2304 if (varRelid != 0)
2305 {
2306 /*
2307 * Caller is forcing restriction mode (eg, because we are examining an
2308 * inner indexscan qual).
2309 */
2310 is_join_clause = false;
2311 }
2312 else if (sjinfo == NULL)
2313 {
2314 /*
2315 * It must be a restriction clause, since it's being evaluated at a
2316 * scan node.
2317 */
2318 is_join_clause = false;
2319 }
2320 else
2321 {
2322 /*
2323 * Otherwise, it's a join if there's more than one base relation used.
2324 */
2325 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2326 }
2327
2328 if (is_join_clause)
2329 {
2330 /* Estimate selectivity for a join clause. */
2331 s1 = join_selectivity(root, opno,
2332 opargs,
2333 inputcollid,
2334 jointype,
2335 sjinfo);
2336 }
2337 else
2338 {
2339 /* Estimate selectivity for a restriction clause. */
2341 opargs,
2342 inputcollid,
2343 varRelid);
2344 }
2345
2346 return s1;
2347}
int NumRelids(PlannerInfo *root, Node *clause)
Definition: clauses.c:2145
#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:2183
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:2222
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 1897 of file selfuncs.c.

1903{
1904 Oid operator = clause->opno;
1905 bool useOr = clause->useOr;
1906 bool isEquality = false;
1907 bool isInequality = false;
1908 Node *leftop;
1909 Node *rightop;
1910 Oid nominal_element_type;
1911 Oid nominal_element_collation;
1912 TypeCacheEntry *typentry;
1913 RegProcedure oprsel;
1914 FmgrInfo oprselproc;
1916 Selectivity s1disjoint;
1917
1918 /* First, deconstruct the expression */
1919 Assert(list_length(clause->args) == 2);
1920 leftop = (Node *) linitial(clause->args);
1921 rightop = (Node *) lsecond(clause->args);
1922
1923 /* aggressively reduce both sides to constants */
1924 leftop = estimate_expression_value(root, leftop);
1925 rightop = estimate_expression_value(root, rightop);
1926
1927 /* get nominal (after relabeling) element type of rightop */
1928 nominal_element_type = get_base_element_type(exprType(rightop));
1929 if (!OidIsValid(nominal_element_type))
1930 return (Selectivity) 0.5; /* probably shouldn't happen */
1931 /* get nominal collation, too, for generating constants */
1932 nominal_element_collation = exprCollation(rightop);
1933
1934 /* look through any binary-compatible relabeling of rightop */
1935 rightop = strip_array_coercion(rightop);
1936
1937 /*
1938 * Detect whether the operator is the default equality or inequality
1939 * operator of the array element type.
1940 */
1941 typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1942 if (OidIsValid(typentry->eq_opr))
1943 {
1944 if (operator == typentry->eq_opr)
1945 isEquality = true;
1946 else if (get_negator(operator) == typentry->eq_opr)
1947 isInequality = true;
1948 }
1949
1950 /*
1951 * If it is equality or inequality, we might be able to estimate this as a
1952 * form of array containment; for instance "const = ANY(column)" can be
1953 * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1954 * that, and returns the selectivity estimate if successful, or -1 if not.
1955 */
1956 if ((isEquality || isInequality) && !is_join_clause)
1957 {
1958 s1 = scalararraysel_containment(root, leftop, rightop,
1959 nominal_element_type,
1960 isEquality, useOr, varRelid);
1961 if (s1 >= 0.0)
1962 return s1;
1963 }
1964
1965 /*
1966 * Look up the underlying operator's selectivity estimator. Punt if it
1967 * hasn't got one.
1968 */
1969 if (is_join_clause)
1970 oprsel = get_oprjoin(operator);
1971 else
1972 oprsel = get_oprrest(operator);
1973 if (!oprsel)
1974 return (Selectivity) 0.5;
1975 fmgr_info(oprsel, &oprselproc);
1976
1977 /*
1978 * In the array-containment check above, we must only believe that an
1979 * operator is equality or inequality if it is the default btree equality
1980 * operator (or its negator) for the element type, since those are the
1981 * operators that array containment will use. But in what follows, we can
1982 * be a little laxer, and also believe that any operators using eqsel() or
1983 * neqsel() as selectivity estimator act like equality or inequality.
1984 */
1985 if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1986 isEquality = true;
1987 else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1988 isInequality = true;
1989
1990 /*
1991 * We consider three cases:
1992 *
1993 * 1. rightop is an Array constant: deconstruct the array, apply the
1994 * operator's selectivity function for each array element, and merge the
1995 * results in the same way that clausesel.c does for AND/OR combinations.
1996 *
1997 * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1998 * function for each element of the ARRAY[] construct, and merge.
1999 *
2000 * 3. otherwise, make a guess ...
2001 */
2002 if (rightop && IsA(rightop, Const))
2003 {
2004 Datum arraydatum = ((Const *) rightop)->constvalue;
2005 bool arrayisnull = ((Const *) rightop)->constisnull;
2006 ArrayType *arrayval;
2007 int16 elmlen;
2008 bool elmbyval;
2009 char elmalign;
2010 int num_elems;
2011 Datum *elem_values;
2012 bool *elem_nulls;
2013 int i;
2014
2015 if (arrayisnull) /* qual can't succeed if null array */
2016 return (Selectivity) 0.0;
2017 arrayval = DatumGetArrayTypeP(arraydatum);
2019 &elmlen, &elmbyval, &elmalign);
2020 deconstruct_array(arrayval,
2021 ARR_ELEMTYPE(arrayval),
2022 elmlen, elmbyval, elmalign,
2023 &elem_values, &elem_nulls, &num_elems);
2024
2025 /*
2026 * For generic operators, we assume the probability of success is
2027 * independent for each array element. But for "= ANY" or "<> ALL",
2028 * if the array elements are distinct (which'd typically be the case)
2029 * then the probabilities are disjoint, and we should just sum them.
2030 *
2031 * If we were being really tense we would try to confirm that the
2032 * elements are all distinct, but that would be expensive and it
2033 * doesn't seem to be worth the cycles; it would amount to penalizing
2034 * well-written queries in favor of poorly-written ones. However, we
2035 * do protect ourselves a little bit by checking whether the
2036 * disjointness assumption leads to an impossible (out of range)
2037 * probability; if so, we fall back to the normal calculation.
2038 */
2039 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2040
2041 for (i = 0; i < num_elems; i++)
2042 {
2043 List *args;
2045
2046 args = list_make2(leftop,
2047 makeConst(nominal_element_type,
2048 -1,
2049 nominal_element_collation,
2050 elmlen,
2051 elem_values[i],
2052 elem_nulls[i],
2053 elmbyval));
2054 if (is_join_clause)
2055 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2056 clause->inputcollid,
2058 ObjectIdGetDatum(operator),
2060 Int16GetDatum(jointype),
2061 PointerGetDatum(sjinfo)));
2062 else
2063 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2064 clause->inputcollid,
2066 ObjectIdGetDatum(operator),
2068 Int32GetDatum(varRelid)));
2069
2070 if (useOr)
2071 {
2072 s1 = s1 + s2 - s1 * s2;
2073 if (isEquality)
2074 s1disjoint += s2;
2075 }
2076 else
2077 {
2078 s1 = s1 * s2;
2079 if (isInequality)
2080 s1disjoint += s2 - 1.0;
2081 }
2082 }
2083
2084 /* accept disjoint-probability estimate if in range */
2085 if ((useOr ? isEquality : isInequality) &&
2086 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2087 s1 = s1disjoint;
2088 }
2089 else if (rightop && IsA(rightop, ArrayExpr) &&
2090 !((ArrayExpr *) rightop)->multidims)
2091 {
2092 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2093 int16 elmlen;
2094 bool elmbyval;
2095 ListCell *l;
2096
2097 get_typlenbyval(arrayexpr->element_typeid,
2098 &elmlen, &elmbyval);
2099
2100 /*
2101 * We use the assumption of disjoint probabilities here too, although
2102 * the odds of equal array elements are rather higher if the elements
2103 * are not all constants (which they won't be, else constant folding
2104 * would have reduced the ArrayExpr to a Const). In this path it's
2105 * critical to have the sanity check on the s1disjoint estimate.
2106 */
2107 s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2108
2109 foreach(l, arrayexpr->elements)
2110 {
2111 Node *elem = (Node *) lfirst(l);
2112 List *args;
2114
2115 /*
2116 * Theoretically, if elem isn't of nominal_element_type we should
2117 * insert a RelabelType, but it seems unlikely that any operator
2118 * estimation function would really care ...
2119 */
2120 args = list_make2(leftop, elem);
2121 if (is_join_clause)
2122 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2123 clause->inputcollid,
2125 ObjectIdGetDatum(operator),
2127 Int16GetDatum(jointype),
2128 PointerGetDatum(sjinfo)));
2129 else
2130 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2131 clause->inputcollid,
2133 ObjectIdGetDatum(operator),
2135 Int32GetDatum(varRelid)));
2136
2137 if (useOr)
2138 {
2139 s1 = s1 + s2 - s1 * s2;
2140 if (isEquality)
2141 s1disjoint += s2;
2142 }
2143 else
2144 {
2145 s1 = s1 * s2;
2146 if (isInequality)
2147 s1disjoint += s2 - 1.0;
2148 }
2149 }
2150
2151 /* accept disjoint-probability estimate if in range */
2152 if ((useOr ? isEquality : isInequality) &&
2153 s1disjoint >= 0.0 && s1disjoint <= 1.0)
2154 s1 = s1disjoint;
2155 }
2156 else
2157 {
2158 CaseTestExpr *dummyexpr;
2159 List *args;
2161 int i;
2162
2163 /*
2164 * We need a dummy rightop to pass to the operator selectivity
2165 * routine. It can be pretty much anything that doesn't look like a
2166 * constant; CaseTestExpr is a convenient choice.
2167 */
2168 dummyexpr = makeNode(CaseTestExpr);
2169 dummyexpr->typeId = nominal_element_type;
2170 dummyexpr->typeMod = -1;
2171 dummyexpr->collation = clause->inputcollid;
2172 args = list_make2(leftop, dummyexpr);
2173 if (is_join_clause)
2174 s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2175 clause->inputcollid,
2177 ObjectIdGetDatum(operator),
2179 Int16GetDatum(jointype),
2180 PointerGetDatum(sjinfo)));
2181 else
2182 s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2183 clause->inputcollid,
2185 ObjectIdGetDatum(operator),
2187 Int32GetDatum(varRelid)));
2188 s1 = useOr ? 0.0 : 1.0;
2189
2190 /*
2191 * Arbitrarily assume 10 elements in the eventual array value (see
2192 * also estimate_array_length). We don't risk an assumption of
2193 * disjoint probabilities here.
2194 */
2195 for (i = 0; i < 10; i++)
2196 {
2197 if (useOr)
2198 s1 = s1 + s2 - s1 * s2;
2199 else
2200 s1 = s1 * s2;
2201 }
2202 }
2203
2204 /* result should be in range, but make sure... */
2206
2207 return s1;
2208}
#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(const ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3632
int16_t int16
Definition: c.h:536
regproc RegProcedure
Definition: c.h:658
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1197
Datum FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1224
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1724
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2438
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1748
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2418
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2999
Oid get_negator(Oid opno)
Definition: lsyscache.c:1700
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:332
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:475
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
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(const Datum *mcelem, int nmcelem, const float4 *numbers, int nnumbers, const Datum *array_data, int nitems, const float4 *hist, int nhist, Oid operator, TypeCacheEntry *typentry)
static Selectivity mcelem_array_contain_overlap_selec(const Datum *mcelem, int nmcelem, const float4 *numbers, int nnumbers, const 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 6492 of file selfuncs.c.

6493{
6494 if (vardata->acl_ok)
6495 return true; /* have SELECT privs and no securityQuals */
6496
6497 if (!OidIsValid(func_oid))
6498 return false;
6499
6500 if (get_func_leakproof(func_oid))
6501 return true;
6502
6504 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6505 get_func_name(func_oid))));
6506 return false;
6507}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:150
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:2004
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1775

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

368{
369 double selec;
370 double nullfrac = 0.0;
371 bool isdefault;
372 Oid opfuncoid;
373
374 /*
375 * If the constant is NULL, assume operator is strict and return zero, ie,
376 * operator will never return TRUE. (It's zero even for a negator op.)
377 */
378 if (constisnull)
379 return 0.0;
380
381 /*
382 * Grab the nullfrac for use below. Note we allow use of nullfrac
383 * regardless of security check.
384 */
385 if (HeapTupleIsValid(vardata->statsTuple))
386 {
387 Form_pg_statistic stats;
388
389 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
390 nullfrac = stats->stanullfrac;
391 }
392
393 /*
394 * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
395 * assume there is exactly one match regardless of anything else. (This
396 * is slightly bogus, since the index or clause's equality operator might
397 * be different from ours, but it's much more likely to be right than
398 * ignoring the information.)
399 */
400 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
401 {
402 selec = 1.0 / vardata->rel->tuples;
403 }
404 else if (HeapTupleIsValid(vardata->statsTuple) &&
406 (opfuncoid = get_opcode(oproid))))
407 {
408 AttStatsSlot sslot;
409 bool match = false;
410 int i;
411
412 /*
413 * Is the constant "=" to any of the column's most common values?
414 * (Although the given operator may not really be "=", we will assume
415 * that seeing whether it returns TRUE is an appropriate test. If you
416 * don't like this, maybe you shouldn't be using eqsel for your
417 * operator...)
418 */
419 if (get_attstatsslot(&sslot, vardata->statsTuple,
420 STATISTIC_KIND_MCV, InvalidOid,
422 {
423 LOCAL_FCINFO(fcinfo, 2);
424 FmgrInfo eqproc;
425
426 fmgr_info(opfuncoid, &eqproc);
427
428 /*
429 * Save a few cycles by setting up the fcinfo struct just once.
430 * Using FunctionCallInvoke directly also avoids failure if the
431 * eqproc returns NULL, though really equality functions should
432 * never do that.
433 */
434 InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
435 NULL, NULL);
436 fcinfo->args[0].isnull = false;
437 fcinfo->args[1].isnull = false;
438 /* be careful to apply operator right way 'round */
439 if (varonleft)
440 fcinfo->args[1].value = constval;
441 else
442 fcinfo->args[0].value = constval;
443
444 for (i = 0; i < sslot.nvalues; i++)
445 {
446 Datum fresult;
447
448 if (varonleft)
449 fcinfo->args[0].value = sslot.values[i];
450 else
451 fcinfo->args[1].value = sslot.values[i];
452 fcinfo->isnull = false;
453 fresult = FunctionCallInvoke(fcinfo);
454 if (!fcinfo->isnull && DatumGetBool(fresult))
455 {
456 match = true;
457 break;
458 }
459 }
460 }
461 else
462 {
463 /* no most-common-value info available */
464 i = 0; /* keep compiler quiet */
465 }
466
467 if (match)
468 {
469 /*
470 * Constant is "=" to this common value. We know selectivity
471 * exactly (or as exactly as ANALYZE could calculate it, anyway).
472 */
473 selec = sslot.numbers[i];
474 }
475 else
476 {
477 /*
478 * Comparison is against a constant that is neither NULL nor any
479 * of the common values. Its selectivity cannot be more than
480 * this:
481 */
482 double sumcommon = 0.0;
483 double otherdistinct;
484
485 for (i = 0; i < sslot.nnumbers; i++)
486 sumcommon += sslot.numbers[i];
487 selec = 1.0 - sumcommon - nullfrac;
488 CLAMP_PROBABILITY(selec);
489
490 /*
491 * and in fact it's probably a good deal less. We approximate that
492 * all the not-common values share this remaining fraction
493 * equally, so we divide by the number of other distinct values.
494 */
495 otherdistinct = get_variable_numdistinct(vardata, &isdefault) -
496 sslot.nnumbers;
497 if (otherdistinct > 1)
498 selec /= otherdistinct;
499
500 /*
501 * Another cross-check: selectivity shouldn't be estimated as more
502 * than the least common "most common value".
503 */
504 if (sslot.nnumbers > 0 && selec > sslot.numbers[sslot.nnumbers - 1])
505 selec = sslot.numbers[sslot.nnumbers - 1];
506 }
507
508 free_attstatsslot(&sslot);
509 }
510 else
511 {
512 /*
513 * No ANALYZE stats available, so make a guess using estimated number
514 * of distinct values and assuming they are equally common. (The guess
515 * is unlikely to be very good, but we do know a few special cases.)
516 */
517 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
518 }
519
520 /* now adjust if we wanted <> rather than = */
521 if (negate)
522 selec = 1.0 - selec - nullfrac;
523
524 /* result should be in range, but make sure... */
525 CLAMP_PROBABILITY(selec);
526
527 return selec;
528}

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

539{
540 double selec;
541 double nullfrac = 0.0;
542 bool isdefault;
543
544 /*
545 * Grab the nullfrac for use below.
546 */
547 if (HeapTupleIsValid(vardata->statsTuple))
548 {
549 Form_pg_statistic stats;
550
551 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
552 nullfrac = stats->stanullfrac;
553 }
554
555 /*
556 * If we matched the var to a unique index, DISTINCT or GROUP-BY clause,
557 * assume there is exactly one match regardless of anything else. (This
558 * is slightly bogus, since the index or clause's equality operator might
559 * be different from ours, but it's much more likely to be right than
560 * ignoring the information.)
561 */
562 if (vardata->isunique && vardata->rel && vardata->rel->tuples >= 1.0)
563 {
564 selec = 1.0 / vardata->rel->tuples;
565 }
566 else if (HeapTupleIsValid(vardata->statsTuple))
567 {
568 double ndistinct;
569 AttStatsSlot sslot;
570
571 /*
572 * Search is for a value that we do not know a priori, but we will
573 * assume it is not NULL. Estimate the selectivity as non-null
574 * fraction divided by number of distinct values, so that we get a
575 * result averaged over all possible values whether common or
576 * uncommon. (Essentially, we are assuming that the not-yet-known
577 * comparison value is equally likely to be any of the possible
578 * values, regardless of their frequency in the table. Is that a good
579 * idea?)
580 */
581 selec = 1.0 - nullfrac;
582 ndistinct = get_variable_numdistinct(vardata, &isdefault);
583 if (ndistinct > 1)
584 selec /= ndistinct;
585
586 /*
587 * Cross-check: selectivity should never be estimated as more than the
588 * most common value's.
589 */
590 if (get_attstatsslot(&sslot, vardata->statsTuple,
591 STATISTIC_KIND_MCV, InvalidOid,
593 {
594 if (sslot.nnumbers > 0 && selec > sslot.numbers[0])
595 selec = sslot.numbers[0];
596 free_attstatsslot(&sslot);
597 }
598 }
599 else
600 {
601 /*
602 * No ANALYZE stats available, so make a guess using estimated number
603 * of distinct values and assuming they are equally common. (The guess
604 * is unlikely to be very good, but we do know a few special cases.)
605 */
606 selec = 1.0 / get_variable_numdistinct(vardata, &isdefault);
607 }
608
609 /* now adjust if we wanted <> rather than = */
610 if (negate)
611 selec = 1.0 - selec - nullfrac;
612
613 /* result should be in range, but make sure... */
614 CLAMP_PROBABILITY(selec);
615
616 return selec;
617}

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 184 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