Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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

7219{
7220 List *predExtraQuals = NIL;
7221 ListCell *lc;
7222
7223 if (index->indpred == NIL)
7224 return indexQuals;
7225
7226 foreach(lc, index->indpred)
7227 {
7228 Node *predQual = (Node *) lfirst(lc);
7229 List *oneQual = list_make1(predQual);
7230
7231 if (!predicate_implied_by(oneQual, indexQuals, false))
7232 predExtraQuals = list_concat(predExtraQuals, oneQual);
7233 }
7234 return list_concat(predExtraQuals, indexQuals);
7235}
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 5911 of file selfuncs.c.

5912{
5913 RelOptInfo *rel = find_base_rel_noerr(root, varno);
5914 RangeTblEntry *rte = planner_rt_fetch(varno, root);
5915 Oid userid;
5916 int varattno;
5917
5918 Assert(rte->rtekind == RTE_RELATION);
5919
5920 /*
5921 * Determine the user ID to use for privilege checks (either the current
5922 * user or the view owner, if we're accessing the table via a view).
5923 *
5924 * Normally the relation will have an associated RelOptInfo from which we
5925 * can find the userid, but it might not if it's a RETURNING Var for an
5926 * INSERT target relation. In that case use the RTEPermissionInfo
5927 * associated with the RTE.
5928 *
5929 * If we navigate up to a parent relation, we keep using the same userid,
5930 * since it's the same in all relations of a given inheritance tree.
5931 */
5932 if (rel)
5933 userid = rel->userid;
5934 else
5935 {
5936 RTEPermissionInfo *perminfo;
5937
5938 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
5939 userid = perminfo->checkAsUser;
5940 }
5941 if (!OidIsValid(userid))
5942 userid = GetUserId();
5943
5944 /*
5945 * Permissions and securityQuals must be checked on the table actually
5946 * mentioned in the query, so if this is an inheritance child, navigate up
5947 * to the inheritance root parent. If the user can read the whole table
5948 * or the required columns there, then they can read from the child table
5949 * too. For per-column checks, we must find out which of the root
5950 * parent's attributes the child relation's attributes correspond to.
5951 */
5952 if (root->append_rel_array != NULL)
5953 {
5954 AppendRelInfo *appinfo;
5955
5956 appinfo = root->append_rel_array[varno];
5957
5958 /*
5959 * Partitions are mapped to their immediate parent, not the root
5960 * parent, so must be ready to walk up multiple AppendRelInfos. But
5961 * stop if we hit a parent that is not RTE_RELATION --- that's a
5962 * flattened UNION ALL subquery, not an inheritance parent.
5963 */
5964 while (appinfo &&
5966 root)->rtekind == RTE_RELATION)
5967 {
5968 Bitmapset *parent_varattnos = NULL;
5969
5970 /*
5971 * For each child attribute, find the corresponding parent
5972 * attribute. In rare cases, the attribute may be local to the
5973 * child table, in which case, we've got to live with having no
5974 * access to this column.
5975 */
5976 varattno = -1;
5977 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
5978 {
5979 AttrNumber attno;
5980 AttrNumber parent_attno;
5981
5982 attno = varattno + FirstLowInvalidHeapAttributeNumber;
5983
5984 if (attno == InvalidAttrNumber)
5985 {
5986 /*
5987 * Whole-row reference, so must map each column of the
5988 * child to the parent table.
5989 */
5990 for (attno = 1; attno <= appinfo->num_child_cols; attno++)
5991 {
5992 parent_attno = appinfo->parent_colnos[attno - 1];
5993 if (parent_attno == 0)
5994 return false; /* attr is local to child */
5995 parent_varattnos =
5996 bms_add_member(parent_varattnos,
5997 parent_attno - FirstLowInvalidHeapAttributeNumber);
5998 }
5999 }
6000 else
6001 {
6002 if (attno < 0)
6003 {
6004 /* System attnos are the same in all tables */
6005 parent_attno = attno;
6006 }
6007 else
6008 {
6009 if (attno > appinfo->num_child_cols)
6010 return false; /* safety check */
6011 parent_attno = appinfo->parent_colnos[attno - 1];
6012 if (parent_attno == 0)
6013 return false; /* attr is local to child */
6014 }
6015 parent_varattnos =
6016 bms_add_member(parent_varattnos,
6017 parent_attno - FirstLowInvalidHeapAttributeNumber);
6018 }
6019 }
6020
6021 /* If the parent is itself a child, continue up */
6022 varno = appinfo->parent_relid;
6023 varattnos = parent_varattnos;
6024 appinfo = root->append_rel_array[varno];
6025 }
6026
6027 /* Perform the access check on this parent rel */
6028 rte = planner_rt_fetch(varno, root);
6029 Assert(rte->rtekind == RTE_RELATION);
6030 }
6031
6032 /*
6033 * For all rows to be accessible, there must be no securityQuals from
6034 * security barrier views or RLS policies.
6035 */
6036 if (rte->securityQuals != NIL)
6037 return false;
6038
6039 /*
6040 * Test for table-level SELECT privilege.
6041 *
6042 * If varattnos is non-NULL, this is sufficient to give access to all
6043 * requested attributes, even for a child table, since we have verified
6044 * that all required child columns have matching parent columns.
6045 *
6046 * If varattnos is NULL (whole-table access requested), this doesn't
6047 * necessarily guarantee that the user can read all columns of a child
6048 * table, but we allow it anyway (see comments in examine_variable()) and
6049 * don't bother checking any column privileges.
6050 */
6051 if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
6052 return true;
6053
6054 if (varattnos == NULL)
6055 return false; /* whole-table access requested */
6056
6057 /*
6058 * Don't have table-level SELECT privilege, so check per-column
6059 * privileges.
6060 */
6061 varattno = -1;
6062 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6063 {
6065
6066 if (attno == InvalidAttrNumber)
6067 {
6068 /* Whole-row reference, so must have access to all columns */
6069 if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
6071 return false;
6072 }
6073 else
6074 {
6075 if (pg_attribute_aclcheck(rte->relid, attno, userid,
6077 return false;
6078 }
6079 }
6080
6081 /* If we reach here, have all required column privileges */
6082 return true;
6083}
@ 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:1306
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define OidIsValid(objectId)
Definition: c.h:775
Assert(PointerIsAligned(start, uint64))
Oid GetUserId(void)
Definition: miscinit.c:469
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_RELATION
Definition: parsenodes.h:1042
#define ACL_SELECT
Definition: parsenodes.h:77
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:591
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:438
Index parent_relid
Definition: pathnodes.h:3104
int num_child_cols
Definition: pathnodes.h:3140
RTEKind rtekind
Definition: parsenodes.h:1077
Oid userid
Definition: pathnodes.h:998
#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 1555 of file selfuncs.c.

1557{
1558 VariableStatData vardata;
1559 double selec;
1560
1561 examine_variable(root, arg, varRelid, &vardata);
1562
1563 if (HeapTupleIsValid(vardata.statsTuple))
1564 {
1565 Form_pg_statistic stats;
1566 double freq_null;
1567 AttStatsSlot sslot;
1568
1569 stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1570 freq_null = stats->stanullfrac;
1571
1572 if (get_attstatsslot(&sslot, vardata.statsTuple,
1573 STATISTIC_KIND_MCV, InvalidOid,
1575 && sslot.nnumbers > 0)
1576 {
1577 double freq_true;
1578 double freq_false;
1579
1580 /*
1581 * Get first MCV frequency and derive frequency for true.
1582 */
1583 if (DatumGetBool(sslot.values[0]))
1584 freq_true = sslot.numbers[0];
1585 else
1586 freq_true = 1.0 - sslot.numbers[0] - freq_null;
1587
1588 /*
1589 * Next derive frequency for false. Then use these as appropriate
1590 * to derive frequency for each case.
1591 */
1592 freq_false = 1.0 - freq_true - freq_null;
1593
1594 switch (booltesttype)
1595 {
1596 case IS_UNKNOWN:
1597 /* select only NULL values */
1598 selec = freq_null;
1599 break;
1600 case IS_NOT_UNKNOWN:
1601 /* select non-NULL values */
1602 selec = 1.0 - freq_null;
1603 break;
1604 case IS_TRUE:
1605 /* select only TRUE values */
1606 selec = freq_true;
1607 break;
1608 case IS_NOT_TRUE:
1609 /* select non-TRUE values */
1610 selec = 1.0 - freq_true;
1611 break;
1612 case IS_FALSE:
1613 /* select only FALSE values */
1614 selec = freq_false;
1615 break;
1616 case IS_NOT_FALSE:
1617 /* select non-FALSE values */
1618 selec = 1.0 - freq_false;
1619 break;
1620 default:
1621 elog(ERROR, "unrecognized booltesttype: %d",
1622 (int) booltesttype);
1623 selec = 0.0; /* Keep compiler quiet */
1624 break;
1625 }
1626
1627 free_attstatsslot(&sslot);
1628 }
1629 else
1630 {
1631 /*
1632 * No most-common-value info available. Still have null fraction
1633 * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1634 * for null fraction and assume a 50-50 split of TRUE and FALSE.
1635 */
1636 switch (booltesttype)
1637 {
1638 case IS_UNKNOWN:
1639 /* select only NULL values */
1640 selec = freq_null;
1641 break;
1642 case IS_NOT_UNKNOWN:
1643 /* select non-NULL values */
1644 selec = 1.0 - freq_null;
1645 break;
1646 case IS_TRUE:
1647 case IS_FALSE:
1648 /* Assume we select half of the non-NULL values */
1649 selec = (1.0 - freq_null) / 2.0;
1650 break;
1651 case IS_NOT_TRUE:
1652 case IS_NOT_FALSE:
1653 /* Assume we select NULLs plus half of the non-NULLs */
1654 /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1655 selec = (freq_null + 1.0) / 2.0;
1656 break;
1657 default:
1658 elog(ERROR, "unrecognized booltesttype: %d",
1659 (int) booltesttype);
1660 selec = 0.0; /* Keep compiler quiet */
1661 break;
1662 }
1663 }
1664 }
1665 else
1666 {
1667 /*
1668 * If we can't get variable statistics for the argument, perhaps
1669 * clause_selectivity can do something with it. We ignore the
1670 * possibility of a NULL value when using clause_selectivity, and just
1671 * assume the value is either TRUE or FALSE.
1672 */
1673 switch (booltesttype)
1674 {
1675 case IS_UNKNOWN:
1676 selec = DEFAULT_UNK_SEL;
1677 break;
1678 case IS_NOT_UNKNOWN:
1679 selec = DEFAULT_NOT_UNK_SEL;
1680 break;
1681 case IS_TRUE:
1682 case IS_NOT_FALSE:
1683 selec = (double) clause_selectivity(root, arg,
1684 varRelid,
1685 jointype, sjinfo);
1686 break;
1687 case IS_FALSE:
1688 case IS_NOT_TRUE:
1689 selec = 1.0 - (double) clause_selectivity(root, arg,
1690 varRelid,
1691 jointype, sjinfo);
1692 break;
1693 default:
1694 elog(ERROR, "unrecognized booltesttype: %d",
1695 (int) booltesttype);
1696 selec = 0.0; /* Keep compiler quiet */
1697 break;
1698 }
1699 }
1700
1701 ReleaseVariableStats(vardata);
1702
1703 /* result should be in range, but make sure... */
1704 CLAMP_PROBABILITY(selec);
1705
1706 return (Selectivity) selec;
1707}
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:1987
@ IS_NOT_FALSE
Definition: primnodes.h:1987
@ IS_NOT_UNKNOWN
Definition: primnodes.h:1987
@ IS_TRUE
Definition: primnodes.h:1987
@ IS_UNKNOWN
Definition: primnodes.h:1987
@ IS_FALSE
Definition: primnodes.h:1987
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:5309
#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 1516 of file selfuncs.c.

1517{
1518 VariableStatData vardata;
1519 double selec;
1520
1521 examine_variable(root, arg, varRelid, &vardata);
1522 if (HeapTupleIsValid(vardata.statsTuple))
1523 {
1524 /*
1525 * A boolean variable V is equivalent to the clause V = 't', so we
1526 * compute the selectivity as if that is what we have.
1527 */
1528 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1529 BoolGetDatum(true), false, true, false);
1530 }
1531 else if (is_funcclause(arg))
1532 {
1533 /*
1534 * If we have no stats and it's a function call, estimate 0.3333333.
1535 * This seems a pretty unprincipled choice, but Postgres has been
1536 * using that estimate for function calls since 1992. The hoariness
1537 * of this behavior suggests that we should not be in too much hurry
1538 * to use another value.
1539 */
1540 selec = 0.3333333;
1541 }
1542 else
1543 {
1544 /* Otherwise, the default estimate is 0.5 */
1545 selec = 0.5;
1546 }
1547 ReleaseVariableStats(vardata);
1548 return selec;
1549}
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:299

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

2155{
2156 /* look through any binary-compatible relabeling of arrayexpr */
2157 arrayexpr = strip_array_coercion(arrayexpr);
2158
2159 if (arrayexpr && IsA(arrayexpr, Const))
2160 {
2161 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2162 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2163 ArrayType *arrayval;
2164
2165 if (arrayisnull)
2166 return 0;
2167 arrayval = DatumGetArrayTypeP(arraydatum);
2168 return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2169 }
2170 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2171 !((ArrayExpr *) arrayexpr)->multidims)
2172 {
2173 return list_length(((ArrayExpr *) arrayexpr)->elements);
2174 }
2175 else if (arrayexpr && root)
2176 {
2177 /* See if we can find any statistics about it */
2178 VariableStatData vardata;
2179 AttStatsSlot sslot;
2180 double nelem = 0;
2181
2182 examine_variable(root, arrayexpr, 0, &vardata);
2183 if (HeapTupleIsValid(vardata.statsTuple))
2184 {
2185 /*
2186 * Found stats, so use the average element count, which is stored
2187 * in the last stanumbers element of the DECHIST statistics.
2188 * Actually that is the average count of *distinct* elements;
2189 * perhaps we should scale it up somewhat?
2190 */
2191 if (get_attstatsslot(&sslot, vardata.statsTuple,
2192 STATISTIC_KIND_DECHIST, InvalidOid,
2194 {
2195 if (sslot.nnumbers > 0)
2196 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2197 free_attstatsslot(&sslot);
2198 }
2199 }
2200 ReleaseVariableStats(vardata);
2201
2202 if (nelem > 0)
2203 return nelem;
2204 }
2205
2206 /* Else use a default guess --- this should match scalararraysel */
2207 return 10;
2208}
#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:1798

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

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

4196{
4197 Size hashentrysize;
4198
4199 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4200 path->pathtarget->width,
4201 agg_costs->transitionSpace);
4202
4203 /*
4204 * Note that this disregards the effect of fill-factor and growth policy
4205 * of the hash table. That's probably ok, given that the default
4206 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4207 * "double-in-size" growth policies here.
4208 */
4209 return hashentrysize * dNumGroups;
4210}
size_t Size
Definition: c.h:611
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1700
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 3808 of file selfuncs.c.

3811{
3812 List *clauses;
3813 List *otherclauses;
3814 double ndistinct;
3815
3816 if (list_length(hashclauses) <= 1)
3817 {
3818 /*
3819 * Nothing to do for a single clause. Could we employ univariate
3820 * extended stat here?
3821 */
3822 return hashclauses;
3823 }
3824
3825 /* "clauses" is the list of hashclauses we've not dealt with yet */
3826 clauses = list_copy(hashclauses);
3827 /* "otherclauses" holds clauses we are going to return to caller */
3828 otherclauses = NIL;
3829 /* current estimate of ndistinct */
3830 ndistinct = 1.0;
3831 while (clauses != NIL)
3832 {
3833 ListCell *lc;
3834 int relid = -1;
3835 List *varinfos = NIL;
3836 List *origin_rinfos = NIL;
3837 double mvndistinct;
3838 List *origin_varinfos;
3839 int group_relid = -1;
3840 RelOptInfo *group_rel = NULL;
3841 ListCell *lc1,
3842 *lc2;
3843
3844 /*
3845 * Find clauses, referencing the same single base relation and try to
3846 * estimate such a group with extended statistics. Create varinfo for
3847 * an approved clause, push it to otherclauses, if it can't be
3848 * estimated here or ignore to process at the next iteration.
3849 */
3850 foreach(lc, clauses)
3851 {
3853 Node *expr;
3854 Relids relids;
3855 GroupVarInfo *varinfo;
3856
3857 /*
3858 * Find the inner side of the join, which we need to estimate the
3859 * number of buckets. Use outer_is_left because the
3860 * clause_sides_match_join routine has called on hash clauses.
3861 */
3862 relids = rinfo->outer_is_left ?
3863 rinfo->right_relids : rinfo->left_relids;
3864 expr = rinfo->outer_is_left ?
3865 get_rightop(rinfo->clause) : get_leftop(rinfo->clause);
3866
3867 if (bms_get_singleton_member(relids, &relid) &&
3868 root->simple_rel_array[relid]->statlist != NIL)
3869 {
3870 bool is_duplicate = false;
3871
3872 /*
3873 * This inner-side expression references only one relation.
3874 * Extended statistics on this clause can exist.
3875 */
3876 if (group_relid < 0)
3877 {
3878 RangeTblEntry *rte = root->simple_rte_array[relid];
3879
3880 if (!rte || (rte->relkind != RELKIND_RELATION &&
3881 rte->relkind != RELKIND_MATVIEW &&
3882 rte->relkind != RELKIND_FOREIGN_TABLE &&
3883 rte->relkind != RELKIND_PARTITIONED_TABLE))
3884 {
3885 /* Extended statistics can't exist in principle */
3886 otherclauses = lappend(otherclauses, rinfo);
3887 clauses = foreach_delete_current(clauses, lc);
3888 continue;
3889 }
3890
3891 group_relid = relid;
3892 group_rel = root->simple_rel_array[relid];
3893 }
3894 else if (group_relid != relid)
3895 {
3896 /*
3897 * Being in the group forming state we don't need other
3898 * clauses.
3899 */
3900 continue;
3901 }
3902
3903 /*
3904 * We're going to add the new clause to the varinfos list. We
3905 * might re-use add_unique_group_var(), but we don't do so for
3906 * two reasons.
3907 *
3908 * 1) We must keep the origin_rinfos list ordered exactly the
3909 * same way as varinfos.
3910 *
3911 * 2) add_unique_group_var() is designed for
3912 * estimate_num_groups(), where a larger number of groups is
3913 * worse. While estimating the number of hash buckets, we
3914 * have the opposite: a lesser number of groups is worse.
3915 * Therefore, we don't have to remove "known equal" vars: the
3916 * removed var may valuably contribute to the multivariate
3917 * statistics to grow the number of groups.
3918 */
3919
3920 /*
3921 * Clear nullingrels to correctly match hash keys. See
3922 * add_unique_group_var()'s comment for details.
3923 */
3924 expr = remove_nulling_relids(expr, root->outer_join_rels, NULL);
3925
3926 /*
3927 * Detect and exclude exact duplicates from the list of hash
3928 * keys (like add_unique_group_var does).
3929 */
3930 foreach(lc1, varinfos)
3931 {
3932 varinfo = (GroupVarInfo *) lfirst(lc1);
3933
3934 if (!equal(expr, varinfo->var))
3935 continue;
3936
3937 is_duplicate = true;
3938 break;
3939 }
3940
3941 if (is_duplicate)
3942 {
3943 /*
3944 * Skip exact duplicates. Adding them to the otherclauses
3945 * list also doesn't make sense.
3946 */
3947 continue;
3948 }
3949
3950 /*
3951 * Initialize GroupVarInfo. We only use it to call
3952 * estimate_multivariate_ndistinct(), which doesn't care about
3953 * ndistinct and isdefault fields. Thus, skip these fields.
3954 */
3955 varinfo = (GroupVarInfo *) palloc0(sizeof(GroupVarInfo));
3956 varinfo->var = expr;
3957 varinfo->rel = root->simple_rel_array[relid];
3958 varinfos = lappend(varinfos, varinfo);
3959
3960 /*
3961 * Remember the link to RestrictInfo for the case the clause
3962 * is failed to be estimated.
3963 */
3964 origin_rinfos = lappend(origin_rinfos, rinfo);
3965 }
3966 else
3967 {
3968 /* This clause can't be estimated with extended statistics */
3969 otherclauses = lappend(otherclauses, rinfo);
3970 }
3971
3972 clauses = foreach_delete_current(clauses, lc);
3973 }
3974
3975 if (list_length(varinfos) < 2)
3976 {
3977 /*
3978 * Multivariate statistics doesn't apply to single columns except
3979 * for expressions, but it has not been implemented yet.
3980 */
3981 otherclauses = list_concat(otherclauses, origin_rinfos);
3982 list_free_deep(varinfos);
3983 list_free(origin_rinfos);
3984 continue;
3985 }
3986
3987 Assert(group_rel != NULL);
3988
3989 /* Employ the extended statistics. */
3990 origin_varinfos = varinfos;
3991 for (;;)
3992 {
3993 bool estimated = estimate_multivariate_ndistinct(root,
3994 group_rel,
3995 &varinfos,
3996 &mvndistinct);
3997
3998 if (!estimated)
3999 break;
4000
4001 /*
4002 * We've got an estimation. Use ndistinct value in a consistent
4003 * way - according to the caller's logic (see
4004 * final_cost_hashjoin).
4005 */
4006 if (ndistinct < mvndistinct)
4007 ndistinct = mvndistinct;
4008 Assert(ndistinct >= 1.0);
4009 }
4010
4011 Assert(list_length(origin_varinfos) == list_length(origin_rinfos));
4012
4013 /* Collect unmatched clauses as otherclauses. */
4014 forboth(lc1, origin_varinfos, lc2, origin_rinfos)
4015 {
4016 GroupVarInfo *vinfo = lfirst(lc1);
4017
4018 if (!list_member_ptr(varinfos, vinfo))
4019 /* Already estimated */
4020 continue;
4021
4022 /* Can't be estimated here - push to the returning list */
4023 otherclauses = lappend(otherclauses, lfirst(lc2));
4024 }
4025 }
4026
4027 *innerbucketsize = 1.0 / ndistinct;
4028 return otherclauses;
4029}
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:715
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
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:4235
RelOptInfo * rel
Definition: selfuncs.c:3320
Node * var
Definition: selfuncs.c:3319
Expr * clause
Definition: pathnodes.h:2704

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

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

◆ examine_variable()

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

Definition at line 5309 of file selfuncs.c.

5311{
5312 Node *basenode;
5313 Relids varnos;
5314 Relids basevarnos;
5315 RelOptInfo *onerel;
5316
5317 /* Make sure we don't return dangling pointers in vardata */
5318 MemSet(vardata, 0, sizeof(VariableStatData));
5319
5320 /* Save the exposed type of the expression */
5321 vardata->vartype = exprType(node);
5322
5323 /* Look inside any binary-compatible relabeling */
5324
5325 if (IsA(node, RelabelType))
5326 basenode = (Node *) ((RelabelType *) node)->arg;
5327 else
5328 basenode = node;
5329
5330 /* Fast path for a simple Var */
5331
5332 if (IsA(basenode, Var) &&
5333 (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5334 {
5335 Var *var = (Var *) basenode;
5336
5337 /* Set up result fields other than the stats tuple */
5338 vardata->var = basenode; /* return Var without relabeling */
5339 vardata->rel = find_base_rel(root, var->varno);
5340 vardata->atttype = var->vartype;
5341 vardata->atttypmod = var->vartypmod;
5342 vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5343
5344 /* Try to locate some stats */
5345 examine_simple_variable(root, var, vardata);
5346
5347 return;
5348 }
5349
5350 /*
5351 * Okay, it's a more complicated expression. Determine variable
5352 * membership. Note that when varRelid isn't zero, only vars of that
5353 * relation are considered "real" vars.
5354 */
5355 varnos = pull_varnos(root, basenode);
5356 basevarnos = bms_difference(varnos, root->outer_join_rels);
5357
5358 onerel = NULL;
5359
5360 if (bms_is_empty(basevarnos))
5361 {
5362 /* No Vars at all ... must be pseudo-constant clause */
5363 }
5364 else
5365 {
5366 int relid;
5367
5368 /* Check if the expression is in vars of a single base relation */
5369 if (bms_get_singleton_member(basevarnos, &relid))
5370 {
5371 if (varRelid == 0 || varRelid == relid)
5372 {
5373 onerel = find_base_rel(root, relid);
5374 vardata->rel = onerel;
5375 node = basenode; /* strip any relabeling */
5376 }
5377 /* else treat it as a constant */
5378 }
5379 else
5380 {
5381 /* varnos has multiple relids */
5382 if (varRelid == 0)
5383 {
5384 /* treat it as a variable of a join relation */
5385 vardata->rel = find_join_rel(root, varnos);
5386 node = basenode; /* strip any relabeling */
5387 }
5388 else if (bms_is_member(varRelid, varnos))
5389 {
5390 /* ignore the vars belonging to other relations */
5391 vardata->rel = find_base_rel(root, varRelid);
5392 node = basenode; /* strip any relabeling */
5393 /* note: no point in expressional-index search here */
5394 }
5395 /* else treat it as a constant */
5396 }
5397 }
5398
5399 bms_free(basevarnos);
5400
5401 vardata->var = node;
5402 vardata->atttype = exprType(node);
5403 vardata->atttypmod = exprTypmod(node);
5404
5405 if (onerel)
5406 {
5407 /*
5408 * We have an expression in vars of a single relation. Try to match
5409 * it to expressional index columns, in hopes of finding some
5410 * statistics.
5411 *
5412 * Note that we consider all index columns including INCLUDE columns,
5413 * since there could be stats for such columns. But the test for
5414 * uniqueness needs to be warier.
5415 *
5416 * XXX it's conceivable that there are multiple matches with different
5417 * index opfamilies; if so, we need to pick one that matches the
5418 * operator we are estimating for. FIXME later.
5419 */
5420 ListCell *ilist;
5421 ListCell *slist;
5422
5423 /*
5424 * The nullingrels bits within the expression could prevent us from
5425 * matching it to expressional index columns or to the expressions in
5426 * extended statistics. So strip them out first.
5427 */
5428 if (bms_overlap(varnos, root->outer_join_rels))
5429 node = remove_nulling_relids(node, root->outer_join_rels, NULL);
5430
5431 foreach(ilist, onerel->indexlist)
5432 {
5433 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5434 ListCell *indexpr_item;
5435 int pos;
5436
5437 indexpr_item = list_head(index->indexprs);
5438 if (indexpr_item == NULL)
5439 continue; /* no expressions here... */
5440
5441 for (pos = 0; pos < index->ncolumns; pos++)
5442 {
5443 if (index->indexkeys[pos] == 0)
5444 {
5445 Node *indexkey;
5446
5447 if (indexpr_item == NULL)
5448 elog(ERROR, "too few entries in indexprs list");
5449 indexkey = (Node *) lfirst(indexpr_item);
5450 if (indexkey && IsA(indexkey, RelabelType))
5451 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5452 if (equal(node, indexkey))
5453 {
5454 /*
5455 * Found a match ... is it a unique index? Tests here
5456 * should match has_unique_index().
5457 */
5458 if (index->unique &&
5459 index->nkeycolumns == 1 &&
5460 pos == 0 &&
5461 (index->indpred == NIL || index->predOK))
5462 vardata->isunique = true;
5463
5464 /*
5465 * Has it got stats? We only consider stats for
5466 * non-partial indexes, since partial indexes probably
5467 * don't reflect whole-relation statistics; the above
5468 * check for uniqueness is the only info we take from
5469 * a partial index.
5470 *
5471 * An index stats hook, however, must make its own
5472 * decisions about what to do with partial indexes.
5473 */
5475 (*get_index_stats_hook) (root, index->indexoid,
5476 pos + 1, vardata))
5477 {
5478 /*
5479 * The hook took control of acquiring a stats
5480 * tuple. If it did supply a tuple, it'd better
5481 * have supplied a freefunc.
5482 */
5483 if (HeapTupleIsValid(vardata->statsTuple) &&
5484 !vardata->freefunc)
5485 elog(ERROR, "no function provided to release variable stats with");
5486 }
5487 else if (index->indpred == NIL)
5488 {
5489 vardata->statsTuple =
5490 SearchSysCache3(STATRELATTINH,
5491 ObjectIdGetDatum(index->indexoid),
5492 Int16GetDatum(pos + 1),
5493 BoolGetDatum(false));
5494 vardata->freefunc = ReleaseSysCache;
5495
5496 if (HeapTupleIsValid(vardata->statsTuple))
5497 {
5498 /*
5499 * Test if user has permission to access all
5500 * rows from the index's table.
5501 *
5502 * For simplicity, we insist on the whole
5503 * table being selectable, rather than trying
5504 * to identify which column(s) the index
5505 * depends on.
5506 *
5507 * Note that for an inheritance child,
5508 * permissions are checked on the inheritance
5509 * root parent, and whole-table select
5510 * privilege on the parent doesn't quite
5511 * guarantee that the user could read all
5512 * columns of the child. But in practice it's
5513 * unlikely that any interesting security
5514 * violation could result from allowing access
5515 * to the expression index's stats, so we
5516 * allow it anyway. See similar code in
5517 * examine_simple_variable() for additional
5518 * comments.
5519 */
5520 vardata->acl_ok =
5522 index->rel->relid,
5523 NULL);
5524 }
5525 else
5526 {
5527 /* suppress leakproofness checks later */
5528 vardata->acl_ok = true;
5529 }
5530 }
5531 if (vardata->statsTuple)
5532 break;
5533 }
5534 indexpr_item = lnext(index->indexprs, indexpr_item);
5535 }
5536 }
5537 if (vardata->statsTuple)
5538 break;
5539 }
5540
5541 /*
5542 * Search extended statistics for one with a matching expression.
5543 * There might be multiple ones, so just grab the first one. In the
5544 * future, we might consider the statistics target (and pick the most
5545 * accurate statistics) and maybe some other parameters.
5546 */
5547 foreach(slist, onerel->statlist)
5548 {
5549 StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5550 RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5551 ListCell *expr_item;
5552 int pos;
5553
5554 /*
5555 * Stop once we've found statistics for the expression (either
5556 * from extended stats, or for an index in the preceding loop).
5557 */
5558 if (vardata->statsTuple)
5559 break;
5560
5561 /* skip stats without per-expression stats */
5562 if (info->kind != STATS_EXT_EXPRESSIONS)
5563 continue;
5564
5565 /* skip stats with mismatching stxdinherit value */
5566 if (info->inherit != rte->inh)
5567 continue;
5568
5569 pos = 0;
5570 foreach(expr_item, info->exprs)
5571 {
5572 Node *expr = (Node *) lfirst(expr_item);
5573
5574 Assert(expr);
5575
5576 /* strip RelabelType before comparing it */
5577 if (expr && IsA(expr, RelabelType))
5578 expr = (Node *) ((RelabelType *) expr)->arg;
5579
5580 /* found a match, see if we can extract pg_statistic row */
5581 if (equal(node, expr))
5582 {
5583 /*
5584 * XXX Not sure if we should cache the tuple somewhere.
5585 * Now we just create a new copy every time.
5586 */
5587 vardata->statsTuple =
5588 statext_expressions_load(info->statOid, rte->inh, pos);
5589
5590 vardata->freefunc = ReleaseDummy;
5591
5592 /*
5593 * Test if user has permission to access all rows from the
5594 * table.
5595 *
5596 * For simplicity, we insist on the whole table being
5597 * selectable, rather than trying to identify which
5598 * column(s) the statistics object depends on.
5599 *
5600 * Note that for an inheritance child, permissions are
5601 * checked on the inheritance root parent, and whole-table
5602 * select privilege on the parent doesn't quite guarantee
5603 * that the user could read all columns of the child. But
5604 * in practice it's unlikely that any interesting security
5605 * violation could result from allowing access to the
5606 * expression stats, so we allow it anyway. See similar
5607 * code in examine_simple_variable() for additional
5608 * comments.
5609 */
5610 vardata->acl_ok = all_rows_selectable(root,
5611 onerel->relid,
5612 NULL);
5613
5614 break;
5615 }
5616
5617 pos++;
5618 }
5619 }
5620 }
5621
5622 bms_free(varnos);
5623}
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:346
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define MemSet(start, val, len)
Definition: c.h:1020
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:2325
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:416
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:529
bool all_rows_selectable(PlannerInfo *root, Index varno, Bitmapset *varattnos)
Definition: selfuncs.c:5911
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5635
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:148
static void ReleaseDummy(HeapTuple tuple)
Definition: selfuncs.c:5268
Index relid
Definition: pathnodes.h:954
List * statlist
Definition: pathnodes.h:978
List * indexlist
Definition: pathnodes.h:976
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 918 of file selfuncs.c.

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

6999{
7000 IndexOptInfo *index = path->indexinfo;
7001 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7002 List *indexOrderBys = path->indexorderbys;
7003 Cost indexStartupCost;
7004 Cost indexTotalCost;
7005 Selectivity indexSelectivity;
7006 double indexCorrelation;
7007 double numIndexPages;
7008 double numIndexTuples;
7009 double spc_random_page_cost;
7010 double num_sa_scans;
7011 double num_outer_scans;
7012 double num_scans;
7013 double qual_op_cost;
7014 double qual_arg_cost;
7015 List *selectivityQuals;
7016 ListCell *l;
7017
7018 /*
7019 * If the index is partial, AND the index predicate with the explicitly
7020 * given indexquals to produce a more accurate idea of the index
7021 * selectivity.
7022 */
7023 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7024
7025 /*
7026 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
7027 * just assume that the number of index descents is the number of distinct
7028 * combinations of array elements from all of the scan's SAOP clauses.
7029 */
7030 num_sa_scans = costs->num_sa_scans;
7031 if (num_sa_scans < 1)
7032 {
7033 num_sa_scans = 1;
7034 foreach(l, indexQuals)
7035 {
7036 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
7037
7038 if (IsA(rinfo->clause, ScalarArrayOpExpr))
7039 {
7040 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
7041 double alength = estimate_array_length(root, lsecond(saop->args));
7042
7043 if (alength > 1)
7044 num_sa_scans *= alength;
7045 }
7046 }
7047 }
7048
7049 /* Estimate the fraction of main-table tuples that will be visited */
7050 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7051 index->rel->relid,
7052 JOIN_INNER,
7053 NULL);
7054
7055 /*
7056 * If caller didn't give us an estimate, estimate the number of index
7057 * tuples that will be visited. We do it in this rather peculiar-looking
7058 * way in order to get the right answer for partial indexes.
7059 */
7060 numIndexTuples = costs->numIndexTuples;
7061 if (numIndexTuples <= 0.0)
7062 {
7063 numIndexTuples = indexSelectivity * index->rel->tuples;
7064
7065 /*
7066 * The above calculation counts all the tuples visited across all
7067 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
7068 * average per-indexscan number, so adjust. This is a handy place to
7069 * round to integer, too. (If caller supplied tuple estimate, it's
7070 * responsible for handling these considerations.)
7071 */
7072 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7073 }
7074
7075 /*
7076 * We can bound the number of tuples by the index size in any case. Also,
7077 * always estimate at least one tuple is touched, even when
7078 * indexSelectivity estimate is tiny.
7079 */
7080 if (numIndexTuples > index->tuples)
7081 numIndexTuples = index->tuples;
7082 if (numIndexTuples < 1.0)
7083 numIndexTuples = 1.0;
7084
7085 /*
7086 * Estimate the number of index pages that will be retrieved.
7087 *
7088 * We use the simplistic method of taking a pro-rata fraction of the total
7089 * number of index pages. In effect, this counts only leaf pages and not
7090 * any overhead such as index metapage or upper tree levels.
7091 *
7092 * In practice access to upper index levels is often nearly free because
7093 * those tend to stay in cache under load; moreover, the cost involved is
7094 * highly dependent on index type. We therefore ignore such costs here
7095 * and leave it to the caller to add a suitable charge if needed.
7096 */
7097 if (index->pages > 1 && index->tuples > 1)
7098 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
7099 else
7100 numIndexPages = 1.0;
7101
7102 /* fetch estimated page cost for tablespace containing index */
7103 get_tablespace_page_costs(index->reltablespace,
7104 &spc_random_page_cost,
7105 NULL);
7106
7107 /*
7108 * Now compute the disk access costs.
7109 *
7110 * The above calculations are all per-index-scan. However, if we are in a
7111 * nestloop inner scan, we can expect the scan to be repeated (with
7112 * different search keys) for each row of the outer relation. Likewise,
7113 * ScalarArrayOpExpr quals result in multiple index scans. This creates
7114 * the potential for cache effects to reduce the number of disk page
7115 * fetches needed. We want to estimate the average per-scan I/O cost in
7116 * the presence of caching.
7117 *
7118 * We use the Mackert-Lohman formula (see costsize.c for details) to
7119 * estimate the total number of page fetches that occur. While this
7120 * wasn't what it was designed for, it seems a reasonable model anyway.
7121 * Note that we are counting pages not tuples anymore, so we take N = T =
7122 * index size, as if there were one "tuple" per page.
7123 */
7124 num_outer_scans = loop_count;
7125 num_scans = num_sa_scans * num_outer_scans;
7126
7127 if (num_scans > 1)
7128 {
7129 double pages_fetched;
7130
7131 /* total page fetches ignoring cache effects */
7132 pages_fetched = numIndexPages * num_scans;
7133
7134 /* use Mackert and Lohman formula to adjust for cache effects */
7135 pages_fetched = index_pages_fetched(pages_fetched,
7136 index->pages,
7137 (double) index->pages,
7138 root);
7139
7140 /*
7141 * Now compute the total disk access cost, and then report a pro-rated
7142 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7143 * since that's internal to the indexscan.)
7144 */
7145 indexTotalCost = (pages_fetched * spc_random_page_cost)
7146 / num_outer_scans;
7147 }
7148 else
7149 {
7150 /*
7151 * For a single index scan, we just charge spc_random_page_cost per
7152 * page touched.
7153 */
7154 indexTotalCost = numIndexPages * spc_random_page_cost;
7155 }
7156
7157 /*
7158 * CPU cost: any complex expressions in the indexquals will need to be
7159 * evaluated once at the start of the scan to reduce them to runtime keys
7160 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7161 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7162 * indexqual operator. Because we have numIndexTuples as a per-scan
7163 * number, we have to multiply by num_sa_scans to get the correct result
7164 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7165 * ORDER BY expressions.
7166 *
7167 * Note: this neglects the possible costs of rechecking lossy operators.
7168 * Detecting that that might be needed seems more expensive than it's
7169 * worth, though, considering all the other inaccuracies here ...
7170 */
7171 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
7172 index_other_operands_eval_cost(root, indexOrderBys);
7173 qual_op_cost = cpu_operator_cost *
7174 (list_length(indexQuals) + list_length(indexOrderBys));
7175
7176 indexStartupCost = qual_arg_cost;
7177 indexTotalCost += qual_arg_cost;
7178 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7179
7180 /*
7181 * Generic assumption about index correlation: there isn't any.
7182 */
7183 indexCorrelation = 0.0;
7184
7185 /*
7186 * Return everything to caller.
7187 */
7188 costs->indexStartupCost = indexStartupCost;
7189 costs->indexTotalCost = indexTotalCost;
7190 costs->indexSelectivity = indexSelectivity;
7191 costs->indexCorrelation = indexCorrelation;
7192 costs->numIndexPages = numIndexPages;
7193 costs->numIndexTuples = numIndexTuples;
7194 costs->spc_random_page_cost = spc_random_page_cost;
7195 costs->num_sa_scans = num_sa_scans;
7196}
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
double cpu_operator_cost
Definition: costsize.c:134
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:908
double cpu_index_tuple_cost
Definition: costsize.c:133
double Cost
Definition: nodes.h: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:6911
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:7218
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2154
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6941
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:1870
List * indexorderbys
Definition: pathnodes.h:1871
IndexOptInfo * indexinfo
Definition: pathnodes.h:1869

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

5243{
5244 Node *left,
5245 *right;
5246
5247 if (list_length(args) != 2)
5248 elog(ERROR, "join operator should take two arguments");
5249
5250 left = (Node *) linitial(args);
5251 right = (Node *) lsecond(args);
5252
5253 examine_variable(root, left, 0, vardata1);
5254 examine_variable(root, right, 0, vardata2);
5255
5256 if (vardata1->rel &&
5257 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5258 *join_is_reversed = true; /* var1 is on RHS */
5259 else if (vardata2->rel &&
5260 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5261 *join_is_reversed = true; /* var2 is on LHS */
5262 else
5263 *join_is_reversed = false;
5264}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Relids relids
Definition: pathnodes.h:908
Relids syn_lefthand
Definition: pathnodes.h:3031
Relids syn_righthand
Definition: pathnodes.h:3032

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

6912{
6913 List *result = NIL;
6914 ListCell *lc;
6915
6916 foreach(lc, indexclauses)
6917 {
6918 IndexClause *iclause = lfirst_node(IndexClause, lc);
6919 ListCell *lc2;
6920
6921 foreach(lc2, iclause->indexquals)
6922 {
6923 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6924
6925 result = lappend(result, rinfo);
6926 }
6927 }
6928 return result;
6929}
List * indexquals
Definition: pathnodes.h:1918

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

5183{
5184 Node *left,
5185 *right;
5186 VariableStatData rdata;
5187
5188 /* Fail if not a binary opclause (probably shouldn't happen) */
5189 if (list_length(args) != 2)
5190 return false;
5191
5192 left = (Node *) linitial(args);
5193 right = (Node *) lsecond(args);
5194
5195 /*
5196 * Examine both sides. Note that when varRelid is nonzero, Vars of other
5197 * relations will be treated as pseudoconstants.
5198 */
5199 examine_variable(root, left, varRelid, vardata);
5200 examine_variable(root, right, varRelid, &rdata);
5201
5202 /*
5203 * If one side is a variable and the other not, we win.
5204 */
5205 if (vardata->rel && rdata.rel == NULL)
5206 {
5207 *varonleft = true;
5208 *other = estimate_expression_value(root, rdata.var);
5209 /* Assume we need no ReleaseVariableStats(rdata) here */
5210 return true;
5211 }
5212
5213 if (vardata->rel == NULL && rdata.rel)
5214 {
5215 *varonleft = false;
5216 *other = estimate_expression_value(root, vardata->var);
5217 /* Assume we need no ReleaseVariableStats(*vardata) here */
5218 *vardata = rdata;
5219 return true;
5220 }
5221
5222 /* Oops, clause has wrong structure (probably var op var) */
5223 ReleaseVariableStats(*vardata);
5224 ReleaseVariableStats(rdata);
5225
5226 return false;
5227}
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2403

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

6210{
6211 double stadistinct;
6212 double stanullfrac = 0.0;
6213 double ntuples;
6214
6215 *isdefault = false;
6216
6217 /*
6218 * Determine the stadistinct value to use. There are cases where we can
6219 * get an estimate even without a pg_statistic entry, or can get a better
6220 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6221 * (otherwise, assume no nulls, for lack of any better idea).
6222 */
6223 if (HeapTupleIsValid(vardata->statsTuple))
6224 {
6225 /* Use the pg_statistic entry */
6226 Form_pg_statistic stats;
6227
6228 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6229 stadistinct = stats->stadistinct;
6230 stanullfrac = stats->stanullfrac;
6231 }
6232 else if (vardata->vartype == BOOLOID)
6233 {
6234 /*
6235 * Special-case boolean columns: presumably, two distinct values.
6236 *
6237 * Are there any other datatypes we should wire in special estimates
6238 * for?
6239 */
6240 stadistinct = 2.0;
6241 }
6242 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6243 {
6244 /*
6245 * If the Var represents a column of a VALUES RTE, assume it's unique.
6246 * This could of course be very wrong, but it should tend to be true
6247 * in well-written queries. We could consider examining the VALUES'
6248 * contents to get some real statistics; but that only works if the
6249 * entries are all constants, and it would be pretty expensive anyway.
6250 */
6251 stadistinct = -1.0; /* unique (and all non null) */
6252 }
6253 else
6254 {
6255 /*
6256 * We don't keep statistics for system columns, but in some cases we
6257 * can infer distinctness anyway.
6258 */
6259 if (vardata->var && IsA(vardata->var, Var))
6260 {
6261 switch (((Var *) vardata->var)->varattno)
6262 {
6264 stadistinct = -1.0; /* unique (and all non null) */
6265 break;
6267 stadistinct = 1.0; /* only 1 value */
6268 break;
6269 default:
6270 stadistinct = 0.0; /* means "unknown" */
6271 break;
6272 }
6273 }
6274 else
6275 stadistinct = 0.0; /* means "unknown" */
6276
6277 /*
6278 * XXX consider using estimate_num_groups on expressions?
6279 */
6280 }
6281
6282 /*
6283 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6284 * variable, assume it is unique no matter what pg_statistic says; the
6285 * statistics could be out of date, or we might have found a partial
6286 * unique index that proves the var is unique for this query. However,
6287 * we'd better still believe the null-fraction statistic.
6288 */
6289 if (vardata->isunique)
6290 stadistinct = -1.0 * (1.0 - stanullfrac);
6291
6292 /*
6293 * If we had an absolute estimate, use that.
6294 */
6295 if (stadistinct > 0.0)
6296 return clamp_row_est(stadistinct);
6297
6298 /*
6299 * Otherwise we need to get the relation size; punt if not available.
6300 */
6301 if (vardata->rel == NULL)
6302 {
6303 *isdefault = true;
6304 return DEFAULT_NUM_DISTINCT;
6305 }
6306 ntuples = vardata->rel->tuples;
6307 if (ntuples <= 0.0)
6308 {
6309 *isdefault = true;
6310 return DEFAULT_NUM_DISTINCT;
6311 }
6312
6313 /*
6314 * If we had a relative estimate, use that.
6315 */
6316 if (stadistinct < 0.0)
6317 return clamp_row_est(-stadistinct * ntuples);
6318
6319 /*
6320 * With no data, estimate ndistinct = ntuples if the table is small, else
6321 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6322 * that the behavior isn't discontinuous.
6323 */
6324 if (ntuples < DEFAULT_NUM_DISTINCT)
6325 return clamp_row_est(ntuples);
6326
6327 *isdefault = true;
6328 return DEFAULT_NUM_DISTINCT;
6329}
@ RTE_VALUES
Definition: parsenodes.h:1047
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
RTEKind rtekind
Definition: pathnodes.h:958
#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 827 of file selfuncs.c.

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

6942{
6943 Cost qual_arg_cost = 0;
6944 ListCell *lc;
6945
6946 foreach(lc, indexquals)
6947 {
6948 Expr *clause = (Expr *) lfirst(lc);
6949 Node *other_operand;
6950 QualCost index_qual_cost;
6951
6952 /*
6953 * Index quals will have RestrictInfos, indexorderbys won't. Look
6954 * through RestrictInfo if present.
6955 */
6956 if (IsA(clause, RestrictInfo))
6957 clause = ((RestrictInfo *) clause)->clause;
6958
6959 if (IsA(clause, OpExpr))
6960 {
6961 OpExpr *op = (OpExpr *) clause;
6962
6963 other_operand = (Node *) lsecond(op->args);
6964 }
6965 else if (IsA(clause, RowCompareExpr))
6966 {
6967 RowCompareExpr *rc = (RowCompareExpr *) clause;
6968
6969 other_operand = (Node *) rc->rargs;
6970 }
6971 else if (IsA(clause, ScalarArrayOpExpr))
6972 {
6973 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6974
6975 other_operand = (Node *) lsecond(saop->args);
6976 }
6977 else if (IsA(clause, NullTest))
6978 {
6979 other_operand = NULL;
6980 }
6981 else
6982 {
6983 elog(ERROR, "unsupported indexqual type: %d",
6984 (int) nodeTag(clause));
6985 other_operand = NULL; /* keep compiler quiet */
6986 }
6987
6988 cost_qual_eval_node(&index_qual_cost, other_operand, root);
6989 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
6990 }
6991 return qual_arg_cost;
6992}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4817
#define nodeTag(nodeptr)
Definition: nodes.h:139
List * args
Definition: primnodes.h:855
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 1045 of file selfuncs.c.

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

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

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

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

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

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

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

2223{
2225 Oid opno = linitial_oid(clause->opnos);
2226 Oid inputcollid = linitial_oid(clause->inputcollids);
2227 List *opargs;
2228 bool is_join_clause;
2229
2230 /* Build equivalent arg list for single operator */
2231 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2232
2233 /*
2234 * Decide if it's a join clause. This should match clausesel.c's
2235 * treat_as_join_clause(), except that we intentionally consider only the
2236 * leading columns and not the rest of the clause.
2237 */
2238 if (varRelid != 0)
2239 {
2240 /*
2241 * Caller is forcing restriction mode (eg, because we are examining an
2242 * inner indexscan qual).
2243 */
2244 is_join_clause = false;
2245 }
2246 else if (sjinfo == NULL)
2247 {
2248 /*
2249 * It must be a restriction clause, since it's being evaluated at a
2250 * scan node.
2251 */
2252 is_join_clause = false;
2253 }
2254 else
2255 {
2256 /*
2257 * Otherwise, it's a join if there's more than one base relation used.
2258 */
2259 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2260 }
2261
2262 if (is_join_clause)
2263 {
2264 /* Estimate selectivity for a join clause. */
2265 s1 = join_selectivity(root, opno,
2266 opargs,
2267 inputcollid,
2268 jointype,
2269 sjinfo);
2270 }
2271 else
2272 {
2273 /* Estimate selectivity for a restriction clause. */
2275 opargs,
2276 inputcollid,
2277 varRelid);
2278 }
2279
2280 return s1;
2281}
int NumRelids(PlannerInfo *root, Node *clause)
Definition: clauses.c:2137
#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:2073
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:2112
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 1831 of file selfuncs.c.

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

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

Referenced by scalararraysel().

◆ statistic_proc_security_check()

bool statistic_proc_security_check ( VariableStatData vardata,
Oid  func_oid 
)

Definition at line 6180 of file selfuncs.c.

6181{
6182 if (vardata->acl_ok)
6183 return true; /* have SELECT privs and no securityQuals */
6184
6185 if (!OidIsValid(func_oid))
6186 return false;
6187
6188 if (get_func_leakproof(func_oid))
6189 return true;
6190
6192 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6193 get_func_name(func_oid))));
6194 return false;
6195}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1161
#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 299 of file selfuncs.c.

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

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

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

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