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

7619{
7620 List *predExtraQuals = NIL;
7621 ListCell *lc;
7622
7623 if (index->indpred == NIL)
7624 return indexQuals;
7625
7626 foreach(lc, index->indpred)
7627 {
7628 Node *predQual = (Node *) lfirst(lc);
7629 List *oneQual = list_make1(predQual);
7630
7631 if (!predicate_implied_by(oneQual, indexQuals, false))
7632 predExtraQuals = list_concat(predExtraQuals, oneQual);
7633 }
7634 return list_concat(predExtraQuals, indexQuals);
7635}
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 6304 of file selfuncs.c.

6305{
6306 RelOptInfo *rel = find_base_rel_noerr(root, varno);
6307 RangeTblEntry *rte = planner_rt_fetch(varno, root);
6308 Oid userid;
6309 int varattno;
6310
6311 Assert(rte->rtekind == RTE_RELATION);
6312
6313 /*
6314 * Determine the user ID to use for privilege checks (either the current
6315 * user or the view owner, if we're accessing the table via a view).
6316 *
6317 * Normally the relation will have an associated RelOptInfo from which we
6318 * can find the userid, but it might not if it's a RETURNING Var for an
6319 * INSERT target relation. In that case use the RTEPermissionInfo
6320 * associated with the RTE.
6321 *
6322 * If we navigate up to a parent relation, we keep using the same userid,
6323 * since it's the same in all relations of a given inheritance tree.
6324 */
6325 if (rel)
6326 userid = rel->userid;
6327 else
6328 {
6329 RTEPermissionInfo *perminfo;
6330
6331 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
6332 userid = perminfo->checkAsUser;
6333 }
6334 if (!OidIsValid(userid))
6335 userid = GetUserId();
6336
6337 /*
6338 * Permissions and securityQuals must be checked on the table actually
6339 * mentioned in the query, so if this is an inheritance child, navigate up
6340 * to the inheritance root parent. If the user can read the whole table
6341 * or the required columns there, then they can read from the child table
6342 * too. For per-column checks, we must find out which of the root
6343 * parent's attributes the child relation's attributes correspond to.
6344 */
6345 if (root->append_rel_array != NULL)
6346 {
6347 AppendRelInfo *appinfo;
6348
6349 appinfo = root->append_rel_array[varno];
6350
6351 /*
6352 * Partitions are mapped to their immediate parent, not the root
6353 * parent, so must be ready to walk up multiple AppendRelInfos. But
6354 * stop if we hit a parent that is not RTE_RELATION --- that's a
6355 * flattened UNION ALL subquery, not an inheritance parent.
6356 */
6357 while (appinfo &&
6359 root)->rtekind == RTE_RELATION)
6360 {
6361 Bitmapset *parent_varattnos = NULL;
6362
6363 /*
6364 * For each child attribute, find the corresponding parent
6365 * attribute. In rare cases, the attribute may be local to the
6366 * child table, in which case, we've got to live with having no
6367 * access to this column.
6368 */
6369 varattno = -1;
6370 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6371 {
6372 AttrNumber attno;
6373 AttrNumber parent_attno;
6374
6375 attno = varattno + FirstLowInvalidHeapAttributeNumber;
6376
6377 if (attno == InvalidAttrNumber)
6378 {
6379 /*
6380 * Whole-row reference, so must map each column of the
6381 * child to the parent table.
6382 */
6383 for (attno = 1; attno <= appinfo->num_child_cols; attno++)
6384 {
6385 parent_attno = appinfo->parent_colnos[attno - 1];
6386 if (parent_attno == 0)
6387 return false; /* attr is local to child */
6388 parent_varattnos =
6389 bms_add_member(parent_varattnos,
6390 parent_attno - FirstLowInvalidHeapAttributeNumber);
6391 }
6392 }
6393 else
6394 {
6395 if (attno < 0)
6396 {
6397 /* System attnos are the same in all tables */
6398 parent_attno = attno;
6399 }
6400 else
6401 {
6402 if (attno > appinfo->num_child_cols)
6403 return false; /* safety check */
6404 parent_attno = appinfo->parent_colnos[attno - 1];
6405 if (parent_attno == 0)
6406 return false; /* attr is local to child */
6407 }
6408 parent_varattnos =
6409 bms_add_member(parent_varattnos,
6410 parent_attno - FirstLowInvalidHeapAttributeNumber);
6411 }
6412 }
6413
6414 /* If the parent is itself a child, continue up */
6415 varno = appinfo->parent_relid;
6416 varattnos = parent_varattnos;
6417 appinfo = root->append_rel_array[varno];
6418 }
6419
6420 /* Perform the access check on this parent rel */
6421 rte = planner_rt_fetch(varno, root);
6422 Assert(rte->rtekind == RTE_RELATION);
6423 }
6424
6425 /*
6426 * For all rows to be accessible, there must be no securityQuals from
6427 * security barrier views or RLS policies.
6428 */
6429 if (rte->securityQuals != NIL)
6430 return false;
6431
6432 /*
6433 * Test for table-level SELECT privilege.
6434 *
6435 * If varattnos is non-NULL, this is sufficient to give access to all
6436 * requested attributes, even for a child table, since we have verified
6437 * that all required child columns have matching parent columns.
6438 *
6439 * If varattnos is NULL (whole-table access requested), this doesn't
6440 * necessarily guarantee that the user can read all columns of a child
6441 * table, but we allow it anyway (see comments in examine_variable()) and
6442 * don't bother checking any column privileges.
6443 */
6444 if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
6445 return true;
6446
6447 if (varattnos == NULL)
6448 return false; /* whole-table access requested */
6449
6450 /*
6451 * Don't have table-level SELECT privilege, so check per-column
6452 * privileges.
6453 */
6454 varattno = -1;
6455 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6456 {
6458
6459 if (attno == InvalidAttrNumber)
6460 {
6461 /* Whole-row reference, so must have access to all columns */
6462 if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
6464 return false;
6465 }
6466 else
6467 {
6468 if (pg_attribute_aclcheck(rte->relid, attno, userid,
6470 return false;
6471 }
6472 }
6473
6474 /* If we reach here, have all required column privileges */
6475 return true;
6476}
@ 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:3910
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3868
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4039
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1305
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
#define OidIsValid(objectId)
Definition: c.h:794
Assert(PointerIsAligned(start, uint64))
Oid GetUserId(void)
Definition: miscinit.c:469
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_RELATION
Definition: parsenodes.h:1070
#define ACL_SELECT
Definition: parsenodes.h:77
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:610
unsigned int Oid
Definition: postgres_ext.h:32
tree ctl root
Definition: radixtree.h:1857
RelOptInfo * find_base_rel_noerr(PlannerInfo *root, int relid)
Definition: relnode.c:551
Index parent_relid
Definition: pathnodes.h:3192
int num_child_cols
Definition: pathnodes.h:3228
RTEKind rtekind
Definition: parsenodes.h:1105
#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 1624 of file selfuncs.c.

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

1586{
1587 VariableStatData vardata;
1588 double selec;
1589
1590 examine_variable(root, arg, varRelid, &vardata);
1591 if (HeapTupleIsValid(vardata.statsTuple))
1592 {
1593 /*
1594 * A boolean variable V is equivalent to the clause V = 't', so we
1595 * compute the selectivity as if that is what we have.
1596 */
1597 selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1598 BoolGetDatum(true), false, true, false);
1599 }
1600 else if (is_funcclause(arg))
1601 {
1602 /*
1603 * If we have no stats and it's a function call, estimate 0.3333333.
1604 * This seems a pretty unprincipled choice, but Postgres has been
1605 * using that estimate for function calls since 1992. The hoariness
1606 * of this behavior suggests that we should not be in too much hurry
1607 * to use another value.
1608 */
1609 selec = 0.3333333;
1610 }
1611 else
1612 {
1613 /* Otherwise, the default estimate is 0.5 */
1614 selec = 0.5;
1615 }
1616 ReleaseVariableStats(vardata);
1617 return selec;
1618}
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:368

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

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

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

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

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

Referenced by final_cost_hashjoin().

◆ estimate_hashagg_tablesize()

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

Definition at line 4521 of file selfuncs.c.

4523{
4524 Size hashentrysize;
4525
4526 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4527 path->pathtarget->width,
4528 agg_costs->transitionSpace);
4529
4530 /*
4531 * Note that this disregards the effect of fill-factor and growth policy
4532 * of the hash table. That's probably ok, given that the default
4533 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4534 * "double-in-size" growth policies here.
4535 */
4536 return hashentrysize * dNumGroups;
4537}
size_t Size
Definition: c.h:625
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1698
Size transitionSpace
Definition: pathnodes.h:62

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

Referenced by consider_groupingsets_paths().

◆ estimate_multivariate_bucketsize()

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

Definition at line 4123 of file selfuncs.c.

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

References Assert(), bms_get_singleton_member(), RestrictInfo::clause, equal(), estimate_multivariate_ndistinct(), forboth, foreach_delete_current, get_leftop(), get_rightop(), lappend(), lfirst, lfirst_node, list_concat(), list_copy(), list_free(), list_free_deep(), list_length(), list_member_ptr(), NIL, palloc0_object, 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 3771 of file selfuncs.c.

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

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

Referenced by adjust_rowcount_for_semijoins(), build_setop_child_paths(), cost_incremental_sort(), cost_memoize_rescan(), create_final_distinct_paths(), create_final_unique_paths(), create_partial_distinct_paths(), create_partial_unique_paths(), create_rel_agg_info(), estimate_path_cost_size(), generate_grouped_paths(), generate_union_paths(), get_number_of_groups(), and get_windowclause_startup_tuples().

◆ examine_variable()

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

Definition at line 5636 of file selfuncs.c.

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

References VariableStatData::acl_ok, all_rows_selectable(), arg, Assert(), VariableStatData::atttype, VariableStatData::atttypmod, bms_difference(), bms_free(), bms_get_singleton_member(), bms_is_empty, bms_is_member(), bms_overlap(), BoolGetDatum(), elog, equal(), ERROR, examine_simple_variable(), StatisticExtInfo::exprs, exprType(), exprTypmod(), find_base_rel(), find_join_rel(), VariableStatData::freefunc, get_index_stats_hook, has_unique_index(), HeapTupleIsValid, if(), RelOptInfo::indexlist, RangeTblEntry::inh, StatisticExtInfo::inherit, Int16GetDatum(), IsA, VariableStatData::isunique, StatisticExtInfo::kind, lfirst, list_head(), lnext(), MemSet, NIL, ObjectIdGetDatum(), planner_rt_fetch, pull_varnos(), VariableStatData::rel, ReleaseDummy(), ReleaseSysCache(), RelOptInfo::relid, remove_nulling_relids(), root, SearchSysCache3(), statext_expressions_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, VariableStatData::statsTuple, strip_all_phvs_deep(), 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 987 of file selfuncs.c.

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

7399{
7400 IndexOptInfo *index = path->indexinfo;
7401 List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7402 List *indexOrderBys = path->indexorderbys;
7403 Cost indexStartupCost;
7404 Cost indexTotalCost;
7405 Selectivity indexSelectivity;
7406 double indexCorrelation;
7407 double numIndexPages;
7408 double numIndexTuples;
7409 double spc_random_page_cost;
7410 double num_sa_scans;
7411 double num_outer_scans;
7412 double num_scans;
7413 double qual_op_cost;
7414 double qual_arg_cost;
7415 List *selectivityQuals;
7416 ListCell *l;
7417
7418 /*
7419 * If the index is partial, AND the index predicate with the explicitly
7420 * given indexquals to produce a more accurate idea of the index
7421 * selectivity.
7422 */
7423 selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
7424
7425 /*
7426 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
7427 * just assume that the number of index descents is the number of distinct
7428 * combinations of array elements from all of the scan's SAOP clauses.
7429 */
7430 num_sa_scans = costs->num_sa_scans;
7431 if (num_sa_scans < 1)
7432 {
7433 num_sa_scans = 1;
7434 foreach(l, indexQuals)
7435 {
7436 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
7437
7438 if (IsA(rinfo->clause, ScalarArrayOpExpr))
7439 {
7440 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
7441 double alength = estimate_array_length(root, lsecond(saop->args));
7442
7443 if (alength > 1)
7444 num_sa_scans *= alength;
7445 }
7446 }
7447 }
7448
7449 /* Estimate the fraction of main-table tuples that will be visited */
7450 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7451 index->rel->relid,
7452 JOIN_INNER,
7453 NULL);
7454
7455 /*
7456 * If caller didn't give us an estimate, estimate the number of index
7457 * tuples that will be visited. We do it in this rather peculiar-looking
7458 * way in order to get the right answer for partial indexes.
7459 */
7460 numIndexTuples = costs->numIndexTuples;
7461 if (numIndexTuples <= 0.0)
7462 {
7463 numIndexTuples = indexSelectivity * index->rel->tuples;
7464
7465 /*
7466 * The above calculation counts all the tuples visited across all
7467 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
7468 * average per-indexscan number, so adjust. This is a handy place to
7469 * round to integer, too. (If caller supplied tuple estimate, it's
7470 * responsible for handling these considerations.)
7471 */
7472 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7473 }
7474
7475 /*
7476 * We can bound the number of tuples by the index size in any case. Also,
7477 * always estimate at least one tuple is touched, even when
7478 * indexSelectivity estimate is tiny.
7479 */
7480 if (numIndexTuples > index->tuples)
7481 numIndexTuples = index->tuples;
7482 if (numIndexTuples < 1.0)
7483 numIndexTuples = 1.0;
7484
7485 /*
7486 * Estimate the number of index pages that will be retrieved.
7487 *
7488 * We use the simplistic method of taking a pro-rata fraction of the total
7489 * number of index pages. In effect, this counts only leaf pages and not
7490 * any overhead such as index metapage or upper tree levels.
7491 *
7492 * In practice access to upper index levels is often nearly free because
7493 * those tend to stay in cache under load; moreover, the cost involved is
7494 * highly dependent on index type. We therefore ignore such costs here
7495 * and leave it to the caller to add a suitable charge if needed.
7496 */
7497 if (index->pages > 1 && index->tuples > 1)
7498 numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
7499 else
7500 numIndexPages = 1.0;
7501
7502 /* fetch estimated page cost for tablespace containing index */
7503 get_tablespace_page_costs(index->reltablespace,
7504 &spc_random_page_cost,
7505 NULL);
7506
7507 /*
7508 * Now compute the disk access costs.
7509 *
7510 * The above calculations are all per-index-scan. However, if we are in a
7511 * nestloop inner scan, we can expect the scan to be repeated (with
7512 * different search keys) for each row of the outer relation. Likewise,
7513 * ScalarArrayOpExpr quals result in multiple index scans. This creates
7514 * the potential for cache effects to reduce the number of disk page
7515 * fetches needed. We want to estimate the average per-scan I/O cost in
7516 * the presence of caching.
7517 *
7518 * We use the Mackert-Lohman formula (see costsize.c for details) to
7519 * estimate the total number of page fetches that occur. While this
7520 * wasn't what it was designed for, it seems a reasonable model anyway.
7521 * Note that we are counting pages not tuples anymore, so we take N = T =
7522 * index size, as if there were one "tuple" per page.
7523 */
7524 num_outer_scans = loop_count;
7525 num_scans = num_sa_scans * num_outer_scans;
7526
7527 if (num_scans > 1)
7528 {
7529 double pages_fetched;
7530
7531 /* total page fetches ignoring cache effects */
7532 pages_fetched = numIndexPages * num_scans;
7533
7534 /* use Mackert and Lohman formula to adjust for cache effects */
7535 pages_fetched = index_pages_fetched(pages_fetched,
7536 index->pages,
7537 (double) index->pages,
7538 root);
7539
7540 /*
7541 * Now compute the total disk access cost, and then report a pro-rated
7542 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7543 * since that's internal to the indexscan.)
7544 */
7545 indexTotalCost = (pages_fetched * spc_random_page_cost)
7546 / num_outer_scans;
7547 }
7548 else
7549 {
7550 /*
7551 * For a single index scan, we just charge spc_random_page_cost per
7552 * page touched.
7553 */
7554 indexTotalCost = numIndexPages * spc_random_page_cost;
7555 }
7556
7557 /*
7558 * CPU cost: any complex expressions in the indexquals will need to be
7559 * evaluated once at the start of the scan to reduce them to runtime keys
7560 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7561 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7562 * indexqual operator. Because we have numIndexTuples as a per-scan
7563 * number, we have to multiply by num_sa_scans to get the correct result
7564 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7565 * ORDER BY expressions.
7566 *
7567 * Note: this neglects the possible costs of rechecking lossy operators.
7568 * Detecting that that might be needed seems more expensive than it's
7569 * worth, though, considering all the other inaccuracies here ...
7570 */
7571 qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
7572 index_other_operands_eval_cost(root, indexOrderBys);
7573 qual_op_cost = cpu_operator_cost *
7574 (list_length(indexQuals) + list_length(indexOrderBys));
7575
7576 indexStartupCost = qual_arg_cost;
7577 indexTotalCost += qual_arg_cost;
7578 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7579
7580 /*
7581 * Generic assumption about index correlation: there isn't any.
7582 */
7583 indexCorrelation = 0.0;
7584
7585 /*
7586 * Return everything to caller.
7587 */
7588 costs->indexStartupCost = indexStartupCost;
7589 costs->indexTotalCost = indexTotalCost;
7590 costs->indexSelectivity = indexSelectivity;
7591 costs->indexCorrelation = indexCorrelation;
7592 costs->numIndexPages = numIndexPages;
7593 costs->numIndexTuples = numIndexTuples;
7594 costs->spc_random_page_cost = spc_random_page_cost;
7595 costs->num_sa_scans = num_sa_scans;
7596}
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
double cpu_operator_cost
Definition: costsize.c:134
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:882
double cpu_index_tuple_cost
Definition: costsize.c:133
double Cost
Definition: nodes.h:261
@ JOIN_INNER
Definition: nodes.h:303
#define lsecond(l)
Definition: pg_list.h:183
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:7311
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:7618
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2223
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:7341
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Selectivity indexSelectivity
Definition: selfuncs.h:129
Cost indexStartupCost
Definition: selfuncs.h:127
double indexCorrelation
Definition: selfuncs.h:130
double spc_random_page_cost
Definition: selfuncs.h:135
double num_sa_scans
Definition: selfuncs.h:136
Cost indexTotalCost
Definition: selfuncs.h:128
double numIndexPages
Definition: selfuncs.h:133
double numIndexTuples
Definition: selfuncs.h:134
List * indexclauses
Definition: pathnodes.h:1959
List * indexorderbys
Definition: pathnodes.h:1960
IndexOptInfo * indexinfo
Definition: pathnodes.h:1958

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

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

◆ get_join_variables()

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

Definition at line 5567 of file selfuncs.c.

5570{
5571 Node *left,
5572 *right;
5573
5574 if (list_length(args) != 2)
5575 elog(ERROR, "join operator should take two arguments");
5576
5577 left = (Node *) linitial(args);
5578 right = (Node *) lsecond(args);
5579
5580 examine_variable(root, left, 0, vardata1);
5581 examine_variable(root, right, 0, vardata2);
5582
5583 if (vardata1->rel &&
5584 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5585 *join_is_reversed = true; /* var1 is on RHS */
5586 else if (vardata2->rel &&
5587 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5588 *join_is_reversed = true; /* var2 is on LHS */
5589 else
5590 *join_is_reversed = false;
5591}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Relids relids
Definition: pathnodes.h:927
Relids syn_lefthand
Definition: pathnodes.h:3119
Relids syn_righthand
Definition: pathnodes.h:3120

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

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

◆ get_quals_from_indexclauses()

List * get_quals_from_indexclauses ( List indexclauses)

Definition at line 7311 of file selfuncs.c.

7312{
7313 List *result = NIL;
7314 ListCell *lc;
7315
7316 foreach(lc, indexclauses)
7317 {
7318 IndexClause *iclause = lfirst_node(IndexClause, lc);
7319 ListCell *lc2;
7320
7321 foreach(lc2, iclause->indexquals)
7322 {
7323 RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
7324
7325 result = lappend(result, rinfo);
7326 }
7327 }
7328 return result;
7329}
List * indexquals
Definition: pathnodes.h:2007

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

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

◆ get_restriction_variable()

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

Definition at line 5507 of file selfuncs.c.

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

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

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

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool *  isdefault 
)

Definition at line 6602 of file selfuncs.c.

6603{
6604 double stadistinct;
6605 double stanullfrac = 0.0;
6606 double ntuples;
6607
6608 *isdefault = false;
6609
6610 /*
6611 * Determine the stadistinct value to use. There are cases where we can
6612 * get an estimate even without a pg_statistic entry, or can get a better
6613 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6614 * (otherwise, assume no nulls, for lack of any better idea).
6615 */
6616 if (HeapTupleIsValid(vardata->statsTuple))
6617 {
6618 /* Use the pg_statistic entry */
6619 Form_pg_statistic stats;
6620
6621 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6622 stadistinct = stats->stadistinct;
6623 stanullfrac = stats->stanullfrac;
6624 }
6625 else if (vardata->vartype == BOOLOID)
6626 {
6627 /*
6628 * Special-case boolean columns: presumably, two distinct values.
6629 *
6630 * Are there any other datatypes we should wire in special estimates
6631 * for?
6632 */
6633 stadistinct = 2.0;
6634 }
6635 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6636 {
6637 /*
6638 * If the Var represents a column of a VALUES RTE, assume it's unique.
6639 * This could of course be very wrong, but it should tend to be true
6640 * in well-written queries. We could consider examining the VALUES'
6641 * contents to get some real statistics; but that only works if the
6642 * entries are all constants, and it would be pretty expensive anyway.
6643 */
6644 stadistinct = -1.0; /* unique (and all non null) */
6645 }
6646 else
6647 {
6648 /*
6649 * We don't keep statistics for system columns, but in some cases we
6650 * can infer distinctness anyway.
6651 */
6652 if (vardata->var && IsA(vardata->var, Var))
6653 {
6654 switch (((Var *) vardata->var)->varattno)
6655 {
6657 stadistinct = -1.0; /* unique (and all non null) */
6658 break;
6660 stadistinct = 1.0; /* only 1 value */
6661 break;
6662 default:
6663 stadistinct = 0.0; /* means "unknown" */
6664 break;
6665 }
6666 }
6667 else
6668 stadistinct = 0.0; /* means "unknown" */
6669
6670 /*
6671 * XXX consider using estimate_num_groups on expressions?
6672 */
6673 }
6674
6675 /*
6676 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6677 * variable, assume it is unique no matter what pg_statistic says; the
6678 * statistics could be out of date, or we might have found a partial
6679 * unique index that proves the var is unique for this query. However,
6680 * we'd better still believe the null-fraction statistic.
6681 */
6682 if (vardata->isunique)
6683 stadistinct = -1.0 * (1.0 - stanullfrac);
6684
6685 /*
6686 * If we had an absolute estimate, use that.
6687 */
6688 if (stadistinct > 0.0)
6689 return clamp_row_est(stadistinct);
6690
6691 /*
6692 * Otherwise we need to get the relation size; punt if not available.
6693 */
6694 if (vardata->rel == NULL)
6695 {
6696 *isdefault = true;
6697 return DEFAULT_NUM_DISTINCT;
6698 }
6699 ntuples = vardata->rel->tuples;
6700 if (ntuples <= 0.0)
6701 {
6702 *isdefault = true;
6703 return DEFAULT_NUM_DISTINCT;
6704 }
6705
6706 /*
6707 * If we had a relative estimate, use that.
6708 */
6709 if (stadistinct < 0.0)
6710 return clamp_row_est(-stadistinct * ntuples);
6711
6712 /*
6713 * With no data, estimate ndistinct = ntuples if the table is small, else
6714 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6715 * that the behavior isn't discontinuous.
6716 */
6717 if (ntuples < DEFAULT_NUM_DISTINCT)
6718 return clamp_row_est(ntuples);
6719
6720 *isdefault = true;
6721 return DEFAULT_NUM_DISTINCT;
6722}
@ RTE_VALUES
Definition: parsenodes.h:1075
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
RTEKind rtekind
Definition: pathnodes.h:977
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21

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

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

◆ histogram_selectivity()

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

Definition at line 896 of file selfuncs.c.

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

7342{
7343 Cost qual_arg_cost = 0;
7344 ListCell *lc;
7345
7346 foreach(lc, indexquals)
7347 {
7348 Expr *clause = (Expr *) lfirst(lc);
7349 Node *other_operand;
7350 QualCost index_qual_cost;
7351
7352 /*
7353 * Index quals will have RestrictInfos, indexorderbys won't. Look
7354 * through RestrictInfo if present.
7355 */
7356 if (IsA(clause, RestrictInfo))
7357 clause = ((RestrictInfo *) clause)->clause;
7358
7359 if (IsA(clause, OpExpr))
7360 {
7361 OpExpr *op = (OpExpr *) clause;
7362
7363 other_operand = (Node *) lsecond(op->args);
7364 }
7365 else if (IsA(clause, RowCompareExpr))
7366 {
7367 RowCompareExpr *rc = (RowCompareExpr *) clause;
7368
7369 other_operand = (Node *) rc->rargs;
7370 }
7371 else if (IsA(clause, ScalarArrayOpExpr))
7372 {
7373 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
7374
7375 other_operand = (Node *) lsecond(saop->args);
7376 }
7377 else if (IsA(clause, NullTest))
7378 {
7379 other_operand = NULL;
7380 }
7381 else
7382 {
7383 elog(ERROR, "unsupported indexqual type: %d",
7384 (int) nodeTag(clause));
7385 other_operand = NULL; /* keep compiler quiet */
7386 }
7387
7388 cost_qual_eval_node(&index_qual_cost, other_operand, root);
7389 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
7390 }
7391 return qual_arg_cost;
7392}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4808
#define nodeTag(nodeptr)
Definition: nodes.h:139
List * args
Definition: primnodes.h:868
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

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

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

◆ ineq_histogram_selectivity()

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

Definition at line 1114 of file selfuncs.c.

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

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

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

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

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

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

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

Referenced by clause_selectivity_ext(), and clauselist_selectivity_ext().

◆ rowcomparesel()

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

Definition at line 2289 of file selfuncs.c.

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

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

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

Referenced by clause_selectivity_ext().

◆ scalararraysel_containment()

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

Definition at line 81 of file array_selfuncs.c.

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

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

Referenced by scalararraysel().

◆ statistic_proc_security_check()

bool statistic_proc_security_check ( VariableStatData vardata,
Oid  func_oid 
)

Definition at line 6573 of file selfuncs.c.

6574{
6575 if (vardata->acl_ok)
6576 return true; /* have SELECT privs and no securityQuals */
6577
6578 if (!OidIsValid(func_oid))
6579 return false;
6580
6581 if (get_func_leakproof(func_oid))
6582 return true;
6583
6585 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6586 get_func_name(func_oid))));
6587 return false;
6588}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:150
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1987
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1758

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

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

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

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

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

Referenced by eqsel_internal().

Variable Documentation

◆ get_index_stats_hook

PGDLLIMPORT get_index_stats_hook_type get_index_stats_hook
extern

Definition at line 184 of file selfuncs.c.

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

◆ get_relation_stats_hook

PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook
extern