PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 }
 
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

#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().

#define DEFAULT_MATCH_SEL   0.005

Definition at line 43 of file selfuncs.h.

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

#define DEFAULT_NOT_UNK_SEL   (1.0 - DEFAULT_UNK_SEL)

Definition at line 50 of file selfuncs.h.

Referenced by booltestsel(), and nulltestsel().

#define DEFAULT_NUM_DISTINCT   200

Definition at line 46 of file selfuncs.h.

Referenced by get_variable_numdistinct().

#define DEFAULT_RANGE_INEQ_SEL   0.005

Definition at line 40 of file selfuncs.h.

Referenced by clauselist_selectivity(), and default_range_selectivity().

#define DEFAULT_UNK_SEL   0.005

Definition at line 49 of file selfuncs.h.

Referenced by booltestsel(), and nulltestsel().

#define ReleaseVariableStats (   vardata)

Typedef Documentation

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

Definition at line 147 of file selfuncs.h.

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

Definition at line 142 of file selfuncs.h.

Enumeration Type Documentation

Enumerator
Pattern_Prefix_None 
Pattern_Prefix_Partial 
Pattern_Prefix_Exact 

Definition at line 94 of file selfuncs.h.

Enumerator
Pattern_Type_Like 
Pattern_Type_Like_IC 
Pattern_Type_Regex 
Pattern_Type_Regex_IC 

Definition at line 88 of file selfuncs.h.

Function Documentation

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

Definition at line 1581 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, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by clause_selectivity().

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

Definition at line 1542 of file selfuncs.c.

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

Referenced by clause_selectivity().

1543 {
1544  VariableStatData vardata;
1545  double selec;
1546 
1547  examine_variable(root, arg, varRelid, &vardata);
1548  if (HeapTupleIsValid(vardata.statsTuple))
1549  {
1550  /*
1551  * A boolean variable V is equivalent to the clause V = 't', so we
1552  * compute the selectivity as if that is what we have.
1553  */
1554  selec = var_eq_const(&vardata, BooleanEqualOperator,
1555  BoolGetDatum(true), false, true, false);
1556  }
1557  else if (is_funcclause(arg))
1558  {
1559  /*
1560  * If we have no stats and it's a function call, estimate 0.3333333.
1561  * This seems a pretty unprincipled choice, but Postgres has been
1562  * using that estimate for function calls since 1992. The hoariness
1563  * of this behavior suggests that we should not be in too much hurry
1564  * to use another value.
1565  */
1566  selec = 0.3333333;
1567  }
1568  else
1569  {
1570  /* Otherwise, the default estimate is 0.5 */
1571  selec = 0.5;
1572  }
1573  ReleaseVariableStats(vardata);
1574  return selec;
1575 }
HeapTuple statsTuple
Definition: selfuncs.h:71
#define is_funcclause(clause)
Definition: clauses.h:21
#define BooleanEqualOperator
Definition: pg_operator.h:114
static double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:297
#define BoolGetDatum(X)
Definition: postgres.h:408
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
List* deconstruct_indexquals ( IndexPath path)

Definition at line 6425 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().

6426 {
6427  List *result = NIL;
6428  IndexOptInfo *index = path->indexinfo;
6429  ListCell *lcc,
6430  *lci;
6431 
6432  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6433  {
6434  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6435  int indexcol = lfirst_int(lci);
6436  Expr *clause;
6437  Node *leftop,
6438  *rightop;
6439  IndexQualInfo *qinfo;
6440 
6441  clause = rinfo->clause;
6442 
6443  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6444  qinfo->rinfo = rinfo;
6445  qinfo->indexcol = indexcol;
6446 
6447  if (IsA(clause, OpExpr))
6448  {
6449  qinfo->clause_op = ((OpExpr *) clause)->opno;
6450  leftop = get_leftop(clause);
6451  rightop = get_rightop(clause);
6452  if (match_index_to_operand(leftop, indexcol, index))
6453  {
6454  qinfo->varonleft = true;
6455  qinfo->other_operand = rightop;
6456  }
6457  else
6458  {
6459  Assert(match_index_to_operand(rightop, indexcol, index));
6460  qinfo->varonleft = false;
6461  qinfo->other_operand = leftop;
6462  }
6463  }
6464  else if (IsA(clause, RowCompareExpr))
6465  {
6466  RowCompareExpr *rc = (RowCompareExpr *) clause;
6467 
6468  qinfo->clause_op = linitial_oid(rc->opnos);
6469  /* Examine only first columns to determine left/right sides */
6471  indexcol, index))
6472  {
6473  qinfo->varonleft = true;
6474  qinfo->other_operand = (Node *) rc->rargs;
6475  }
6476  else
6477  {
6479  indexcol, index));
6480  qinfo->varonleft = false;
6481  qinfo->other_operand = (Node *) rc->largs;
6482  }
6483  }
6484  else if (IsA(clause, ScalarArrayOpExpr))
6485  {
6486  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6487 
6488  qinfo->clause_op = saop->opno;
6489  /* index column is always on the left in this case */
6491  indexcol, index));
6492  qinfo->varonleft = true;
6493  qinfo->other_operand = (Node *) lsecond(saop->args);
6494  }
6495  else if (IsA(clause, NullTest))
6496  {
6497  qinfo->clause_op = InvalidOid;
6498  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6499  indexcol, index));
6500  qinfo->varonleft = true;
6501  qinfo->other_operand = NULL;
6502  }
6503  else
6504  {
6505  elog(ERROR, "unsupported indexqual type: %d",
6506  (int) nodeTag(clause));
6507  }
6508 
6509  result = lappend(result, qinfo);
6510  }
6511  return result;
6512 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
IndexOptInfo * indexinfo
Definition: relation.h:1119
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3180
Definition: nodes.h:510
RestrictInfo * rinfo
Definition: selfuncs.h:106
#define lsecond(l)
Definition: pg_list.h:116
Definition: type.h:89
List * indexquals
Definition: relation.h:1121
#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:199
#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:1835
bool varonleft
Definition: selfuncs.h:108
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:681
#define linitial_oid(l)
Definition: pg_list.h:113
#define nodeTag(nodeptr)
Definition: nodes.h:515
Node * get_rightop(const Expr *clause)
Definition: clauses.c:216
List * indexqualcols
Definition: relation.h:1122
void * palloc(Size size)
Definition: mcxt.c:848
Node * other_operand
Definition: selfuncs.h:110
void * arg
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
int estimate_array_length ( Node arrayexpr)

Definition at line 2167 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().

2168 {
2169  /* look through any binary-compatible relabeling of arrayexpr */
2170  arrayexpr = strip_array_coercion(arrayexpr);
2171 
2172  if (arrayexpr && IsA(arrayexpr, Const))
2173  {
2174  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2175  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2176  ArrayType *arrayval;
2177 
2178  if (arrayisnull)
2179  return 0;
2180  arrayval = DatumGetArrayTypeP(arraydatum);
2181  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2182  }
2183  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2184  !((ArrayExpr *) arrayexpr)->multidims)
2185  {
2186  return list_length(((ArrayExpr *) arrayexpr)->elements);
2187  }
2188  else
2189  {
2190  /* default guess --- see also scalararraysel */
2191  return 10;
2192  }
2193 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
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:372
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:1815
#define DatumGetArrayTypeP(X)
Definition: array.h:246
void estimate_hash_bucket_stats ( PlannerInfo root,
Node hashkey,
double  nbuckets,
Selectivity mcv_freq,
Selectivity bucketsize_frac 
)

Definition at line 3696 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, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by final_cost_hashjoin().

3699 {
3700  VariableStatData vardata;
3701  double estfract,
3702  ndistinct,
3703  stanullfrac,
3704  avgfreq;
3705  bool isdefault;
3706  AttStatsSlot sslot;
3707 
3708  examine_variable(root, hashkey, 0, &vardata);
3709 
3710  /* Look up the frequency of the most common value, if available */
3711  *mcv_freq = 0.0;
3712 
3713  if (HeapTupleIsValid(vardata.statsTuple))
3714  {
3715  if (get_attstatsslot(&sslot, vardata.statsTuple,
3718  {
3719  /*
3720  * The first MCV stat is for the most common value.
3721  */
3722  if (sslot.nnumbers > 0)
3723  *mcv_freq = sslot.numbers[0];
3724  free_attstatsslot(&sslot);
3725  }
3726  }
3727 
3728  /* Get number of distinct values */
3729  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3730 
3731  /*
3732  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3733  * mcv_freq is known to be even higher than that, use it instead.
3734  */
3735  if (isdefault)
3736  {
3737  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3738  ReleaseVariableStats(vardata);
3739  return;
3740  }
3741 
3742  /* Get fraction that are null */
3743  if (HeapTupleIsValid(vardata.statsTuple))
3744  {
3745  Form_pg_statistic stats;
3746 
3747  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3748  stanullfrac = stats->stanullfrac;
3749  }
3750  else
3751  stanullfrac = 0.0;
3752 
3753  /* Compute avg freq of all distinct data values in raw relation */
3754  avgfreq = (1.0 - stanullfrac) / ndistinct;
3755 
3756  /*
3757  * Adjust ndistinct to account for restriction clauses. Observe we are
3758  * assuming that the data distribution is affected uniformly by the
3759  * restriction clauses!
3760  *
3761  * XXX Possibly better way, but much more expensive: multiply by
3762  * selectivity of rel's restriction clauses that mention the target Var.
3763  */
3764  if (vardata.rel && vardata.rel->tuples > 0)
3765  {
3766  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3767  ndistinct = clamp_row_est(ndistinct);
3768  }
3769 
3770  /*
3771  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3772  * number of buckets is less than the expected number of distinct values;
3773  * otherwise it is 1/ndistinct.
3774  */
3775  if (ndistinct > nbuckets)
3776  estfract = 1.0 / nbuckets;
3777  else
3778  estfract = 1.0 / ndistinct;
3779 
3780  /*
3781  * Adjust estimated bucketsize upward to account for skewed distribution.
3782  */
3783  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3784  estfract *= *mcv_freq / avgfreq;
3785 
3786  /*
3787  * Clamp bucketsize to sane range (the above adjustment could easily
3788  * produce an out-of-range result). We set the lower bound a little above
3789  * zero, since zero isn't a very sane result.
3790  */
3791  if (estfract < 1.0e-6)
3792  estfract = 1.0e-6;
3793  else if (estfract > 1.0)
3794  estfract = 1.0;
3795 
3796  *bucketsize_frac = (Selectivity) estfract;
3797 
3798  ReleaseVariableStats(vardata);
3799 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:625
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:640
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5070
float4 * numbers
Definition: lsyscache.h:52
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
double rows
Definition: relation.h:588
#define InvalidOid
Definition: postgres_ext.h:36
#define Max(x, y)
Definition: c.h:806
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
double clamp_row_est(double nrows)
Definition: costsize.c:174
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
double estimate_num_groups ( PlannerInfo root,
List groupExprs,
double  input_rows,
List **  pgset 
)

Definition at line 3360 of file selfuncs.c.

References add_unique_group_var(), Assert, BOOLOID, clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), 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().

3362 {
3363  List *varinfos = NIL;
3364  double numdistinct;
3365  ListCell *l;
3366  int i;
3367 
3368  /*
3369  * We don't ever want to return an estimate of zero groups, as that tends
3370  * to lead to division-by-zero and other unpleasantness. The input_rows
3371  * estimate is usually already at least 1, but clamp it just in case it
3372  * isn't.
3373  */
3374  input_rows = clamp_row_est(input_rows);
3375 
3376  /*
3377  * If no grouping columns, there's exactly one group. (This can't happen
3378  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3379  * corner cases with set operations.)
3380  */
3381  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3382  return 1.0;
3383 
3384  /*
3385  * Count groups derived from boolean grouping expressions. For other
3386  * expressions, find the unique Vars used, treating an expression as a Var
3387  * if we can find stats for it. For each one, record the statistical
3388  * estimate of number of distinct values (total in its table, without
3389  * regard for filtering).
3390  */
3391  numdistinct = 1.0;
3392 
3393  i = 0;
3394  foreach(l, groupExprs)
3395  {
3396  Node *groupexpr = (Node *) lfirst(l);
3397  VariableStatData vardata;
3398  List *varshere;
3399  ListCell *l2;
3400 
3401  /* is expression in this grouping set? */
3402  if (pgset && !list_member_int(*pgset, i++))
3403  continue;
3404 
3405  /* Short-circuit for expressions returning boolean */
3406  if (exprType(groupexpr) == BOOLOID)
3407  {
3408  numdistinct *= 2.0;
3409  continue;
3410  }
3411 
3412  /*
3413  * If examine_variable is able to deduce anything about the GROUP BY
3414  * expression, treat it as a single variable even if it's really more
3415  * complicated.
3416  */
3417  examine_variable(root, groupexpr, 0, &vardata);
3418  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3419  {
3420  varinfos = add_unique_group_var(root, varinfos,
3421  groupexpr, &vardata);
3422  ReleaseVariableStats(vardata);
3423  continue;
3424  }
3425  ReleaseVariableStats(vardata);
3426 
3427  /*
3428  * Else pull out the component Vars. Handle PlaceHolderVars by
3429  * recursing into their arguments (effectively assuming that the
3430  * PlaceHolderVar doesn't change the number of groups, which boils
3431  * down to ignoring the possible addition of nulls to the result set).
3432  */
3433  varshere = pull_var_clause(groupexpr,
3437 
3438  /*
3439  * If we find any variable-free GROUP BY item, then either it is a
3440  * constant (and we can ignore it) or it contains a volatile function;
3441  * in the latter case we punt and assume that each input row will
3442  * yield a distinct group.
3443  */
3444  if (varshere == NIL)
3445  {
3446  if (contain_volatile_functions(groupexpr))
3447  return input_rows;
3448  continue;
3449  }
3450 
3451  /*
3452  * Else add variables to varinfos list
3453  */
3454  foreach(l2, varshere)
3455  {
3456  Node *var = (Node *) lfirst(l2);
3457 
3458  examine_variable(root, var, 0, &vardata);
3459  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3460  ReleaseVariableStats(vardata);
3461  }
3462  }
3463 
3464  /*
3465  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3466  * list.
3467  */
3468  if (varinfos == NIL)
3469  {
3470  /* Guard against out-of-range answers */
3471  if (numdistinct > input_rows)
3472  numdistinct = input_rows;
3473  return numdistinct;
3474  }
3475 
3476  /*
3477  * Group Vars by relation and estimate total numdistinct.
3478  *
3479  * For each iteration of the outer loop, we process the frontmost Var in
3480  * varinfos, plus all other Vars in the same relation. We remove these
3481  * Vars from the newvarinfos list for the next iteration. This is the
3482  * easiest way to group Vars of same rel together.
3483  */
3484  do
3485  {
3486  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3487  RelOptInfo *rel = varinfo1->rel;
3488  double reldistinct = 1;
3489  double relmaxndistinct = reldistinct;
3490  int relvarcount = 0;
3491  List *newvarinfos = NIL;
3492  List *relvarinfos = NIL;
3493 
3494  /*
3495  * Split the list of varinfos in two - one for the current rel, one
3496  * for remaining Vars on other rels.
3497  */
3498  relvarinfos = lcons(varinfo1, relvarinfos);
3499  for_each_cell(l, lnext(list_head(varinfos)))
3500  {
3501  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3502 
3503  if (varinfo2->rel == varinfo1->rel)
3504  {
3505  /* varinfos on current rel */
3506  relvarinfos = lcons(varinfo2, relvarinfos);
3507  }
3508  else
3509  {
3510  /* not time to process varinfo2 yet */
3511  newvarinfos = lcons(varinfo2, newvarinfos);
3512  }
3513  }
3514 
3515  /*
3516  * Get the numdistinct estimate for the Vars of this rel. We
3517  * iteratively search for multivariate n-distinct with maximum number
3518  * of vars; assuming that each var group is independent of the others,
3519  * we multiply them together. Any remaining relvarinfos after no more
3520  * multivariate matches are found are assumed independent too, so
3521  * their individual ndistinct estimates are multiplied also.
3522  *
3523  * While iterating, count how many separate numdistinct values we
3524  * apply. We apply a fudge factor below, but only if we multiplied
3525  * more than one such values.
3526  */
3527  while (relvarinfos)
3528  {
3529  double mvndistinct;
3530 
3531  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3532  &mvndistinct))
3533  {
3534  reldistinct *= mvndistinct;
3535  if (relmaxndistinct < mvndistinct)
3536  relmaxndistinct = mvndistinct;
3537  relvarcount++;
3538  }
3539  else
3540  {
3541  foreach(l, relvarinfos)
3542  {
3543  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3544 
3545  reldistinct *= varinfo2->ndistinct;
3546  if (relmaxndistinct < varinfo2->ndistinct)
3547  relmaxndistinct = varinfo2->ndistinct;
3548  relvarcount++;
3549  }
3550 
3551  /* we're done with this relation */
3552  relvarinfos = NIL;
3553  }
3554  }
3555 
3556  /*
3557  * Sanity check --- don't divide by zero if empty relation.
3558  */
3559  Assert(IS_SIMPLE_REL(rel));
3560  if (rel->tuples > 0)
3561  {
3562  /*
3563  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3564  * fudge factor is because the Vars are probably correlated but we
3565  * don't know by how much. We should never clamp to less than the
3566  * largest ndistinct value for any of the Vars, though, since
3567  * there will surely be at least that many groups.
3568  */
3569  double clamp = rel->tuples;
3570 
3571  if (relvarcount > 1)
3572  {
3573  clamp *= 0.1;
3574  if (clamp < relmaxndistinct)
3575  {
3576  clamp = relmaxndistinct;
3577  /* for sanity in case some ndistinct is too large: */
3578  if (clamp > rel->tuples)
3579  clamp = rel->tuples;
3580  }
3581  }
3582  if (reldistinct > clamp)
3583  reldistinct = clamp;
3584 
3585  /*
3586  * Update the estimate based on the restriction selectivity,
3587  * guarding against division by zero when reldistinct is zero.
3588  * Also skip this if we know that we are returning all rows.
3589  */
3590  if (reldistinct > 0 && rel->rows < rel->tuples)
3591  {
3592  /*
3593  * Given a table containing N rows with n distinct values in a
3594  * uniform distribution, if we select p rows at random then
3595  * the expected number of distinct values selected is
3596  *
3597  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3598  *
3599  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3600  *
3601  * See "Approximating block accesses in database
3602  * organizations", S. B. Yao, Communications of the ACM,
3603  * Volume 20 Issue 4, April 1977 Pages 260-261.
3604  *
3605  * Alternatively, re-arranging the terms from the factorials,
3606  * this may be written as
3607  *
3608  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3609  *
3610  * This form of the formula is more efficient to compute in
3611  * the common case where p is larger than N/n. Additionally,
3612  * as pointed out by Dell'Era, if i << N for all terms in the
3613  * product, it can be approximated by
3614  *
3615  * n * (1 - ((N-p)/N)^(N/n))
3616  *
3617  * See "Expected distinct values when selecting from a bag
3618  * without replacement", Alberto Dell'Era,
3619  * http://www.adellera.it/investigations/distinct_balls/.
3620  *
3621  * The condition i << N is equivalent to n >> 1, so this is a
3622  * good approximation when the number of distinct values in
3623  * the table is large. It turns out that this formula also
3624  * works well even when n is small.
3625  */
3626  reldistinct *=
3627  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3628  rel->tuples / reldistinct));
3629  }
3630  reldistinct = clamp_row_est(reldistinct);
3631 
3632  /*
3633  * Update estimate of total distinct groups.
3634  */
3635  numdistinct *= reldistinct;
3636  }
3637 
3638  varinfos = newvarinfos;
3639  } while (varinfos != NIL);
3640 
3641  numdistinct = ceil(numdistinct);
3642 
3643  /* Guard against out-of-range answers */
3644  if (numdistinct > input_rows)
3645  numdistinct = input_rows;
3646  if (numdistinct < 1.0)
3647  numdistinct = 1.0;
3648 
3649  return numdistinct;
3650 }
#define NIL
Definition: pg_list.h:69
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
HeapTuple statsTuple
Definition: selfuncs.h:71
double tuples
Definition: relation.h:625
Definition: nodes.h:510
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
double ndistinct
Definition: selfuncs.c:3238
#define PVC_RECURSE_PLACEHOLDERS
Definition: var.h:26
#define IS_SIMPLE_REL(rel)
Definition: relation.h:561
#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:3820
#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:3242
double rows
Definition: relation.h:588
List * lcons(void *datum, List *list)
Definition: list.c:259
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
#define Assert(condition)
Definition: c.h:681
#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 BOOLOID
Definition: pg_type.h:288
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
int i
double clamp_row_est(double nrows)
Definition: costsize.c:174
Definition: pg_list.h:45
RelOptInfo * rel
Definition: selfuncs.c:3237
void examine_variable ( PlannerInfo root,
Node node,
int  varRelid,
VariableStatData vardata 
)

Definition at line 4663 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, 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().

4665 {
4666  Node *basenode;
4667  Relids varnos;
4668  RelOptInfo *onerel;
4669 
4670  /* Make sure we don't return dangling pointers in vardata */
4671  MemSet(vardata, 0, sizeof(VariableStatData));
4672 
4673  /* Save the exposed type of the expression */
4674  vardata->vartype = exprType(node);
4675 
4676  /* Look inside any binary-compatible relabeling */
4677 
4678  if (IsA(node, RelabelType))
4679  basenode = (Node *) ((RelabelType *) node)->arg;
4680  else
4681  basenode = node;
4682 
4683  /* Fast path for a simple Var */
4684 
4685  if (IsA(basenode, Var) &&
4686  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4687  {
4688  Var *var = (Var *) basenode;
4689 
4690  /* Set up result fields other than the stats tuple */
4691  vardata->var = basenode; /* return Var without relabeling */
4692  vardata->rel = find_base_rel(root, var->varno);
4693  vardata->atttype = var->vartype;
4694  vardata->atttypmod = var->vartypmod;
4695  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4696 
4697  /* Try to locate some stats */
4698  examine_simple_variable(root, var, vardata);
4699 
4700  return;
4701  }
4702 
4703  /*
4704  * Okay, it's a more complicated expression. Determine variable
4705  * membership. Note that when varRelid isn't zero, only vars of that
4706  * relation are considered "real" vars.
4707  */
4708  varnos = pull_varnos(basenode);
4709 
4710  onerel = NULL;
4711 
4712  switch (bms_membership(varnos))
4713  {
4714  case BMS_EMPTY_SET:
4715  /* No Vars at all ... must be pseudo-constant clause */
4716  break;
4717  case BMS_SINGLETON:
4718  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4719  {
4720  onerel = find_base_rel(root,
4721  (varRelid ? varRelid : bms_singleton_member(varnos)));
4722  vardata->rel = onerel;
4723  node = basenode; /* strip any relabeling */
4724  }
4725  /* else treat it as a constant */
4726  break;
4727  case BMS_MULTIPLE:
4728  if (varRelid == 0)
4729  {
4730  /* treat it as a variable of a join relation */
4731  vardata->rel = find_join_rel(root, varnos);
4732  node = basenode; /* strip any relabeling */
4733  }
4734  else if (bms_is_member(varRelid, varnos))
4735  {
4736  /* ignore the vars belonging to other relations */
4737  vardata->rel = find_base_rel(root, varRelid);
4738  node = basenode; /* strip any relabeling */
4739  /* note: no point in expressional-index search here */
4740  }
4741  /* else treat it as a constant */
4742  break;
4743  }
4744 
4745  bms_free(varnos);
4746 
4747  vardata->var = node;
4748  vardata->atttype = exprType(node);
4749  vardata->atttypmod = exprTypmod(node);
4750 
4751  if (onerel)
4752  {
4753  /*
4754  * We have an expression in vars of a single relation. Try to match
4755  * it to expressional index columns, in hopes of finding some
4756  * statistics.
4757  *
4758  * XXX it's conceivable that there are multiple matches with different
4759  * index opfamilies; if so, we need to pick one that matches the
4760  * operator we are estimating for. FIXME later.
4761  */
4762  ListCell *ilist;
4763 
4764  foreach(ilist, onerel->indexlist)
4765  {
4766  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4767  ListCell *indexpr_item;
4768  int pos;
4769 
4770  indexpr_item = list_head(index->indexprs);
4771  if (indexpr_item == NULL)
4772  continue; /* no expressions here... */
4773 
4774  for (pos = 0; pos < index->ncolumns; pos++)
4775  {
4776  if (index->indexkeys[pos] == 0)
4777  {
4778  Node *indexkey;
4779 
4780  if (indexpr_item == NULL)
4781  elog(ERROR, "too few entries in indexprs list");
4782  indexkey = (Node *) lfirst(indexpr_item);
4783  if (indexkey && IsA(indexkey, RelabelType))
4784  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4785  if (equal(node, indexkey))
4786  {
4787  /*
4788  * Found a match ... is it a unique index? Tests here
4789  * should match has_unique_index().
4790  */
4791  if (index->unique &&
4792  index->ncolumns == 1 &&
4793  (index->indpred == NIL || index->predOK))
4794  vardata->isunique = true;
4795 
4796  /*
4797  * Has it got stats? We only consider stats for
4798  * non-partial indexes, since partial indexes probably
4799  * don't reflect whole-relation statistics; the above
4800  * check for uniqueness is the only info we take from
4801  * a partial index.
4802  *
4803  * An index stats hook, however, must make its own
4804  * decisions about what to do with partial indexes.
4805  */
4806  if (get_index_stats_hook &&
4807  (*get_index_stats_hook) (root, index->indexoid,
4808  pos + 1, vardata))
4809  {
4810  /*
4811  * The hook took control of acquiring a stats
4812  * tuple. If it did supply a tuple, it'd better
4813  * have supplied a freefunc.
4814  */
4815  if (HeapTupleIsValid(vardata->statsTuple) &&
4816  !vardata->freefunc)
4817  elog(ERROR, "no function provided to release variable stats with");
4818  }
4819  else if (index->indpred == NIL)
4820  {
4821  vardata->statsTuple =
4823  ObjectIdGetDatum(index->indexoid),
4824  Int16GetDatum(pos + 1),
4825  BoolGetDatum(false));
4826  vardata->freefunc = ReleaseSysCache;
4827 
4828  if (HeapTupleIsValid(vardata->statsTuple))
4829  {
4830  /* Get index's table for permission check */
4831  RangeTblEntry *rte;
4832 
4833  rte = planner_rt_fetch(index->rel->relid, root);
4834  Assert(rte->rtekind == RTE_RELATION);
4835 
4836  /*
4837  * For simplicity, we insist on the whole
4838  * table being selectable, rather than trying
4839  * to identify which column(s) the index
4840  * depends on.
4841  */
4842  vardata->acl_ok =
4844  ACL_SELECT) == ACLCHECK_OK);
4845  }
4846  else
4847  {
4848  /* suppress leakproofness checks later */
4849  vardata->acl_ok = true;
4850  }
4851  }
4852  if (vardata->statsTuple)
4853  break;
4854  }
4855  indexpr_item = lnext(indexpr_item);
4856  }
4857  }
4858  if (vardata->statsTuple)
4859  break;
4860  }
4861  }
4862 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
bool predOK
Definition: relation.h:752
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:342
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2972
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:457
Definition: nodes.h:510
#define MemSet(start, val, len)
Definition: c.h:863
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4874
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:753
Definition: type.h:89
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1746
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:170
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:729
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: relation.h:613
Index varno
Definition: primnodes.h:166
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:634
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:73
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:526
List * indexlist
Definition: relation.h:622
#define BoolGetDatum(X)
Definition: postgres.h:408
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
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:4422
RTEKind rtekind
Definition: parsenodes.h:945
void * arg
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
List * indpred
Definition: relation.h:742
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
List * indexprs
Definition: relation.h:741
int32 vartypmod
Definition: primnodes.h:171
void genericcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
List qinfos,
GenericCosts costs 
)

Definition at line 6574 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().

6579 {
6580  IndexOptInfo *index = path->indexinfo;
6581  List *indexQuals = path->indexquals;
6582  List *indexOrderBys = path->indexorderbys;
6583  Cost indexStartupCost;
6584  Cost indexTotalCost;
6585  Selectivity indexSelectivity;
6586  double indexCorrelation;
6587  double numIndexPages;
6588  double numIndexTuples;
6589  double spc_random_page_cost;
6590  double num_sa_scans;
6591  double num_outer_scans;
6592  double num_scans;
6593  double qual_op_cost;
6594  double qual_arg_cost;
6595  List *selectivityQuals;
6596  ListCell *l;
6597 
6598  /*
6599  * If the index is partial, AND the index predicate with the explicitly
6600  * given indexquals to produce a more accurate idea of the index
6601  * selectivity.
6602  */
6603  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6604 
6605  /*
6606  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6607  * index scans that will be performed.
6608  */
6609  num_sa_scans = 1;
6610  foreach(l, indexQuals)
6611  {
6612  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6613 
6614  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6615  {
6616  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6617  int alength = estimate_array_length(lsecond(saop->args));
6618 
6619  if (alength > 1)
6620  num_sa_scans *= alength;
6621  }
6622  }
6623 
6624  /* Estimate the fraction of main-table tuples that will be visited */
6625  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6626  index->rel->relid,
6627  JOIN_INNER,
6628  NULL);
6629 
6630  /*
6631  * If caller didn't give us an estimate, estimate the number of index
6632  * tuples that will be visited. We do it in this rather peculiar-looking
6633  * way in order to get the right answer for partial indexes.
6634  */
6635  numIndexTuples = costs->numIndexTuples;
6636  if (numIndexTuples <= 0.0)
6637  {
6638  numIndexTuples = indexSelectivity * index->rel->tuples;
6639 
6640  /*
6641  * The above calculation counts all the tuples visited across all
6642  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6643  * average per-indexscan number, so adjust. This is a handy place to
6644  * round to integer, too. (If caller supplied tuple estimate, it's
6645  * responsible for handling these considerations.)
6646  */
6647  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6648  }
6649 
6650  /*
6651  * We can bound the number of tuples by the index size in any case. Also,
6652  * always estimate at least one tuple is touched, even when
6653  * indexSelectivity estimate is tiny.
6654  */
6655  if (numIndexTuples > index->tuples)
6656  numIndexTuples = index->tuples;
6657  if (numIndexTuples < 1.0)
6658  numIndexTuples = 1.0;
6659 
6660  /*
6661  * Estimate the number of index pages that will be retrieved.
6662  *
6663  * We use the simplistic method of taking a pro-rata fraction of the total
6664  * number of index pages. In effect, this counts only leaf pages and not
6665  * any overhead such as index metapage or upper tree levels.
6666  *
6667  * In practice access to upper index levels is often nearly free because
6668  * those tend to stay in cache under load; moreover, the cost involved is
6669  * highly dependent on index type. We therefore ignore such costs here
6670  * and leave it to the caller to add a suitable charge if needed.
6671  */
6672  if (index->pages > 1 && index->tuples > 1)
6673  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6674  else
6675  numIndexPages = 1.0;
6676 
6677  /* fetch estimated page cost for tablespace containing index */
6679  &spc_random_page_cost,
6680  NULL);
6681 
6682  /*
6683  * Now compute the disk access costs.
6684  *
6685  * The above calculations are all per-index-scan. However, if we are in a
6686  * nestloop inner scan, we can expect the scan to be repeated (with
6687  * different search keys) for each row of the outer relation. Likewise,
6688  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6689  * the potential for cache effects to reduce the number of disk page
6690  * fetches needed. We want to estimate the average per-scan I/O cost in
6691  * the presence of caching.
6692  *
6693  * We use the Mackert-Lohman formula (see costsize.c for details) to
6694  * estimate the total number of page fetches that occur. While this
6695  * wasn't what it was designed for, it seems a reasonable model anyway.
6696  * Note that we are counting pages not tuples anymore, so we take N = T =
6697  * index size, as if there were one "tuple" per page.
6698  */
6699  num_outer_scans = loop_count;
6700  num_scans = num_sa_scans * num_outer_scans;
6701 
6702  if (num_scans > 1)
6703  {
6704  double pages_fetched;
6705 
6706  /* total page fetches ignoring cache effects */
6707  pages_fetched = numIndexPages * num_scans;
6708 
6709  /* use Mackert and Lohman formula to adjust for cache effects */
6710  pages_fetched = index_pages_fetched(pages_fetched,
6711  index->pages,
6712  (double) index->pages,
6713  root);
6714 
6715  /*
6716  * Now compute the total disk access cost, and then report a pro-rated
6717  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6718  * since that's internal to the indexscan.)
6719  */
6720  indexTotalCost = (pages_fetched * spc_random_page_cost)
6721  / num_outer_scans;
6722  }
6723  else
6724  {
6725  /*
6726  * For a single index scan, we just charge spc_random_page_cost per
6727  * page touched.
6728  */
6729  indexTotalCost = numIndexPages * spc_random_page_cost;
6730  }
6731 
6732  /*
6733  * CPU cost: any complex expressions in the indexquals will need to be
6734  * evaluated once at the start of the scan to reduce them to runtime keys
6735  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6736  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6737  * indexqual operator. Because we have numIndexTuples as a per-scan
6738  * number, we have to multiply by num_sa_scans to get the correct result
6739  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6740  * ORDER BY expressions.
6741  *
6742  * Note: this neglects the possible costs of rechecking lossy operators.
6743  * Detecting that that might be needed seems more expensive than it's
6744  * worth, though, considering all the other inaccuracies here ...
6745  */
6746  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6747  orderby_operands_eval_cost(root, path);
6748  qual_op_cost = cpu_operator_cost *
6749  (list_length(indexQuals) + list_length(indexOrderBys));
6750 
6751  indexStartupCost = qual_arg_cost;
6752  indexTotalCost += qual_arg_cost;
6753  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6754 
6755  /*
6756  * Generic assumption about index correlation: there isn't any.
6757  */
6758  indexCorrelation = 0.0;
6759 
6760  /*
6761  * Return everything to caller.
6762  */
6763  costs->indexStartupCost = indexStartupCost;
6764  costs->indexTotalCost = indexTotalCost;
6765  costs->indexSelectivity = indexSelectivity;
6766  costs->indexCorrelation = indexCorrelation;
6767  costs->numIndexPages = numIndexPages;
6768  costs->numIndexTuples = numIndexTuples;
6769  costs->spc_random_page_cost = spc_random_page_cost;
6770  costs->num_sa_scans = num_sa_scans;
6771 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
IndexOptInfo * indexinfo
Definition: relation.h:1119
double tuples
Definition: relation.h:625
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6793
Oid reltablespace
Definition: relation.h:720
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6520
double Selectivity
Definition: nodes.h:640
double tuples
Definition: relation.h:725
#define lsecond(l)
Definition: pg_list.h:116
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6545
Definition: type.h:89
BlockNumber pages
Definition: relation.h:724
List * indexquals
Definition: relation.h:1121
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2167
RelOptInfo * rel
Definition: relation.h:721
double num_sa_scans
Definition: selfuncs.h:138
double cpu_operator_cost
Definition: costsize.c:108
Cost indexTotalCost
Definition: selfuncs.h:130
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:613
Expr * clause
Definition: relation.h:1835
double indexCorrelation
Definition: selfuncs.h:132
List * indexorderbys
Definition: relation.h:1123
double spc_random_page_cost
Definition: selfuncs.h:137
double numIndexTuples
Definition: selfuncs.h:136
#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:129
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:107
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:814
double Cost
Definition: nodes.h:641
double numIndexPages
Definition: selfuncs.h:135
void get_join_variables ( PlannerInfo root,
List args,
SpecialJoinInfo sjinfo,
VariableStatData vardata1,
VariableStatData vardata2,
bool join_is_reversed 
)

Definition at line 4601 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(), and networkjoinsel().

4604 {
4605  Node *left,
4606  *right;
4607 
4608  if (list_length(args) != 2)
4609  elog(ERROR, "join operator should take two arguments");
4610 
4611  left = (Node *) linitial(args);
4612  right = (Node *) lsecond(args);
4613 
4614  examine_variable(root, left, 0, vardata1);
4615  examine_variable(root, right, 0, vardata2);
4616 
4617  if (vardata1->rel &&
4618  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4619  *join_is_reversed = true; /* var1 is on RHS */
4620  else if (vardata2->rel &&
4621  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4622  *join_is_reversed = true; /* var2 is on LHS */
4623  else
4624  *join_is_reversed = false;
4625 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:510
#define lsecond(l)
Definition: pg_list.h:116
Relids syn_lefthand
Definition: relation.h:2009
Relids syn_righthand
Definition: relation.h:2010
#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:308
Relids relids
Definition: relation.h:585
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
static int list_length(const List *l)
Definition: pg_list.h:89
#define elog
Definition: elog.h:219
bool get_restriction_variable ( PlannerInfo root,
List args,
int  varRelid,
VariableStatData vardata,
Node **  other,
bool varonleft 
)

Definition at line 4541 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().

4544 {
4545  Node *left,
4546  *right;
4547  VariableStatData rdata;
4548 
4549  /* Fail if not a binary opclause (probably shouldn't happen) */
4550  if (list_length(args) != 2)
4551  return false;
4552 
4553  left = (Node *) linitial(args);
4554  right = (Node *) lsecond(args);
4555 
4556  /*
4557  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4558  * relations will be treated as pseudoconstants.
4559  */
4560  examine_variable(root, left, varRelid, vardata);
4561  examine_variable(root, right, varRelid, &rdata);
4562 
4563  /*
4564  * If one side is a variable and the other not, we win.
4565  */
4566  if (vardata->rel && rdata.rel == NULL)
4567  {
4568  *varonleft = true;
4569  *other = estimate_expression_value(root, rdata.var);
4570  /* Assume we need no ReleaseVariableStats(rdata) here */
4571  return true;
4572  }
4573 
4574  if (vardata->rel == NULL && rdata.rel)
4575  {
4576  *varonleft = false;
4577  *other = estimate_expression_value(root, vardata->var);
4578  /* Assume we need no ReleaseVariableStats(*vardata) here */
4579  *vardata = rdata;
4580  return true;
4581  }
4582 
4583  /* Oops, clause has wrong structure (probably var op var) */
4584  ReleaseVariableStats(*vardata);
4585  ReleaseVariableStats(rdata);
4586 
4587  return false;
4588 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2462
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:510
#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:4663
static int list_length(const List *l)
Definition: pg_list.h:89
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

Definition at line 5070 of file selfuncs.c.

References BOOLOID, 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().

5071 {
5072  double stadistinct;
5073  double stanullfrac = 0.0;
5074  double ntuples;
5075 
5076  *isdefault = false;
5077 
5078  /*
5079  * Determine the stadistinct value to use. There are cases where we can
5080  * get an estimate even without a pg_statistic entry, or can get a better
5081  * value than is in pg_statistic. Grab stanullfrac too if we can find it
5082  * (otherwise, assume no nulls, for lack of any better idea).
5083  */
5084  if (HeapTupleIsValid(vardata->statsTuple))
5085  {
5086  /* Use the pg_statistic entry */
5087  Form_pg_statistic stats;
5088 
5089  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5090  stadistinct = stats->stadistinct;
5091  stanullfrac = stats->stanullfrac;
5092  }
5093  else if (vardata->vartype == BOOLOID)
5094  {
5095  /*
5096  * Special-case boolean columns: presumably, two distinct values.
5097  *
5098  * Are there any other datatypes we should wire in special estimates
5099  * for?
5100  */
5101  stadistinct = 2.0;
5102  }
5103  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5104  {
5105  /*
5106  * If the Var represents a column of a VALUES RTE, assume it's unique.
5107  * This could of course be very wrong, but it should tend to be true
5108  * in well-written queries. We could consider examining the VALUES'
5109  * contents to get some real statistics; but that only works if the
5110  * entries are all constants, and it would be pretty expensive anyway.
5111  */
5112  stadistinct = -1.0; /* unique (and all non null) */
5113  }
5114  else
5115  {
5116  /*
5117  * We don't keep statistics for system columns, but in some cases we
5118  * can infer distinctness anyway.
5119  */
5120  if (vardata->var && IsA(vardata->var, Var))
5121  {
5122  switch (((Var *) vardata->var)->varattno)
5123  {
5126  stadistinct = -1.0; /* unique (and all non null) */
5127  break;
5129  stadistinct = 1.0; /* only 1 value */
5130  break;
5131  default:
5132  stadistinct = 0.0; /* means "unknown" */
5133  break;
5134  }
5135  }
5136  else
5137  stadistinct = 0.0; /* means "unknown" */
5138 
5139  /*
5140  * XXX consider using estimate_num_groups on expressions?
5141  */
5142  }
5143 
5144  /*
5145  * If there is a unique index or DISTINCT clause for the variable, assume
5146  * it is unique no matter what pg_statistic says; the statistics could be
5147  * out of date, or we might have found a partial unique index that proves
5148  * the var is unique for this query. However, we'd better still believe
5149  * the null-fraction statistic.
5150  */
5151  if (vardata->isunique)
5152  stadistinct = -1.0 * (1.0 - stanullfrac);
5153 
5154  /*
5155  * If we had an absolute estimate, use that.
5156  */
5157  if (stadistinct > 0.0)
5158  return clamp_row_est(stadistinct);
5159 
5160  /*
5161  * Otherwise we need to get the relation size; punt if not available.
5162  */
5163  if (vardata->rel == NULL)
5164  {
5165  *isdefault = true;
5166  return DEFAULT_NUM_DISTINCT;
5167  }
5168  ntuples = vardata->rel->tuples;
5169  if (ntuples <= 0.0)
5170  {
5171  *isdefault = true;
5172  return DEFAULT_NUM_DISTINCT;
5173  }
5174 
5175  /*
5176  * If we had a relative estimate, use that.
5177  */
5178  if (stadistinct < 0.0)
5179  return clamp_row_est(-stadistinct * ntuples);
5180 
5181  /*
5182  * With no data, estimate ndistinct = ntuples if the table is small, else
5183  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5184  * that the behavior isn't discontinuous.
5185  */
5186  if (ntuples < DEFAULT_NUM_DISTINCT)
5187  return clamp_row_est(ntuples);
5188 
5189  *isdefault = true;
5190  return DEFAULT_NUM_DISTINCT;
5191 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
double tuples
Definition: relation.h:625
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: primnodes.h:163
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define TableOidAttributeNumber
Definition: sysattr.h:27
RTEKind rtekind
Definition: relation.h:615
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define BOOLOID
Definition: pg_type.h:288
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:46
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
double clamp_row_est(double nrows)
Definition: costsize.c:174
double histogram_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Datum  constval,
bool  varonleft,
int  min_hist_size,
int  n_skip,
int *  hist_size 
)

Definition at line 709 of file selfuncs.c.

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

Referenced by ltreeparentsel(), and patternsel().

713 {
714  double result;
715  AttStatsSlot sslot;
716 
717  /* check sanity of parameters */
718  Assert(n_skip >= 0);
719  Assert(min_hist_size > 2 * n_skip);
720 
721  if (HeapTupleIsValid(vardata->statsTuple) &&
722  statistic_proc_security_check(vardata, opproc->fn_oid) &&
723  get_attstatsslot(&sslot, vardata->statsTuple,
726  {
727  *hist_size = sslot.nvalues;
728  if (sslot.nvalues >= min_hist_size)
729  {
730  int nmatch = 0;
731  int i;
732 
733  for (i = n_skip; i < sslot.nvalues - n_skip; i++)
734  {
735  if (varonleft ?
738  sslot.values[i],
739  constval)) :
742  constval,
743  sslot.values[i])))
744  nmatch++;
745  }
746  result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
747  }
748  else
749  result = -1;
750  free_attstatsslot(&sslot);
751  }
752  else
753  {
754  *hist_size = 0;
755  result = -1;
756  }
757 
758  return result;
759 }
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
#define STATISTIC_KIND_HISTOGRAM
Definition: pg_statistic.h:222
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5041
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1042
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define DatumGetBool(X)
Definition: postgres.h:399
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define Assert(condition)
Definition: c.h:681
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
Const* make_greater_string ( const Const str_const,
FmgrInfo ltproc,
Oid  collation 
)

Definition at line 6199 of file selfuncs.c.

References Assert, byte_increment(), BYTEAOID, Const::consttype, Const::constvalue, DatumGetBool, DatumGetByteaPP, DatumGetCString, DatumGetPointer, DirectFunctionCall1, FunctionCall2Coll(), lc_collate_is_c(), NAMEOID, 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().

6200 {
6201  Oid datatype = str_const->consttype;
6202  char *workstr;
6203  int len;
6204  Datum cmpstr;
6205  text *cmptxt = NULL;
6206  mbcharacter_incrementer charinc;
6207 
6208  /*
6209  * Get a modifiable copy of the prefix string in C-string format, and set
6210  * up the string we will compare to as a Datum. In C locale this can just
6211  * be the given prefix string, otherwise we need to add a suffix. Types
6212  * NAME and BYTEA sort bytewise so they don't need a suffix either.
6213  */
6214  if (datatype == NAMEOID)
6215  {
6217  str_const->constvalue));
6218  len = strlen(workstr);
6219  cmpstr = str_const->constvalue;
6220  }
6221  else if (datatype == BYTEAOID)
6222  {
6223  bytea *bstr = DatumGetByteaPP(str_const->constvalue);
6224 
6225  len = VARSIZE_ANY_EXHDR(bstr);
6226  workstr = (char *) palloc(len);
6227  memcpy(workstr, VARDATA_ANY(bstr), len);
6228  Assert((Pointer) bstr == DatumGetPointer(str_const->constvalue));
6229  cmpstr = str_const->constvalue;
6230  }
6231  else
6232  {
6233  workstr = TextDatumGetCString(str_const->constvalue);
6234  len = strlen(workstr);
6235  if (lc_collate_is_c(collation) || len == 0)
6236  cmpstr = str_const->constvalue;
6237  else
6238  {
6239  /* If first time through, determine the suffix to use */
6240  static char suffixchar = 0;
6241  static Oid suffixcollation = 0;
6242 
6243  if (!suffixchar || suffixcollation != collation)
6244  {
6245  char *best;
6246 
6247  best = "Z";
6248  if (varstr_cmp(best, 1, "z", 1, collation) < 0)
6249  best = "z";
6250  if (varstr_cmp(best, 1, "y", 1, collation) < 0)
6251  best = "y";
6252  if (varstr_cmp(best, 1, "9", 1, collation) < 0)
6253  best = "9";
6254  suffixchar = *best;
6255  suffixcollation = collation;
6256  }
6257 
6258  /* And build the string to compare to */
6259  cmptxt = (text *) palloc(VARHDRSZ + len + 1);
6260  SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
6261  memcpy(VARDATA(cmptxt), workstr, len);
6262  *(VARDATA(cmptxt) + len) = suffixchar;
6263  cmpstr = PointerGetDatum(cmptxt);
6264  }
6265  }
6266 
6267  /* Select appropriate character-incrementer function */
6268  if (datatype == BYTEAOID)
6269  charinc = byte_increment;
6270  else
6272 
6273  /* And search ... */
6274  while (len > 0)
6275  {
6276  int charlen;
6277  unsigned char *lastchar;
6278 
6279  /* Identify the last character --- for bytea, just the last byte */
6280  if (datatype == BYTEAOID)
6281  charlen = 1;
6282  else
6283  charlen = len - pg_mbcliplen(workstr, len, len - 1);
6284  lastchar = (unsigned char *) (workstr + len - charlen);
6285 
6286  /*
6287  * Try to generate a larger string by incrementing the last character
6288  * (for BYTEA, we treat each byte as a character).
6289  *
6290  * Note: the incrementer function is expected to return true if it's
6291  * generated a valid-per-the-encoding new character, otherwise false.
6292  * The contents of the character on false return are unspecified.
6293  */
6294  while (charinc(lastchar, charlen))
6295  {
6296  Const *workstr_const;
6297 
6298  if (datatype == BYTEAOID)
6299  workstr_const = string_to_bytea_const(workstr, len);
6300  else
6301  workstr_const = string_to_const(workstr, datatype);
6302 
6303  if (DatumGetBool(FunctionCall2Coll(ltproc,
6304  collation,
6305  cmpstr,
6306  workstr_const->constvalue)))
6307  {
6308  /* Successfully made a string larger than cmpstr */
6309  if (cmptxt)
6310  pfree(cmptxt);
6311  pfree(workstr);
6312  return workstr_const;
6313  }
6314 
6315  /* No good, release unusable value and try again */
6316  pfree(DatumGetPointer(workstr_const->constvalue));
6317  pfree(workstr_const);
6318  }
6319 
6320  /*
6321  * No luck here, so truncate off the last character and try to
6322  * increment the next one.
6323  */
6324  len -= charlen;
6325  workstr[len] = '\0';
6326  }
6327 
6328  /* Failed... */
6329  if (cmptxt)
6330  pfree(cmptxt);
6331  pfree(workstr);
6332 
6333  return NULL;
6334 }
Datum constvalue
Definition: primnodes.h:196
#define NAMEOID
Definition: pg_type.h:300
#define VARDATA_ANY(PTR)
Definition: postgres.h:347
#define VARDATA(PTR)
Definition: postgres.h:303
#define PointerGetDatum(X)
Definition: postgres.h:562
#define VARHDRSZ
Definition: c.h:439
#define DatumGetByteaPP(X)
Definition: fmgr.h:255
static Const * string_to_bytea_const(const char *str, size_t str_len)
Definition: selfuncs.c:6405
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1042
unsigned int Oid
Definition: postgres_ext.h:31
static bool byte_increment(unsigned char *ptr, int len)
Definition: selfuncs.c:6149
static Const * string_to_const(const char *str, Oid datatype)
Definition: selfuncs.c:6362
Oid consttype
Definition: primnodes.h:192
void pfree(void *pointer)
Definition: mcxt.c:949
char * Pointer
Definition: c.h:235
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1128
#define DatumGetCString(X)
Definition: postgres.h:572
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:820
#define DatumGetBool(X)
Definition: postgres.h:399
#define TextDatumGetCString(d)
Definition: builtins.h:92
uintptr_t Datum
Definition: postgres.h:372
bool(* mbcharacter_incrementer)(unsigned char *mbstr, int len)
Definition: pg_wchar.h:369
#define Assert(condition)
Definition: c.h:681
int varstr_cmp(char *arg1, int len1, char *arg2, int len2, Oid collid)
Definition: varlena.c:1382
#define BYTEAOID
Definition: pg_type.h:292
#define DatumGetPointer(X)
Definition: postgres.h:555
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:340
void * palloc(Size size)
Definition: mcxt.c:848
mbcharacter_incrementer pg_database_encoding_character_incrementer(void)
Definition: wchar.c:1842
Definition: c.h:433
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:328
Datum nameout(PG_FUNCTION_ARGS)
Definition: name.c:69
double mcv_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Datum  constval,
bool  varonleft,
double *  sumcommonp 
)

Definition at line 637 of file selfuncs.c.

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

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

640 {
641  double mcv_selec,
642  sumcommon;
643  AttStatsSlot sslot;
644  int i;
645 
646  mcv_selec = 0.0;
647  sumcommon = 0.0;
648 
649  if (HeapTupleIsValid(vardata->statsTuple) &&
650  statistic_proc_security_check(vardata, opproc->fn_oid) &&
651  get_attstatsslot(&sslot, vardata->statsTuple,
654  {
655  for (i = 0; i < sslot.nvalues; i++)
656  {
657  if (varonleft ?
660  sslot.values[i],
661  constval)) :
664  constval,
665  sslot.values[i])))
666  mcv_selec += sslot.numbers[i];
667  sumcommon += sslot.numbers[i];
668  }
669  free_attstatsslot(&sslot);
670  }
671 
672  *sumcommonp = sumcommon;
673  return mcv_selec;
674 }
#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:5041
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1042
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
float4 * numbers
Definition: lsyscache.h:52
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define DatumGetBool(X)
Definition: postgres.h:399
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
void mergejoinscansel ( PlannerInfo root,
Node clause,
Oid  opfamily,
int  strategy,
bool  nulls_first,
Selectivity leftstart,
Selectivity leftend,
Selectivity rightstart,
Selectivity rightend 
)

Definition at line 2936 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().

2940 {
2941  Node *left,
2942  *right;
2943  VariableStatData leftvar,
2944  rightvar;
2945  int op_strategy;
2946  Oid op_lefttype;
2947  Oid op_righttype;
2948  Oid opno,
2949  lsortop,
2950  rsortop,
2951  lstatop,
2952  rstatop,
2953  ltop,
2954  leop,
2955  revltop,
2956  revleop;
2957  bool isgt;
2958  Datum leftmin,
2959  leftmax,
2960  rightmin,
2961  rightmax;
2962  double selec;
2963 
2964  /* Set default results if we can't figure anything out. */
2965  /* XXX should default "start" fraction be a bit more than 0? */
2966  *leftstart = *rightstart = 0.0;
2967  *leftend = *rightend = 1.0;
2968 
2969  /* Deconstruct the merge clause */
2970  if (!is_opclause(clause))
2971  return; /* shouldn't happen */
2972  opno = ((OpExpr *) clause)->opno;
2973  left = get_leftop((Expr *) clause);
2974  right = get_rightop((Expr *) clause);
2975  if (!right)
2976  return; /* shouldn't happen */
2977 
2978  /* Look for stats for the inputs */
2979  examine_variable(root, left, 0, &leftvar);
2980  examine_variable(root, right, 0, &rightvar);
2981 
2982  /* Extract the operator's declared left/right datatypes */
2983  get_op_opfamily_properties(opno, opfamily, false,
2984  &op_strategy,
2985  &op_lefttype,
2986  &op_righttype);
2987  Assert(op_strategy == BTEqualStrategyNumber);
2988 
2989  /*
2990  * Look up the various operators we need. If we don't find them all, it
2991  * probably means the opfamily is broken, but we just fail silently.
2992  *
2993  * Note: we expect that pg_statistic histograms will be sorted by the '<'
2994  * operator, regardless of which sort direction we are considering.
2995  */
2996  switch (strategy)
2997  {
2998  case BTLessStrategyNumber:
2999  isgt = false;
3000  if (op_lefttype == op_righttype)
3001  {
3002  /* easy case */
3003  ltop = get_opfamily_member(opfamily,
3004  op_lefttype, op_righttype,
3006  leop = get_opfamily_member(opfamily,
3007  op_lefttype, op_righttype,
3009  lsortop = ltop;
3010  rsortop = ltop;
3011  lstatop = lsortop;
3012  rstatop = rsortop;
3013  revltop = ltop;
3014  revleop = leop;
3015  }
3016  else
3017  {
3018  ltop = get_opfamily_member(opfamily,
3019  op_lefttype, op_righttype,
3021  leop = get_opfamily_member(opfamily,
3022  op_lefttype, op_righttype,
3024  lsortop = get_opfamily_member(opfamily,
3025  op_lefttype, op_lefttype,
3027  rsortop = get_opfamily_member(opfamily,
3028  op_righttype, op_righttype,
3030  lstatop = lsortop;
3031  rstatop = rsortop;
3032  revltop = get_opfamily_member(opfamily,
3033  op_righttype, op_lefttype,
3035  revleop = get_opfamily_member(opfamily,
3036  op_righttype, op_lefttype,
3038  }
3039  break;
3041  /* descending-order case */
3042  isgt = true;
3043  if (op_lefttype == op_righttype)
3044  {
3045  /* easy case */
3046  ltop = get_opfamily_member(opfamily,
3047  op_lefttype, op_righttype,
3049  leop = get_opfamily_member(opfamily,
3050  op_lefttype, op_righttype,
3052  lsortop = ltop;
3053  rsortop = ltop;
3054  lstatop = get_opfamily_member(opfamily,
3055  op_lefttype, op_lefttype,
3057  rstatop = lstatop;
3058  revltop = ltop;
3059  revleop = leop;
3060  }
3061  else
3062  {
3063  ltop = get_opfamily_member(opfamily,
3064  op_lefttype, op_righttype,
3066  leop = get_opfamily_member(opfamily,
3067  op_lefttype, op_righttype,
3069  lsortop = get_opfamily_member(opfamily,
3070  op_lefttype, op_lefttype,
3072  rsortop = get_opfamily_member(opfamily,
3073  op_righttype, op_righttype,
3075  lstatop = get_opfamily_member(opfamily,
3076  op_lefttype, op_lefttype,
3078  rstatop = get_opfamily_member(opfamily,
3079  op_righttype, op_righttype,
3081  revltop = get_opfamily_member(opfamily,
3082  op_righttype, op_lefttype,
3084  revleop = get_opfamily_member(opfamily,
3085  op_righttype, op_lefttype,
3087  }
3088  break;
3089  default:
3090  goto fail; /* shouldn't get here */
3091  }
3092 
3093  if (!OidIsValid(lsortop) ||
3094  !OidIsValid(rsortop) ||
3095  !OidIsValid(lstatop) ||
3096  !OidIsValid(rstatop) ||
3097  !OidIsValid(ltop) ||
3098  !OidIsValid(leop) ||
3099  !OidIsValid(revltop) ||
3100  !OidIsValid(revleop))
3101  goto fail; /* insufficient info in catalogs */
3102 
3103  /* Try to get ranges of both inputs */
3104  if (!isgt)
3105  {
3106  if (!get_variable_range(root, &leftvar, lstatop,
3107  &leftmin, &leftmax))
3108  goto fail; /* no range available from stats */
3109  if (!get_variable_range(root, &rightvar, rstatop,
3110  &rightmin, &rightmax))
3111  goto fail; /* no range available from stats */
3112  }
3113  else
3114  {
3115  /* need to swap the max and min */
3116  if (!get_variable_range(root, &leftvar, lstatop,
3117  &leftmax, &leftmin))
3118  goto fail; /* no range available from stats */
3119  if (!get_variable_range(root, &rightvar, rstatop,
3120  &rightmax, &rightmin))
3121  goto fail; /* no range available from stats */
3122  }
3123 
3124  /*
3125  * Now, the fraction of the left variable that will be scanned is the
3126  * fraction that's <= the right-side maximum value. But only believe
3127  * non-default estimates, else stick with our 1.0.
3128  */
3129  selec = scalarineqsel(root, leop, isgt, true, &leftvar,
3130  rightmax, op_righttype);
3131  if (selec != DEFAULT_INEQ_SEL)
3132  *leftend = selec;
3133 
3134  /* And similarly for the right variable. */
3135  selec = scalarineqsel(root, revleop, isgt, true, &rightvar,
3136  leftmax, op_lefttype);
3137  if (selec != DEFAULT_INEQ_SEL)
3138  *rightend = selec;
3139 
3140  /*
3141  * Only one of the two "end" fractions can really be less than 1.0;
3142  * believe the smaller estimate and reset the other one to exactly 1.0. If
3143  * we get exactly equal estimates (as can easily happen with self-joins),
3144  * believe neither.
3145  */
3146  if (*leftend > *rightend)
3147  *leftend = 1.0;
3148  else if (*leftend < *rightend)
3149  *rightend = 1.0;
3150  else
3151  *leftend = *rightend = 1.0;
3152 
3153  /*
3154  * Also, the fraction of the left variable that will be scanned before the
3155  * first join pair is found is the fraction that's < the right-side
3156  * minimum value. But only believe non-default estimates, else stick with
3157  * our own default.
3158  */
3159  selec = scalarineqsel(root, ltop, isgt, false, &leftvar,
3160  rightmin, op_righttype);
3161  if (selec != DEFAULT_INEQ_SEL)
3162  *leftstart = selec;
3163 
3164  /* And similarly for the right variable. */
3165  selec = scalarineqsel(root, revltop, isgt, false, &rightvar,
3166  leftmin, op_lefttype);
3167  if (selec != DEFAULT_INEQ_SEL)
3168  *rightstart = selec;
3169 
3170  /*
3171  * Only one of the two "start" fractions can really be more than zero;
3172  * believe the larger estimate and reset the other one to exactly 0.0. If
3173  * we get exactly equal estimates (as can easily happen with self-joins),
3174  * believe neither.
3175  */
3176  if (*leftstart < *rightstart)
3177  *leftstart = 0.0;
3178  else if (*leftstart > *rightstart)
3179  *rightstart = 0.0;
3180  else
3181  *leftstart = *rightstart = 0.0;
3182 
3183  /*
3184  * If the sort order is nulls-first, we're going to have to skip over any
3185  * nulls too. These would not have been counted by scalarineqsel, and we
3186  * can safely add in this fraction regardless of whether we believe
3187  * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3188  */
3189  if (nulls_first)
3190  {
3191  Form_pg_statistic stats;
3192 
3193  if (HeapTupleIsValid(leftvar.statsTuple))
3194  {
3195  stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3196  *leftstart += stats->stanullfrac;
3197  CLAMP_PROBABILITY(*leftstart);
3198  *leftend += stats->stanullfrac;
3199  CLAMP_PROBABILITY(*leftend);
3200  }
3201  if (HeapTupleIsValid(rightvar.statsTuple))
3202  {
3203  stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3204  *rightstart += stats->stanullfrac;
3205  CLAMP_PROBABILITY(*rightstart);
3206  *rightend += stats->stanullfrac;
3207  CLAMP_PROBABILITY(*rightend);
3208  }
3209  }
3210 
3211  /* Disbelieve start >= end, just in case that can happen */
3212  if (*leftstart >= *leftend)
3213  {
3214  *leftstart = 0.0;
3215  *leftend = 1.0;
3216  }
3217  if (*rightstart >= *rightend)
3218  {
3219  *rightstart = 0.0;
3220  *rightend = 1.0;
3221  }
3222 
3223 fail:
3224  ReleaseVariableStats(leftvar);
3225  ReleaseVariableStats(rightvar);
3226 }
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Definition: nodes.h:510
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define OidIsValid(objectId)
Definition: c.h:532
#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:199
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
uintptr_t Datum
Definition: postgres.h:372
static double scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, bool iseq, VariableStatData *vardata, Datum constval, Oid consttype)
Definition: selfuncs.c:562
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
#define Assert(condition)
Definition: c.h:681
Node * get_rightop(const Expr *clause)
Definition: clauses.c:216
#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:5203
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32
Selectivity nulltestsel ( PlannerInfo root,
NullTestType  nulltesttype,
Node arg,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1739 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().

1741 {
1742  VariableStatData vardata;
1743  double selec;
1744 
1745  examine_variable(root, arg, varRelid, &vardata);
1746 
1747  if (HeapTupleIsValid(vardata.statsTuple))
1748  {
1749  Form_pg_statistic stats;
1750  double freq_null;
1751 
1752  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1753  freq_null = stats->stanullfrac;
1754 
1755  switch (nulltesttype)
1756  {
1757  case IS_NULL:
1758 
1759  /*
1760  * Use freq_null directly.
1761  */
1762  selec = freq_null;
1763  break;
1764  case IS_NOT_NULL:
1765 
1766  /*
1767  * Select not unknown (not null) values. Calculate from
1768  * freq_null.
1769  */
1770  selec = 1.0 - freq_null;
1771  break;
1772  default:
1773  elog(ERROR, "unrecognized nulltesttype: %d",
1774  (int) nulltesttype);
1775  return (Selectivity) 0; /* keep compiler quiet */
1776  }
1777  }
1778  else
1779  {
1780  /*
1781  * No ANALYZE stats available, so make a guess
1782  */
1783  switch (nulltesttype)
1784  {
1785  case IS_NULL:
1786  selec = DEFAULT_UNK_SEL;
1787  break;
1788  case IS_NOT_NULL:
1789  selec = DEFAULT_NOT_UNK_SEL;
1790  break;
1791  default:
1792  elog(ERROR, "unrecognized nulltesttype: %d",
1793  (int) nulltesttype);
1794  return (Selectivity) 0; /* keep compiler quiet */
1795  }
1796  }
1797 
1798  ReleaseVariableStats(vardata);
1799 
1800  /* result should be in range, but make sure... */
1801  CLAMP_PROBABILITY(selec);
1802 
1803  return (Selectivity) selec;
1804 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
double Selectivity
Definition: nodes.h:640
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#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:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog
Definition: elog.h:219
Pattern_Prefix_Status pattern_fixed_prefix ( Const patt,
Pattern_Type  ptype,
Oid  collation,
Const **  prefix,
Selectivity rest_selec 
)

Definition at line 5833 of file selfuncs.c.

References elog, ERROR, like_fixed_prefix(), Pattern_Prefix_None, Pattern_Type_Like, Pattern_Type_Like_IC, Pattern_Type_Regex, Pattern_Type_Regex_IC, and regex_fixed_prefix().

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

5835 {
5836  Pattern_Prefix_Status result;
5837 
5838  switch (ptype)
5839  {
5840  case Pattern_Type_Like:
5841  result = like_fixed_prefix(patt, false, collation,
5842  prefix, rest_selec);
5843  break;
5844  case Pattern_Type_Like_IC:
5845  result = like_fixed_prefix(patt, true, collation,
5846  prefix, rest_selec);
5847  break;
5848  case Pattern_Type_Regex:
5849  result = regex_fixed_prefix(patt, false, collation,
5850  prefix, rest_selec);
5851  break;
5852  case Pattern_Type_Regex_IC:
5853  result = regex_fixed_prefix(patt, true, collation,
5854  prefix, rest_selec);
5855  break;
5856  default:
5857  elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5858  result = Pattern_Prefix_None; /* keep compiler quiet */
5859  break;
5860  }
5861  return result;
5862 }
static Pattern_Prefix_Status regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5765
static Pattern_Prefix_Status like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5657
#define ERROR
Definition: elog.h:43
#define elog
Definition: elog.h:219
Pattern_Prefix_Status
Definition: selfuncs.h:94
Selectivity rowcomparesel ( PlannerInfo root,
RowCompareExpr clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 2205 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().

2208 {
2209  Selectivity s1;
2210  Oid opno = linitial_oid(clause->opnos);
2211  Oid inputcollid = linitial_oid(clause->inputcollids);
2212  List *opargs;
2213  bool is_join_clause;
2214 
2215  /* Build equivalent arg list for single operator */
2216  opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2217 
2218  /*
2219  * Decide if it's a join clause. This should match clausesel.c's
2220  * treat_as_join_clause(), except that we intentionally consider only the
2221  * leading columns and not the rest of the clause.
2222  */
2223  if (varRelid != 0)
2224  {
2225  /*
2226  * Caller is forcing restriction mode (eg, because we are examining an
2227  * inner indexscan qual).
2228  */
2229  is_join_clause = false;
2230  }
2231  else if (sjinfo == NULL)
2232  {
2233  /*
2234  * It must be a restriction clause, since it's being evaluated at a
2235  * scan node.
2236  */
2237  is_join_clause = false;
2238  }
2239  else
2240  {
2241  /*
2242  * Otherwise, it's a join if there's more than one relation used.
2243  */
2244  is_join_clause = (NumRelids((Node *) opargs) > 1);
2245  }
2246 
2247  if (is_join_clause)
2248  {
2249  /* Estimate selectivity for a join clause. */
2250  s1 = join_selectivity(root, opno,
2251  opargs,
2252  inputcollid,
2253  jointype,
2254  sjinfo);
2255  }
2256  else
2257  {
2258  /* Estimate selectivity for a restriction clause. */
2259  s1 = restriction_selectivity(root, opno,
2260  opargs,
2261  inputcollid,
2262  varRelid);
2263  }
2264 
2265  return s1;
2266 }
#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:1665
Definition: nodes.h:510
double Selectivity
Definition: nodes.h:640
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:1702
List * inputcollids
Definition: primnodes.h:1034
Definition: pg_list.h:45
int NumRelids(Node *clause)
Definition: clauses.c:2246
Selectivity scalararraysel ( PlannerInfo root,
ScalarArrayOpExpr clause,
bool  is_join_clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1848 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().

1854 {
1855  Oid operator = clause->opno;
1856  bool useOr = clause->useOr;
1857  bool isEquality = false;
1858  bool isInequality = false;
1859  Node *leftop;
1860  Node *rightop;
1861  Oid nominal_element_type;
1862  Oid nominal_element_collation;
1863  TypeCacheEntry *typentry;
1864  RegProcedure oprsel;
1865  FmgrInfo oprselproc;
1866  Selectivity s1;
1867  Selectivity s1disjoint;
1868 
1869  /* First, deconstruct the expression */
1870  Assert(list_length(clause->args) == 2);
1871  leftop = (Node *) linitial(clause->args);
1872  rightop = (Node *) lsecond(clause->args);
1873 
1874  /* aggressively reduce both sides to constants */
1875  leftop = estimate_expression_value(root, leftop);
1876  rightop = estimate_expression_value(root, rightop);
1877 
1878  /* get nominal (after relabeling) element type of rightop */
1879  nominal_element_type = get_base_element_type(exprType(rightop));
1880  if (!OidIsValid(nominal_element_type))
1881  return (Selectivity) 0.5; /* probably shouldn't happen */
1882  /* get nominal collation, too, for generating constants */
1883  nominal_element_collation = exprCollation(rightop);
1884 
1885  /* look through any binary-compatible relabeling of rightop */
1886  rightop = strip_array_coercion(rightop);
1887 
1888  /*
1889  * Detect whether the operator is the default equality or inequality
1890  * operator of the array element type.
1891  */
1892  typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1893  if (OidIsValid(typentry->eq_opr))
1894  {
1895  if (operator == typentry->eq_opr)
1896  isEquality = true;
1897  else if (get_negator(operator) == typentry->eq_opr)
1898  isInequality = true;
1899  }
1900 
1901  /*
1902  * If it is equality or inequality, we might be able to estimate this as a
1903  * form of array containment; for instance "const = ANY(column)" can be
1904  * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1905  * that, and returns the selectivity estimate if successful, or -1 if not.
1906  */
1907  if ((isEquality || isInequality) && !is_join_clause)
1908  {
1909  s1 = scalararraysel_containment(root, leftop, rightop,
1910  nominal_element_type,
1911  isEquality, useOr, varRelid);
1912  if (s1 >= 0.0)
1913  return s1;
1914  }
1915 
1916  /*
1917  * Look up the underlying operator's selectivity estimator. Punt if it
1918  * hasn't got one.
1919  */
1920  if (is_join_clause)
1921  oprsel = get_oprjoin(operator);
1922  else
1923  oprsel = get_oprrest(operator);
1924  if (!oprsel)
1925  return (Selectivity) 0.5;
1926  fmgr_info(oprsel, &oprselproc);
1927 
1928  /*
1929  * In the array-containment check above, we must only believe that an
1930  * operator is equality or inequality if it is the default btree equality
1931  * operator (or its negator) for the element type, since those are the
1932  * operators that array containment will use. But in what follows, we can
1933  * be a little laxer, and also believe that any operators using eqsel() or
1934  * neqsel() as selectivity estimator act like equality or inequality.
1935  */
1936  if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1937  isEquality = true;
1938  else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1939  isInequality = true;
1940 
1941  /*
1942  * We consider three cases:
1943  *
1944  * 1. rightop is an Array constant: deconstruct the array, apply the
1945  * operator's selectivity function for each array element, and merge the
1946  * results in the same way that clausesel.c does for AND/OR combinations.
1947  *
1948  * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1949  * function for each element of the ARRAY[] construct, and merge.
1950  *
1951  * 3. otherwise, make a guess ...
1952  */
1953  if (rightop && IsA(rightop, Const))
1954  {
1955  Datum arraydatum = ((Const *) rightop)->constvalue;
1956  bool arrayisnull = ((Const *) rightop)->constisnull;
1957  ArrayType *arrayval;
1958  int16 elmlen;
1959  bool elmbyval;
1960  char elmalign;
1961  int num_elems;
1962  Datum *elem_values;
1963  bool *elem_nulls;
1964  int i;
1965 
1966  if (arrayisnull) /* qual can't succeed if null array */
1967  return (Selectivity) 0.0;
1968  arrayval = DatumGetArrayTypeP(arraydatum);
1970  &elmlen, &elmbyval, &elmalign);
1971  deconstruct_array(arrayval,
1972  ARR_ELEMTYPE(arrayval),
1973  elmlen, elmbyval, elmalign,
1974  &elem_values, &elem_nulls, &num_elems);
1975 
1976  /*
1977  * For generic operators, we assume the probability of success is
1978  * independent for each array element. But for "= ANY" or "<> ALL",
1979  * if the array elements are distinct (which'd typically be the case)
1980  * then the probabilities are disjoint, and we should just sum them.
1981  *
1982  * If we were being really tense we would try to confirm that the
1983  * elements are all distinct, but that would be expensive and it
1984  * doesn't seem to be worth the cycles; it would amount to penalizing
1985  * well-written queries in favor of poorly-written ones. However, we
1986  * do protect ourselves a little bit by checking whether the
1987  * disjointness assumption leads to an impossible (out of range)
1988  * probability; if so, we fall back to the normal calculation.
1989  */
1990  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1991 
1992  for (i = 0; i < num_elems; i++)
1993  {
1994  List *args;
1995  Selectivity s2;
1996 
1997  args = list_make2(leftop,
1998  makeConst(nominal_element_type,
1999  -1,
2000  nominal_element_collation,
2001  elmlen,
2002  elem_values[i],
2003  elem_nulls[i],
2004  elmbyval));
2005  if (is_join_clause)
2006  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2007  clause->inputcollid,
2008  PointerGetDatum(root),
2009  ObjectIdGetDatum(operator),
2010  PointerGetDatum(args),
2011  Int16GetDatum(jointype),
2012  PointerGetDatum(sjinfo)));
2013  else
2014  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2015  clause->inputcollid,
2016  PointerGetDatum(root),
2017  ObjectIdGetDatum(operator),
2018  PointerGetDatum(args),
2019  Int32GetDatum(varRelid)));
2020 
2021  if (useOr)
2022  {
2023  s1 = s1 + s2 - s1 * s2;
2024  if (isEquality)
2025  s1disjoint += s2;
2026  }
2027  else
2028  {
2029  s1 = s1 * s2;
2030  if (isInequality)
2031  s1disjoint += s2 - 1.0;
2032  }
2033  }
2034 
2035  /* accept disjoint-probability estimate if in range */
2036  if ((useOr ? isEquality : isInequality) &&
2037  s1disjoint >= 0.0 && s1disjoint <= 1.0)
2038  s1 = s1disjoint;
2039  }
2040  else if (rightop && IsA(rightop, ArrayExpr) &&
2041  !((ArrayExpr *) rightop)->multidims)
2042  {
2043  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2044  int16 elmlen;
2045  bool elmbyval;
2046  ListCell *l;
2047 
2048  get_typlenbyval(arrayexpr->element_typeid,
2049  &elmlen, &elmbyval);
2050 
2051  /*
2052  * We use the assumption of disjoint probabilities here too, although
2053  * the odds of equal array elements are rather higher if the elements
2054  * are not all constants (which they won't be, else constant folding
2055  * would have reduced the ArrayExpr to a Const). In this path it's
2056  * critical to have the sanity check on the s1disjoint estimate.
2057  */
2058  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
2059 
2060  foreach(l, arrayexpr->elements)
2061  {
2062  Node *elem = (Node *) lfirst(l);
2063  List *args;
2064  Selectivity s2;
2065 
2066  /*
2067  * Theoretically, if elem isn't of nominal_element_type we should
2068  * insert a RelabelType, but it seems unlikely that any operator
2069  * estimation function would really care ...
2070  */
2071  args = list_make2(leftop, elem);
2072  if (is_join_clause)
2073  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2074  clause->inputcollid,
2075  PointerGetDatum(root),
2076  ObjectIdGetDatum(operator),
2077  PointerGetDatum(args),
2078  Int16GetDatum(jointype),
2079  PointerGetDatum(sjinfo)));
2080  else
2081  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2082  clause->inputcollid,
2083  PointerGetDatum(root),
2084  ObjectIdGetDatum(operator),
2085  PointerGetDatum(args),
2086  Int32GetDatum(varRelid)));
2087 
2088  if (useOr)
2089  {
2090  s1 = s1 + s2 - s1 * s2;
2091  if (isEquality)
2092  s1disjoint += s2;
2093  }
2094  else
2095  {
2096  s1 = s1 * s2;
2097  if (isInequality)
2098  s1disjoint += s2 - 1.0;
2099  }
2100  }
2101 
2102  /* accept disjoint-probability estimate if in range */
2103  if ((useOr ? isEquality : isInequality) &&
2104  s1disjoint >= 0.0 && s1disjoint <= 1.0)
2105  s1 = s1disjoint;
2106  }
2107  else
2108  {
2109  CaseTestExpr *dummyexpr;
2110  List *args;
2111  Selectivity s2;
2112  int i;
2113 
2114  /*
2115  * We need a dummy rightop to pass to the operator selectivity
2116  * routine. It can be pretty much anything that doesn't look like a
2117  * constant; CaseTestExpr is a convenient choice.
2118  */
2119  dummyexpr = makeNode(CaseTestExpr);
2120  dummyexpr->typeId = nominal_element_type;
2121  dummyexpr->typeMod = -1;
2122  dummyexpr->collation = clause->inputcollid;
2123  args = list_make2(leftop, dummyexpr);
2124  if (is_join_clause)
2125  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2126  clause->inputcollid,
2127  PointerGetDatum(root),
2128  ObjectIdGetDatum(operator),
2129  PointerGetDatum(args),
2130  Int16GetDatum(jointype),
2131  PointerGetDatum(sjinfo)));
2132  else
2133  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2134  clause->inputcollid,
2135  PointerGetDatum(root),
2136  ObjectIdGetDatum(operator),
2137  PointerGetDatum(args),
2138  Int32GetDatum(varRelid)));
2139  s1 = useOr ? 0.0 : 1.0;
2140 
2141  /*
2142  * Arbitrarily assume 10 elements in the eventual array value (see
2143  * also estimate_array_length). We don't risk an assumption of
2144  * disjoint probabilities here.
2145  */
2146  for (i = 0; i < 10; i++)
2147  {
2148  if (useOr)
2149  s1 = s1 + s2 - s1 * s2;
2150  else
2151  s1 = s1 * s2;
2152  }
2153  }
2154 
2155  /* result should be in range, but make sure... */
2156  CLAMP_PROBABILITY(s1);
2157 
2158  return s1;
2159 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
signed short int16
Definition: c.h:245
Definition: fmgr.h:56
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1385
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2462
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2021
#define PointerGetDatum(X)
Definition: postgres.h:562
Datum FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1116
regproc RegProcedure
Definition: c.h:389
#define Int16GetDatum(X)
Definition: postgres.h:457
Definition: nodes.h:510
#define TYPECACHE_EQ_OPR
Definition: typcache.h:114
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1089
double Selectivity
Definition: nodes.h:640
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:296
#define OidIsValid(objectId)
Definition: c.h:532
#define lsecond(l)
Definition: pg_list.h:116
int32 typeMod
Definition: primnodes.h:937
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define linitial(l)
Definition: pg_list.h:111
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
char * s1
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:122
List * elements
Definition: primnodes.h:955
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1361
char * s2
#define DatumGetFloat8(X)
Definition: postgres.h:734
uintptr_t Datum
Definition: postgres.h:372
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:310
#define makeNode(_type_)
Definition: nodes.h:558
#define Assert(condition)
Definition: c.h:681
#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:2001
Oid element_typeid
Definition: primnodes.h:954
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:2557
#define Int32GetDatum(X)
Definition: postgres.h:485
int i
Oid get_negator(Oid opno)
Definition: lsyscache.c:1337
Definition: pg_list.h:45
#define ARR_ELEMTYPE(a)
Definition: array.h:277
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1815
#define DatumGetArrayTypeP(X)
Definition: array.h:246
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, OID_ARRAY_CONTAINED_OP, OID_ARRAY_CONTAINS_OP, OidIsValid, VariableStatData::rel, ReleaseVariableStats, STATISTIC_KIND_DECHIST, STATISTIC_KIND_MCELEM, 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,
149  {
150  /* For ALL case, also get histogram of distinct-element counts */
151  if (useOr ||
152  !get_attstatsslot(&hslot, vardata.statsTuple,
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,
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,
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,
192  cmpfunc);
193  else
194  selec = mcelem_array_contained_selec(NULL, 0,
195  NULL, 0,
196  &constval, 1,
197  NULL, 0,
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,
215  cmpfunc);
216  else
217  selec = mcelem_array_contained_selec(NULL, 0,
218  NULL, 0,
219  &constval, 1,
220  NULL, 0,
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:561
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#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:5041
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:640
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define OidIsValid(objectId)
Definition: c.h:532
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
FmgrInfo cmp_proc_finfo
Definition: typcache.h:71
#define OID_ARRAY_CONTAINS_OP
Definition: pg_operator.h:1569
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define STATISTIC_KIND_DECHIST
Definition: pg_statistic.h:270
float4 * numbers
Definition: lsyscache.h:52
#define OID_ARRAY_CONTAINED_OP
Definition: pg_operator.h:1572
uintptr_t Datum
Definition: postgres.h:372
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:310
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
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 STATISTIC_KIND_MCELEM
Definition: pg_statistic.h:257
#define TYPECACHE_CMP_PROC_FINFO
Definition: typcache.h:120
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:3011
bool statistic_proc_security_check ( VariableStatData vardata,
Oid  func_oid 
)

Definition at line 5041 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().

5042 {
5043  if (vardata->acl_ok)
5044  return true;
5045 
5046  if (!OidIsValid(func_oid))
5047  return false;
5048 
5049  if (get_func_leakproof(func_oid))
5050  return true;
5051 
5052  ereport(DEBUG2,
5053  (errmsg_internal("not using statistics because function \"%s\" is not leak-proof",
5054  get_func_name(func_oid))));
5055  return false;
5056 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1622
#define OidIsValid(objectId)
Definition: c.h:532
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1412
#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

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().

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().