PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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)
static int fb(int x)

Definition at line 63 of file selfuncs.h.

64 { \
65 if (p < 0.0) \
66 p = 0.0; \
67 else if (p > 1.0) \
68 p = 1.0; \
69 } while (0)

◆ 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.

104 { \
105 if (HeapTupleIsValid((vardata).statsTuple)) \

◆ 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 152 of file selfuncs.h.

◆ get_relation_stats_hook_type

Definition at line 147 of file selfuncs.h.

◆ VariableStatData

Function Documentation

◆ add_predicate_to_index_quals()

List * add_predicate_to_index_quals ( IndexOptInfo index,
List indexQuals 
)
extern

Definition at line 7737 of file selfuncs.c.

7738{
7740 ListCell *lc;
7741
7742 if (index->indpred == NIL)
7743 return indexQuals;
7744
7745 foreach(lc, index->indpred)
7746 {
7747 Node *predQual = (Node *) lfirst(lc);
7749
7752 }
7754}
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:244
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition predtest.c:154
Definition pg_list.h:54
Definition nodes.h:133
Definition type.h:97

References fb(), 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 
)
extern

Definition at line 6415 of file selfuncs.c.

6416{
6417 RelOptInfo *rel = find_base_rel_noerr(root, varno);
6419 Oid userid;
6420 int varattno;
6421
6422 Assert(rte->rtekind == RTE_RELATION);
6423
6424 /*
6425 * Determine the user ID to use for privilege checks (either the current
6426 * user or the view owner, if we're accessing the table via a view).
6427 *
6428 * Normally the relation will have an associated RelOptInfo from which we
6429 * can find the userid, but it might not if it's a RETURNING Var for an
6430 * INSERT target relation. In that case use the RTEPermissionInfo
6431 * associated with the RTE.
6432 *
6433 * If we navigate up to a parent relation, we keep using the same userid,
6434 * since it's the same in all relations of a given inheritance tree.
6435 */
6436 if (rel)
6437 userid = rel->userid;
6438 else
6439 {
6441
6442 perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
6443 userid = perminfo->checkAsUser;
6444 }
6445 if (!OidIsValid(userid))
6446 userid = GetUserId();
6447
6448 /*
6449 * Permissions and securityQuals must be checked on the table actually
6450 * mentioned in the query, so if this is an inheritance child, navigate up
6451 * to the inheritance root parent. If the user can read the whole table
6452 * or the required columns there, then they can read from the child table
6453 * too. For per-column checks, we must find out which of the root
6454 * parent's attributes the child relation's attributes correspond to.
6455 */
6456 if (root->append_rel_array != NULL)
6457 {
6459
6460 appinfo = root->append_rel_array[varno];
6461
6462 /*
6463 * Partitions are mapped to their immediate parent, not the root
6464 * parent, so must be ready to walk up multiple AppendRelInfos. But
6465 * stop if we hit a parent that is not RTE_RELATION --- that's a
6466 * flattened UNION ALL subquery, not an inheritance parent.
6467 */
6468 while (appinfo &&
6469 planner_rt_fetch(appinfo->parent_relid,
6470 root)->rtekind == RTE_RELATION)
6471 {
6473
6474 /*
6475 * For each child attribute, find the corresponding parent
6476 * attribute. In rare cases, the attribute may be local to the
6477 * child table, in which case, we've got to live with having no
6478 * access to this column.
6479 */
6480 varattno = -1;
6481 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6482 {
6483 AttrNumber attno;
6485
6486 attno = varattno + FirstLowInvalidHeapAttributeNumber;
6487
6488 if (attno == InvalidAttrNumber)
6489 {
6490 /*
6491 * Whole-row reference, so must map each column of the
6492 * child to the parent table.
6493 */
6494 for (attno = 1; attno <= appinfo->num_child_cols; attno++)
6495 {
6496 parent_attno = appinfo->parent_colnos[attno - 1];
6497 if (parent_attno == 0)
6498 return false; /* attr is local to child */
6502 }
6503 }
6504 else
6505 {
6506 if (attno < 0)
6507 {
6508 /* System attnos are the same in all tables */
6509 parent_attno = attno;
6510 }
6511 else
6512 {
6513 if (attno > appinfo->num_child_cols)
6514 return false; /* safety check */
6515 parent_attno = appinfo->parent_colnos[attno - 1];
6516 if (parent_attno == 0)
6517 return false; /* attr is local to child */
6518 }
6522 }
6523 }
6524
6525 /* If the parent is itself a child, continue up */
6526 varno = appinfo->parent_relid;
6527 varattnos = parent_varattnos;
6528 appinfo = root->append_rel_array[varno];
6529 }
6530
6531 /* Perform the access check on this parent rel */
6532 rte = planner_rt_fetch(varno, root);
6533 Assert(rte->rtekind == RTE_RELATION);
6534 }
6535
6536 /*
6537 * For all rows to be accessible, there must be no securityQuals from
6538 * security barrier views or RLS policies.
6539 */
6540 if (rte->securityQuals != NIL)
6541 return false;
6542
6543 /*
6544 * Test for table-level SELECT privilege.
6545 *
6546 * If varattnos is non-NULL, this is sufficient to give access to all
6547 * requested attributes, even for a child table, since we have verified
6548 * that all required child columns have matching parent columns.
6549 *
6550 * If varattnos is NULL (whole-table access requested), this doesn't
6551 * necessarily guarantee that the user can read all columns of a child
6552 * table, but we allow it anyway (see comments in examine_variable()) and
6553 * don't bother checking any column privileges.
6554 */
6555 if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) == ACLCHECK_OK)
6556 return true;
6557
6558 if (varattnos == NULL)
6559 return false; /* whole-table access requested */
6560
6561 /*
6562 * Don't have table-level SELECT privilege, so check per-column
6563 * privileges.
6564 */
6565 varattno = -1;
6566 while ((varattno = bms_next_member(varattnos, varattno)) >= 0)
6567 {
6569
6570 if (attno == InvalidAttrNumber)
6571 {
6572 /* Whole-row reference, so must have access to all columns */
6573 if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
6575 return false;
6576 }
6577 else
6578 {
6579 if (pg_attribute_aclcheck(rte->relid, attno, userid,
6581 return false;
6582 }
6583 }
6584
6585 /* If we reach here, have all required column privileges */
6586 return true;
6587}
@ ACLCHECK_OK
Definition acl.h:184
@ ACLMASK_ALL
Definition acl.h:177
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition aclchk.c:3976
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition aclchk.c:3934
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4105
int16 AttrNumber
Definition attnum.h:21
#define InvalidAttrNumber
Definition attnum.h:23
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1425
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:934
#define Assert(condition)
Definition c.h:1002
#define OidIsValid(objectId)
Definition c.h:917
Oid GetUserId(void)
Definition miscinit.c:470
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_RELATION
#define ACL_SELECT
Definition parsenodes.h:77
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:704
unsigned int Oid
tree ctl root
Definition radixtree.h:1857
RelOptInfo * find_base_rel_noerr(PlannerInfo *root, int relid)
Definition relnode.c:566
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References ACL_SELECT, ACLCHECK_OK, ACLMASK_ALL, Assert, bms_add_member(), bms_next_member(), fb(), find_base_rel_noerr(), FirstLowInvalidHeapAttributeNumber, getRTEPermissionInfo(), GetUserId(), InvalidAttrNumber, NIL, OidIsValid, pg_attribute_aclcheck(), pg_attribute_aclcheck_all(), pg_class_aclcheck(), planner_rt_fetch, root, RTE_RELATION, 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 
)
extern

Definition at line 1626 of file selfuncs.c.

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

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

Referenced by clause_selectivity_ext().

◆ boolvarsel()

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

Definition at line 1587 of file selfuncs.c.

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

References arg, BoolGetDatum(), examine_variable(), fb(), HeapTupleIsValid, InvalidOid, is_funcclause(), ReleaseVariableStats, root, and var_eq_const().

Referenced by clause_selectivity_ext().

◆ estimate_array_length()

double estimate_array_length ( PlannerInfo root,
Node arrayexpr 
)
extern

Definition at line 2242 of file selfuncs.c.

2243{
2244 /* look through any binary-compatible relabeling of arrayexpr */
2245 arrayexpr = strip_array_coercion(arrayexpr);
2246
2247 if (arrayexpr && IsA(arrayexpr, Const))
2248 {
2249 Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2250 bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2252
2253 if (arrayisnull)
2254 return 0;
2257 }
2258 else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2259 !((ArrayExpr *) arrayexpr)->multidims)
2260 {
2261 return list_length(((ArrayExpr *) arrayexpr)->elements);
2262 }
2263 else if (arrayexpr && root)
2264 {
2265 /* See if we can find any statistics about it */
2268 double nelem = 0;
2269
2270 /*
2271 * Skip calling examine_variable for Var with varno 0, which has no
2272 * valid relation entry and would error in find_base_rel. Such a Var
2273 * can appear when a nested set operation's output type doesn't match
2274 * the parent's expected type, because recurse_set_operations builds a
2275 * projection target list using generate_setop_tlist with varno 0, and
2276 * if the required type coercion involves an ArrayCoerceExpr, we can
2277 * be called on that Var.
2278 */
2279 if (IsA(arrayexpr, Var) && ((Var *) arrayexpr)->varno == 0)
2280 return 10; /* default guess, should match scalararraysel */
2281
2282 examine_variable(root, arrayexpr, 0, &vardata);
2283 if (HeapTupleIsValid(vardata.statsTuple))
2284 {
2285 /*
2286 * Found stats, so use the average element count, which is stored
2287 * in the last stanumbers element of the DECHIST statistics.
2288 * Actually that is the average count of *distinct* elements;
2289 * perhaps we should scale it up somewhat?
2290 */
2291 if (get_attstatsslot(&sslot, vardata.statsTuple,
2294 {
2295 if (sslot.nnumbers > 0)
2296 nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2298 }
2299 }
2301
2302 if (nelem > 0)
2303 return nelem;
2304 }
2305
2306 /* Else use a default guess --- this should match scalararraysel */
2307 return 10;
2308}
#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:215
#define IsA(nodeptr, _type_)
Definition nodes.h:162
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:1869

References ARR_DIMS, ARR_NDIM, ArrayGetNItems(), ATTSTATSSLOT_NUMBERS, clamp_row_est(), DatumGetArrayTypeP, examine_variable(), fb(), free_attstatsslot(), get_attstatsslot(), HeapTupleIsValid, InvalidOid, IsA, list_length(), ReleaseVariableStats, root, 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 
)
extern

Definition at line 4424 of file selfuncs.c.

4427{
4429 double estfract,
4430 ndistinct;
4431 bool isdefault;
4433
4435
4436 /* Initialize *mcv_freq to "unknown" */
4437 *mcv_freq = 0.0;
4438
4439 /* Look up the frequency of the most common value, if available */
4440 if (HeapTupleIsValid(vardata.statsTuple))
4441 {
4442 if (get_attstatsslot(&sslot, vardata.statsTuple,
4445 {
4446 /*
4447 * The first MCV stat is for the most common value.
4448 */
4449 if (sslot.nnumbers > 0)
4450 *mcv_freq = sslot.numbers[0];
4452 }
4453 else if (get_attstatsslot(&sslot, vardata.statsTuple,
4455 0))
4456 {
4457 /*
4458 * If there are no recorded MCVs, but we do have a histogram, then
4459 * assume that ANALYZE determined that the column is unique.
4460 */
4461 if (vardata.rel && vardata.rel->tuples > 0)
4462 *mcv_freq = 1.0 / vardata.rel->tuples;
4463 }
4464 }
4465
4466 /* Get number of distinct values */
4467 ndistinct = get_variable_numdistinct(&vardata, &isdefault);
4468
4469 /*
4470 * If ndistinct isn't real, punt. We normally return 0.1, but if the
4471 * mcv_freq is known to be even higher than that, use it instead.
4472 */
4473 if (isdefault)
4474 {
4477 return;
4478 }
4479
4480 /*
4481 * Adjust ndistinct to account for restriction clauses. Observe we are
4482 * assuming that the data distribution is affected uniformly by the
4483 * restriction clauses!
4484 *
4485 * XXX Possibly better way, but much more expensive: multiply by
4486 * selectivity of rel's restriction clauses that mention the target Var.
4487 */
4488 if (vardata.rel && vardata.rel->tuples > 0)
4489 {
4490 ndistinct *= vardata.rel->rows / vardata.rel->tuples;
4491 ndistinct = clamp_row_est(ndistinct);
4492 }
4493
4494 /*
4495 * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
4496 * number of buckets is less than the expected number of distinct values;
4497 * otherwise it is 1/ndistinct.
4498 */
4499 if (ndistinct > nbuckets)
4500 estfract = 1.0 / nbuckets;
4501 else
4502 estfract = 1.0 / ndistinct;
4503
4504 /*
4505 * Clamp the bucketsize fraction to be not less than the MCV frequency,
4506 * since whichever bucket the MCV values end up in will have at least that
4507 * size. This has no effect if *mcv_freq is still zero.
4508 */
4510
4512
4514}
#define Max(x, y)
Definition c.h:1125
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition selfuncs.c:6713

References ATTSTATSSLOT_NUMBERS, clamp_row_est(), examine_variable(), fb(), free_attstatsslot(), get_attstatsslot(), get_variable_numdistinct(), HeapTupleIsValid, InvalidOid, Max, ReleaseVariableStats, and root.

Referenced by final_cost_hashjoin().

◆ estimate_hashagg_tablesize()

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

Definition at line 4530 of file selfuncs.c.

4532{
4533 Size hashentrysize;
4534
4535 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
4536 path->pathtarget->width,
4537 agg_costs->transitionSpace);
4538
4539 /*
4540 * Note that this disregards the effect of fill-factor and growth policy
4541 * of the hash table. That's probably ok, given that the default
4542 * fill-factor is relatively high. It'd be hard to meaningfully factor in
4543 * "double-in-size" growth policies here.
4544 */
4545 return hashentrysize * dNumGroups;
4546}
size_t Size
Definition c.h:748
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition nodeAgg.c:1700

References fb(), hash_agg_entry_size(), list_length(), and root.

Referenced by consider_groupingsets_paths().

◆ estimate_multivariate_bucketsize()

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

Definition at line 4156 of file selfuncs.c.

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

References Assert, bms_get_singleton_member(), RestrictInfo::clause, equal(), estimate_multivariate_ndistinct(), fb(), 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, remove_nulling_relids(), and root.

Referenced by final_cost_hashjoin().

◆ estimate_num_groups()

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

Definition at line 3804 of file selfuncs.c.

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

◆ examine_variable()

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

Definition at line 5651 of file selfuncs.c.

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

References all_rows_selectable(), arg, Assert, 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(), fb(), find_base_rel(), find_join_rel(), get_index_stats_hook, has_unique_index(), HeapTupleIsValid, StatisticExtInfo::inherit, Int16GetDatum(), IsA, StatisticExtInfo::kind, lfirst, list_head(), lnext(), MemSet, NIL, ObjectIdGetDatum(), planner_rt_fetch, pull_varnos(), ReleaseDummy(), ReleaseSysCache(), remove_nulling_relids(), root, SearchSysCache3(), statext_expressions_load(), StatisticExtInfo::statOid, strip_all_phvs_deep(), Var::varattno, and Var::varno.

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 
)
extern

Definition at line 989 of file selfuncs.c.

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

References CLAMP_PROBABILITY, fb(), fmgr_info(), get_opcode(), get_restriction_variable(), GETSTRUCT(), HeapTupleIsValid, histogram_selectivity(), IsA, mcv_selectivity(), ReleaseVariableStats, and root.

Referenced by ltreeparentsel(), and matchingsel().

◆ genericcostestimate()

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

Definition at line 7512 of file selfuncs.c.

7516{
7517 IndexOptInfo *index = path->indexinfo;
7520 Cost indexStartupCost;
7521 Cost indexTotalCost;
7522 Selectivity indexSelectivity;
7523 double indexCorrelation;
7524 double numIndexPages;
7525 double numIndexTuples;
7526 double spc_random_page_cost;
7527 double num_sa_scans;
7528 double num_outer_scans;
7529 double num_scans;
7530 double qual_op_cost;
7531 double qual_arg_cost;
7533 ListCell *l;
7534
7535 /*
7536 * If the index is partial, AND the index predicate with the explicitly
7537 * given indexquals to produce a more accurate idea of the index
7538 * selectivity.
7539 */
7541
7542 /*
7543 * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
7544 * just assume that the number of index descents is the number of distinct
7545 * combinations of array elements from all of the scan's SAOP clauses.
7546 */
7547 num_sa_scans = costs->num_sa_scans;
7548 if (num_sa_scans < 1)
7549 {
7550 num_sa_scans = 1;
7551 foreach(l, indexQuals)
7552 {
7553 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
7554
7555 if (IsA(rinfo->clause, ScalarArrayOpExpr))
7556 {
7557 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
7558 double alength = estimate_array_length(root, lsecond(saop->args));
7559
7560 if (alength > 1)
7561 num_sa_scans *= alength;
7562 }
7563 }
7564 }
7565
7566 /* Estimate the fraction of main-table tuples that will be visited */
7567 indexSelectivity = clauselist_selectivity(root, selectivityQuals,
7568 index->rel->relid,
7569 JOIN_INNER,
7570 NULL);
7571
7572 /*
7573 * If caller didn't give us an estimate, estimate the number of index
7574 * tuples that will be visited. We do it in this rather peculiar-looking
7575 * way in order to get the right answer for partial indexes.
7576 */
7577 numIndexTuples = costs->numIndexTuples;
7578 if (numIndexTuples <= 0.0)
7579 {
7580 numIndexTuples = indexSelectivity * index->rel->tuples;
7581
7582 /*
7583 * The above calculation counts all the tuples visited across all
7584 * scans induced by ScalarArrayOpExpr nodes. We want to consider the
7585 * average per-indexscan number, so adjust. This is a handy place to
7586 * round to integer, too. (If caller supplied tuple estimate, it's
7587 * responsible for handling these considerations.)
7588 */
7589 numIndexTuples = rint(numIndexTuples / num_sa_scans);
7590 }
7591
7592 /*
7593 * We can bound the number of tuples by the index size in any case. Also,
7594 * always estimate at least one tuple is touched, even when
7595 * indexSelectivity estimate is tiny.
7596 */
7597 if (numIndexTuples > index->tuples)
7598 numIndexTuples = index->tuples;
7599 if (numIndexTuples < 1.0)
7600 numIndexTuples = 1.0;
7601
7602 /*
7603 * Estimate the number of index pages that will be retrieved.
7604 *
7605 * We use the simplistic method of taking a pro-rata fraction of the total
7606 * number of index leaf pages. We disregard any overhead such as index
7607 * metapages or upper tree levels.
7608 *
7609 * In practice access to upper index levels is often nearly free because
7610 * those tend to stay in cache under load; moreover, the cost involved is
7611 * highly dependent on index type. We therefore ignore such costs here
7612 * and leave it to the caller to add a suitable charge if needed.
7613 */
7614 if (index->pages > costs->numNonLeafPages && index->tuples > 1)
7615 numIndexPages =
7616 ceil(numIndexTuples * (index->pages - costs->numNonLeafPages)
7617 / index->tuples);
7618 else
7619 numIndexPages = 1.0;
7620
7621 /* fetch estimated page cost for tablespace containing index */
7622 get_tablespace_page_costs(index->reltablespace,
7623 &spc_random_page_cost,
7624 NULL);
7625
7626 /*
7627 * Now compute the disk access costs.
7628 *
7629 * The above calculations are all per-index-scan. However, if we are in a
7630 * nestloop inner scan, we can expect the scan to be repeated (with
7631 * different search keys) for each row of the outer relation. Likewise,
7632 * ScalarArrayOpExpr quals result in multiple index scans. This creates
7633 * the potential for cache effects to reduce the number of disk page
7634 * fetches needed. We want to estimate the average per-scan I/O cost in
7635 * the presence of caching.
7636 *
7637 * We use the Mackert-Lohman formula (see costsize.c for details) to
7638 * estimate the total number of page fetches that occur. While this
7639 * wasn't what it was designed for, it seems a reasonable model anyway.
7640 * Note that we are counting pages not tuples anymore, so we take N = T =
7641 * index size, as if there were one "tuple" per page.
7642 */
7644 num_scans = num_sa_scans * num_outer_scans;
7645
7646 if (num_scans > 1)
7647 {
7648 double pages_fetched;
7649
7650 /* total page fetches ignoring cache effects */
7651 pages_fetched = numIndexPages * num_scans;
7652
7653 /* use Mackert and Lohman formula to adjust for cache effects */
7655 index->pages,
7656 (double) index->pages,
7657 root);
7658
7659 /*
7660 * Now compute the total disk access cost, and then report a pro-rated
7661 * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
7662 * since that's internal to the indexscan.)
7663 */
7664 indexTotalCost = (pages_fetched * spc_random_page_cost)
7666 }
7667 else
7668 {
7669 /*
7670 * For a single index scan, we just charge spc_random_page_cost per
7671 * page touched.
7672 */
7673 indexTotalCost = numIndexPages * spc_random_page_cost;
7674 }
7675
7676 /*
7677 * CPU cost: any complex expressions in the indexquals will need to be
7678 * evaluated once at the start of the scan to reduce them to runtime keys
7679 * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
7680 * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
7681 * indexqual operator. Because we have numIndexTuples as a per-scan
7682 * number, we have to multiply by num_sa_scans to get the correct result
7683 * for ScalarArrayOpExpr cases. Similarly add in costs for any index
7684 * ORDER BY expressions.
7685 *
7686 * Note: this neglects the possible costs of rechecking lossy operators.
7687 * Detecting that that might be needed seems more expensive than it's
7688 * worth, though, considering all the other inaccuracies here ...
7689 */
7694
7695 indexStartupCost = qual_arg_cost;
7696 indexTotalCost += qual_arg_cost;
7697 indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
7698
7699 /*
7700 * Generic assumption about index correlation: there isn't any.
7701 */
7702 indexCorrelation = 0.0;
7703
7704 /*
7705 * Return everything to caller.
7706 */
7707 costs->indexStartupCost = indexStartupCost;
7708 costs->indexTotalCost = indexTotalCost;
7709 costs->indexSelectivity = indexSelectivity;
7710 costs->indexCorrelation = indexCorrelation;
7711 costs->numIndexPages = numIndexPages;
7712 costs->numIndexTuples = numIndexTuples;
7713 costs->spc_random_page_cost = spc_random_page_cost;
7714 costs->num_sa_scans = num_sa_scans;
7715}
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition clausesel.c:100
double cpu_operator_cost
Definition costsize.c:135
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition costsize.c:898
double cpu_index_tuple_cost
Definition costsize.c:134
double Cost
Definition nodes.h:259
@ JOIN_INNER
Definition nodes.h:301
#define lsecond(l)
Definition pg_list.h:183
List * get_quals_from_indexclauses(List *indexclauses)
Definition selfuncs.c:7423
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition selfuncs.c:7737
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition selfuncs.c:2242
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition selfuncs.c:7453
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition spccache.c:183
Selectivity indexSelectivity
Definition selfuncs.h:135
BlockNumber numNonLeafPages
Definition selfuncs.h:143
Cost indexStartupCost
Definition selfuncs.h:133
double indexCorrelation
Definition selfuncs.h:136
double spc_random_page_cost
Definition selfuncs.h:141
double num_sa_scans
Definition selfuncs.h:142
Cost indexTotalCost
Definition selfuncs.h:134
double numIndexPages
Definition selfuncs.h:139
double numIndexTuples
Definition selfuncs.h:140
List * indexclauses
Definition pathnodes.h:2057
List * indexorderbys
Definition pathnodes.h:2058
IndexOptInfo * indexinfo
Definition pathnodes.h:2056

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, RestrictInfo::clause, clauselist_selectivity(), cpu_index_tuple_cost, cpu_operator_cost, estimate_array_length(), fb(), 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, GenericCosts::numNonLeafPages, 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 
)
extern

Definition at line 5582 of file selfuncs.c.

5585{
5586 Node *left,
5587 *right;
5588
5589 if (list_length(args) != 2)
5590 elog(ERROR, "join operator should take two arguments");
5591
5592 left = (Node *) linitial(args);
5593 right = (Node *) lsecond(args);
5594
5595 examine_variable(root, left, 0, vardata1);
5596 examine_variable(root, right, 0, vardata2);
5597
5598 if (vardata1->rel &&
5599 bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
5600 *join_is_reversed = true; /* var1 is on RHS */
5601 else if (vardata2->rel &&
5602 bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
5603 *join_is_reversed = true; /* var2 is on LHS */
5604 else
5605 *join_is_reversed = false;
5606}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:547
Relids syn_lefthand
Definition pathnodes.h:3228
Relids syn_righthand
Definition pathnodes.h:3229

References bms_is_subset(), elog, ERROR, examine_variable(), fb(), linitial, list_length(), lsecond, 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)
extern

Definition at line 7423 of file selfuncs.c.

7424{
7425 List *result = NIL;
7426 ListCell *lc;
7427
7428 foreach(lc, indexclauses)
7429 {
7431 ListCell *lc2;
7432
7433 foreach(lc2, iclause->indexquals)
7434 {
7436
7437 result = lappend(result, rinfo);
7438 }
7439 }
7440 return result;
7441}
uint32 result

References fb(), lappend(), lfirst_node, NIL, and result.

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 
)
extern

Definition at line 5522 of file selfuncs.c.

5525{
5526 Node *left,
5527 *right;
5529
5530 /* Fail if not a binary opclause (probably shouldn't happen) */
5531 if (list_length(args) != 2)
5532 return false;
5533
5534 left = (Node *) linitial(args);
5535 right = (Node *) lsecond(args);
5536
5537 /*
5538 * Examine both sides. Note that when varRelid is nonzero, Vars of other
5539 * relations will be treated as pseudoconstants.
5540 */
5541 examine_variable(root, left, varRelid, vardata);
5542 examine_variable(root, right, varRelid, &rdata);
5543
5544 /*
5545 * If one side is a variable and the other not, we win.
5546 */
5547 if (vardata->rel && rdata.rel == NULL)
5548 {
5549 *varonleft = true;
5551 /* Assume we need no ReleaseVariableStats(rdata) here */
5552 return true;
5553 }
5554
5555 if (vardata->rel == NULL && rdata.rel)
5556 {
5557 *varonleft = false;
5559 /* Assume we need no ReleaseVariableStats(*vardata) here */
5560 *vardata = rdata;
5561 return true;
5562 }
5563
5564 /* Oops, clause has wrong structure (probably var op var) */
5567
5568 return false;
5569}
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition clauses.c:2660

References estimate_expression_value(), examine_variable(), fb(), linitial, list_length(), lsecond, ReleaseVariableStats, and root.

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 
)
extern

Definition at line 6713 of file selfuncs.c.

6714{
6715 double stadistinct;
6716 double stanullfrac = 0.0;
6717 double ntuples;
6718
6719 *isdefault = false;
6720
6721 /*
6722 * Determine the stadistinct value to use. There are cases where we can
6723 * get an estimate even without a pg_statistic entry, or can get a better
6724 * value than is in pg_statistic. Grab stanullfrac too if we can find it
6725 * (otherwise, assume no nulls, for lack of any better idea).
6726 */
6727 if (HeapTupleIsValid(vardata->statsTuple))
6728 {
6729 /* Use the pg_statistic entry */
6730 Form_pg_statistic stats;
6731
6732 stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
6733 stadistinct = stats->stadistinct;
6734 stanullfrac = stats->stanullfrac;
6735 }
6736 else if (vardata->vartype == BOOLOID)
6737 {
6738 /*
6739 * Special-case boolean columns: presumably, two distinct values.
6740 *
6741 * Are there any other datatypes we should wire in special estimates
6742 * for?
6743 */
6744 stadistinct = 2.0;
6745 }
6746 else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
6747 {
6748 /*
6749 * If the Var represents a column of a VALUES RTE, assume it's unique.
6750 * This could of course be very wrong, but it should tend to be true
6751 * in well-written queries. We could consider examining the VALUES'
6752 * contents to get some real statistics; but that only works if the
6753 * entries are all constants, and it would be pretty expensive anyway.
6754 */
6755 stadistinct = -1.0; /* unique (and all non null) */
6756 }
6757 else
6758 {
6759 /*
6760 * We don't keep statistics for system columns, but in some cases we
6761 * can infer distinctness anyway.
6762 */
6763 if (vardata->var && IsA(vardata->var, Var))
6764 {
6765 switch (((Var *) vardata->var)->varattno)
6766 {
6768 stadistinct = -1.0; /* unique (and all non null) */
6769 break;
6771 stadistinct = 1.0; /* only 1 value */
6772 break;
6773 default:
6774 stadistinct = 0.0; /* means "unknown" */
6775 break;
6776 }
6777 }
6778 else
6779 stadistinct = 0.0; /* means "unknown" */
6780
6781 /*
6782 * XXX consider using estimate_num_groups on expressions?
6783 */
6784 }
6785
6786 /*
6787 * If there is a unique index, DISTINCT or GROUP-BY clause for the
6788 * variable, assume it is unique no matter what pg_statistic says; the
6789 * statistics could be out of date, or we might have found a partial
6790 * unique index that proves the var is unique for this query. However,
6791 * we'd better still believe the null-fraction statistic.
6792 */
6793 if (vardata->isunique)
6794 stadistinct = -1.0 * (1.0 - stanullfrac);
6795
6796 /*
6797 * If we had an absolute estimate, use that.
6798 */
6799 if (stadistinct > 0.0)
6800 return clamp_row_est(stadistinct);
6801
6802 /*
6803 * Otherwise we need to get the relation size; punt if not available.
6804 */
6805 if (vardata->rel == NULL)
6806 {
6807 *isdefault = true;
6808 return DEFAULT_NUM_DISTINCT;
6809 }
6810 ntuples = vardata->rel->tuples;
6811 if (ntuples <= 0.0)
6812 {
6813 *isdefault = true;
6814 return DEFAULT_NUM_DISTINCT;
6815 }
6816
6817 /*
6818 * If we had a relative estimate, use that.
6819 */
6820 if (stadistinct < 0.0)
6821 return clamp_row_est(-stadistinct * ntuples);
6822
6823 /*
6824 * With no data, estimate ndistinct = ntuples if the table is small, else
6825 * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
6826 * that the behavior isn't discontinuous.
6827 */
6828 if (ntuples < DEFAULT_NUM_DISTINCT)
6829 return clamp_row_est(ntuples);
6830
6831 *isdefault = true;
6832 return DEFAULT_NUM_DISTINCT;
6833}
@ RTE_VALUES
#define DEFAULT_NUM_DISTINCT
Definition selfuncs.h:52
#define TableOidAttributeNumber
Definition sysattr.h:26
#define SelfItemPointerAttributeNumber
Definition sysattr.h:21

References clamp_row_est(), DEFAULT_NUM_DISTINCT, fb(), GETSTRUCT(), HeapTupleIsValid, IsA, RTE_VALUES, SelfItemPointerAttributeNumber, and TableOidAttributeNumber.

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 
)
extern

Definition at line 898 of file selfuncs.c.

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

References Assert, ATTSTATSSLOT_VALUES, DatumGetBool(), fb(), free_attstatsslot(), FunctionCallInvoke, get_attstatsslot(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, result, and statistic_proc_security_check().

Referenced by generic_restriction_selectivity(), and patternsel_common().

◆ index_other_operands_eval_cost()

Cost index_other_operands_eval_cost ( PlannerInfo root,
List indexquals 
)
extern

Definition at line 7453 of file selfuncs.c.

7454{
7455 Cost qual_arg_cost = 0;
7456 ListCell *lc;
7457
7458 foreach(lc, indexquals)
7459 {
7460 Expr *clause = (Expr *) lfirst(lc);
7463
7464 /*
7465 * Index quals will have RestrictInfos, indexorderbys won't. Look
7466 * through RestrictInfo if present.
7467 */
7468 if (IsA(clause, RestrictInfo))
7469 clause = ((RestrictInfo *) clause)->clause;
7470
7471 if (IsA(clause, OpExpr))
7472 {
7473 OpExpr *op = (OpExpr *) clause;
7474
7475 other_operand = (Node *) lsecond(op->args);
7476 }
7477 else if (IsA(clause, RowCompareExpr))
7478 {
7479 RowCompareExpr *rc = (RowCompareExpr *) clause;
7480
7481 other_operand = (Node *) rc->rargs;
7482 }
7483 else if (IsA(clause, ScalarArrayOpExpr))
7484 {
7485 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
7486
7487 other_operand = (Node *) lsecond(saop->args);
7488 }
7489 else if (IsA(clause, NullTest))
7490 {
7492 }
7493 else
7494 {
7495 elog(ERROR, "unsupported indexqual type: %d",
7496 (int) nodeTag(clause));
7497 other_operand = NULL; /* keep compiler quiet */
7498 }
7499
7501 qual_arg_cost += index_qual_cost.startup + index_qual_cost.per_tuple;
7502 }
7503 return qual_arg_cost;
7504}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition costsize.c:4949
#define nodeTag(nodeptr)
Definition nodes.h:137
List * args
Definition primnodes.h:853

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

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 
)
extern

Definition at line 1116 of file selfuncs.c.

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

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, comparison_ops_are_compatible(), convert_to_scalar(), DatumGetBool(), fb(), free_attstatsslot(), FunctionCall2Coll(), FunctionCallInvoke, get_actual_variable_range(), get_attstatsslot(), get_variable_numdistinct(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, AttStatsSlot::nvalues, root, statistic_proc_security_check(), and val.

Referenced by prefix_selectivity(), and scalarineqsel().

◆ mcv_selectivity()

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

Definition at line 807 of file selfuncs.c.

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

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, DatumGetBool(), fb(), free_attstatsslot(), FunctionCallInvoke, get_attstatsslot(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, and statistic_proc_security_check().

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 
)
extern

Definition at line 3318 of file selfuncs.c.

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

Referenced by cached_scansel().

◆ nulltestsel()

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

Definition at line 1784 of file selfuncs.c.

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

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

Referenced by clause_selectivity_ext(), and clauselist_selectivity_ext().

◆ rowcomparesel()

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

Definition at line 2320 of file selfuncs.c.

2323{
2325 Oid opno = linitial_oid(clause->opnos);
2326 Oid inputcollid = linitial_oid(clause->inputcollids);
2327 List *opargs;
2328 bool is_join_clause;
2329
2330 /* Build equivalent arg list for single operator */
2331 opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2332
2333 /*
2334 * Decide if it's a join clause. This should match clausesel.c's
2335 * treat_as_join_clause(), except that we intentionally consider only the
2336 * leading columns and not the rest of the clause.
2337 */
2338 if (varRelid != 0)
2339 {
2340 /*
2341 * Caller is forcing restriction mode (eg, because we are examining an
2342 * inner indexscan qual).
2343 */
2344 is_join_clause = false;
2345 }
2346 else if (sjinfo == NULL)
2347 {
2348 /*
2349 * It must be a restriction clause, since it's being evaluated at a
2350 * scan node.
2351 */
2352 is_join_clause = false;
2353 }
2354 else
2355 {
2356 /*
2357 * Otherwise, it's a join if there's more than one base relation used.
2358 */
2359 is_join_clause = (NumRelids(root, (Node *) opargs) > 1);
2360 }
2361
2362 if (is_join_clause)
2363 {
2364 /* Estimate selectivity for a join clause. */
2365 s1 = join_selectivity(root, opno,
2366 opargs,
2367 inputcollid,
2368 jointype,
2369 sjinfo);
2370 }
2371 else
2372 {
2373 /* Estimate selectivity for a restriction clause. */
2375 opargs,
2376 inputcollid,
2377 varRelid);
2378 }
2379
2380 return s1;
2381}
int NumRelids(PlannerInfo *root, Node *clause)
Definition clauses.c:2391
#define linitial_oid(l)
Definition pg_list.h:180
#define list_make2(x1, x2)
Definition pg_list.h:246
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition plancat.c:2225
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition plancat.c:2264
char * s1

References fb(), 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 
)
extern

Definition at line 1902 of file selfuncs.c.

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

References ScalarArrayOpExpr::args, ARR_ELEMTYPE, array_contains_nulls(), Assert, CLAMP_PROBABILITY, DatumGetArrayTypeP, DatumGetFloat8(), deconstruct_array(), TypeCacheEntry::eq_opr, estimate_expression_value(), exprCollation(), exprType(), fb(), 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, 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 
)
extern

Definition at line 81 of file array_selfuncs.c.

85{
88 Datum constval;
89 TypeCacheEntry *typentry;
91
92 /*
93 * rightop must be a variable, else punt.
94 */
96 if (!vardata.rel)
97 {
99 return -1.0;
100 }
101
102 /*
103 * leftop must be a constant, else punt.
104 */
105 if (!IsA(leftop, Const))
106 {
108 return -1.0;
109 }
110 if (((Const *) leftop)->constisnull)
111 {
112 /* qual can't succeed if null on left */
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 {
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) &&
136 {
137 Form_pg_statistic stats;
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,
147 {
148 /* For ALL case, also get histogram of distinct-element counts */
149 if (useOr ||
150 !get_attstatsslot(&hslot, vardata.statsTuple,
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,
167 typentry);
168 else
170 sslot.nvalues,
171 sslot.numbers,
172 sslot.nnumbers,
173 &constval, 1,
174 hslot.numbers,
175 hslot.nnumbers,
177 typentry);
178
181 }
182 else
183 {
184 /* No most-common-elements info, so do without */
185 if (useOr)
187 NULL, 0,
188 &constval, 1,
190 typentry);
191 else
193 NULL, 0,
194 &constval, 1,
195 NULL, 0,
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,
213 typentry);
214 else
216 NULL, 0,
217 &constval, 1,
218 NULL, 0,
220 typentry);
221 /* we assume no nulls here, so no stanullfrac correction */
222 }
223
225
226 /*
227 * If the operator is <>, invert the results.
228 */
229 if (!isEquality)
230 selec = 1.0 - selec;
231
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)
Oid fn_oid
Definition fmgr.h:59
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(), fb(), FmgrInfo::fn_oid, free_attstatsslot(), get_attstatsslot(), GETSTRUCT(), HeapTupleIsValid, InvalidOid, IsA, lookup_type_cache(), mcelem_array_contain_overlap_selec(), mcelem_array_contained_selec(), OidIsValid, ReleaseVariableStats, root, statistic_proc_security_check(), and TYPECACHE_CMP_PROC_FINFO.

Referenced by scalararraysel().

◆ statistic_proc_security_check()

bool statistic_proc_security_check ( VariableStatData vardata,
Oid  func_oid 
)
extern

Definition at line 6684 of file selfuncs.c.

6685{
6686 if (vardata->acl_ok)
6687 return true; /* have SELECT privs and no securityQuals */
6688
6689 if (!OidIsValid(func_oid))
6690 return false;
6691
6693 return true;
6694
6696 (errmsg_internal("not using statistics because function \"%s\" is not leakproof",
6698 return false;
6699}
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG2
Definition elog.h:30
#define ereport(elevel,...)
Definition elog.h:152
bool get_func_leakproof(Oid funcid)
Definition lsyscache.c:2151
char * get_func_name(Oid funcid)
Definition lsyscache.c:1922

References DEBUG2, ereport, errmsg_internal(), fb(), get_func_leakproof(), get_func_name(), and OidIsValid.

Referenced by calc_arraycontsel(), calc_hist_selectivity(), 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 
)
extern

Definition at line 370 of file selfuncs.c.

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

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool(), fb(), fmgr_info(), free_attstatsslot(), FunctionCallInvoke, get_attstatsslot(), get_opcode(), get_variable_numdistinct(), GETSTRUCT(), HeapTupleIsValid, i, InitFunctionCallInfoData, InvalidOid, LOCAL_FCINFO, and statistic_proc_security_check().

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 
)
extern

Definition at line 541 of file selfuncs.c.

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

References ATTSTATSSLOT_NUMBERS, CLAMP_PROBABILITY, fb(), free_attstatsslot(), get_attstatsslot(), get_variable_numdistinct(), GETSTRUCT(), HeapTupleIsValid, and InvalidOid.

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