PostgreSQL Source Code  git master
selfuncs.h File Reference
#include "fmgr.h"
#include "access/htup.h"
#include "nodes/relation.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  VariableStatData
 
struct  IndexQualInfo
 
struct  GenericCosts
 

Macros

#define DEFAULT_EQ_SEL   0.005
 
#define DEFAULT_INEQ_SEL   0.3333333333333333
 
#define DEFAULT_RANGE_INEQ_SEL   0.005
 
#define DEFAULT_MATCH_SEL   0.005
 
#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 ReleaseVariableStats(vardata)
 

Typedefs

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)
 

Enumerations

enum  Pattern_Type {
  Pattern_Type_Like, Pattern_Type_Like_IC, Pattern_Type_Regex, Pattern_Type_Regex_IC,
  Pattern_Type_Prefix
}
 
enum  Pattern_Prefix_Status { Pattern_Prefix_None, Pattern_Prefix_Partial, Pattern_Prefix_Exact }
 

Functions

void examine_variable (PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
 
bool statistic_proc_security_check (VariableStatData *vardata, Oid func_oid)
 
bool get_restriction_variable (PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
 
void get_join_variables (PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
 
double get_variable_numdistinct (VariableStatData *vardata, bool *isdefault)
 
double mcv_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Datum constval, bool varonleft, double *sumcommonp)
 
double histogram_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
 
Pattern_Prefix_Status pattern_fixed_prefix (Const *patt, Pattern_Type ptype, Oid collation, Const **prefix, Selectivity *rest_selec)
 
Constmake_greater_string (const Const *str_const, FmgrInfo *ltproc, Oid collation)
 
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)
 
int estimate_array_length (Node *arrayexpr)
 
Selectivity rowcomparesel (PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
Listdeconstruct_indexquals (IndexPath *path)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, 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

◆ DEFAULT_EQ_SEL

#define DEFAULT_EQ_SEL   0.005

Definition at line 34 of file selfuncs.h.

Referenced by _int_matchsel(), eqsel_internal(), int_query_opr_selec(), and neqjoinsel().

◆ DEFAULT_INEQ_SEL

◆ DEFAULT_MATCH_SEL

#define DEFAULT_MATCH_SEL   0.005

Definition at line 43 of file selfuncs.h.

Referenced by patternjoinsel(), patternsel(), and prefix_selectivity().

◆ DEFAULT_NOT_UNK_SEL

#define DEFAULT_NOT_UNK_SEL   (1.0 - DEFAULT_UNK_SEL)

Definition at line 50 of file selfuncs.h.

Referenced by booltestsel(), and nulltestsel().

◆ DEFAULT_NUM_DISTINCT

#define DEFAULT_NUM_DISTINCT   200

Definition at line 46 of file selfuncs.h.

Referenced by get_variable_numdistinct().

◆ DEFAULT_RANGE_INEQ_SEL

#define DEFAULT_RANGE_INEQ_SEL   0.005

Definition at line 40 of file selfuncs.h.

Referenced by clauselist_selectivity(), and default_range_selectivity().

◆ DEFAULT_UNK_SEL

#define DEFAULT_UNK_SEL   0.005

Definition at line 49 of file selfuncs.h.

Referenced by booltestsel(), and nulltestsel().

◆ ReleaseVariableStats

#define ReleaseVariableStats (   vardata)

Typedef Documentation

◆ get_index_stats_hook_type

typedef bool(* get_index_stats_hook_type) (PlannerInfo *root, Oid indexOid, AttrNumber indexattnum, VariableStatData *vardata)

Definition at line 150 of file selfuncs.h.

◆ get_relation_stats_hook_type

typedef bool(* get_relation_stats_hook_type) (PlannerInfo *root, RangeTblEntry *rte, AttrNumber attnum, VariableStatData *vardata)

Definition at line 145 of file selfuncs.h.

◆ VariableStatData

Enumeration Type Documentation

◆ Pattern_Prefix_Status

Enumerator
Pattern_Prefix_None 
Pattern_Prefix_Partial 
Pattern_Prefix_Exact 

Definition at line 97 of file selfuncs.h.

◆ Pattern_Type

Enumerator
Pattern_Type_Like 
Pattern_Type_Like_IC 
Pattern_Type_Regex 
Pattern_Type_Regex_IC 
Pattern_Type_Prefix 

Definition at line 88 of file selfuncs.h.

Function Documentation

◆ booltestsel()

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

Definition at line 1593 of file selfuncs.c.

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

Referenced by clause_selectivity().

1595 {
1596  VariableStatData vardata;
1597  double selec;
1598 
1599  examine_variable(root, arg, varRelid, &vardata);
1600 
1601  if (HeapTupleIsValid(vardata.statsTuple))
1602  {
1603  Form_pg_statistic stats;
1604  double freq_null;
1605  AttStatsSlot sslot;
1606 
1607  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1608  freq_null = stats->stanullfrac;
1609 
1610  if (get_attstatsslot(&sslot, vardata.statsTuple,
1611  STATISTIC_KIND_MCV, InvalidOid,
1613  && sslot.nnumbers > 0)
1614  {
1615  double freq_true;
1616  double freq_false;
1617 
1618  /*
1619  * Get first MCV frequency and derive frequency for true.
1620  */
1621  if (DatumGetBool(sslot.values[0]))
1622  freq_true = sslot.numbers[0];
1623  else
1624  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1625 
1626  /*
1627  * Next derive frequency for false. Then use these as appropriate
1628  * to derive frequency for each case.
1629  */
1630  freq_false = 1.0 - freq_true - freq_null;
1631 
1632  switch (booltesttype)
1633  {
1634  case IS_UNKNOWN:
1635  /* select only NULL values */
1636  selec = freq_null;
1637  break;
1638  case IS_NOT_UNKNOWN:
1639  /* select non-NULL values */
1640  selec = 1.0 - freq_null;
1641  break;
1642  case IS_TRUE:
1643  /* select only TRUE values */
1644  selec = freq_true;
1645  break;
1646  case IS_NOT_TRUE:
1647  /* select non-TRUE values */
1648  selec = 1.0 - freq_true;
1649  break;
1650  case IS_FALSE:
1651  /* select only FALSE values */
1652  selec = freq_false;
1653  break;
1654  case IS_NOT_FALSE:
1655  /* select non-FALSE values */
1656  selec = 1.0 - freq_false;
1657  break;
1658  default:
1659  elog(ERROR, "unrecognized booltesttype: %d",
1660  (int) booltesttype);
1661  selec = 0.0; /* Keep compiler quiet */
1662  break;
1663  }
1664 
1665  free_attstatsslot(&sslot);
1666  }
1667  else
1668  {
1669  /*
1670  * No most-common-value info available. Still have null fraction
1671  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1672  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1673  */
1674  switch (booltesttype)
1675  {
1676  case IS_UNKNOWN:
1677  /* select only NULL values */
1678  selec = freq_null;
1679  break;
1680  case IS_NOT_UNKNOWN:
1681  /* select non-NULL values */
1682  selec = 1.0 - freq_null;
1683  break;
1684  case IS_TRUE:
1685  case IS_FALSE:
1686  /* Assume we select half of the non-NULL values */
1687  selec = (1.0 - freq_null) / 2.0;
1688  break;
1689  case IS_NOT_TRUE:
1690  case IS_NOT_FALSE:
1691  /* Assume we select NULLs plus half of the non-NULLs */
1692  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1693  selec = (freq_null + 1.0) / 2.0;
1694  break;
1695  default:
1696  elog(ERROR, "unrecognized booltesttype: %d",
1697  (int) booltesttype);
1698  selec = 0.0; /* Keep compiler quiet */
1699  break;
1700  }
1701  }
1702  }
1703  else
1704  {
1705  /*
1706  * If we can't get variable statistics for the argument, perhaps
1707  * clause_selectivity can do something with it. We ignore the
1708  * possibility of a NULL value when using clause_selectivity, and just
1709  * assume the value is either TRUE or FALSE.
1710  */
1711  switch (booltesttype)
1712  {
1713  case IS_UNKNOWN:
1714  selec = DEFAULT_UNK_SEL;
1715  break;
1716  case IS_NOT_UNKNOWN:
1717  selec = DEFAULT_NOT_UNK_SEL;
1718  break;
1719  case IS_TRUE:
1720  case IS_NOT_FALSE:
1721  selec = (double) clause_selectivity(root, arg,
1722  varRelid,
1723  jointype, sjinfo);
1724  break;
1725  case IS_FALSE:
1726  case IS_NOT_TRUE:
1727  selec = 1.0 - (double) clause_selectivity(root, arg,
1728  varRelid,
1729  jointype, sjinfo);
1730  break;
1731  default:
1732  elog(ERROR, "unrecognized booltesttype: %d",
1733  (int) booltesttype);
1734  selec = 0.0; /* Keep compiler quiet */
1735  break;
1736  }
1737  }
1738 
1739  ReleaseVariableStats(vardata);
1740 
1741  /* result should be in range, but make sure... */
1742  CLAMP_PROBABILITY(selec);
1743 
1744  return (Selectivity) selec;
1745 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double Selectivity
Definition: nodes.h:647
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:50
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ERROR
Definition: elog.h:43
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:574
float4 * numbers
Definition: lsyscache.h:52
#define DatumGetBool(X)
Definition: postgres.h:378
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:49
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
Datum * values
Definition: lsyscache.h:49
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog
Definition: elog.h:219
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ boolvarsel()

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

Definition at line 1554 of file selfuncs.c.

References BoolGetDatum, examine_variable(), HeapTupleIsValid, is_funcclause, ReleaseVariableStats, VariableStatData::statsTuple, and var_eq_const().

Referenced by clause_selectivity().

1555 {
1556  VariableStatData vardata;
1557  double selec;
1558 
1559  examine_variable(root, arg, varRelid, &vardata);
1560  if (HeapTupleIsValid(vardata.statsTuple))
1561  {
1562  /*
1563  * A boolean variable V is equivalent to the clause V = 't', so we
1564  * compute the selectivity as if that is what we have.
1565  */
1566  selec = var_eq_const(&vardata, BooleanEqualOperator,
1567  BoolGetDatum(true), false, true, false);
1568  }
1569  else if (is_funcclause(arg))
1570  {
1571  /*
1572  * If we have no stats and it's a function call, estimate 0.3333333.
1573  * This seems a pretty unprincipled choice, but Postgres has been
1574  * using that estimate for function calls since 1992. The hoariness
1575  * of this behavior suggests that we should not be in too much hurry
1576  * to use another value.
1577  */
1578  selec = 0.3333333;
1579  }
1580  else
1581  {
1582  /* Otherwise, the default estimate is 0.5 */
1583  selec = 0.5;
1584  }
1585  ReleaseVariableStats(vardata);
1586  return selec;
1587 }
HeapTuple statsTuple
Definition: selfuncs.h:71
#define is_funcclause(clause)
Definition: clauses.h:21
static double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:298
#define BoolGetDatum(X)
Definition: postgres.h:387
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81

◆ deconstruct_indexquals()

List* deconstruct_indexquals ( IndexPath path)

Definition at line 6552 of file selfuncs.c.

References arg, ScalarArrayOpExpr::args, Assert, RestrictInfo::clause, IndexQualInfo::clause_op, elog, ERROR, forboth, get_leftop(), get_rightop(), IndexQualInfo::indexcol, IndexPath::indexinfo, IndexPath::indexqualcols, IndexPath::indexquals, InvalidOid, IsA, lappend(), RowCompareExpr::largs, lfirst_int, lfirst_node, linitial, linitial_oid, lsecond, match_index_to_operand(), NIL, nodeTag, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, IndexQualInfo::other_operand, palloc(), RowCompareExpr::rargs, IndexQualInfo::rinfo, and IndexQualInfo::varonleft.

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

6553 {
6554  List *result = NIL;
6555  IndexOptInfo *index = path->indexinfo;
6556  ListCell *lcc,
6557  *lci;
6558 
6559  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6560  {
6561  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6562  int indexcol = lfirst_int(lci);
6563  Expr *clause;
6564  Node *leftop,
6565  *rightop;
6566  IndexQualInfo *qinfo;
6567 
6568  clause = rinfo->clause;
6569 
6570  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6571  qinfo->rinfo = rinfo;
6572  qinfo->indexcol = indexcol;
6573 
6574  if (IsA(clause, OpExpr))
6575  {
6576  qinfo->clause_op = ((OpExpr *) clause)->opno;
6577  leftop = get_leftop(clause);
6578  rightop = get_rightop(clause);
6579  if (match_index_to_operand(leftop, indexcol, index))
6580  {
6581  qinfo->varonleft = true;
6582  qinfo->other_operand = rightop;
6583  }
6584  else
6585  {
6586  Assert(match_index_to_operand(rightop, indexcol, index));
6587  qinfo->varonleft = false;
6588  qinfo->other_operand = leftop;
6589  }
6590  }
6591  else if (IsA(clause, RowCompareExpr))
6592  {
6593  RowCompareExpr *rc = (RowCompareExpr *) clause;
6594 
6595  qinfo->clause_op = linitial_oid(rc->opnos);
6596  /* Examine only first columns to determine left/right sides */
6598  indexcol, index))
6599  {
6600  qinfo->varonleft = true;
6601  qinfo->other_operand = (Node *) rc->rargs;
6602  }
6603  else
6604  {
6606  indexcol, index));
6607  qinfo->varonleft = false;
6608  qinfo->other_operand = (Node *) rc->largs;
6609  }
6610  }
6611  else if (IsA(clause, ScalarArrayOpExpr))
6612  {
6613  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6614 
6615  qinfo->clause_op = saop->opno;
6616  /* index column is always on the left in this case */
6618  indexcol, index));
6619  qinfo->varonleft = true;
6620  qinfo->other_operand = (Node *) lsecond(saop->args);
6621  }
6622  else if (IsA(clause, NullTest))
6623  {
6624  qinfo->clause_op = InvalidOid;
6625  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6626  indexcol, index));
6627  qinfo->varonleft = true;
6628  qinfo->other_operand = NULL;
6629  }
6630  else
6631  {
6632  elog(ERROR, "unsupported indexqual type: %d",
6633  (int) nodeTag(clause));
6634  }
6635 
6636  result = lappend(result, qinfo);
6637  }
6638  return result;
6639 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
IndexOptInfo * indexinfo
Definition: relation.h:1155
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3206
Definition: nodes.h:517
RestrictInfo * rinfo
Definition: selfuncs.h:109
#define lsecond(l)
Definition: pg_list.h:116
Definition: type.h:89
List * indexquals
Definition: relation.h:1157
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
Node * get_leftop(const Expr *clause)
Definition: clauses.c:200
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1880
bool varonleft
Definition: selfuncs.h:111
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:699
#define linitial_oid(l)
Definition: pg_list.h:113
#define nodeTag(nodeptr)
Definition: nodes.h:522
Node * get_rightop(const Expr *clause)
Definition: clauses.c:217
List * indexqualcols
Definition: relation.h:1158
void * palloc(Size size)
Definition: mcxt.c:924
Node * other_operand
Definition: selfuncs.h:113
void * arg
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

Definition at line 2179 of file selfuncs.c.

References ARR_DIMS, ARR_NDIM, ArrayGetNItems(), DatumGetArrayTypeP, IsA, list_length(), and strip_array_coercion().

Referenced by btcostestimate(), cost_qual_eval_walker(), cost_tidscan(), genericcostestimate(), and gincost_scalararrayopexpr().

2180 {
2181  /* look through any binary-compatible relabeling of arrayexpr */
2182  arrayexpr = strip_array_coercion(arrayexpr);
2183 
2184  if (arrayexpr && IsA(arrayexpr, Const))
2185  {
2186  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2187  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2188  ArrayType *arrayval;
2189 
2190  if (arrayisnull)
2191  return 0;
2192  arrayval = DatumGetArrayTypeP(arraydatum);
2193  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2194  }
2195  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2196  !((ArrayExpr *) arrayexpr)->multidims)
2197  {
2198  return list_length(((ArrayExpr *) arrayexpr)->elements);
2199  }
2200  else
2201  {
2202  /* default guess --- see also scalararraysel */
2203  return 10;
2204  }
2205 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:279
uintptr_t Datum
Definition: postgres.h:367
static int list_length(const List *l)
Definition: pg_list.h:89
#define ARR_NDIM(a)
Definition: array.h:275
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1827
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ estimate_hash_bucket_stats()

void estimate_hash_bucket_stats ( PlannerInfo root,
Node hashkey,
double  nbuckets,
Selectivity mcv_freq,
Selectivity bucketsize_frac 
)

Definition at line 3782 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

3785 {
3786  VariableStatData vardata;
3787  double estfract,
3788  ndistinct,
3789  stanullfrac,
3790  avgfreq;
3791  bool isdefault;
3792  AttStatsSlot sslot;
3793 
3794  examine_variable(root, hashkey, 0, &vardata);
3795 
3796  /* Look up the frequency of the most common value, if available */
3797  *mcv_freq = 0.0;
3798 
3799  if (HeapTupleIsValid(vardata.statsTuple))
3800  {
3801  if (get_attstatsslot(&sslot, vardata.statsTuple,
3802  STATISTIC_KIND_MCV, InvalidOid,
3804  {
3805  /*
3806  * The first MCV stat is for the most common value.
3807  */
3808  if (sslot.nnumbers > 0)
3809  *mcv_freq = sslot.numbers[0];
3810  free_attstatsslot(&sslot);
3811  }
3812  }
3813 
3814  /* Get number of distinct values */
3815  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3816 
3817  /*
3818  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3819  * mcv_freq is known to be even higher than that, use it instead.
3820  */
3821  if (isdefault)
3822  {
3823  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3824  ReleaseVariableStats(vardata);
3825  return;
3826  }
3827 
3828  /* Get fraction that are null */
3829  if (HeapTupleIsValid(vardata.statsTuple))
3830  {
3831  Form_pg_statistic stats;
3832 
3833  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3834  stanullfrac = stats->stanullfrac;
3835  }
3836  else
3837  stanullfrac = 0.0;
3838 
3839  /* Compute avg freq of all distinct data values in raw relation */
3840  avgfreq = (1.0 - stanullfrac) / ndistinct;
3841 
3842  /*
3843  * Adjust ndistinct to account for restriction clauses. Observe we are
3844  * assuming that the data distribution is affected uniformly by the
3845  * restriction clauses!
3846  *
3847  * XXX Possibly better way, but much more expensive: multiply by
3848  * selectivity of rel's restriction clauses that mention the target Var.
3849  */
3850  if (vardata.rel && vardata.rel->tuples > 0)
3851  {
3852  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3853  ndistinct = clamp_row_est(ndistinct);
3854  }
3855 
3856  /*
3857  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3858  * number of buckets is less than the expected number of distinct values;
3859  * otherwise it is 1/ndistinct.
3860  */
3861  if (ndistinct > nbuckets)
3862  estfract = 1.0 / nbuckets;
3863  else
3864  estfract = 1.0 / ndistinct;
3865 
3866  /*
3867  * Adjust estimated bucketsize upward to account for skewed distribution.
3868  */
3869  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3870  estfract *= *mcv_freq / avgfreq;
3871 
3872  /*
3873  * Clamp bucketsize to sane range (the above adjustment could easily
3874  * produce an out-of-range result). We set the lower bound a little above
3875  * zero, since zero isn't a very sane result.
3876  */
3877  if (estfract < 1.0e-6)
3878  estfract = 1.0e-6;
3879  else if (estfract > 1.0)
3880  estfract = 1.0;
3881 
3882  *bucketsize_frac = (Selectivity) estfract;
3883 
3884  ReleaseVariableStats(vardata);
3885 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:652
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:647
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5183
float4 * numbers
Definition: lsyscache.h:52
double rows
Definition: relation.h:615
#define InvalidOid
Definition: postgres_ext.h:36
#define Max(x, y)
Definition: c.h:851
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
double clamp_row_est(double nrows)
Definition: costsize.c:188
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ estimate_num_groups()

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

Definition at line 3419 of file selfuncs.c.

References add_unique_group_var(), Assert, clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), expression_returns_set_rows(), exprType(), for_each_cell, HeapTupleIsValid, i, IS_SIMPLE_REL, VariableStatData::isunique, lcons(), lfirst, linitial, list_head(), list_length(), list_member_int(), lnext, GroupVarInfo::ndistinct, NIL, pull_var_clause(), PVC_RECURSE_AGGREGATES, PVC_RECURSE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, GroupVarInfo::rel, ReleaseVariableStats, RelOptInfo::rows, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by adjust_rowcount_for_semijoins(), create_distinct_paths(), create_unique_path(), estimate_path_cost_size(), get_number_of_groups(), and recurse_set_operations().

3421 {
3422  List *varinfos = NIL;
3423  double srf_multiplier = 1.0;
3424  double numdistinct;
3425  ListCell *l;
3426  int i;
3427 
3428  /*
3429  * We don't ever want to return an estimate of zero groups, as that tends
3430  * to lead to division-by-zero and other unpleasantness. The input_rows
3431  * estimate is usually already at least 1, but clamp it just in case it
3432  * isn't.
3433  */
3434  input_rows = clamp_row_est(input_rows);
3435 
3436  /*
3437  * If no grouping columns, there's exactly one group. (This can't happen
3438  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3439  * corner cases with set operations.)
3440  */
3441  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3442  return 1.0;
3443 
3444  /*
3445  * Count groups derived from boolean grouping expressions. For other
3446  * expressions, find the unique Vars used, treating an expression as a Var
3447  * if we can find stats for it. For each one, record the statistical
3448  * estimate of number of distinct values (total in its table, without
3449  * regard for filtering).
3450  */
3451  numdistinct = 1.0;
3452 
3453  i = 0;
3454  foreach(l, groupExprs)
3455  {
3456  Node *groupexpr = (Node *) lfirst(l);
3457  double this_srf_multiplier;
3458  VariableStatData vardata;
3459  List *varshere;
3460  ListCell *l2;
3461 
3462  /* is expression in this grouping set? */
3463  if (pgset && !list_member_int(*pgset, i++))
3464  continue;
3465 
3466  /*
3467  * Set-returning functions in grouping columns are a bit problematic.
3468  * The code below will effectively ignore their SRF nature and come up
3469  * with a numdistinct estimate as though they were scalar functions.
3470  * We compensate by scaling up the end result by the largest SRF
3471  * rowcount estimate. (This will be an overestimate if the SRF
3472  * produces multiple copies of any output value, but it seems best to
3473  * assume the SRF's outputs are distinct. In any case, it's probably
3474  * pointless to worry too much about this without much better
3475  * estimates for SRF output rowcounts than we have today.)
3476  */
3477  this_srf_multiplier = expression_returns_set_rows(groupexpr);
3478  if (srf_multiplier < this_srf_multiplier)
3479  srf_multiplier = this_srf_multiplier;
3480 
3481  /* Short-circuit for expressions returning boolean */
3482  if (exprType(groupexpr) == BOOLOID)
3483  {
3484  numdistinct *= 2.0;
3485  continue;
3486  }
3487 
3488  /*
3489  * If examine_variable is able to deduce anything about the GROUP BY
3490  * expression, treat it as a single variable even if it's really more
3491  * complicated.
3492  */
3493  examine_variable(root, groupexpr, 0, &vardata);
3494  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3495  {
3496  varinfos = add_unique_group_var(root, varinfos,
3497  groupexpr, &vardata);
3498  ReleaseVariableStats(vardata);
3499  continue;
3500  }
3501  ReleaseVariableStats(vardata);
3502 
3503  /*
3504  * Else pull out the component Vars. Handle PlaceHolderVars by
3505  * recursing into their arguments (effectively assuming that the
3506  * PlaceHolderVar doesn't change the number of groups, which boils
3507  * down to ignoring the possible addition of nulls to the result set).
3508  */
3509  varshere = pull_var_clause(groupexpr,
3513 
3514  /*
3515  * If we find any variable-free GROUP BY item, then either it is a
3516  * constant (and we can ignore it) or it contains a volatile function;
3517  * in the latter case we punt and assume that each input row will
3518  * yield a distinct group.
3519  */
3520  if (varshere == NIL)
3521  {
3522  if (contain_volatile_functions(groupexpr))
3523  return input_rows;
3524  continue;
3525  }
3526 
3527  /*
3528  * Else add variables to varinfos list
3529  */
3530  foreach(l2, varshere)
3531  {
3532  Node *var = (Node *) lfirst(l2);
3533 
3534  examine_variable(root, var, 0, &vardata);
3535  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3536  ReleaseVariableStats(vardata);
3537  }
3538  }
3539 
3540  /*
3541  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3542  * list.
3543  */
3544  if (varinfos == NIL)
3545  {
3546  /* Apply SRF multiplier as we would do in the long path */
3547  numdistinct *= srf_multiplier;
3548  /* Round off */
3549  numdistinct = ceil(numdistinct);
3550  /* Guard against out-of-range answers */
3551  if (numdistinct > input_rows)
3552  numdistinct = input_rows;
3553  if (numdistinct < 1.0)
3554  numdistinct = 1.0;
3555  return numdistinct;
3556  }
3557 
3558  /*
3559  * Group Vars by relation and estimate total numdistinct.
3560  *
3561  * For each iteration of the outer loop, we process the frontmost Var in
3562  * varinfos, plus all other Vars in the same relation. We remove these
3563  * Vars from the newvarinfos list for the next iteration. This is the
3564  * easiest way to group Vars of same rel together.
3565  */
3566  do
3567  {
3568  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3569  RelOptInfo *rel = varinfo1->rel;
3570  double reldistinct = 1;
3571  double relmaxndistinct = reldistinct;
3572  int relvarcount = 0;
3573  List *newvarinfos = NIL;
3574  List *relvarinfos = NIL;
3575 
3576  /*
3577  * Split the list of varinfos in two - one for the current rel, one
3578  * for remaining Vars on other rels.
3579  */
3580  relvarinfos = lcons(varinfo1, relvarinfos);
3581  for_each_cell(l, lnext(list_head(varinfos)))
3582  {
3583  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3584 
3585  if (varinfo2->rel == varinfo1->rel)
3586  {
3587  /* varinfos on current rel */
3588  relvarinfos = lcons(varinfo2, relvarinfos);
3589  }
3590  else
3591  {
3592  /* not time to process varinfo2 yet */
3593  newvarinfos = lcons(varinfo2, newvarinfos);
3594  }
3595  }
3596 
3597  /*
3598  * Get the numdistinct estimate for the Vars of this rel. We
3599  * iteratively search for multivariate n-distinct with maximum number
3600  * of vars; assuming that each var group is independent of the others,
3601  * we multiply them together. Any remaining relvarinfos after no more
3602  * multivariate matches are found are assumed independent too, so
3603  * their individual ndistinct estimates are multiplied also.
3604  *
3605  * While iterating, count how many separate numdistinct values we
3606  * apply. We apply a fudge factor below, but only if we multiplied
3607  * more than one such values.
3608  */
3609  while (relvarinfos)
3610  {
3611  double mvndistinct;
3612 
3613  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3614  &mvndistinct))
3615  {
3616  reldistinct *= mvndistinct;
3617  if (relmaxndistinct < mvndistinct)
3618  relmaxndistinct = mvndistinct;
3619  relvarcount++;
3620  }
3621  else
3622  {
3623  foreach(l, relvarinfos)
3624  {
3625  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3626 
3627  reldistinct *= varinfo2->ndistinct;
3628  if (relmaxndistinct < varinfo2->ndistinct)
3629  relmaxndistinct = varinfo2->ndistinct;
3630  relvarcount++;
3631  }
3632 
3633  /* we're done with this relation */
3634  relvarinfos = NIL;
3635  }
3636  }
3637 
3638  /*
3639  * Sanity check --- don't divide by zero if empty relation.
3640  */
3641  Assert(IS_SIMPLE_REL(rel));
3642  if (rel->tuples > 0)
3643  {
3644  /*
3645  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3646  * fudge factor is because the Vars are probably correlated but we
3647  * don't know by how much. We should never clamp to less than the
3648  * largest ndistinct value for any of the Vars, though, since
3649  * there will surely be at least that many groups.
3650  */
3651  double clamp = rel->tuples;
3652 
3653  if (relvarcount > 1)
3654  {
3655  clamp *= 0.1;
3656  if (clamp < relmaxndistinct)
3657  {
3658  clamp = relmaxndistinct;
3659  /* for sanity in case some ndistinct is too large: */
3660  if (clamp > rel->tuples)
3661  clamp = rel->tuples;
3662  }
3663  }
3664  if (reldistinct > clamp)
3665  reldistinct = clamp;
3666 
3667  /*
3668  * Update the estimate based on the restriction selectivity,
3669  * guarding against division by zero when reldistinct is zero.
3670  * Also skip this if we know that we are returning all rows.
3671  */
3672  if (reldistinct > 0 && rel->rows < rel->tuples)
3673  {
3674  /*
3675  * Given a table containing N rows with n distinct values in a
3676  * uniform distribution, if we select p rows at random then
3677  * the expected number of distinct values selected is
3678  *
3679  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3680  *
3681  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3682  *
3683  * See "Approximating block accesses in database
3684  * organizations", S. B. Yao, Communications of the ACM,
3685  * Volume 20 Issue 4, April 1977 Pages 260-261.
3686  *
3687  * Alternatively, re-arranging the terms from the factorials,
3688  * this may be written as
3689  *
3690  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3691  *
3692  * This form of the formula is more efficient to compute in
3693  * the common case where p is larger than N/n. Additionally,
3694  * as pointed out by Dell'Era, if i << N for all terms in the
3695  * product, it can be approximated by
3696  *
3697  * n * (1 - ((N-p)/N)^(N/n))
3698  *
3699  * See "Expected distinct values when selecting from a bag
3700  * without replacement", Alberto Dell'Era,
3701  * http://www.adellera.it/investigations/distinct_balls/.
3702  *
3703  * The condition i << N is equivalent to n >> 1, so this is a
3704  * good approximation when the number of distinct values in
3705  * the table is large. It turns out that this formula also
3706  * works well even when n is small.
3707  */
3708  reldistinct *=
3709  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3710  rel->tuples / reldistinct));
3711  }
3712  reldistinct = clamp_row_est(reldistinct);
3713 
3714  /*
3715  * Update estimate of total distinct groups.
3716  */
3717  numdistinct *= reldistinct;
3718  }
3719 
3720  varinfos = newvarinfos;
3721  } while (varinfos != NIL);
3722 
3723  /* Now we can account for the effects of any SRFs */
3724  numdistinct *= srf_multiplier;
3725 
3726  /* Round off */
3727  numdistinct = ceil(numdistinct);
3728 
3729  /* Guard against out-of-range answers */
3730  if (numdistinct > input_rows)
3731  numdistinct = input_rows;
3732  if (numdistinct < 1.0)
3733  numdistinct = 1.0;
3734 
3735  return numdistinct;
3736 }
#define NIL
Definition: pg_list.h:69
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
HeapTuple statsTuple
Definition: selfuncs.h:71
double expression_returns_set_rows(Node *clause)
Definition: clauses.c:803
double tuples
Definition: relation.h:652
Definition: nodes.h:517
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:958
double ndistinct
Definition: selfuncs.c:3297
#define PVC_RECURSE_PLACEHOLDERS
Definition: var.h:26
#define IS_SIMPLE_REL(rel)
Definition: relation.h:585
#define linitial(l)
Definition: pg_list.h:111
bool list_member_int(const List *list, int datum)
Definition: list.c:485
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
static bool estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
Definition: selfuncs.c:3906
#define lnext(lc)
Definition: pg_list.h:105
static List * add_unique_group_var(PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
Definition: selfuncs.c:3301
double rows
Definition: relation.h:615
List * lcons(void *datum, List *list)
Definition: list.c:259
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
int i
double clamp_row_est(double nrows)
Definition: costsize.c:188
Definition: pg_list.h:45
RelOptInfo * rel
Definition: selfuncs.c:3296

◆ examine_variable()

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

Definition at line 4776 of file selfuncs.c.

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, arg, Assert, VariableStatData::atttype, VariableStatData::atttypmod, BMS_EMPTY_SET, bms_free(), bms_is_member(), bms_membership(), BMS_MULTIPLE, BMS_SINGLETON, bms_singleton_member(), BoolGetDatum, elog, equal(), ERROR, examine_simple_variable(), exprType(), exprTypmod(), find_base_rel(), find_join_rel(), VariableStatData::freefunc, get_index_stats_hook, GetUserId(), has_unique_index(), HeapTupleIsValid, IndexOptInfo::indexkeys, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, IndexOptInfo::indpred, Int16GetDatum, IsA, VariableStatData::isunique, lfirst, list_head(), lnext, MemSet, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, ObjectIdGetDatum, pg_class_aclcheck(), planner_rt_fetch, IndexOptInfo::predOK, pull_varnos(), VariableStatData::rel, IndexOptInfo::rel, ReleaseSysCache(), RelOptInfo::relid, RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::unique, VariableStatData::var, Var::varattno, Var::varno, VariableStatData::vartype, Var::vartype, and Var::vartypmod.

Referenced by booltestsel(), boolvarsel(), estimate_hash_bucket_stats(), estimate_num_groups(), get_join_variables(), get_restriction_variable(), mergejoinscansel(), nulltestsel(), and scalararraysel_containment().

4778 {
4779  Node *basenode;
4780  Relids varnos;
4781  RelOptInfo *onerel;
4782 
4783  /* Make sure we don't return dangling pointers in vardata */
4784  MemSet(vardata, 0, sizeof(VariableStatData));
4785 
4786  /* Save the exposed type of the expression */
4787  vardata->vartype = exprType(node);
4788 
4789  /* Look inside any binary-compatible relabeling */
4790 
4791  if (IsA(node, RelabelType))
4792  basenode = (Node *) ((RelabelType *) node)->arg;
4793  else
4794  basenode = node;
4795 
4796  /* Fast path for a simple Var */
4797 
4798  if (IsA(basenode, Var) &&
4799  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4800  {
4801  Var *var = (Var *) basenode;
4802 
4803  /* Set up result fields other than the stats tuple */
4804  vardata->var = basenode; /* return Var without relabeling */
4805  vardata->rel = find_base_rel(root, var->varno);
4806  vardata->atttype = var->vartype;
4807  vardata->atttypmod = var->vartypmod;
4808  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4809 
4810  /* Try to locate some stats */
4811  examine_simple_variable(root, var, vardata);
4812 
4813  return;
4814  }
4815 
4816  /*
4817  * Okay, it's a more complicated expression. Determine variable
4818  * membership. Note that when varRelid isn't zero, only vars of that
4819  * relation are considered "real" vars.
4820  */
4821  varnos = pull_varnos(basenode);
4822 
4823  onerel = NULL;
4824 
4825  switch (bms_membership(varnos))
4826  {
4827  case BMS_EMPTY_SET:
4828  /* No Vars at all ... must be pseudo-constant clause */
4829  break;
4830  case BMS_SINGLETON:
4831  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4832  {
4833  onerel = find_base_rel(root,
4834  (varRelid ? varRelid : bms_singleton_member(varnos)));
4835  vardata->rel = onerel;
4836  node = basenode; /* strip any relabeling */
4837  }
4838  /* else treat it as a constant */
4839  break;
4840  case BMS_MULTIPLE:
4841  if (varRelid == 0)
4842  {
4843  /* treat it as a variable of a join relation */
4844  vardata->rel = find_join_rel(root, varnos);
4845  node = basenode; /* strip any relabeling */
4846  }
4847  else if (bms_is_member(varRelid, varnos))
4848  {
4849  /* ignore the vars belonging to other relations */
4850  vardata->rel = find_base_rel(root, varRelid);
4851  node = basenode; /* strip any relabeling */
4852  /* note: no point in expressional-index search here */
4853  }
4854  /* else treat it as a constant */
4855  break;
4856  }
4857 
4858  bms_free(varnos);
4859 
4860  vardata->var = node;
4861  vardata->atttype = exprType(node);
4862  vardata->atttypmod = exprTypmod(node);
4863 
4864  if (onerel)
4865  {
4866  /*
4867  * We have an expression in vars of a single relation. Try to match
4868  * it to expressional index columns, in hopes of finding some
4869  * statistics.
4870  *
4871  * XXX it's conceivable that there are multiple matches with different
4872  * index opfamilies; if so, we need to pick one that matches the
4873  * operator we are estimating for. FIXME later.
4874  */
4875  ListCell *ilist;
4876 
4877  foreach(ilist, onerel->indexlist)
4878  {
4879  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4880  ListCell *indexpr_item;
4881  int pos;
4882 
4883  indexpr_item = list_head(index->indexprs);
4884  if (indexpr_item == NULL)
4885  continue; /* no expressions here... */
4886 
4887  for (pos = 0; pos < index->ncolumns; pos++)
4888  {
4889  if (index->indexkeys[pos] == 0)
4890  {
4891  Node *indexkey;
4892 
4893  if (indexpr_item == NULL)
4894  elog(ERROR, "too few entries in indexprs list");
4895  indexkey = (Node *) lfirst(indexpr_item);
4896  if (indexkey && IsA(indexkey, RelabelType))
4897  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4898  if (equal(node, indexkey))
4899  {
4900  /*
4901  * Found a match ... is it a unique index? Tests here
4902  * should match has_unique_index().
4903  */
4904  if (index->unique &&
4905  index->nkeycolumns == 1 &&
4906  (index->indpred == NIL || index->predOK))
4907  vardata->isunique = true;
4908 
4909  /*
4910  * Has it got stats? We only consider stats for
4911  * non-partial indexes, since partial indexes probably
4912  * don't reflect whole-relation statistics; the above
4913  * check for uniqueness is the only info we take from
4914  * a partial index.
4915  *
4916  * An index stats hook, however, must make its own
4917  * decisions about what to do with partial indexes.
4918  */
4919  if (get_index_stats_hook &&
4920  (*get_index_stats_hook) (root, index->indexoid,
4921  pos + 1, vardata))
4922  {
4923  /*
4924  * The hook took control of acquiring a stats
4925  * tuple. If it did supply a tuple, it'd better
4926  * have supplied a freefunc.
4927  */
4928  if (HeapTupleIsValid(vardata->statsTuple) &&
4929  !vardata->freefunc)
4930  elog(ERROR, "no function provided to release variable stats with");
4931  }
4932  else if (index->indpred == NIL)
4933  {
4934  vardata->statsTuple =
4936  ObjectIdGetDatum(index->indexoid),
4937  Int16GetDatum(pos + 1),
4938  BoolGetDatum(false));
4939  vardata->freefunc = ReleaseSysCache;
4940 
4941  if (HeapTupleIsValid(vardata->statsTuple))
4942  {
4943  /* Get index's table for permission check */
4944  RangeTblEntry *rte;
4945 
4946  rte = planner_rt_fetch(index->rel->relid, root);
4947  Assert(rte->rtekind == RTE_RELATION);
4948 
4949  /*
4950  * For simplicity, we insist on the whole
4951  * table being selectable, rather than trying
4952  * to identify which column(s) the index
4953  * depends on.
4954  */
4955  vardata->acl_ok =
4957  ACL_SELECT) == ACLCHECK_OK);
4958  }
4959  else
4960  {
4961  /* suppress leakproofness checks later */
4962  vardata->acl_ok = true;
4963  }
4964  }
4965  if (vardata->statsTuple)
4966  break;
4967  }
4968  indexpr_item = lnext(indexpr_item);
4969  }
4970  }
4971  if (vardata->statsTuple)
4972  break;
4973  }
4974  }
4975 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
bool predOK
Definition: relation.h:788
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:344
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:379
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:436
Definition: nodes.h:517
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:908
AttrNumber varattno
Definition: primnodes.h:169
Definition: primnodes.h:164
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4987
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:789
Definition: type.h:89
RelOptInfo * rel
Definition: relation.h:755
#define planner_rt_fetch(rti, root)
Definition: relation.h:344
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1822
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:171
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int ncolumns
Definition: relation.h:763
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: relation.h:640
Index varno
Definition: primnodes.h:167
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:700
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:75
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:592
List * indexlist
Definition: relation.h:649
#define BoolGetDatum(X)
Definition: postgres.h:387
void bms_free(Bitmapset *a)
Definition: bitmapset.c:267
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int nkeycolumns
Definition: relation.h:764
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4627
RTEKind rtekind
Definition: parsenodes.h:962
void * arg
int * indexkeys
Definition: relation.h:765
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:753
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:279
List * indpred
Definition: relation.h:778
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486
List * indexprs
Definition: relation.h:777
int32 vartypmod
Definition: primnodes.h:172

◆ genericcostestimate()

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

Definition at line 6701 of file selfuncs.c.

References add_predicate_to_quals(), ScalarArrayOpExpr::args, RestrictInfo::clause, clauselist_selectivity(), cpu_index_tuple_cost, cpu_operator_cost, estimate_array_length(), get_tablespace_page_costs(), index_pages_fetched(), GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexPath::indexorderbys, IndexPath::indexquals, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, IsA, JOIN_INNER, lfirst, list_length(), lsecond, GenericCosts::num_sa_scans, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, orderby_operands_eval_cost(), other_operands_eval_cost(), IndexOptInfo::pages, IndexOptInfo::rel, RelOptInfo::relid, IndexOptInfo::reltablespace, rint(), GenericCosts::spc_random_page_cost, RelOptInfo::tuples, and IndexOptInfo::tuples.

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

6706 {
6707  IndexOptInfo *index = path->indexinfo;
6708  List *indexQuals = path->indexquals;
6709  List *indexOrderBys = path->indexorderbys;
6710  Cost indexStartupCost;
6711  Cost indexTotalCost;
6712  Selectivity indexSelectivity;
6713  double indexCorrelation;
6714  double numIndexPages;
6715  double numIndexTuples;
6716  double spc_random_page_cost;
6717  double num_sa_scans;
6718  double num_outer_scans;
6719  double num_scans;
6720  double qual_op_cost;
6721  double qual_arg_cost;
6722  List *selectivityQuals;
6723  ListCell *l;
6724 
6725  /*
6726  * If the index is partial, AND the index predicate with the explicitly
6727  * given indexquals to produce a more accurate idea of the index
6728  * selectivity.
6729  */
6730  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6731 
6732  /*
6733  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6734  * index scans that will be performed.
6735  */
6736  num_sa_scans = 1;
6737  foreach(l, indexQuals)
6738  {
6739  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6740 
6741  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6742  {
6743  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6744  int alength = estimate_array_length(lsecond(saop->args));
6745 
6746  if (alength > 1)
6747  num_sa_scans *= alength;
6748  }
6749  }
6750 
6751  /* Estimate the fraction of main-table tuples that will be visited */
6752  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6753  index->rel->relid,
6754  JOIN_INNER,
6755  NULL);
6756 
6757  /*
6758  * If caller didn't give us an estimate, estimate the number of index
6759  * tuples that will be visited. We do it in this rather peculiar-looking
6760  * way in order to get the right answer for partial indexes.
6761  */
6762  numIndexTuples = costs->numIndexTuples;
6763  if (numIndexTuples <= 0.0)
6764  {
6765  numIndexTuples = indexSelectivity * index->rel->tuples;
6766 
6767  /*
6768  * The above calculation counts all the tuples visited across all
6769  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6770  * average per-indexscan number, so adjust. This is a handy place to
6771  * round to integer, too. (If caller supplied tuple estimate, it's
6772  * responsible for handling these considerations.)
6773  */
6774  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6775  }
6776 
6777  /*
6778  * We can bound the number of tuples by the index size in any case. Also,
6779  * always estimate at least one tuple is touched, even when
6780  * indexSelectivity estimate is tiny.
6781  */
6782  if (numIndexTuples > index->tuples)
6783  numIndexTuples = index->tuples;
6784  if (numIndexTuples < 1.0)
6785  numIndexTuples = 1.0;
6786 
6787  /*
6788  * Estimate the number of index pages that will be retrieved.
6789  *
6790  * We use the simplistic method of taking a pro-rata fraction of the total
6791  * number of index pages. In effect, this counts only leaf pages and not
6792  * any overhead such as index metapage or upper tree levels.
6793  *
6794  * In practice access to upper index levels is often nearly free because
6795  * those tend to stay in cache under load; moreover, the cost involved is
6796  * highly dependent on index type. We therefore ignore such costs here
6797  * and leave it to the caller to add a suitable charge if needed.
6798  */
6799  if (index->pages > 1 && index->tuples > 1)
6800  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6801  else
6802  numIndexPages = 1.0;
6803 
6804  /* fetch estimated page cost for tablespace containing index */
6806  &spc_random_page_cost,
6807  NULL);
6808 
6809  /*
6810  * Now compute the disk access costs.
6811  *
6812  * The above calculations are all per-index-scan. However, if we are in a
6813  * nestloop inner scan, we can expect the scan to be repeated (with
6814  * different search keys) for each row of the outer relation. Likewise,
6815  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6816  * the potential for cache effects to reduce the number of disk page
6817  * fetches needed. We want to estimate the average per-scan I/O cost in
6818  * the presence of caching.
6819  *
6820  * We use the Mackert-Lohman formula (see costsize.c for details) to
6821  * estimate the total number of page fetches that occur. While this
6822  * wasn't what it was designed for, it seems a reasonable model anyway.
6823  * Note that we are counting pages not tuples anymore, so we take N = T =
6824  * index size, as if there were one "tuple" per page.
6825  */
6826  num_outer_scans = loop_count;
6827  num_scans = num_sa_scans * num_outer_scans;
6828 
6829  if (num_scans > 1)
6830  {
6831  double pages_fetched;
6832 
6833  /* total page fetches ignoring cache effects */
6834  pages_fetched = numIndexPages * num_scans;
6835 
6836  /* use Mackert and Lohman formula to adjust for cache effects */
6837  pages_fetched = index_pages_fetched(pages_fetched,
6838  index->pages,
6839  (double) index->pages,
6840  root);
6841 
6842  /*
6843  * Now compute the total disk access cost, and then report a pro-rated
6844  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6845  * since that's internal to the indexscan.)
6846  */
6847  indexTotalCost = (pages_fetched * spc_random_page_cost)
6848  / num_outer_scans;
6849  }
6850  else
6851  {
6852  /*
6853  * For a single index scan, we just charge spc_random_page_cost per
6854  * page touched.
6855  */
6856  indexTotalCost = numIndexPages * spc_random_page_cost;
6857  }
6858 
6859  /*
6860  * CPU cost: any complex expressions in the indexquals will need to be
6861  * evaluated once at the start of the scan to reduce them to runtime keys
6862  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6863  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6864  * indexqual operator. Because we have numIndexTuples as a per-scan
6865  * number, we have to multiply by num_sa_scans to get the correct result
6866  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6867  * ORDER BY expressions.
6868  *
6869  * Note: this neglects the possible costs of rechecking lossy operators.
6870  * Detecting that that might be needed seems more expensive than it's
6871  * worth, though, considering all the other inaccuracies here ...
6872  */
6873  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6874  orderby_operands_eval_cost(root, path);
6875  qual_op_cost = cpu_operator_cost *
6876  (list_length(indexQuals) + list_length(indexOrderBys));
6877 
6878  indexStartupCost = qual_arg_cost;
6879  indexTotalCost += qual_arg_cost;
6880  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6881 
6882  /*
6883  * Generic assumption about index correlation: there isn't any.
6884  */
6885  indexCorrelation = 0.0;
6886 
6887  /*
6888  * Return everything to caller.
6889  */
6890  costs->indexStartupCost = indexStartupCost;
6891  costs->indexTotalCost = indexTotalCost;
6892  costs->indexSelectivity = indexSelectivity;
6893  costs->indexCorrelation = indexCorrelation;
6894  costs->numIndexPages = numIndexPages;
6895  costs->numIndexTuples = numIndexTuples;
6896  costs->spc_random_page_cost = spc_random_page_cost;
6897  costs->num_sa_scans = num_sa_scans;
6898 }
Selectivity indexSelectivity
Definition: selfuncs.h:134
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
IndexOptInfo * indexinfo
Definition: relation.h:1155
double tuples
Definition: relation.h:652
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6920
Oid reltablespace
Definition: relation.h:754
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6647
double Selectivity
Definition: nodes.h:647
double tuples
Definition: relation.h:759
#define lsecond(l)
Definition: pg_list.h:116
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6672
Definition: type.h:89
BlockNumber pages
Definition: relation.h:758
List * indexquals
Definition: relation.h:1157
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2179
RelOptInfo * rel
Definition: relation.h:755
double num_sa_scans
Definition: selfuncs.h:141
double cpu_operator_cost
Definition: costsize.c:115
Cost indexTotalCost
Definition: selfuncs.h:133
double rint(double x)
Definition: rint.c:22
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:640
Expr * clause
Definition: relation.h:1880
double indexCorrelation
Definition: selfuncs.h:135
List * indexorderbys
Definition: relation.h:1159
double spc_random_page_cost
Definition: selfuncs.h:140
double numIndexTuples
Definition: selfuncs.h:139
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Cost indexStartupCost
Definition: selfuncs.h:132
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
Definition: pg_list.h:45
double cpu_index_tuple_cost
Definition: costsize.c:114
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:830
double Cost
Definition: nodes.h:648
double numIndexPages
Definition: selfuncs.h:138

◆ get_join_variables()

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

Definition at line 4714 of file selfuncs.c.

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

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

4717 {
4718  Node *left,
4719  *right;
4720 
4721  if (list_length(args) != 2)
4722  elog(ERROR, "join operator should take two arguments");
4723 
4724  left = (Node *) linitial(args);
4725  right = (Node *) lsecond(args);
4726 
4727  examine_variable(root, left, 0, vardata1);
4728  examine_variable(root, right, 0, vardata2);
4729 
4730  if (vardata1->rel &&
4731  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4732  *join_is_reversed = true; /* var1 is on RHS */
4733  else if (vardata2->rel &&
4734  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4735  *join_is_reversed = true; /* var2 is on LHS */
4736  else
4737  *join_is_reversed = false;
4738 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:517
#define lsecond(l)
Definition: pg_list.h:116
Relids syn_lefthand
Definition: relation.h:2068
Relids syn_righthand
Definition: relation.h:2069
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:374
Relids relids
Definition: relation.h:612
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
static int list_length(const List *l)
Definition: pg_list.h:89
#define elog
Definition: elog.h:219

◆ get_restriction_variable()

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

Definition at line 4654 of file selfuncs.c.

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

Referenced by _int_matchsel(), arraycontsel(), eqsel_internal(), ltreeparentsel(), networksel(), patternsel(), rangesel(), scalarineqsel_wrapper(), and tsmatchsel().

4657 {
4658  Node *left,
4659  *right;
4660  VariableStatData rdata;
4661 
4662  /* Fail if not a binary opclause (probably shouldn't happen) */
4663  if (list_length(args) != 2)
4664  return false;
4665 
4666  left = (Node *) linitial(args);
4667  right = (Node *) lsecond(args);
4668 
4669  /*
4670  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4671  * relations will be treated as pseudoconstants.
4672  */
4673  examine_variable(root, left, varRelid, vardata);
4674  examine_variable(root, right, varRelid, &rdata);
4675 
4676  /*
4677  * If one side is a variable and the other not, we win.
4678  */
4679  if (vardata->rel && rdata.rel == NULL)
4680  {
4681  *varonleft = true;
4682  *other = estimate_expression_value(root, rdata.var);
4683  /* Assume we need no ReleaseVariableStats(rdata) here */
4684  return true;
4685  }
4686 
4687  if (vardata->rel == NULL && rdata.rel)
4688  {
4689  *varonleft = false;
4690  *other = estimate_expression_value(root, vardata->var);
4691  /* Assume we need no ReleaseVariableStats(*vardata) here */
4692  *vardata = rdata;
4693  return true;
4694  }
4695 
4696  /* Oops, clause has wrong structure (probably var op var) */
4697  ReleaseVariableStats(*vardata);
4698  ReleaseVariableStats(rdata);
4699 
4700  return false;
4701 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2493
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:517
#define lsecond(l)
Definition: pg_list.h:116
#define linitial(l)
Definition: pg_list.h:111
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
static int list_length(const List *l)
Definition: pg_list.h:89
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

Definition at line 5183 of file selfuncs.c.

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

Referenced by add_unique_group_var(), eqjoinsel_inner(), eqjoinsel_semi(), estimate_hash_bucket_stats(), ineq_histogram_selectivity(), var_eq_const(), and var_eq_non_const().

5184 {
5185  double stadistinct;
5186  double stanullfrac = 0.0;
5187  double ntuples;
5188 
5189  *isdefault = false;
5190 
5191  /*
5192  * Determine the stadistinct value to use. There are cases where we can
5193  * get an estimate even without a pg_statistic entry, or can get a better
5194  * value than is in pg_statistic. Grab stanullfrac too if we can find it
5195  * (otherwise, assume no nulls, for lack of any better idea).
5196  */
5197  if (HeapTupleIsValid(vardata->statsTuple))
5198  {
5199  /* Use the pg_statistic entry */
5200  Form_pg_statistic stats;
5201 
5202  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5203  stadistinct = stats->stadistinct;
5204  stanullfrac = stats->stanullfrac;
5205  }
5206  else if (vardata->vartype == BOOLOID)
5207  {
5208  /*
5209  * Special-case boolean columns: presumably, two distinct values.
5210  *
5211  * Are there any other datatypes we should wire in special estimates
5212  * for?
5213  */
5214  stadistinct = 2.0;
5215  }
5216  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5217  {
5218  /*
5219  * If the Var represents a column of a VALUES RTE, assume it's unique.
5220  * This could of course be very wrong, but it should tend to be true
5221  * in well-written queries. We could consider examining the VALUES'
5222  * contents to get some real statistics; but that only works if the
5223  * entries are all constants, and it would be pretty expensive anyway.
5224  */
5225  stadistinct = -1.0; /* unique (and all non null) */
5226  }
5227  else
5228  {
5229  /*
5230  * We don't keep statistics for system columns, but in some cases we
5231  * can infer distinctness anyway.
5232  */
5233  if (vardata->var && IsA(vardata->var, Var))
5234  {
5235  switch (((Var *) vardata->var)->varattno)
5236  {
5239  stadistinct = -1.0; /* unique (and all non null) */
5240  break;
5242  stadistinct = 1.0; /* only 1 value */
5243  break;
5244  default:
5245  stadistinct = 0.0; /* means "unknown" */
5246  break;
5247  }
5248  }
5249  else
5250  stadistinct = 0.0; /* means "unknown" */
5251 
5252  /*
5253  * XXX consider using estimate_num_groups on expressions?
5254  */
5255  }
5256 
5257  /*
5258  * If there is a unique index or DISTINCT clause for the variable, assume
5259  * it is unique no matter what pg_statistic says; the statistics could be
5260  * out of date, or we might have found a partial unique index that proves
5261  * the var is unique for this query. However, we'd better still believe
5262  * the null-fraction statistic.
5263  */
5264  if (vardata->isunique)
5265  stadistinct = -1.0 * (1.0 - stanullfrac);
5266 
5267  /*
5268  * If we had an absolute estimate, use that.
5269  */
5270  if (stadistinct > 0.0)
5271  return clamp_row_est(stadistinct);
5272 
5273  /*
5274  * Otherwise we need to get the relation size; punt if not available.
5275  */
5276  if (vardata->rel == NULL)
5277  {
5278  *isdefault = true;
5279  return DEFAULT_NUM_DISTINCT;
5280  }
5281  ntuples = vardata->rel->tuples;
5282  if (ntuples <= 0.0)
5283  {
5284  *isdefault = true;
5285  return DEFAULT_NUM_DISTINCT;
5286  }
5287 
5288  /*
5289  * If we had a relative estimate, use that.
5290  */
5291  if (stadistinct < 0.0)
5292  return clamp_row_est(-stadistinct * ntuples);
5293 
5294  /*
5295  * With no data, estimate ndistinct = ntuples if the table is small, else
5296  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5297  * that the behavior isn't discontinuous.
5298  */
5299  if (ntuples < DEFAULT_NUM_DISTINCT)
5300  return clamp_row_est(ntuples);
5301 
5302  *isdefault = true;
5303  return DEFAULT_NUM_DISTINCT;
5304 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
HeapTuple statsTuple
Definition: selfuncs.h:71
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
double tuples
Definition: relation.h:652
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: primnodes.h:164
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define TableOidAttributeNumber
Definition: sysattr.h:27
RTEKind rtekind
Definition: relation.h:642
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:46
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
double clamp_row_est(double nrows)
Definition: costsize.c:188

◆ histogram_selectivity()

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

Definition at line 711 of file selfuncs.c.

References Assert, ATTSTATSSLOT_VALUES, DatumGetBool, FmgrInfo::fn_oid, free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), HeapTupleIsValid, i, InvalidOid, AttStatsSlot::nvalues, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by ltreeparentsel(), and patternsel().

715 {
716  double result;
717  AttStatsSlot sslot;
718 
719  /* check sanity of parameters */
720  Assert(n_skip >= 0);
721  Assert(min_hist_size > 2 * n_skip);
722 
723  if (HeapTupleIsValid(vardata->statsTuple) &&
724  statistic_proc_security_check(vardata, opproc->fn_oid) &&
725  get_attstatsslot(&sslot, vardata->statsTuple,
726  STATISTIC_KIND_HISTOGRAM, InvalidOid,
728  {
729  *hist_size = sslot.nvalues;
730  if (sslot.nvalues >= min_hist_size)
731  {
732  int nmatch = 0;
733  int i;
734 
735  for (i = n_skip; i < sslot.nvalues - n_skip; i++)
736  {
737  if (varonleft ?
739  DEFAULT_COLLATION_OID,
740  sslot.values[i],
741  constval)) :
743  DEFAULT_COLLATION_OID,
744  constval,
745  sslot.values[i])))
746  nmatch++;
747  }
748  result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
749  }
750  else
751  result = -1;
752  free_attstatsslot(&sslot);
753  }
754  else
755  {
756  *hist_size = 0;
757  result = -1;
758  }
759 
760  return result;
761 }
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5154
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1133
#define DatumGetBool(X)
Definition: postgres.h:378
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
#define Assert(condition)
Definition: c.h:699
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ make_greater_string()

Const* make_greater_string ( const Const str_const,
FmgrInfo ltproc,
Oid  collation 
)

Definition at line 6326 of file selfuncs.c.

References Assert, byte_increment(), Const::consttype, Const::constvalue, DatumGetBool, DatumGetByteaPP, DatumGetCString, DatumGetPointer, DirectFunctionCall1, FunctionCall2Coll(), lc_collate_is_c(), nameout(), palloc(), pfree(), pg_database_encoding_character_incrementer(), pg_mbcliplen(), PointerGetDatum, SET_VARSIZE, string_to_bytea_const(), string_to_const(), TextDatumGetCString, VARDATA, VARDATA_ANY, VARHDRSZ, VARSIZE_ANY_EXHDR, and varstr_cmp().

Referenced by prefix_quals(), and prefix_selectivity().

6327 {
6328  Oid datatype = str_const->consttype;
6329  char *workstr;
6330  int len;
6331  Datum cmpstr;
6332  text *cmptxt = NULL;
6333  mbcharacter_incrementer charinc;
6334 
6335  /*
6336  * Get a modifiable copy of the prefix string in C-string format, and set
6337  * up the string we will compare to as a Datum. In C locale this can just
6338  * be the given prefix string, otherwise we need to add a suffix. Types
6339  * NAME and BYTEA sort bytewise so they don't need a suffix either.
6340  */
6341  if (datatype == NAMEOID)
6342  {
6344  str_const->constvalue));
6345  len = strlen(workstr);
6346  cmpstr = str_const->constvalue;
6347  }
6348  else if (datatype == BYTEAOID)
6349  {
6350  bytea *bstr = DatumGetByteaPP(str_const->constvalue);
6351 
6352  len = VARSIZE_ANY_EXHDR(bstr);
6353  workstr = (char *) palloc(len);
6354  memcpy(workstr, VARDATA_ANY(bstr), len);
6355  Assert((Pointer) bstr == DatumGetPointer(str_const->constvalue));
6356  cmpstr = str_const->constvalue;
6357  }
6358  else
6359  {
6360  workstr = TextDatumGetCString(str_const->constvalue);
6361  len = strlen(workstr);
6362  if (lc_collate_is_c(collation) || len == 0)
6363  cmpstr = str_const->constvalue;
6364  else
6365  {
6366  /* If first time through, determine the suffix to use */
6367  static char suffixchar = 0;
6368  static Oid suffixcollation = 0;
6369 
6370  if (!suffixchar || suffixcollation != collation)
6371  {
6372  char *best;
6373 
6374  best = "Z";
6375  if (varstr_cmp(best, 1, "z", 1, collation) < 0)
6376  best = "z";
6377  if (varstr_cmp(best, 1, "y", 1, collation) < 0)
6378  best = "y";
6379  if (varstr_cmp(best, 1, "9", 1, collation) < 0)
6380  best = "9";
6381  suffixchar = *best;
6382  suffixcollation = collation;
6383  }
6384 
6385  /* And build the string to compare to */
6386  cmptxt = (text *) palloc(VARHDRSZ + len + 1);
6387  SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
6388  memcpy(VARDATA(cmptxt), workstr, len);
6389  *(VARDATA(cmptxt) + len) = suffixchar;
6390  cmpstr = PointerGetDatum(cmptxt);
6391  }
6392  }
6393 
6394  /* Select appropriate character-incrementer function */
6395  if (datatype == BYTEAOID)
6396  charinc = byte_increment;
6397  else
6399 
6400  /* And search ... */
6401  while (len > 0)
6402  {
6403  int charlen;
6404  unsigned char *lastchar;
6405 
6406  /* Identify the last character --- for bytea, just the last byte */
6407  if (datatype == BYTEAOID)
6408  charlen = 1;
6409  else
6410  charlen = len - pg_mbcliplen(workstr, len, len - 1);
6411  lastchar = (unsigned char *) (workstr + len - charlen);
6412 
6413  /*
6414  * Try to generate a larger string by incrementing the last character
6415  * (for BYTEA, we treat each byte as a character).
6416  *
6417  * Note: the incrementer function is expected to return true if it's
6418  * generated a valid-per-the-encoding new character, otherwise false.
6419  * The contents of the character on false return are unspecified.
6420  */
6421  while (charinc(lastchar, charlen))
6422  {
6423  Const *workstr_const;
6424 
6425  if (datatype == BYTEAOID)
6426  workstr_const = string_to_bytea_const(workstr, len);
6427  else
6428  workstr_const = string_to_const(workstr, datatype);
6429 
6430  if (DatumGetBool(FunctionCall2Coll(ltproc,
6431  collation,
6432  cmpstr,
6433  workstr_const->constvalue)))
6434  {
6435  /* Successfully made a string larger than cmpstr */
6436  if (cmptxt)
6437  pfree(cmptxt);
6438  pfree(workstr);
6439  return workstr_const;
6440  }
6441 
6442  /* No good, release unusable value and try again */
6443  pfree(DatumGetPointer(workstr_const->constvalue));
6444  pfree(workstr_const);
6445  }
6446 
6447  /*
6448  * No luck here, so truncate off the last character and try to
6449  * increment the next one.
6450  */
6451  len -= charlen;
6452  workstr[len] = '\0';
6453  }
6454 
6455  /* Failed... */
6456  if (cmptxt)
6457  pfree(cmptxt);
6458  pfree(workstr);
6459 
6460  return NULL;
6461 }
Datum constvalue
Definition: primnodes.h:197
#define VARDATA_ANY(PTR)
Definition: postgres.h:348
#define VARDATA(PTR)
Definition: postgres.h:302
#define PointerGetDatum(X)
Definition: postgres.h:541
#define VARHDRSZ
Definition: c.h:522
#define DatumGetByteaPP(X)
Definition: fmgr.h:260
static Const * string_to_bytea_const(const char *str, size_t str_len)
Definition: selfuncs.c:6532
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:590
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1133
unsigned int Oid
Definition: postgres_ext.h:31
static bool byte_increment(unsigned char *ptr, int len)
Definition: selfuncs.c:6276
static Const * string_to_const(const char *str, Oid datatype)
Definition: selfuncs.c:6489
Oid consttype
Definition: primnodes.h:193
void pfree(void *pointer)
Definition: mcxt.c:1031
char * Pointer
Definition: c.h:302
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1128
#define DatumGetCString(X)
Definition: postgres.h:551
int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
Definition: varlena.c:1381
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
#define DatumGetBool(X)
Definition: postgres.h:378
#define TextDatumGetCString(d)
Definition: builtins.h:96
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:699
#define DatumGetPointer(X)
Definition: postgres.h:534
bool(* mbcharacter_incrementer)(unsigned char *mbstr, int len)
Definition: pg_wchar.h:369
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:341
void * palloc(Size size)
Definition: mcxt.c:924
mbcharacter_incrementer pg_database_encoding_character_incrementer(void)
Definition: wchar.c:1842
Definition: c.h:516
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
Datum nameout(PG_FUNCTION_ARGS)
Definition: name.c:69

◆ mcv_selectivity()

double mcv_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Datum  constval,
bool  varonleft,
double *  sumcommonp 
)

Definition at line 639 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, DatumGetBool, FmgrInfo::fn_oid, free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), HeapTupleIsValid, i, InvalidOid, AttStatsSlot::numbers, AttStatsSlot::nvalues, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by ltreeparentsel(), networksel(), patternsel(), and scalarineqsel().

642 {
643  double mcv_selec,
644  sumcommon;
645  AttStatsSlot sslot;
646  int i;
647 
648  mcv_selec = 0.0;
649  sumcommon = 0.0;
650 
651  if (HeapTupleIsValid(vardata->statsTuple) &&
652  statistic_proc_security_check(vardata, opproc->fn_oid) &&
653  get_attstatsslot(&sslot, vardata->statsTuple,
654  STATISTIC_KIND_MCV, InvalidOid,
656  {
657  for (i = 0; i < sslot.nvalues; i++)
658  {
659  if (varonleft ?
661  DEFAULT_COLLATION_OID,
662  sslot.values[i],
663  constval)) :
665  DEFAULT_COLLATION_OID,
666  constval,
667  sslot.values[i])))
668  mcv_selec += sslot.numbers[i];
669  sumcommon += sslot.numbers[i];
670  }
671  free_attstatsslot(&sslot);
672  }
673 
674  *sumcommonp = sumcommon;
675  return mcv_selec;
676 }
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5154
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1133
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
float4 * numbers
Definition: lsyscache.h:52
#define DatumGetBool(X)
Definition: postgres.h:378
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ mergejoinscansel()

void mergejoinscansel ( PlannerInfo root,
Node clause,
Oid  opfamily,
int  strategy,
bool  nulls_first,
Selectivity leftstart,
Selectivity leftend,
Selectivity rightstart,
Selectivity rightend 
)

Definition at line 2995 of file selfuncs.c.

References Assert, BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, CLAMP_PROBABILITY, DEFAULT_INEQ_SEL, examine_variable(), get_leftop(), get_op_opfamily_properties(), get_opfamily_member(), get_rightop(), get_variable_range(), GETSTRUCT, HeapTupleIsValid, is_opclause, OidIsValid, ReleaseVariableStats, scalarineqsel(), and VariableStatData::statsTuple.

Referenced by cached_scansel().

2999 {
3000  Node *left,
3001  *right;
3002  VariableStatData leftvar,
3003  rightvar;
3004  int op_strategy;
3005  Oid op_lefttype;
3006  Oid op_righttype;
3007  Oid opno,
3008  lsortop,
3009  rsortop,
3010  lstatop,
3011  rstatop,
3012  ltop,
3013  leop,
3014  revltop,
3015  revleop;
3016  bool isgt;
3017  Datum leftmin,
3018  leftmax,
3019  rightmin,
3020  rightmax;
3021  double selec;
3022 
3023  /* Set default results if we can't figure anything out. */
3024  /* XXX should default "start" fraction be a bit more than 0? */
3025  *leftstart = *rightstart = 0.0;
3026  *leftend = *rightend = 1.0;
3027 
3028  /* Deconstruct the merge clause */
3029  if (!is_opclause(clause))
3030  return; /* shouldn't happen */
3031  opno = ((OpExpr *) clause)->opno;
3032  left = get_leftop((Expr *) clause);
3033  right = get_rightop((Expr *) clause);
3034  if (!right)
3035  return; /* shouldn't happen */
3036 
3037  /* Look for stats for the inputs */
3038  examine_variable(root, left, 0, &leftvar);
3039  examine_variable(root, right, 0, &rightvar);
3040 
3041  /* Extract the operator's declared left/right datatypes */
3042  get_op_opfamily_properties(opno, opfamily, false,
3043  &op_strategy,
3044  &op_lefttype,
3045  &op_righttype);
3046  Assert(op_strategy == BTEqualStrategyNumber);
3047 
3048  /*
3049  * Look up the various operators we need. If we don't find them all, it
3050  * probably means the opfamily is broken, but we just fail silently.
3051  *
3052  * Note: we expect that pg_statistic histograms will be sorted by the '<'
3053  * operator, regardless of which sort direction we are considering.
3054  */
3055  switch (strategy)
3056  {
3057  case BTLessStrategyNumber:
3058  isgt = false;
3059  if (op_lefttype == op_righttype)
3060  {
3061  /* easy case */
3062  ltop = get_opfamily_member(opfamily,
3063  op_lefttype, op_righttype,
3065  leop = get_opfamily_member(opfamily,
3066  op_lefttype, op_righttype,
3068  lsortop = ltop;
3069  rsortop = ltop;
3070  lstatop = lsortop;
3071  rstatop = rsortop;
3072  revltop = ltop;
3073  revleop = leop;
3074  }
3075  else
3076  {
3077  ltop = get_opfamily_member(opfamily,
3078  op_lefttype, op_righttype,
3080  leop = get_opfamily_member(opfamily,
3081  op_lefttype, op_righttype,
3083  lsortop = get_opfamily_member(opfamily,
3084  op_lefttype, op_lefttype,
3086  rsortop = get_opfamily_member(opfamily,
3087  op_righttype, op_righttype,
3089  lstatop = lsortop;
3090  rstatop = rsortop;
3091  revltop = get_opfamily_member(opfamily,
3092  op_righttype, op_lefttype,
3094  revleop = get_opfamily_member(opfamily,
3095  op_righttype, op_lefttype,
3097  }
3098  break;
3100  /* descending-order case */
3101  isgt = true;
3102  if (op_lefttype == op_righttype)
3103  {
3104  /* easy case */
3105  ltop = get_opfamily_member(opfamily,
3106  op_lefttype, op_righttype,
3108  leop = get_opfamily_member(opfamily,
3109  op_lefttype, op_righttype,
3111  lsortop = ltop;
3112  rsortop = ltop;
3113  lstatop = get_opfamily_member(opfamily,
3114  op_lefttype, op_lefttype,
3116  rstatop = lstatop;
3117  revltop = ltop;
3118  revleop = leop;
3119  }
3120  else
3121  {
3122  ltop = get_opfamily_member(opfamily,
3123  op_lefttype, op_righttype,
3125  leop = get_opfamily_member(opfamily,
3126  op_lefttype, op_righttype,
3128  lsortop = get_opfamily_member(opfamily,
3129  op_lefttype, op_lefttype,
3131  rsortop = get_opfamily_member(opfamily,
3132  op_righttype, op_righttype,
3134  lstatop = get_opfamily_member(opfamily,
3135  op_lefttype, op_lefttype,
3137  rstatop = get_opfamily_member(opfamily,
3138  op_righttype, op_righttype,
3140  revltop = get_opfamily_member(opfamily,
3141  op_righttype, op_lefttype,
3143  revleop = get_opfamily_member(opfamily,
3144  op_righttype, op_lefttype,
3146  }
3147  break;
3148  default:
3149  goto fail; /* shouldn't get here */
3150  }
3151 
3152  if (!OidIsValid(lsortop) ||
3153  !OidIsValid(rsortop) ||
3154  !OidIsValid(lstatop) ||
3155  !OidIsValid(rstatop) ||
3156  !OidIsValid(ltop) ||
3157  !OidIsValid(leop) ||
3158  !OidIsValid(revltop) ||
3159  !OidIsValid(revleop))
3160  goto fail; /* insufficient info in catalogs */
3161 
3162  /* Try to get ranges of both inputs */
3163  if (!isgt)
3164  {
3165  if (!get_variable_range(root, &leftvar, lstatop,
3166  &leftmin, &leftmax))
3167  goto fail; /* no range available from stats */
3168  if (!get_variable_range(root, &rightvar, rstatop,
3169  &rightmin, &rightmax))
3170  goto fail; /* no range available from stats */
3171  }
3172  else
3173  {
3174  /* need to swap the max and min */
3175  if (!get_variable_range(root, &leftvar, lstatop,
3176  &leftmax, &leftmin))
3177  goto fail; /* no range available from stats */
3178  if (!get_variable_range(root, &rightvar, rstatop,
3179  &rightmax, &rightmin))
3180  goto fail; /* no range available from stats */
3181  }
3182 
3183  /*
3184  * Now, the fraction of the left variable that will be scanned is the
3185  * fraction that's <= the right-side maximum value. But only believe
3186  * non-default estimates, else stick with our 1.0.
3187  */
3188  selec = scalarineqsel(root, leop, isgt, true, &leftvar,
3189  rightmax, op_righttype);
3190  if (selec != DEFAULT_INEQ_SEL)
3191  *leftend = selec;
3192 
3193  /* And similarly for the right variable. */
3194  selec = scalarineqsel(root, revleop, isgt, true, &rightvar,
3195  leftmax, op_lefttype);
3196  if (selec != DEFAULT_INEQ_SEL)
3197  *rightend = selec;
3198 
3199  /*
3200  * Only one of the two "end" fractions can really be less than 1.0;
3201  * believe the smaller estimate and reset the other one to exactly 1.0. If
3202  * we get exactly equal estimates (as can easily happen with self-joins),
3203  * believe neither.
3204  */
3205  if (*leftend > *rightend)
3206  *leftend = 1.0;
3207  else if (*leftend < *rightend)
3208  *rightend = 1.0;
3209  else
3210  *leftend = *rightend = 1.0;
3211 
3212  /*
3213  * Also, the fraction of the left variable that will be scanned before the
3214  * first join pair is found is the fraction that's < the right-side
3215  * minimum value. But only believe non-default estimates, else stick with
3216  * our own default.
3217  */
3218  selec = scalarineqsel(root, ltop, isgt, false, &leftvar,
3219  rightmin, op_righttype);
3220  if (selec != DEFAULT_INEQ_SEL)
3221  *leftstart = selec;
3222 
3223  /* And similarly for the right variable. */
3224  selec = scalarineqsel(root, revltop, isgt, false, &rightvar,
3225  leftmin, op_lefttype);
3226  if (selec != DEFAULT_INEQ_SEL)
3227  *rightstart = selec;
3228 
3229  /*
3230  * Only one of the two "start" fractions can really be more than zero;
3231  * believe the larger estimate and reset the other one to exactly 0.0. If
3232  * we get exactly equal estimates (as can easily happen with self-joins),
3233  * believe neither.
3234  */
3235  if (*leftstart < *rightstart)
3236  *leftstart = 0.0;
3237  else if (*leftstart > *rightstart)
3238  *rightstart = 0.0;
3239  else
3240  *leftstart = *rightstart = 0.0;
3241 
3242  /*
3243  * If the sort order is nulls-first, we're going to have to skip over any
3244  * nulls too. These would not have been counted by scalarineqsel, and we
3245  * can safely add in this fraction regardless of whether we believe
3246  * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3247  */
3248  if (nulls_first)
3249  {
3250  Form_pg_statistic stats;
3251 
3252  if (HeapTupleIsValid(leftvar.statsTuple))
3253  {
3254  stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3255  *leftstart += stats->stanullfrac;
3256  CLAMP_PROBABILITY(*leftstart);
3257  *leftend += stats->stanullfrac;
3258  CLAMP_PROBABILITY(*leftend);
3259  }
3260  if (HeapTupleIsValid(rightvar.statsTuple))
3261  {
3262  stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3263  *rightstart += stats->stanullfrac;
3264  CLAMP_PROBABILITY(*rightstart);
3265  *rightend += stats->stanullfrac;
3266  CLAMP_PROBABILITY(*rightend);
3267  }
3268  }
3269 
3270  /* Disbelieve start >= end, just in case that can happen */
3271  if (*leftstart >= *leftend)
3272  {
3273  *leftstart = 0.0;
3274  *leftend = 1.0;
3275  }
3276  if (*rightstart >= *rightend)
3277  {
3278  *rightstart = 0.0;
3279  *rightend = 1.0;
3280  }
3281 
3282 fail:
3283  ReleaseVariableStats(leftvar);
3284  ReleaseVariableStats(rightvar);
3285 }
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
HeapTuple statsTuple
Definition: selfuncs.h:71
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Definition: nodes.h:517
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define OidIsValid(objectId)
Definition: c.h:605
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define is_opclause(clause)
Definition: clauses.h:20
Node * get_leftop(const Expr *clause)
Definition: clauses.c:200
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
uintptr_t Datum
Definition: postgres.h:367
static double scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq, VariableStatData *vardata, Datum constval, Oid consttype)
Definition: selfuncs.c:564
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
#define Assert(condition)
Definition: c.h:699
Node * get_rightop(const Expr *clause)
Definition: clauses.c:217
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
void get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op, int *strategy, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:133
static bool get_variable_range(PlannerInfo *root, VariableStatData *vardata, Oid sortop, Datum *min, Datum *max)
Definition: selfuncs.c:5316
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32

◆ nulltestsel()

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

Definition at line 1751 of file selfuncs.c.

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

Referenced by clause_selectivity(), and clauselist_selectivity().

1753 {
1754  VariableStatData vardata;
1755  double selec;
1756 
1757  examine_variable(root, arg, varRelid, &vardata);
1758 
1759  if (HeapTupleIsValid(vardata.statsTuple))
1760  {
1761  Form_pg_statistic stats;
1762  double freq_null;
1763 
1764  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1765  freq_null = stats->stanullfrac;
1766 
1767  switch (nulltesttype)
1768  {
1769  case IS_NULL:
1770 
1771  /*
1772  * Use freq_null directly.
1773  */
1774  selec = freq_null;
1775  break;
1776  case IS_NOT_NULL:
1777 
1778  /*
1779  * Select not unknown (not null) values. Calculate from
1780  * freq_null.
1781  */
1782  selec = 1.0 - freq_null;
1783  break;
1784  default:
1785  elog(ERROR, "unrecognized nulltesttype: %d",
1786  (int) nulltesttype);
1787  return (Selectivity) 0; /* keep compiler quiet */
1788  }
1789  }
1790  else
1791  {
1792  /*
1793  * No ANALYZE stats available, so make a guess
1794  */
1795  switch (nulltesttype)
1796  {
1797  case IS_NULL:
1798  selec = DEFAULT_UNK_SEL;
1799  break;
1800  case IS_NOT_NULL:
1801  selec = DEFAULT_NOT_UNK_SEL;
1802  break;
1803  default:
1804  elog(ERROR, "unrecognized nulltesttype: %d",
1805  (int) nulltesttype);
1806  return (Selectivity) 0; /* keep compiler quiet */
1807  }
1808  }
1809 
1810  ReleaseVariableStats(vardata);
1811 
1812  /* result should be in range, but make sure... */
1813  CLAMP_PROBABILITY(selec);
1814 
1815  return (Selectivity) selec;
1816 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
HeapTuple statsTuple
Definition: selfuncs.h:71
double Selectivity
Definition: nodes.h:647
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:50
#define ERROR
Definition: elog.h:43
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:49
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4776
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog
Definition: elog.h:219

◆ pattern_fixed_prefix()

Pattern_Prefix_Status pattern_fixed_prefix ( Const patt,
Pattern_Type  ptype,
Oid  collation,
Const **  prefix,
Selectivity rest_selec 
)

Definition at line 5946 of file selfuncs.c.

References Const::constbyval, Const::constcollid, Const::constisnull, Const::constlen, Const::consttype, Const::consttypmod, Const::constvalue, datumCopy(), elog, ERROR, like_fixed_prefix(), makeConst(), Pattern_Prefix_None, Pattern_Prefix_Partial, Pattern_Type_Like, Pattern_Type_Like_IC, Pattern_Type_Prefix, Pattern_Type_Regex, Pattern_Type_Regex_IC, and regex_fixed_prefix().

Referenced by expand_indexqual_opclause(), match_special_index_operator(), and patternsel().

5948 {
5949  Pattern_Prefix_Status result;
5950 
5951  switch (ptype)
5952  {
5953  case Pattern_Type_Like:
5954  result = like_fixed_prefix(patt, false, collation,
5955  prefix, rest_selec);
5956  break;
5957  case Pattern_Type_Like_IC:
5958  result = like_fixed_prefix(patt, true, collation,
5959  prefix, rest_selec);
5960  break;
5961  case Pattern_Type_Regex:
5962  result = regex_fixed_prefix(patt, false, collation,
5963  prefix, rest_selec);
5964  break;
5965  case Pattern_Type_Regex_IC:
5966  result = regex_fixed_prefix(patt, true, collation,
5967  prefix, rest_selec);
5968  break;
5969  case Pattern_Type_Prefix:
5970  /* Prefix type work is trivial. */
5971  result = Pattern_Prefix_Partial;
5972  *rest_selec = 1.0; /* all */
5973  *prefix = makeConst(patt->consttype,
5974  patt->consttypmod,
5975  patt->constcollid,
5976  patt->constlen,
5977  datumCopy(patt->constvalue,
5978  patt->constbyval,
5979  patt->constlen),
5980  patt->constisnull,
5981  patt->constbyval);
5982  break;
5983  default:
5984  elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5985  result = Pattern_Prefix_None; /* keep compiler quiet */
5986  break;
5987  }
5988  return result;
5989 }
Datum constvalue
Definition: primnodes.h:197
static Pattern_Prefix_Status regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5878
bool constbyval
Definition: primnodes.h:200
static Pattern_Prefix_Status like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5770
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:298
int constlen
Definition: primnodes.h:196
Oid consttype
Definition: primnodes.h:193
#define ERROR
Definition: elog.h:43
Oid constcollid
Definition: primnodes.h:195
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
int32 consttypmod
Definition: primnodes.h:194
#define elog
Definition: elog.h:219
bool constisnull
Definition: primnodes.h:198
Pattern_Prefix_Status
Definition: selfuncs.h:97

◆ rowcomparesel()

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

Definition at line 2217 of file selfuncs.c.

References RowCompareExpr::inputcollids, join_selectivity(), RowCompareExpr::largs, linitial, linitial_oid, list_make2, NumRelids(), RowCompareExpr::opnos, RowCompareExpr::rargs, restriction_selectivity(), and s1.

Referenced by clause_selectivity().

2220 {
2221  Selectivity s1;
2222  Oid opno = linitial_oid(clause->opnos);
2223  Oid inputcollid = linitial_oid(clause->inputcollids);
2224  List *opargs;
2225  bool is_join_clause;
2226 
2227  /* Build equivalent arg list for single operator */
2228  opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2229 
2230  /*
2231  * Decide if it's a join clause. This should match clausesel.c's
2232  * treat_as_join_clause(), except that we intentionally consider only the
2233  * leading columns and not the rest of the clause.
2234  */
2235  if (varRelid != 0)
2236  {
2237  /*
2238  * Caller is forcing restriction mode (eg, because we are examining an
2239  * inner indexscan qual).
2240  */
2241  is_join_clause = false;
2242  }
2243  else if (sjinfo == NULL)
2244  {
2245  /*
2246  * It must be a restriction clause, since it's being evaluated at a
2247  * scan node.
2248  */
2249  is_join_clause = false;
2250  }
2251  else
2252  {
2253  /*
2254  * Otherwise, it's a join if there's more than one relation used.
2255  */
2256  is_join_clause = (NumRelids((Node *) opargs) > 1);
2257  }
2258 
2259  if (is_join_clause)
2260  {
2261  /* Estimate selectivity for a join clause. */
2262  s1 = join_selectivity(root, opno,
2263  opargs,
2264  inputcollid,
2265  jointype,
2266  sjinfo);
2267  }
2268  else
2269  {
2270  /* Estimate selectivity for a restriction clause. */
2271  s1 = restriction_selectivity(root, opno,
2272  opargs,
2273  inputcollid,
2274  varRelid);
2275  }
2276 
2277  return s1;
2278 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1741
Definition: nodes.h:517
double Selectivity
Definition: nodes.h:647
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial(l)
Definition: pg_list.h:111
char * s1
#define linitial_oid(l)
Definition: pg_list.h:113
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1778
List * inputcollids
Definition: primnodes.h:1042
Definition: pg_list.h:45
int NumRelids(Node *clause)
Definition: clauses.c:2273

◆ scalararraysel()

Selectivity scalararraysel ( PlannerInfo root,
ScalarArrayOpExpr clause,
bool  is_join_clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1860 of file selfuncs.c.

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

Referenced by clause_selectivity().

1866 {
1867  Oid operator = clause->opno;
1868  bool useOr = clause->useOr;
1869  bool isEquality = false;
1870  bool isInequality = false;
1871  Node *leftop;
1872  Node *rightop;
1873  Oid nominal_element_type;
1874  Oid nominal_element_collation;
1875  TypeCacheEntry *typentry;
1876  RegProcedure oprsel;
1877  FmgrInfo oprselproc;
1878  Selectivity s1;
1879  Selectivity s1disjoint;
1880 
1881  /* First, deconstruct the expression */
1882  Assert(list_length(clause->args) == 2);
1883  leftop = (Node *) linitial(clause->args);
1884  rightop = (Node *) lsecond(clause->args);
1885 
1886  /* aggressively reduce both sides to constants */
1887  leftop = estimate_expression_value(root, leftop);
1888  rightop = estimate_expression_value(root, rightop);
1889 
1890  /* get nominal (after relabeling) element type of rightop */
1891  nominal_element_type = get_base_element_type(exprType(rightop));
1892  if (!OidIsValid(nominal_element_type))
1893  return (Selectivity) 0.5; /* probably shouldn't happen */
1894  /* get nominal collation, too, for generating constants */
1895  nominal_element_collation = exprCollation(rightop);
1896 
1897  /* look through any binary-compatible relabeling of rightop */
1898  rightop = strip_array_coercion(rightop);
1899 
1900  /*
1901  * Detect whether the operator is the default equality or inequality
1902  * operator of the array element type.
1903  */
1904  typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1905  if (OidIsValid(typentry->eq_opr))
1906  {
1907  if (operator == typentry->eq_opr)
1908  isEquality = true;
1909  else if (get_negator(operator) == typentry->eq_opr)
1910  isInequality = true;
1911  }
1912 
1913  /*
1914  * If it is equality or inequality, we might be able to estimate this as a
1915  * form of array containment; for instance "const = ANY(column)" can be
1916  * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1917  * that, and returns the selectivity estimate if successful, or -1 if not.
1918  */
1919  if ((isEquality || isInequality) && !is_join_clause)
1920  {
1921  s1 = scalararraysel_containment(root, leftop, rightop,
1922  nominal_element_type,
1923  isEquality, useOr, varRelid);
1924  if (s1 >= 0.0)
1925  return s1;
1926  }
1927 
1928  /*
1929  * Look up the underlying operator's selectivity estimator. Punt if it
1930  * hasn't got one.
1931  */
1932  if (is_join_clause)
1933  oprsel = get_oprjoin(operator);
1934  else
1935  oprsel = get_oprrest(operator);
1936  if (!oprsel)
1937  return (Selectivity) 0.5;
1938  fmgr_info(oprsel, &oprselproc);
1939 
1940  /*
1941  * In the array-containment check above, we must only believe that an
1942  * operator is equality or inequality if it is the default btree equality
1943  * operator (or its negator) for the element type, since those are the
1944  * operators that array containment will use. But in what follows, we can
1945  * be a little laxer, and also believe that any operators using eqsel() or
1946  * neqsel() as selectivity estimator act like equality or inequality.
1947  */
1948  if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1949  isEquality = true;
1950  else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1951  isInequality = true;
1952 
1953  /*
1954  * We consider three cases:
1955  *
1956  * 1. rightop is an Array constant: deconstruct the array, apply the
1957  * operator's selectivity function for each array element, and merge the
1958  * results in the same way that clausesel.c does for AND/OR combinations.
1959  *
1960  * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1961  * function for each element of the ARRAY[] construct, and merge.
1962  *
1963  * 3. otherwise, make a guess ...
1964  */
1965  if (rightop && IsA(rightop, Const))
1966  {
1967  Datum arraydatum = ((Const *) rightop)->constvalue;
1968  bool arrayisnull = ((Const *) rightop)->constisnull;
1969  ArrayType *arrayval;
1970  int16 elmlen;
1971  bool elmbyval;
1972  char elmalign;
1973  int num_elems;
1974  Datum *elem_values;
1975  bool *elem_nulls;
1976  int i;
1977 
1978  if (arrayisnull) /* qual can't succeed if null array */
1979  return (Selectivity) 0.0;
1980  arrayval = DatumGetArrayTypeP(arraydatum);
1982  &elmlen, &elmbyval, &elmalign);
1983  deconstruct_array(arrayval,
1984  ARR_ELEMTYPE(arrayval),
1985  elmlen, elmbyval, elmalign,
1986  &elem_values, &elem_nulls, &num_elems);
1987 
1988  /*
1989  * For generic operators, we assume the probability of success is
1990  * independent for each array element. But for "= ANY" or "<> ALL",
1991  * if the array elements are distinct (which'd typically be the case)
1992  * then the probabilities are disjoint, and we should just sum them.
1993  *
1994  * If we were being really tense we would try to confirm that the
1995  * elements are all distinct, but that would be expensive and it
1996  * doesn't seem to be worth the cycles; it would amount to penalizing
1997  * well-written queries in favor of poorly-written ones. However, we
1998  * do protect ourselves a little bit by checking whether the
1999  * disjointness assumption leads to an impossible (out of range)
2000  * probability; if so, we fall back to the normal calculation.
2001  */
2002  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2003 
2004  for (i = 0; i < num_elems; i++)
2005  {
2006  List *args;
2007  Selectivity s2;
2008 
2009  args = list_make2(leftop,
2010  makeConst(nominal_element_type,
2011  -1,
2012  nominal_element_collation,
2013  elmlen,
2014  elem_values[i],
2015  elem_nulls[i],
2016  elmbyval));
2017  if (is_join_clause)
2018  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2019  clause->inputcollid,
2020  PointerGetDatum(root),
2021  ObjectIdGetDatum(operator),
2022  PointerGetDatum(args),
2023  Int16GetDatum(jointype),
2024  PointerGetDatum(sjinfo)));
2025  else
2026  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2027  clause->inputcollid,
2028  PointerGetDatum(root),
2029  ObjectIdGetDatum(operator),
2030  PointerGetDatum(args),
2031  Int32GetDatum(varRelid)));
2032 
2033  if (useOr)
2034  {
2035  s1 = s1 + s2 - s1 * s2;
2036  if (isEquality)
2037  s1disjoint += s2;
2038  }
2039  else
2040  {
2041  s1 = s1 * s2;
2042  if (isInequality)
2043  s1disjoint += s2 - 1.0;
2044  }
2045  }
2046 
2047  /* accept disjoint-probability estimate if in range */
2048  if ((useOr ? isEquality : isInequality) &&
2049  s1disjoint >= 0.0 && s1disjoint <= 1.0)
2050  s1 = s1disjoint;
2051  }
2052  else if (rightop && IsA(rightop, ArrayExpr) &&
2053  !((ArrayExpr *) rightop)->multidims)
2054  {
2055  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2056  int16 elmlen;
2057  bool elmbyval;
2058  ListCell *l;
2059 
2060  get_typlenbyval(arrayexpr->element_typeid,
2061  &elmlen, &elmbyval);
2062 
2063  /*
2064  * We use the assumption of disjoint probabilities here too, although
2065  * the odds of equal array elements are rather higher if the elements
2066  * are not all constants (which they won't be, else constant folding
2067  * would have reduced the ArrayExpr to a Const). In this path it's
2068  * critical to have the sanity check on the s1disjoint estimate.
2069  */
2070  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2071 
2072  foreach(l, arrayexpr->elements)
2073  {
2074  Node *elem = (Node *) lfirst(l);
2075  List *args;
2076  Selectivity s2;
2077 
2078  /*
2079  * Theoretically, if elem isn't of nominal_element_type we should
2080  * insert a RelabelType, but it seems unlikely that any operator
2081  * estimation function would really care ...
2082  */
2083  args = list_make2(leftop, elem);
2084  if (is_join_clause)
2085  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2086  clause->inputcollid,
2087  PointerGetDatum(root),
2088  ObjectIdGetDatum(operator),
2089  PointerGetDatum(args),
2090  Int16GetDatum(jointype),
2091  PointerGetDatum(sjinfo)));
2092  else
2093  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2094  clause->inputcollid,
2095  PointerGetDatum(root),
2096  ObjectIdGetDatum(operator),
2097  PointerGetDatum(args),
2098  Int32GetDatum(varRelid)));
2099 
2100  if (useOr)
2101  {
2102  s1 = s1 + s2 - s1 * s2;
2103  if (isEquality)
2104  s1disjoint += s2;
2105  }
2106  else
2107  {
2108  s1 = s1 * s2;
2109  if (isInequality)
2110  s1disjoint += s2 - 1.0;
2111  }
2112  }
2113 
2114  /* accept disjoint-probability estimate if in range */
2115  if ((useOr ? isEquality : isInequality) &&
2116  s1disjoint >= 0.0 && s1disjoint <= 1.0)
2117  s1 = s1disjoint;
2118  }
2119  else
2120  {
2121  CaseTestExpr *dummyexpr;
2122  List *args;
2123  Selectivity s2;
2124  int i;
2125 
2126  /*
2127  * We need a dummy rightop to pass to the operator selectivity
2128  * routine. It can be pretty much anything that doesn't look like a
2129  * constant; CaseTestExpr is a convenient choice.
2130  */
2131  dummyexpr = makeNode(CaseTestExpr);
2132  dummyexpr->typeId = nominal_element_type;
2133  dummyexpr->typeMod = -1;
2134  dummyexpr->collation = clause->inputcollid;
2135  args = list_make2(leftop, dummyexpr);
2136  if (is_join_clause)
2137  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2138  clause->inputcollid,
2139  PointerGetDatum(root),
2140  ObjectIdGetDatum(operator),
2141  PointerGetDatum(args),
2142  Int16GetDatum(jointype),
2143  PointerGetDatum(sjinfo)));
2144  else
2145  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2146  clause->inputcollid,
2147  PointerGetDatum(root),
2148  ObjectIdGetDatum(operator),
2149  PointerGetDatum(args),
2150  Int32GetDatum(varRelid)));
2151  s1 = useOr ? 0.0 : 1.0;
2152 
2153  /*
2154  * Arbitrarily assume 10 elements in the eventual array value (see
2155  * also estimate_array_length). We don't risk an assumption of
2156  * disjoint probabilities here.
2157  */
2158  for (i = 0; i < 10; i++)
2159  {
2160  if (useOr)
2161  s1 = s1 + s2 - s1 * s2;
2162  else
2163  s1 = s1 * s2;
2164  }
2165  }
2166 
2167  /* result should be in range, but make sure... */
2168  CLAMP_PROBABILITY(s1);
2169 
2170  return s1;
2171 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
signed short int16
Definition: c.h:312
Definition: fmgr.h:56
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1370
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2493
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2025
#define PointerGetDatum(X)
Definition: postgres.h:541
Datum FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1207
regproc RegProcedure
Definition: c.h:472
#define Int16GetDatum(X)
Definition: postgres.h:436
Definition: nodes.h:517
#define TYPECACHE_EQ_OPR
Definition: typcache.h:127
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1180
double Selectivity
Definition: nodes.h:647
unsigned int Oid
Definition: postgres_ext.h:31
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:298
#define OidIsValid(objectId)
Definition: c.h:605
#define lsecond(l)
Definition: pg_list.h:116
int32 typeMod
Definition: primnodes.h:942
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
char * s1
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
List * elements
Definition: primnodes.h:960
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1346
char * s2
#define DatumGetFloat8(X)
Definition: postgres.h:713
uintptr_t Datum
Definition: postgres.h:367
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:321
#define makeNode(_type_)
Definition: nodes.h:565
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Selectivity scalararraysel_containment(PlannerInfo *root, Node *leftop, Node *rightop, Oid elemtype, bool isEquality, bool useOr, int varRelid)
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2005
Oid element_typeid
Definition: primnodes.h:959
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3449
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2575
#define Int32GetDatum(X)
Definition: postgres.h:464
int i
Oid get_negator(Oid opno)
Definition: lsyscache.c:1322
Definition: pg_list.h:45
#define ARR_ELEMTYPE(a)
Definition: array.h:277
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1827
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ scalararraysel_containment()

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

Definition at line 83 of file array_selfuncs.c.

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

Referenced by scalararraysel().

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

◆ statistic_proc_security_check()

bool statistic_proc_security_check ( VariableStatData vardata,
Oid  func_oid 
)

Definition at line 5154 of file selfuncs.c.

References VariableStatData::acl_ok, DEBUG2, ereport, errmsg_internal(), get_func_leakproof(), get_func_name(), and OidIsValid.

Referenced by calc_arraycontsel(), calc_hist_selectivity(), eqjoinsel_inner(), eqjoinsel_semi(), get_variable_range(), histogram_selectivity(), ineq_histogram_selectivity(), mcv_selectivity(), scalararraysel_containment(), and var_eq_const().

5155 {
5156  if (vardata->acl_ok)
5157  return true;
5158 
5159  if (!OidIsValid(func_oid))
5160  return false;
5161 
5162  if (get_func_leakproof(func_oid))
5163  return true;
5164 
5165  ereport(DEBUG2,
5166  (errmsg_internal("not using statistics because function \"%s\" is not leak-proof",
5167  get_func_name(func_oid))));
5168  return false;
5169 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1626
#define OidIsValid(objectId)
Definition: c.h:605
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1397
#define DEBUG2
Definition: elog.h:24
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827

Variable Documentation

◆ get_index_stats_hook

PGDLLIMPORT get_index_stats_hook_type get_index_stats_hook

Definition at line 156 of file selfuncs.c.

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

◆ get_relation_stats_hook

PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook

Definition at line 155 of file selfuncs.c.

Referenced by brincostestimate(), btcostestimate(), and examine_simple_variable().