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)
 
Selectivity estimate_hash_bucketsize (PlannerInfo *root, Node *hashkey, double nbuckets)
 
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(), int_query_opr_selec(), neqjoinsel(), and neqsel().

#define DEFAULT_INEQ_SEL   0.3333333333333333
#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 1480 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().

1482 {
1483  VariableStatData vardata;
1484  double selec;
1485 
1486  examine_variable(root, arg, varRelid, &vardata);
1487 
1488  if (HeapTupleIsValid(vardata.statsTuple))
1489  {
1490  Form_pg_statistic stats;
1491  double freq_null;
1492  AttStatsSlot sslot;
1493 
1494  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1495  freq_null = stats->stanullfrac;
1496 
1497  if (get_attstatsslot(&sslot, vardata.statsTuple,
1500  && sslot.nnumbers > 0)
1501  {
1502  double freq_true;
1503  double freq_false;
1504 
1505  /*
1506  * Get first MCV frequency and derive frequency for true.
1507  */
1508  if (DatumGetBool(sslot.values[0]))
1509  freq_true = sslot.numbers[0];
1510  else
1511  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1512 
1513  /*
1514  * Next derive frequency for false. Then use these as appropriate
1515  * to derive frequency for each case.
1516  */
1517  freq_false = 1.0 - freq_true - freq_null;
1518 
1519  switch (booltesttype)
1520  {
1521  case IS_UNKNOWN:
1522  /* select only NULL values */
1523  selec = freq_null;
1524  break;
1525  case IS_NOT_UNKNOWN:
1526  /* select non-NULL values */
1527  selec = 1.0 - freq_null;
1528  break;
1529  case IS_TRUE:
1530  /* select only TRUE values */
1531  selec = freq_true;
1532  break;
1533  case IS_NOT_TRUE:
1534  /* select non-TRUE values */
1535  selec = 1.0 - freq_true;
1536  break;
1537  case IS_FALSE:
1538  /* select only FALSE values */
1539  selec = freq_false;
1540  break;
1541  case IS_NOT_FALSE:
1542  /* select non-FALSE values */
1543  selec = 1.0 - freq_false;
1544  break;
1545  default:
1546  elog(ERROR, "unrecognized booltesttype: %d",
1547  (int) booltesttype);
1548  selec = 0.0; /* Keep compiler quiet */
1549  break;
1550  }
1551 
1552  free_attstatsslot(&sslot);
1553  }
1554  else
1555  {
1556  /*
1557  * No most-common-value info available. Still have null fraction
1558  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1559  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1560  */
1561  switch (booltesttype)
1562  {
1563  case IS_UNKNOWN:
1564  /* select only NULL values */
1565  selec = freq_null;
1566  break;
1567  case IS_NOT_UNKNOWN:
1568  /* select non-NULL values */
1569  selec = 1.0 - freq_null;
1570  break;
1571  case IS_TRUE:
1572  case IS_FALSE:
1573  /* Assume we select half of the non-NULL values */
1574  selec = (1.0 - freq_null) / 2.0;
1575  break;
1576  case IS_NOT_TRUE:
1577  case IS_NOT_FALSE:
1578  /* Assume we select NULLs plus half of the non-NULLs */
1579  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1580  selec = (freq_null + 1.0) / 2.0;
1581  break;
1582  default:
1583  elog(ERROR, "unrecognized booltesttype: %d",
1584  (int) booltesttype);
1585  selec = 0.0; /* Keep compiler quiet */
1586  break;
1587  }
1588  }
1589  }
1590  else
1591  {
1592  /*
1593  * If we can't get variable statistics for the argument, perhaps
1594  * clause_selectivity can do something with it. We ignore the
1595  * possibility of a NULL value when using clause_selectivity, and just
1596  * assume the value is either TRUE or FALSE.
1597  */
1598  switch (booltesttype)
1599  {
1600  case IS_UNKNOWN:
1601  selec = DEFAULT_UNK_SEL;
1602  break;
1603  case IS_NOT_UNKNOWN:
1604  selec = DEFAULT_NOT_UNK_SEL;
1605  break;
1606  case IS_TRUE:
1607  case IS_NOT_FALSE:
1608  selec = (double) clause_selectivity(root, arg,
1609  varRelid,
1610  jointype, sjinfo);
1611  break;
1612  case IS_FALSE:
1613  case IS_NOT_TRUE:
1614  selec = 1.0 - (double) clause_selectivity(root, arg,
1615  varRelid,
1616  jointype, sjinfo);
1617  break;
1618  default:
1619  elog(ERROR, "unrecognized booltesttype: %d",
1620  (int) booltesttype);
1621  selec = 0.0; /* Keep compiler quiet */
1622  break;
1623  }
1624  }
1625 
1626  ReleaseVariableStats(vardata);
1627 
1628  /* result should be in range, but make sure... */
1629  CLAMP_PROBABILITY(selec);
1630 
1631  return (Selectivity) selec;
1632 }
#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:638
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:572
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:4519
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 1441 of file selfuncs.c.

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

Referenced by clause_selectivity().

1442 {
1443  VariableStatData vardata;
1444  double selec;
1445 
1446  examine_variable(root, arg, varRelid, &vardata);
1447  if (HeapTupleIsValid(vardata.statsTuple))
1448  {
1449  /*
1450  * A boolean variable V is equivalent to the clause V = 't', so we
1451  * compute the selectivity as if that is what we have.
1452  */
1453  selec = var_eq_const(&vardata, BooleanEqualOperator,
1454  BoolGetDatum(true), false, true);
1455  }
1456  else if (is_funcclause(arg))
1457  {
1458  /*
1459  * If we have no stats and it's a function call, estimate 0.3333333.
1460  * This seems a pretty unprincipled choice, but Postgres has been
1461  * using that estimate for function calls since 1992. The hoariness
1462  * of this behavior suggests that we should not be in too much hurry
1463  * to use another value.
1464  */
1465  selec = 0.3333333;
1466  }
1467  else
1468  {
1469  /* Otherwise, the default estimate is 0.5 */
1470  selec = 0.5;
1471  }
1472  ReleaseVariableStats(vardata);
1473  return selec;
1474 }
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)
Definition: selfuncs.c:272
#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:4519
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
List* deconstruct_indexquals ( IndexPath path)

Definition at line 6256 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, NULL, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, IndexQualInfo::other_operand, palloc(), RowCompareExpr::rargs, result, IndexQualInfo::rinfo, and IndexQualInfo::varonleft.

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

6257 {
6258  List *result = NIL;
6259  IndexOptInfo *index = path->indexinfo;
6260  ListCell *lcc,
6261  *lci;
6262 
6263  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6264  {
6265  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6266  int indexcol = lfirst_int(lci);
6267  Expr *clause;
6268  Node *leftop,
6269  *rightop;
6270  IndexQualInfo *qinfo;
6271 
6272  clause = rinfo->clause;
6273 
6274  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6275  qinfo->rinfo = rinfo;
6276  qinfo->indexcol = indexcol;
6277 
6278  if (IsA(clause, OpExpr))
6279  {
6280  qinfo->clause_op = ((OpExpr *) clause)->opno;
6281  leftop = get_leftop(clause);
6282  rightop = get_rightop(clause);
6283  if (match_index_to_operand(leftop, indexcol, index))
6284  {
6285  qinfo->varonleft = true;
6286  qinfo->other_operand = rightop;
6287  }
6288  else
6289  {
6290  Assert(match_index_to_operand(rightop, indexcol, index));
6291  qinfo->varonleft = false;
6292  qinfo->other_operand = leftop;
6293  }
6294  }
6295  else if (IsA(clause, RowCompareExpr))
6296  {
6297  RowCompareExpr *rc = (RowCompareExpr *) clause;
6298 
6299  qinfo->clause_op = linitial_oid(rc->opnos);
6300  /* Examine only first columns to determine left/right sides */
6302  indexcol, index))
6303  {
6304  qinfo->varonleft = true;
6305  qinfo->other_operand = (Node *) rc->rargs;
6306  }
6307  else
6308  {
6310  indexcol, index));
6311  qinfo->varonleft = false;
6312  qinfo->other_operand = (Node *) rc->largs;
6313  }
6314  }
6315  else if (IsA(clause, ScalarArrayOpExpr))
6316  {
6317  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6318 
6319  qinfo->clause_op = saop->opno;
6320  /* index column is always on the left in this case */
6322  indexcol, index));
6323  qinfo->varonleft = true;
6324  qinfo->other_operand = (Node *) lsecond(saop->args);
6325  }
6326  else if (IsA(clause, NullTest))
6327  {
6328  qinfo->clause_op = InvalidOid;
6329  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6330  indexcol, index));
6331  qinfo->varonleft = true;
6332  qinfo->other_operand = NULL;
6333  }
6334  else
6335  {
6336  elog(ERROR, "unsupported indexqual type: %d",
6337  (int) nodeTag(clause));
6338  }
6339 
6340  result = lappend(result, qinfo);
6341  }
6342  return result;
6343 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
IndexOptInfo * indexinfo
Definition: relation.h:1031
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3179
Definition: nodes.h:509
return result
Definition: formatting.c:1632
RestrictInfo * rinfo
Definition: selfuncs.h:106
#define lsecond(l)
Definition: pg_list.h:116
Definition: type.h:90
List * indexquals
Definition: relation.h:1033
#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:1747
bool varonleft
Definition: selfuncs.h:108
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define linitial_oid(l)
Definition: pg_list.h:113
#define nodeTag(nodeptr)
Definition: nodes.h:514
Node * get_rightop(const Expr *clause)
Definition: clauses.c:216
List * indexqualcols
Definition: relation.h:1034
void * palloc(Size size)
Definition: mcxt.c:849
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 2057 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().

2058 {
2059  /* look through any binary-compatible relabeling of arrayexpr */
2060  arrayexpr = strip_array_coercion(arrayexpr);
2061 
2062  if (arrayexpr && IsA(arrayexpr, Const))
2063  {
2064  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2065  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2066  ArrayType *arrayval;
2067 
2068  if (arrayisnull)
2069  return 0;
2070  arrayval = DatumGetArrayTypeP(arraydatum);
2071  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2072  }
2073  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2074  !((ArrayExpr *) arrayexpr)->multidims)
2075  {
2076  return list_length(((ArrayExpr *) arrayexpr)->elements);
2077  }
2078  else
2079  {
2080  /* default guess --- see also scalararraysel */
2081  return 10;
2082  }
2083 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:275
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:271
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1714
#define DatumGetArrayTypeP(X)
Definition: array.h:242
Selectivity estimate_hash_bucketsize ( PlannerInfo root,
Node hashkey,
double  nbuckets 
)

Definition at line 3555 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

3556 {
3557  VariableStatData vardata;
3558  double estfract,
3559  ndistinct,
3560  stanullfrac,
3561  mcvfreq,
3562  avgfreq;
3563  bool isdefault;
3564  AttStatsSlot sslot;
3565 
3566  examine_variable(root, hashkey, 0, &vardata);
3567 
3568  /* Get number of distinct values */
3569  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3570 
3571  /* If ndistinct isn't real, punt and return 0.1, per comments above */
3572  if (isdefault)
3573  {
3574  ReleaseVariableStats(vardata);
3575  return (Selectivity) 0.1;
3576  }
3577 
3578  /* Get fraction that are null */
3579  if (HeapTupleIsValid(vardata.statsTuple))
3580  {
3581  Form_pg_statistic stats;
3582 
3583  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3584  stanullfrac = stats->stanullfrac;
3585  }
3586  else
3587  stanullfrac = 0.0;
3588 
3589  /* Compute avg freq of all distinct data values in raw relation */
3590  avgfreq = (1.0 - stanullfrac) / ndistinct;
3591 
3592  /*
3593  * Adjust ndistinct to account for restriction clauses. Observe we are
3594  * assuming that the data distribution is affected uniformly by the
3595  * restriction clauses!
3596  *
3597  * XXX Possibly better way, but much more expensive: multiply by
3598  * selectivity of rel's restriction clauses that mention the target Var.
3599  */
3600  if (vardata.rel && vardata.rel->tuples > 0)
3601  {
3602  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3603  ndistinct = clamp_row_est(ndistinct);
3604  }
3605 
3606  /*
3607  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3608  * number of buckets is less than the expected number of distinct values;
3609  * otherwise it is 1/ndistinct.
3610  */
3611  if (ndistinct > nbuckets)
3612  estfract = 1.0 / nbuckets;
3613  else
3614  estfract = 1.0 / ndistinct;
3615 
3616  /*
3617  * Look up the frequency of the most common value, if available.
3618  */
3619  mcvfreq = 0.0;
3620 
3621  if (HeapTupleIsValid(vardata.statsTuple))
3622  {
3623  if (get_attstatsslot(&sslot, vardata.statsTuple,
3626  {
3627  /*
3628  * The first MCV stat is for the most common value.
3629  */
3630  if (sslot.nnumbers > 0)
3631  mcvfreq = sslot.numbers[0];
3632  free_attstatsslot(&sslot);
3633  }
3634  }
3635 
3636  /*
3637  * Adjust estimated bucketsize upward to account for skewed distribution.
3638  */
3639  if (avgfreq > 0.0 && mcvfreq > avgfreq)
3640  estfract *= mcvfreq / avgfreq;
3641 
3642  /*
3643  * Clamp bucketsize to sane range (the above adjustment could easily
3644  * produce an out-of-range result). We set the lower bound a little above
3645  * zero, since zero isn't a very sane result.
3646  */
3647  if (estfract < 1.0e-6)
3648  estfract = 1.0e-6;
3649  else if (estfract > 1.0)
3650  estfract = 1.0;
3651 
3652  ReleaseVariableStats(vardata);
3653 
3654  return (Selectivity) estfract;
3655 }
#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:565
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:638
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:4926
float4 * numbers
Definition: lsyscache.h:52
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
double rows
Definition: relation.h:528
#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:4519
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:173
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 3232 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().

3234 {
3235  List *varinfos = NIL;
3236  double numdistinct;
3237  ListCell *l;
3238  int i;
3239 
3240  /*
3241  * We don't ever want to return an estimate of zero groups, as that tends
3242  * to lead to division-by-zero and other unpleasantness. The input_rows
3243  * estimate is usually already at least 1, but clamp it just in case it
3244  * isn't.
3245  */
3246  input_rows = clamp_row_est(input_rows);
3247 
3248  /*
3249  * If no grouping columns, there's exactly one group. (This can't happen
3250  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3251  * corner cases with set operations.)
3252  */
3253  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3254  return 1.0;
3255 
3256  /*
3257  * Count groups derived from boolean grouping expressions. For other
3258  * expressions, find the unique Vars used, treating an expression as a Var
3259  * if we can find stats for it. For each one, record the statistical
3260  * estimate of number of distinct values (total in its table, without
3261  * regard for filtering).
3262  */
3263  numdistinct = 1.0;
3264 
3265  i = 0;
3266  foreach(l, groupExprs)
3267  {
3268  Node *groupexpr = (Node *) lfirst(l);
3269  VariableStatData vardata;
3270  List *varshere;
3271  ListCell *l2;
3272 
3273  /* is expression in this grouping set? */
3274  if (pgset && !list_member_int(*pgset, i++))
3275  continue;
3276 
3277  /* Short-circuit for expressions returning boolean */
3278  if (exprType(groupexpr) == BOOLOID)
3279  {
3280  numdistinct *= 2.0;
3281  continue;
3282  }
3283 
3284  /*
3285  * If examine_variable is able to deduce anything about the GROUP BY
3286  * expression, treat it as a single variable even if it's really more
3287  * complicated.
3288  */
3289  examine_variable(root, groupexpr, 0, &vardata);
3290  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3291  {
3292  varinfos = add_unique_group_var(root, varinfos,
3293  groupexpr, &vardata);
3294  ReleaseVariableStats(vardata);
3295  continue;
3296  }
3297  ReleaseVariableStats(vardata);
3298 
3299  /*
3300  * Else pull out the component Vars. Handle PlaceHolderVars by
3301  * recursing into their arguments (effectively assuming that the
3302  * PlaceHolderVar doesn't change the number of groups, which boils
3303  * down to ignoring the possible addition of nulls to the result set).
3304  */
3305  varshere = pull_var_clause(groupexpr,
3309 
3310  /*
3311  * If we find any variable-free GROUP BY item, then either it is a
3312  * constant (and we can ignore it) or it contains a volatile function;
3313  * in the latter case we punt and assume that each input row will
3314  * yield a distinct group.
3315  */
3316  if (varshere == NIL)
3317  {
3318  if (contain_volatile_functions(groupexpr))
3319  return input_rows;
3320  continue;
3321  }
3322 
3323  /*
3324  * Else add variables to varinfos list
3325  */
3326  foreach(l2, varshere)
3327  {
3328  Node *var = (Node *) lfirst(l2);
3329 
3330  examine_variable(root, var, 0, &vardata);
3331  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3332  ReleaseVariableStats(vardata);
3333  }
3334  }
3335 
3336  /*
3337  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3338  * list.
3339  */
3340  if (varinfos == NIL)
3341  {
3342  /* Guard against out-of-range answers */
3343  if (numdistinct > input_rows)
3344  numdistinct = input_rows;
3345  return numdistinct;
3346  }
3347 
3348  /*
3349  * Group Vars by relation and estimate total numdistinct.
3350  *
3351  * For each iteration of the outer loop, we process the frontmost Var in
3352  * varinfos, plus all other Vars in the same relation. We remove these
3353  * Vars from the newvarinfos list for the next iteration. This is the
3354  * easiest way to group Vars of same rel together.
3355  */
3356  do
3357  {
3358  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3359  RelOptInfo *rel = varinfo1->rel;
3360  double reldistinct = 1;
3361  double relmaxndistinct = reldistinct;
3362  int relvarcount = 0;
3363  List *newvarinfos = NIL;
3364  List *relvarinfos = NIL;
3365 
3366  /*
3367  * Split the list of varinfos in two - one for the current rel, one
3368  * for remaining Vars on other rels.
3369  */
3370  relvarinfos = lcons(varinfo1, relvarinfos);
3371  for_each_cell(l, lnext(list_head(varinfos)))
3372  {
3373  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3374 
3375  if (varinfo2->rel == varinfo1->rel)
3376  {
3377  /* varinfos on current rel */
3378  relvarinfos = lcons(varinfo2, relvarinfos);
3379  }
3380  else
3381  {
3382  /* not time to process varinfo2 yet */
3383  newvarinfos = lcons(varinfo2, newvarinfos);
3384  }
3385  }
3386 
3387  /*
3388  * Get the numdistinct estimate for the Vars of this rel. We
3389  * iteratively search for multivariate n-distinct with maximum number
3390  * of vars; assuming that each var group is independent of the others,
3391  * we multiply them together. Any remaining relvarinfos after no more
3392  * multivariate matches are found are assumed independent too, so
3393  * their individual ndistinct estimates are multiplied also.
3394  *
3395  * While iterating, count how many separate numdistinct values we
3396  * apply. We apply a fudge factor below, but only if we multiplied
3397  * more than one such values.
3398  */
3399  while (relvarinfos)
3400  {
3401  double mvndistinct;
3402 
3403  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3404  &mvndistinct))
3405  {
3406  reldistinct *= mvndistinct;
3407  if (relmaxndistinct < mvndistinct)
3408  relmaxndistinct = mvndistinct;
3409  relvarcount++;
3410  }
3411  else
3412  {
3413  foreach(l, relvarinfos)
3414  {
3415  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3416 
3417  reldistinct *= varinfo2->ndistinct;
3418  if (relmaxndistinct < varinfo2->ndistinct)
3419  relmaxndistinct = varinfo2->ndistinct;
3420  relvarcount++;
3421  }
3422 
3423  /* we're done with this relation */
3424  relvarinfos = NIL;
3425  }
3426  }
3427 
3428  /*
3429  * Sanity check --- don't divide by zero if empty relation.
3430  */
3431  Assert(IS_SIMPLE_REL(rel));
3432  if (rel->tuples > 0)
3433  {
3434  /*
3435  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3436  * fudge factor is because the Vars are probably correlated but we
3437  * don't know by how much. We should never clamp to less than the
3438  * largest ndistinct value for any of the Vars, though, since
3439  * there will surely be at least that many groups.
3440  */
3441  double clamp = rel->tuples;
3442 
3443  if (relvarcount > 1)
3444  {
3445  clamp *= 0.1;
3446  if (clamp < relmaxndistinct)
3447  {
3448  clamp = relmaxndistinct;
3449  /* for sanity in case some ndistinct is too large: */
3450  if (clamp > rel->tuples)
3451  clamp = rel->tuples;
3452  }
3453  }
3454  if (reldistinct > clamp)
3455  reldistinct = clamp;
3456 
3457  /*
3458  * Update the estimate based on the restriction selectivity,
3459  * guarding against division by zero when reldistinct is zero.
3460  * Also skip this if we know that we are returning all rows.
3461  */
3462  if (reldistinct > 0 && rel->rows < rel->tuples)
3463  {
3464  /*
3465  * Given a table containing N rows with n distinct values in a
3466  * uniform distribution, if we select p rows at random then
3467  * the expected number of distinct values selected is
3468  *
3469  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3470  *
3471  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3472  *
3473  * See "Approximating block accesses in database
3474  * organizations", S. B. Yao, Communications of the ACM,
3475  * Volume 20 Issue 4, April 1977 Pages 260-261.
3476  *
3477  * Alternatively, re-arranging the terms from the factorials,
3478  * this may be written as
3479  *
3480  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3481  *
3482  * This form of the formula is more efficient to compute in
3483  * the common case where p is larger than N/n. Additionally,
3484  * as pointed out by Dell'Era, if i << N for all terms in the
3485  * product, it can be approximated by
3486  *
3487  * n * (1 - ((N-p)/N)^(N/n))
3488  *
3489  * See "Expected distinct values when selecting from a bag
3490  * without replacement", Alberto Dell'Era,
3491  * http://www.adellera.it/investigations/distinct_balls/.
3492  *
3493  * The condition i << N is equivalent to n >> 1, so this is a
3494  * good approximation when the number of distinct values in
3495  * the table is large. It turns out that this formula also
3496  * works well even when n is small.
3497  */
3498  reldistinct *=
3499  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3500  rel->tuples / reldistinct));
3501  }
3502  reldistinct = clamp_row_est(reldistinct);
3503 
3504  /*
3505  * Update estimate of total distinct groups.
3506  */
3507  numdistinct *= reldistinct;
3508  }
3509 
3510  varinfos = newvarinfos;
3511  } while (varinfos != NIL);
3512 
3513  numdistinct = ceil(numdistinct);
3514 
3515  /* Guard against out-of-range answers */
3516  if (numdistinct > input_rows)
3517  numdistinct = input_rows;
3518  if (numdistinct < 1.0)
3519  numdistinct = 1.0;
3520 
3521  return numdistinct;
3522 }
#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:565
Definition: nodes.h:509
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:951
double ndistinct
Definition: selfuncs.c:3110
#define PVC_RECURSE_PLACEHOLDERS
Definition: var.h:26
#define IS_SIMPLE_REL(rel)
Definition: relation.h:505
#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:3676
#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:3114
double rows
Definition: relation.h:528
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:4519
#define Assert(condition)
Definition: c.h:675
#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:173
Definition: pg_list.h:45
RelOptInfo * rel
Definition: selfuncs.c:3109
void examine_variable ( PlannerInfo root,
Node node,
int  varRelid,
VariableStatData vardata 
)

Definition at line 4519 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, NULL, 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_bucketsize(), estimate_num_groups(), get_join_variables(), get_restriction_variable(), mergejoinscansel(), nulltestsel(), and scalararraysel_containment().

4521 {
4522  Node *basenode;
4523  Relids varnos;
4524  RelOptInfo *onerel;
4525 
4526  /* Make sure we don't return dangling pointers in vardata */
4527  MemSet(vardata, 0, sizeof(VariableStatData));
4528 
4529  /* Save the exposed type of the expression */
4530  vardata->vartype = exprType(node);
4531 
4532  /* Look inside any binary-compatible relabeling */
4533 
4534  if (IsA(node, RelabelType))
4535  basenode = (Node *) ((RelabelType *) node)->arg;
4536  else
4537  basenode = node;
4538 
4539  /* Fast path for a simple Var */
4540 
4541  if (IsA(basenode, Var) &&
4542  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4543  {
4544  Var *var = (Var *) basenode;
4545 
4546  /* Set up result fields other than the stats tuple */
4547  vardata->var = basenode; /* return Var without relabeling */
4548  vardata->rel = find_base_rel(root, var->varno);
4549  vardata->atttype = var->vartype;
4550  vardata->atttypmod = var->vartypmod;
4551  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4552 
4553  /* Try to locate some stats */
4554  examine_simple_variable(root, var, vardata);
4555 
4556  return;
4557  }
4558 
4559  /*
4560  * Okay, it's a more complicated expression. Determine variable
4561  * membership. Note that when varRelid isn't zero, only vars of that
4562  * relation are considered "real" vars.
4563  */
4564  varnos = pull_varnos(basenode);
4565 
4566  onerel = NULL;
4567 
4568  switch (bms_membership(varnos))
4569  {
4570  case BMS_EMPTY_SET:
4571  /* No Vars at all ... must be pseudo-constant clause */
4572  break;
4573  case BMS_SINGLETON:
4574  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4575  {
4576  onerel = find_base_rel(root,
4577  (varRelid ? varRelid : bms_singleton_member(varnos)));
4578  vardata->rel = onerel;
4579  node = basenode; /* strip any relabeling */
4580  }
4581  /* else treat it as a constant */
4582  break;
4583  case BMS_MULTIPLE:
4584  if (varRelid == 0)
4585  {
4586  /* treat it as a variable of a join relation */
4587  vardata->rel = find_join_rel(root, varnos);
4588  node = basenode; /* strip any relabeling */
4589  }
4590  else if (bms_is_member(varRelid, varnos))
4591  {
4592  /* ignore the vars belonging to other relations */
4593  vardata->rel = find_base_rel(root, varRelid);
4594  node = basenode; /* strip any relabeling */
4595  /* note: no point in expressional-index search here */
4596  }
4597  /* else treat it as a constant */
4598  break;
4599  }
4600 
4601  bms_free(varnos);
4602 
4603  vardata->var = node;
4604  vardata->atttype = exprType(node);
4605  vardata->atttypmod = exprTypmod(node);
4606 
4607  if (onerel)
4608  {
4609  /*
4610  * We have an expression in vars of a single relation. Try to match
4611  * it to expressional index columns, in hopes of finding some
4612  * statistics.
4613  *
4614  * XXX it's conceivable that there are multiple matches with different
4615  * index opfamilies; if so, we need to pick one that matches the
4616  * operator we are estimating for. FIXME later.
4617  */
4618  ListCell *ilist;
4619 
4620  foreach(ilist, onerel->indexlist)
4621  {
4622  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4623  ListCell *indexpr_item;
4624  int pos;
4625 
4626  indexpr_item = list_head(index->indexprs);
4627  if (indexpr_item == NULL)
4628  continue; /* no expressions here... */
4629 
4630  for (pos = 0; pos < index->ncolumns; pos++)
4631  {
4632  if (index->indexkeys[pos] == 0)
4633  {
4634  Node *indexkey;
4635 
4636  if (indexpr_item == NULL)
4637  elog(ERROR, "too few entries in indexprs list");
4638  indexkey = (Node *) lfirst(indexpr_item);
4639  if (indexkey && IsA(indexkey, RelabelType))
4640  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4641  if (equal(node, indexkey))
4642  {
4643  /*
4644  * Found a match ... is it a unique index? Tests here
4645  * should match has_unique_index().
4646  */
4647  if (index->unique &&
4648  index->ncolumns == 1 &&
4649  (index->indpred == NIL || index->predOK))
4650  vardata->isunique = true;
4651 
4652  /*
4653  * Has it got stats? We only consider stats for
4654  * non-partial indexes, since partial indexes probably
4655  * don't reflect whole-relation statistics; the above
4656  * check for uniqueness is the only info we take from
4657  * a partial index.
4658  *
4659  * An index stats hook, however, must make its own
4660  * decisions about what to do with partial indexes.
4661  */
4662  if (get_index_stats_hook &&
4663  (*get_index_stats_hook) (root, index->indexoid,
4664  pos + 1, vardata))
4665  {
4666  /*
4667  * The hook took control of acquiring a stats
4668  * tuple. If it did supply a tuple, it'd better
4669  * have supplied a freefunc.
4670  */
4671  if (HeapTupleIsValid(vardata->statsTuple) &&
4672  !vardata->freefunc)
4673  elog(ERROR, "no function provided to release variable stats with");
4674  }
4675  else if (index->indpred == NIL)
4676  {
4677  vardata->statsTuple =
4679  ObjectIdGetDatum(index->indexoid),
4680  Int16GetDatum(pos + 1),
4681  BoolGetDatum(false));
4682  vardata->freefunc = ReleaseSysCache;
4683 
4684  if (HeapTupleIsValid(vardata->statsTuple))
4685  {
4686  /* Get index's table for permission check */
4687  RangeTblEntry *rte;
4688 
4689  rte = planner_rt_fetch(index->rel->relid, root);
4690  Assert(rte->rtekind == RTE_RELATION);
4691 
4692  /*
4693  * For simplicity, we insist on the whole
4694  * table being selectable, rather than trying
4695  * to identify which column(s) the index
4696  * depends on.
4697  */
4698  vardata->acl_ok =
4700  ACL_SELECT) == ACLCHECK_OK);
4701  }
4702  else
4703  {
4704  /* suppress leakproofness checks later */
4705  vardata->acl_ok = true;
4706  }
4707  }
4708  if (vardata->statsTuple)
4709  break;
4710  }
4711  indexpr_item = lnext(indexpr_item);
4712  }
4713  }
4714  if (vardata->statsTuple)
4715  break;
4716  }
4717  }
4718 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
bool predOK
Definition: relation.h:663
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:308
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2962
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:283
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:509
#define MemSet(start, val, len)
Definition: c.h:857
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4730
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:664
Definition: type.h:90
RelOptInfo * rel
Definition: relation.h:633
#define planner_rt_fetch(rti, root)
Definition: relation.h:325
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1733
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:170
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int ncolumns
Definition: relation.h:641
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: relation.h:553
Index varno
Definition: primnodes.h:166
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:634
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define ACL_SELECT
Definition: parsenodes.h:73
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:526
List * indexlist
Definition: relation.h:562
#define BoolGetDatum(X)
Definition: postgres.h:408
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:155
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
RTEKind rtekind
Definition: parsenodes.h:929
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:160
void * arg
int * indexkeys
Definition: relation.h:642
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:631
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:243
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
List * indpred
Definition: relation.h:654
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
List * indexprs
Definition: relation.h:653
int32 vartypmod
Definition: primnodes.h:171
void genericcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
List qinfos,
GenericCosts costs 
)

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

6410 {
6411  IndexOptInfo *index = path->indexinfo;
6412  List *indexQuals = path->indexquals;
6413  List *indexOrderBys = path->indexorderbys;
6414  Cost indexStartupCost;
6415  Cost indexTotalCost;
6416  Selectivity indexSelectivity;
6417  double indexCorrelation;
6418  double numIndexPages;
6419  double numIndexTuples;
6420  double spc_random_page_cost;
6421  double num_sa_scans;
6422  double num_outer_scans;
6423  double num_scans;
6424  double qual_op_cost;
6425  double qual_arg_cost;
6426  List *selectivityQuals;
6427  ListCell *l;
6428 
6429  /*
6430  * If the index is partial, AND the index predicate with the explicitly
6431  * given indexquals to produce a more accurate idea of the index
6432  * selectivity.
6433  */
6434  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6435 
6436  /*
6437  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6438  * index scans that will be performed.
6439  */
6440  num_sa_scans = 1;
6441  foreach(l, indexQuals)
6442  {
6443  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6444 
6445  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6446  {
6447  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6448  int alength = estimate_array_length(lsecond(saop->args));
6449 
6450  if (alength > 1)
6451  num_sa_scans *= alength;
6452  }
6453  }
6454 
6455  /* Estimate the fraction of main-table tuples that will be visited */
6456  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6457  index->rel->relid,
6458  JOIN_INNER,
6459  NULL);
6460 
6461  /*
6462  * If caller didn't give us an estimate, estimate the number of index
6463  * tuples that will be visited. We do it in this rather peculiar-looking
6464  * way in order to get the right answer for partial indexes.
6465  */
6466  numIndexTuples = costs->numIndexTuples;
6467  if (numIndexTuples <= 0.0)
6468  {
6469  numIndexTuples = indexSelectivity * index->rel->tuples;
6470 
6471  /*
6472  * The above calculation counts all the tuples visited across all
6473  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6474  * average per-indexscan number, so adjust. This is a handy place to
6475  * round to integer, too. (If caller supplied tuple estimate, it's
6476  * responsible for handling these considerations.)
6477  */
6478  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6479  }
6480 
6481  /*
6482  * We can bound the number of tuples by the index size in any case. Also,
6483  * always estimate at least one tuple is touched, even when
6484  * indexSelectivity estimate is tiny.
6485  */
6486  if (numIndexTuples > index->tuples)
6487  numIndexTuples = index->tuples;
6488  if (numIndexTuples < 1.0)
6489  numIndexTuples = 1.0;
6490 
6491  /*
6492  * Estimate the number of index pages that will be retrieved.
6493  *
6494  * We use the simplistic method of taking a pro-rata fraction of the total
6495  * number of index pages. In effect, this counts only leaf pages and not
6496  * any overhead such as index metapage or upper tree levels.
6497  *
6498  * In practice access to upper index levels is often nearly free because
6499  * those tend to stay in cache under load; moreover, the cost involved is
6500  * highly dependent on index type. We therefore ignore such costs here
6501  * and leave it to the caller to add a suitable charge if needed.
6502  */
6503  if (index->pages > 1 && index->tuples > 1)
6504  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6505  else
6506  numIndexPages = 1.0;
6507 
6508  /* fetch estimated page cost for tablespace containing index */
6510  &spc_random_page_cost,
6511  NULL);
6512 
6513  /*
6514  * Now compute the disk access costs.
6515  *
6516  * The above calculations are all per-index-scan. However, if we are in a
6517  * nestloop inner scan, we can expect the scan to be repeated (with
6518  * different search keys) for each row of the outer relation. Likewise,
6519  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6520  * the potential for cache effects to reduce the number of disk page
6521  * fetches needed. We want to estimate the average per-scan I/O cost in
6522  * the presence of caching.
6523  *
6524  * We use the Mackert-Lohman formula (see costsize.c for details) to
6525  * estimate the total number of page fetches that occur. While this
6526  * wasn't what it was designed for, it seems a reasonable model anyway.
6527  * Note that we are counting pages not tuples anymore, so we take N = T =
6528  * index size, as if there were one "tuple" per page.
6529  */
6530  num_outer_scans = loop_count;
6531  num_scans = num_sa_scans * num_outer_scans;
6532 
6533  if (num_scans > 1)
6534  {
6535  double pages_fetched;
6536 
6537  /* total page fetches ignoring cache effects */
6538  pages_fetched = numIndexPages * num_scans;
6539 
6540  /* use Mackert and Lohman formula to adjust for cache effects */
6541  pages_fetched = index_pages_fetched(pages_fetched,
6542  index->pages,
6543  (double) index->pages,
6544  root);
6545 
6546  /*
6547  * Now compute the total disk access cost, and then report a pro-rated
6548  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6549  * since that's internal to the indexscan.)
6550  */
6551  indexTotalCost = (pages_fetched * spc_random_page_cost)
6552  / num_outer_scans;
6553  }
6554  else
6555  {
6556  /*
6557  * For a single index scan, we just charge spc_random_page_cost per
6558  * page touched.
6559  */
6560  indexTotalCost = numIndexPages * spc_random_page_cost;
6561  }
6562 
6563  /*
6564  * CPU cost: any complex expressions in the indexquals will need to be
6565  * evaluated once at the start of the scan to reduce them to runtime keys
6566  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6567  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6568  * indexqual operator. Because we have numIndexTuples as a per-scan
6569  * number, we have to multiply by num_sa_scans to get the correct result
6570  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6571  * ORDER BY expressions.
6572  *
6573  * Note: this neglects the possible costs of rechecking lossy operators.
6574  * Detecting that that might be needed seems more expensive than it's
6575  * worth, though, considering all the other inaccuracies here ...
6576  */
6577  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6578  orderby_operands_eval_cost(root, path);
6579  qual_op_cost = cpu_operator_cost *
6580  (list_length(indexQuals) + list_length(indexOrderBys));
6581 
6582  indexStartupCost = qual_arg_cost;
6583  indexTotalCost += qual_arg_cost;
6584  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6585 
6586  /*
6587  * Generic assumption about index correlation: there isn't any.
6588  */
6589  indexCorrelation = 0.0;
6590 
6591  /*
6592  * Return everything to caller.
6593  */
6594  costs->indexStartupCost = indexStartupCost;
6595  costs->indexTotalCost = indexTotalCost;
6596  costs->indexSelectivity = indexSelectivity;
6597  costs->indexCorrelation = indexCorrelation;
6598  costs->numIndexPages = numIndexPages;
6599  costs->numIndexTuples = numIndexTuples;
6600  costs->spc_random_page_cost = spc_random_page_cost;
6601  costs->num_sa_scans = num_sa_scans;
6602 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
IndexOptInfo * indexinfo
Definition: relation.h:1031
double tuples
Definition: relation.h:565
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6624
Oid reltablespace
Definition: relation.h:632
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6351
double Selectivity
Definition: nodes.h:638
double tuples
Definition: relation.h:637
#define lsecond(l)
Definition: pg_list.h:116
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6376
Definition: type.h:90
BlockNumber pages
Definition: relation.h:636
List * indexquals
Definition: relation.h:1033
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2057
RelOptInfo * rel
Definition: relation.h:633
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:553
Expr * clause
Definition: relation.h:1747
double indexCorrelation
Definition: selfuncs.h:132
List * indexorderbys
Definition: relation.h:1035
double spc_random_page_cost
Definition: selfuncs.h:137
double numIndexTuples
Definition: selfuncs.h:136
#define NULL
Definition: c.h:229
#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:813
double Cost
Definition: nodes.h:639
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 4457 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().

4460 {
4461  Node *left,
4462  *right;
4463 
4464  if (list_length(args) != 2)
4465  elog(ERROR, "join operator should take two arguments");
4466 
4467  left = (Node *) linitial(args);
4468  right = (Node *) lsecond(args);
4469 
4470  examine_variable(root, left, 0, vardata1);
4471  examine_variable(root, right, 0, vardata2);
4472 
4473  if (vardata1->rel &&
4474  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4475  *join_is_reversed = true; /* var1 is on RHS */
4476  else if (vardata2->rel &&
4477  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4478  *join_is_reversed = true; /* var2 is on LHS */
4479  else
4480  *join_is_reversed = false;
4481 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:509
#define lsecond(l)
Definition: pg_list.h:116
Relids syn_lefthand
Definition: relation.h:1919
Relids syn_righthand
Definition: relation.h:1920
#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:525
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4519
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 4397 of file selfuncs.c.

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

Referenced by _int_matchsel(), arraycontsel(), eqsel(), ltreeparentsel(), networksel(), patternsel(), rangesel(), scalargtsel(), scalarltsel(), and tsmatchsel().

4400 {
4401  Node *left,
4402  *right;
4403  VariableStatData rdata;
4404 
4405  /* Fail if not a binary opclause (probably shouldn't happen) */
4406  if (list_length(args) != 2)
4407  return false;
4408 
4409  left = (Node *) linitial(args);
4410  right = (Node *) lsecond(args);
4411 
4412  /*
4413  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4414  * relations will be treated as pseudoconstants.
4415  */
4416  examine_variable(root, left, varRelid, vardata);
4417  examine_variable(root, right, varRelid, &rdata);
4418 
4419  /*
4420  * If one side is a variable and the other not, we win.
4421  */
4422  if (vardata->rel && rdata.rel == NULL)
4423  {
4424  *varonleft = true;
4425  *other = estimate_expression_value(root, rdata.var);
4426  /* Assume we need no ReleaseVariableStats(rdata) here */
4427  return true;
4428  }
4429 
4430  if (vardata->rel == NULL && rdata.rel)
4431  {
4432  *varonleft = false;
4433  *other = estimate_expression_value(root, vardata->var);
4434  /* Assume we need no ReleaseVariableStats(*vardata) here */
4435  *vardata = rdata;
4436  return true;
4437  }
4438 
4439  /* Oops, clause has wrong structure (probably var op var) */
4440  ReleaseVariableStats(*vardata);
4441  ReleaseVariableStats(rdata);
4442 
4443  return false;
4444 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2433
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:509
#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:4519
#define NULL
Definition: c.h:229
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 4926 of file selfuncs.c.

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

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

4927 {
4928  double stadistinct;
4929  double stanullfrac = 0.0;
4930  double ntuples;
4931 
4932  *isdefault = false;
4933 
4934  /*
4935  * Determine the stadistinct value to use. There are cases where we can
4936  * get an estimate even without a pg_statistic entry, or can get a better
4937  * value than is in pg_statistic. Grab stanullfrac too if we can find it
4938  * (otherwise, assume no nulls, for lack of any better idea).
4939  */
4940  if (HeapTupleIsValid(vardata->statsTuple))
4941  {
4942  /* Use the pg_statistic entry */
4943  Form_pg_statistic stats;
4944 
4945  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4946  stadistinct = stats->stadistinct;
4947  stanullfrac = stats->stanullfrac;
4948  }
4949  else if (vardata->vartype == BOOLOID)
4950  {
4951  /*
4952  * Special-case boolean columns: presumably, two distinct values.
4953  *
4954  * Are there any other datatypes we should wire in special estimates
4955  * for?
4956  */
4957  stadistinct = 2.0;
4958  }
4959  else
4960  {
4961  /*
4962  * We don't keep statistics for system columns, but in some cases we
4963  * can infer distinctness anyway.
4964  */
4965  if (vardata->var && IsA(vardata->var, Var))
4966  {
4967  switch (((Var *) vardata->var)->varattno)
4968  {
4971  stadistinct = -1.0; /* unique (and all non null) */
4972  break;
4974  stadistinct = 1.0; /* only 1 value */
4975  break;
4976  default:
4977  stadistinct = 0.0; /* means "unknown" */
4978  break;
4979  }
4980  }
4981  else
4982  stadistinct = 0.0; /* means "unknown" */
4983 
4984  /*
4985  * XXX consider using estimate_num_groups on expressions?
4986  */
4987  }
4988 
4989  /*
4990  * If there is a unique index or DISTINCT clause for the variable, assume
4991  * it is unique no matter what pg_statistic says; the statistics could be
4992  * out of date, or we might have found a partial unique index that proves
4993  * the var is unique for this query. However, we'd better still believe
4994  * the null-fraction statistic.
4995  */
4996  if (vardata->isunique)
4997  stadistinct = -1.0 * (1.0 - stanullfrac);
4998 
4999  /*
5000  * If we had an absolute estimate, use that.
5001  */
5002  if (stadistinct > 0.0)
5003  return clamp_row_est(stadistinct);
5004 
5005  /*
5006  * Otherwise we need to get the relation size; punt if not available.
5007  */
5008  if (vardata->rel == NULL)
5009  {
5010  *isdefault = true;
5011  return DEFAULT_NUM_DISTINCT;
5012  }
5013  ntuples = vardata->rel->tuples;
5014  if (ntuples <= 0.0)
5015  {
5016  *isdefault = true;
5017  return DEFAULT_NUM_DISTINCT;
5018  }
5019 
5020  /*
5021  * If we had a relative estimate, use that.
5022  */
5023  if (stadistinct < 0.0)
5024  return clamp_row_est(-stadistinct * ntuples);
5025 
5026  /*
5027  * With no data, estimate ndistinct = ntuples if the table is small, else
5028  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
5029  * that the behavior isn't discontinuous.
5030  */
5031  if (ntuples < DEFAULT_NUM_DISTINCT)
5032  return clamp_row_est(ntuples);
5033 
5034  *isdefault = true;
5035  return DEFAULT_NUM_DISTINCT;
5036 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#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:565
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
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#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:173
double histogram_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Datum  constval,
bool  varonleft,
int  min_hist_size,
int  n_skip,
int *  hist_size 
)

Definition at line 677 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, result, STATISTIC_KIND_HISTOGRAM, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by ltreeparentsel(), and patternsel().

681 {
682  double result;
683  AttStatsSlot sslot;
684 
685  /* check sanity of parameters */
686  Assert(n_skip >= 0);
687  Assert(min_hist_size > 2 * n_skip);
688 
689  if (HeapTupleIsValid(vardata->statsTuple) &&
690  statistic_proc_security_check(vardata, opproc->fn_oid) &&
691  get_attstatsslot(&sslot, vardata->statsTuple,
694  {
695  *hist_size = sslot.nvalues;
696  if (sslot.nvalues >= min_hist_size)
697  {
698  int nmatch = 0;
699  int i;
700 
701  for (i = n_skip; i < sslot.nvalues - n_skip; i++)
702  {
703  if (varonleft ?
706  sslot.values[i],
707  constval)) :
710  constval,
711  sslot.values[i])))
712  nmatch++;
713  }
714  result = ((double) nmatch) / ((double) (sslot.nvalues - 2 * n_skip));
715  }
716  else
717  result = -1;
718  free_attstatsslot(&sslot);
719  }
720  else
721  {
722  *hist_size = 0;
723  result = -1;
724  }
725 
726  return result;
727 }
#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:4897
return result
Definition: formatting.c:1632
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1047
#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:675
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 6030 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(), NULL, 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().

6031 {
6032  Oid datatype = str_const->consttype;
6033  char *workstr;
6034  int len;
6035  Datum cmpstr;
6036  text *cmptxt = NULL;
6037  mbcharacter_incrementer charinc;
6038 
6039  /*
6040  * Get a modifiable copy of the prefix string in C-string format, and set
6041  * up the string we will compare to as a Datum. In C locale this can just
6042  * be the given prefix string, otherwise we need to add a suffix. Types
6043  * NAME and BYTEA sort bytewise so they don't need a suffix either.
6044  */
6045  if (datatype == NAMEOID)
6046  {
6048  str_const->constvalue));
6049  len = strlen(workstr);
6050  cmpstr = str_const->constvalue;
6051  }
6052  else if (datatype == BYTEAOID)
6053  {
6054  bytea *bstr = DatumGetByteaPP(str_const->constvalue);
6055 
6056  len = VARSIZE_ANY_EXHDR(bstr);
6057  workstr = (char *) palloc(len);
6058  memcpy(workstr, VARDATA_ANY(bstr), len);
6059  Assert((Pointer) bstr == DatumGetPointer(str_const->constvalue));
6060  cmpstr = str_const->constvalue;
6061  }
6062  else
6063  {
6064  workstr = TextDatumGetCString(str_const->constvalue);
6065  len = strlen(workstr);
6066  if (lc_collate_is_c(collation) || len == 0)
6067  cmpstr = str_const->constvalue;
6068  else
6069  {
6070  /* If first time through, determine the suffix to use */
6071  static char suffixchar = 0;
6072  static Oid suffixcollation = 0;
6073 
6074  if (!suffixchar || suffixcollation != collation)
6075  {
6076  char *best;
6077 
6078  best = "Z";
6079  if (varstr_cmp(best, 1, "z", 1, collation) < 0)
6080  best = "z";
6081  if (varstr_cmp(best, 1, "y", 1, collation) < 0)
6082  best = "y";
6083  if (varstr_cmp(best, 1, "9", 1, collation) < 0)
6084  best = "9";
6085  suffixchar = *best;
6086  suffixcollation = collation;
6087  }
6088 
6089  /* And build the string to compare to */
6090  cmptxt = (text *) palloc(VARHDRSZ + len + 1);
6091  SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
6092  memcpy(VARDATA(cmptxt), workstr, len);
6093  *(VARDATA(cmptxt) + len) = suffixchar;
6094  cmpstr = PointerGetDatum(cmptxt);
6095  }
6096  }
6097 
6098  /* Select appropriate character-incrementer function */
6099  if (datatype == BYTEAOID)
6100  charinc = byte_increment;
6101  else
6103 
6104  /* And search ... */
6105  while (len > 0)
6106  {
6107  int charlen;
6108  unsigned char *lastchar;
6109 
6110  /* Identify the last character --- for bytea, just the last byte */
6111  if (datatype == BYTEAOID)
6112  charlen = 1;
6113  else
6114  charlen = len - pg_mbcliplen(workstr, len, len - 1);
6115  lastchar = (unsigned char *) (workstr + len - charlen);
6116 
6117  /*
6118  * Try to generate a larger string by incrementing the last character
6119  * (for BYTEA, we treat each byte as a character).
6120  *
6121  * Note: the incrementer function is expected to return true if it's
6122  * generated a valid-per-the-encoding new character, otherwise false.
6123  * The contents of the character on false return are unspecified.
6124  */
6125  while (charinc(lastchar, charlen))
6126  {
6127  Const *workstr_const;
6128 
6129  if (datatype == BYTEAOID)
6130  workstr_const = string_to_bytea_const(workstr, len);
6131  else
6132  workstr_const = string_to_const(workstr, datatype);
6133 
6134  if (DatumGetBool(FunctionCall2Coll(ltproc,
6135  collation,
6136  cmpstr,
6137  workstr_const->constvalue)))
6138  {
6139  /* Successfully made a string larger than cmpstr */
6140  if (cmptxt)
6141  pfree(cmptxt);
6142  pfree(workstr);
6143  return workstr_const;
6144  }
6145 
6146  /* No good, release unusable value and try again */
6147  pfree(DatumGetPointer(workstr_const->constvalue));
6148  pfree(workstr_const);
6149  }
6150 
6151  /*
6152  * No luck here, so truncate off the last character and try to
6153  * increment the next one.
6154  */
6155  len -= charlen;
6156  workstr[len] = '\0';
6157  }
6158 
6159  /* Failed... */
6160  if (cmptxt)
6161  pfree(cmptxt);
6162  pfree(workstr);
6163 
6164  return NULL;
6165 }
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:445
#define DatumGetByteaPP(X)
Definition: fmgr.h:255
static Const * string_to_bytea_const(const char *str, size_t str_len)
Definition: selfuncs.c:6236
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1047
unsigned int Oid
Definition: postgres_ext.h:31
static bool byte_increment(unsigned char *ptr, int len)
Definition: selfuncs.c:5980
static Const * string_to_const(const char *str, Oid datatype)
Definition: selfuncs.c:6193
Oid consttype
Definition: primnodes.h:192
void pfree(void *pointer)
Definition: mcxt.c:950
char * Pointer
Definition: c.h:245
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:831
#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:356
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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:849
mbcharacter_incrementer pg_database_encoding_character_incrementer(void)
Definition: wchar.c:1842
Definition: c.h:439
#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 605 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().

608 {
609  double mcv_selec,
610  sumcommon;
611  AttStatsSlot sslot;
612  int i;
613 
614  mcv_selec = 0.0;
615  sumcommon = 0.0;
616 
617  if (HeapTupleIsValid(vardata->statsTuple) &&
618  statistic_proc_security_check(vardata, opproc->fn_oid) &&
619  get_attstatsslot(&sslot, vardata->statsTuple,
622  {
623  for (i = 0; i < sslot.nvalues; i++)
624  {
625  if (varonleft ?
628  sslot.values[i],
629  constval)) :
632  constval,
633  sslot.values[i])))
634  mcv_selec += sslot.numbers[i];
635  sumcommon += sslot.numbers[i];
636  }
637  free_attstatsslot(&sslot);
638  }
639 
640  *sumcommonp = sumcommon;
641  return mcv_selec;
642 }
#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:4897
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1047
#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 2808 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().

2812 {
2813  Node *left,
2814  *right;
2815  VariableStatData leftvar,
2816  rightvar;
2817  int op_strategy;
2818  Oid op_lefttype;
2819  Oid op_righttype;
2820  Oid opno,
2821  lsortop,
2822  rsortop,
2823  lstatop,
2824  rstatop,
2825  ltop,
2826  leop,
2827  revltop,
2828  revleop;
2829  bool isgt;
2830  Datum leftmin,
2831  leftmax,
2832  rightmin,
2833  rightmax;
2834  double selec;
2835 
2836  /* Set default results if we can't figure anything out. */
2837  /* XXX should default "start" fraction be a bit more than 0? */
2838  *leftstart = *rightstart = 0.0;
2839  *leftend = *rightend = 1.0;
2840 
2841  /* Deconstruct the merge clause */
2842  if (!is_opclause(clause))
2843  return; /* shouldn't happen */
2844  opno = ((OpExpr *) clause)->opno;
2845  left = get_leftop((Expr *) clause);
2846  right = get_rightop((Expr *) clause);
2847  if (!right)
2848  return; /* shouldn't happen */
2849 
2850  /* Look for stats for the inputs */
2851  examine_variable(root, left, 0, &leftvar);
2852  examine_variable(root, right, 0, &rightvar);
2853 
2854  /* Extract the operator's declared left/right datatypes */
2855  get_op_opfamily_properties(opno, opfamily, false,
2856  &op_strategy,
2857  &op_lefttype,
2858  &op_righttype);
2859  Assert(op_strategy == BTEqualStrategyNumber);
2860 
2861  /*
2862  * Look up the various operators we need. If we don't find them all, it
2863  * probably means the opfamily is broken, but we just fail silently.
2864  *
2865  * Note: we expect that pg_statistic histograms will be sorted by the '<'
2866  * operator, regardless of which sort direction we are considering.
2867  */
2868  switch (strategy)
2869  {
2870  case BTLessStrategyNumber:
2871  isgt = false;
2872  if (op_lefttype == op_righttype)
2873  {
2874  /* easy case */
2875  ltop = get_opfamily_member(opfamily,
2876  op_lefttype, op_righttype,
2878  leop = get_opfamily_member(opfamily,
2879  op_lefttype, op_righttype,
2881  lsortop = ltop;
2882  rsortop = ltop;
2883  lstatop = lsortop;
2884  rstatop = rsortop;
2885  revltop = ltop;
2886  revleop = leop;
2887  }
2888  else
2889  {
2890  ltop = get_opfamily_member(opfamily,
2891  op_lefttype, op_righttype,
2893  leop = get_opfamily_member(opfamily,
2894  op_lefttype, op_righttype,
2896  lsortop = get_opfamily_member(opfamily,
2897  op_lefttype, op_lefttype,
2899  rsortop = get_opfamily_member(opfamily,
2900  op_righttype, op_righttype,
2902  lstatop = lsortop;
2903  rstatop = rsortop;
2904  revltop = get_opfamily_member(opfamily,
2905  op_righttype, op_lefttype,
2907  revleop = get_opfamily_member(opfamily,
2908  op_righttype, op_lefttype,
2910  }
2911  break;
2913  /* descending-order case */
2914  isgt = true;
2915  if (op_lefttype == op_righttype)
2916  {
2917  /* easy case */
2918  ltop = get_opfamily_member(opfamily,
2919  op_lefttype, op_righttype,
2921  leop = get_opfamily_member(opfamily,
2922  op_lefttype, op_righttype,
2924  lsortop = ltop;
2925  rsortop = ltop;
2926  lstatop = get_opfamily_member(opfamily,
2927  op_lefttype, op_lefttype,
2929  rstatop = lstatop;
2930  revltop = ltop;
2931  revleop = leop;
2932  }
2933  else
2934  {
2935  ltop = get_opfamily_member(opfamily,
2936  op_lefttype, op_righttype,
2938  leop = get_opfamily_member(opfamily,
2939  op_lefttype, op_righttype,
2941  lsortop = get_opfamily_member(opfamily,
2942  op_lefttype, op_lefttype,
2944  rsortop = get_opfamily_member(opfamily,
2945  op_righttype, op_righttype,
2947  lstatop = get_opfamily_member(opfamily,
2948  op_lefttype, op_lefttype,
2950  rstatop = get_opfamily_member(opfamily,
2951  op_righttype, op_righttype,
2953  revltop = get_opfamily_member(opfamily,
2954  op_righttype, op_lefttype,
2956  revleop = get_opfamily_member(opfamily,
2957  op_righttype, op_lefttype,
2959  }
2960  break;
2961  default:
2962  goto fail; /* shouldn't get here */
2963  }
2964 
2965  if (!OidIsValid(lsortop) ||
2966  !OidIsValid(rsortop) ||
2967  !OidIsValid(lstatop) ||
2968  !OidIsValid(rstatop) ||
2969  !OidIsValid(ltop) ||
2970  !OidIsValid(leop) ||
2971  !OidIsValid(revltop) ||
2972  !OidIsValid(revleop))
2973  goto fail; /* insufficient info in catalogs */
2974 
2975  /* Try to get ranges of both inputs */
2976  if (!isgt)
2977  {
2978  if (!get_variable_range(root, &leftvar, lstatop,
2979  &leftmin, &leftmax))
2980  goto fail; /* no range available from stats */
2981  if (!get_variable_range(root, &rightvar, rstatop,
2982  &rightmin, &rightmax))
2983  goto fail; /* no range available from stats */
2984  }
2985  else
2986  {
2987  /* need to swap the max and min */
2988  if (!get_variable_range(root, &leftvar, lstatop,
2989  &leftmax, &leftmin))
2990  goto fail; /* no range available from stats */
2991  if (!get_variable_range(root, &rightvar, rstatop,
2992  &rightmax, &rightmin))
2993  goto fail; /* no range available from stats */
2994  }
2995 
2996  /*
2997  * Now, the fraction of the left variable that will be scanned is the
2998  * fraction that's <= the right-side maximum value. But only believe
2999  * non-default estimates, else stick with our 1.0.
3000  */
3001  selec = scalarineqsel(root, leop, isgt, &leftvar,
3002  rightmax, op_righttype);
3003  if (selec != DEFAULT_INEQ_SEL)
3004  *leftend = selec;
3005 
3006  /* And similarly for the right variable. */
3007  selec = scalarineqsel(root, revleop, isgt, &rightvar,
3008  leftmax, op_lefttype);
3009  if (selec != DEFAULT_INEQ_SEL)
3010  *rightend = selec;
3011 
3012  /*
3013  * Only one of the two "end" fractions can really be less than 1.0;
3014  * believe the smaller estimate and reset the other one to exactly 1.0. If
3015  * we get exactly equal estimates (as can easily happen with self-joins),
3016  * believe neither.
3017  */
3018  if (*leftend > *rightend)
3019  *leftend = 1.0;
3020  else if (*leftend < *rightend)
3021  *rightend = 1.0;
3022  else
3023  *leftend = *rightend = 1.0;
3024 
3025  /*
3026  * Also, the fraction of the left variable that will be scanned before the
3027  * first join pair is found is the fraction that's < the right-side
3028  * minimum value. But only believe non-default estimates, else stick with
3029  * our own default.
3030  */
3031  selec = scalarineqsel(root, ltop, isgt, &leftvar,
3032  rightmin, op_righttype);
3033  if (selec != DEFAULT_INEQ_SEL)
3034  *leftstart = selec;
3035 
3036  /* And similarly for the right variable. */
3037  selec = scalarineqsel(root, revltop, isgt, &rightvar,
3038  leftmin, op_lefttype);
3039  if (selec != DEFAULT_INEQ_SEL)
3040  *rightstart = selec;
3041 
3042  /*
3043  * Only one of the two "start" fractions can really be more than zero;
3044  * believe the larger estimate and reset the other one to exactly 0.0. If
3045  * we get exactly equal estimates (as can easily happen with self-joins),
3046  * believe neither.
3047  */
3048  if (*leftstart < *rightstart)
3049  *leftstart = 0.0;
3050  else if (*leftstart > *rightstart)
3051  *rightstart = 0.0;
3052  else
3053  *leftstart = *rightstart = 0.0;
3054 
3055  /*
3056  * If the sort order is nulls-first, we're going to have to skip over any
3057  * nulls too. These would not have been counted by scalarineqsel, and we
3058  * can safely add in this fraction regardless of whether we believe
3059  * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3060  */
3061  if (nulls_first)
3062  {
3063  Form_pg_statistic stats;
3064 
3065  if (HeapTupleIsValid(leftvar.statsTuple))
3066  {
3067  stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3068  *leftstart += stats->stanullfrac;
3069  CLAMP_PROBABILITY(*leftstart);
3070  *leftend += stats->stanullfrac;
3071  CLAMP_PROBABILITY(*leftend);
3072  }
3073  if (HeapTupleIsValid(rightvar.statsTuple))
3074  {
3075  stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3076  *rightstart += stats->stanullfrac;
3077  CLAMP_PROBABILITY(*rightstart);
3078  *rightend += stats->stanullfrac;
3079  CLAMP_PROBABILITY(*rightend);
3080  }
3081  }
3082 
3083  /* Disbelieve start >= end, just in case that can happen */
3084  if (*leftstart >= *leftend)
3085  {
3086  *leftstart = 0.0;
3087  *leftend = 1.0;
3088  }
3089  if (*rightstart >= *rightend)
3090  {
3091  *rightstart = 0.0;
3092  *rightend = 1.0;
3093  }
3094 
3095 fail:
3096  ReleaseVariableStats(leftvar);
3097  ReleaseVariableStats(rightvar);
3098 }
#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:509
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:538
static double scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, VariableStatData *vardata, Datum constval, Oid consttype)
Definition: selfuncs.c:531
#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
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4519
#define Assert(condition)
Definition: c.h:675
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:5048
#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 1638 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().

1640 {
1641  VariableStatData vardata;
1642  double selec;
1643 
1644  examine_variable(root, arg, varRelid, &vardata);
1645 
1646  if (HeapTupleIsValid(vardata.statsTuple))
1647  {
1648  Form_pg_statistic stats;
1649  double freq_null;
1650 
1651  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1652  freq_null = stats->stanullfrac;
1653 
1654  switch (nulltesttype)
1655  {
1656  case IS_NULL:
1657 
1658  /*
1659  * Use freq_null directly.
1660  */
1661  selec = freq_null;
1662  break;
1663  case IS_NOT_NULL:
1664 
1665  /*
1666  * Select not unknown (not null) values. Calculate from
1667  * freq_null.
1668  */
1669  selec = 1.0 - freq_null;
1670  break;
1671  default:
1672  elog(ERROR, "unrecognized nulltesttype: %d",
1673  (int) nulltesttype);
1674  return (Selectivity) 0; /* keep compiler quiet */
1675  }
1676  }
1677  else
1678  {
1679  /*
1680  * No ANALYZE stats available, so make a guess
1681  */
1682  switch (nulltesttype)
1683  {
1684  case IS_NULL:
1685  selec = DEFAULT_UNK_SEL;
1686  break;
1687  case IS_NOT_NULL:
1688  selec = DEFAULT_NOT_UNK_SEL;
1689  break;
1690  default:
1691  elog(ERROR, "unrecognized nulltesttype: %d",
1692  (int) nulltesttype);
1693  return (Selectivity) 0; /* keep compiler quiet */
1694  }
1695  }
1696 
1697  ReleaseVariableStats(vardata);
1698 
1699  /* result should be in range, but make sure... */
1700  CLAMP_PROBABILITY(selec);
1701 
1702  return (Selectivity) selec;
1703 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
double Selectivity
Definition: nodes.h:638
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:4519
#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 5665 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, regex_fixed_prefix(), and result.

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

5667 {
5669 
5670  switch (ptype)
5671  {
5672  case Pattern_Type_Like:
5673  result = like_fixed_prefix(patt, false, collation,
5674  prefix, rest_selec);
5675  break;
5676  case Pattern_Type_Like_IC:
5677  result = like_fixed_prefix(patt, true, collation,
5678  prefix, rest_selec);
5679  break;
5680  case Pattern_Type_Regex:
5681  result = regex_fixed_prefix(patt, false, collation,
5682  prefix, rest_selec);
5683  break;
5684  case Pattern_Type_Regex_IC:
5685  result = regex_fixed_prefix(patt, true, collation,
5686  prefix, rest_selec);
5687  break;
5688  default:
5689  elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5690  result = Pattern_Prefix_None; /* keep compiler quiet */
5691  break;
5692  }
5693  return result;
5694 }
static Pattern_Prefix_Status regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5597
static Pattern_Prefix_Status like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5489
return result
Definition: formatting.c:1632
#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 2095 of file selfuncs.c.

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

Referenced by clause_selectivity().

2098 {
2099  Selectivity s1;
2100  Oid opno = linitial_oid(clause->opnos);
2101  Oid inputcollid = linitial_oid(clause->inputcollids);
2102  List *opargs;
2103  bool is_join_clause;
2104 
2105  /* Build equivalent arg list for single operator */
2106  opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2107 
2108  /*
2109  * Decide if it's a join clause. This should match clausesel.c's
2110  * treat_as_join_clause(), except that we intentionally consider only the
2111  * leading columns and not the rest of the clause.
2112  */
2113  if (varRelid != 0)
2114  {
2115  /*
2116  * Caller is forcing restriction mode (eg, because we are examining an
2117  * inner indexscan qual).
2118  */
2119  is_join_clause = false;
2120  }
2121  else if (sjinfo == NULL)
2122  {
2123  /*
2124  * It must be a restriction clause, since it's being evaluated at a
2125  * scan node.
2126  */
2127  is_join_clause = false;
2128  }
2129  else
2130  {
2131  /*
2132  * Otherwise, it's a join if there's more than one relation used.
2133  */
2134  is_join_clause = (NumRelids((Node *) opargs) > 1);
2135  }
2136 
2137  if (is_join_clause)
2138  {
2139  /* Estimate selectivity for a join clause. */
2140  s1 = join_selectivity(root, opno,
2141  opargs,
2142  inputcollid,
2143  jointype,
2144  sjinfo);
2145  }
2146  else
2147  {
2148  /* Estimate selectivity for a restriction clause. */
2149  s1 = restriction_selectivity(root, opno,
2150  opargs,
2151  inputcollid,
2152  varRelid);
2153  }
2154 
2155  return s1;
2156 }
#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:1652
Definition: nodes.h:509
double Selectivity
Definition: nodes.h:638
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial(l)
Definition: pg_list.h:111
char * s1
#define NULL
Definition: c.h:229
#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:1689
List * inputcollids
Definition: primnodes.h:1033
Definition: pg_list.h:45
int NumRelids(Node *clause)
Definition: clauses.c:2217
Selectivity scalararraysel ( PlannerInfo root,
ScalarArrayOpExpr clause,
bool  is_join_clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

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

1744 {
1745  Oid operator = clause->opno;
1746  bool useOr = clause->useOr;
1747  bool isEquality = false;
1748  bool isInequality = false;
1749  Node *leftop;
1750  Node *rightop;
1751  Oid nominal_element_type;
1752  Oid nominal_element_collation;
1753  TypeCacheEntry *typentry;
1754  RegProcedure oprsel;
1755  FmgrInfo oprselproc;
1756  Selectivity s1;
1757  Selectivity s1disjoint;
1758 
1759  /* First, deconstruct the expression */
1760  Assert(list_length(clause->args) == 2);
1761  leftop = (Node *) linitial(clause->args);
1762  rightop = (Node *) lsecond(clause->args);
1763 
1764  /* aggressively reduce both sides to constants */
1765  leftop = estimate_expression_value(root, leftop);
1766  rightop = estimate_expression_value(root, rightop);
1767 
1768  /* get nominal (after relabeling) element type of rightop */
1769  nominal_element_type = get_base_element_type(exprType(rightop));
1770  if (!OidIsValid(nominal_element_type))
1771  return (Selectivity) 0.5; /* probably shouldn't happen */
1772  /* get nominal collation, too, for generating constants */
1773  nominal_element_collation = exprCollation(rightop);
1774 
1775  /* look through any binary-compatible relabeling of rightop */
1776  rightop = strip_array_coercion(rightop);
1777 
1778  /*
1779  * Detect whether the operator is the default equality or inequality
1780  * operator of the array element type.
1781  */
1782  typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1783  if (OidIsValid(typentry->eq_opr))
1784  {
1785  if (operator == typentry->eq_opr)
1786  isEquality = true;
1787  else if (get_negator(operator) == typentry->eq_opr)
1788  isInequality = true;
1789  }
1790 
1791  /*
1792  * If it is equality or inequality, we might be able to estimate this as a
1793  * form of array containment; for instance "const = ANY(column)" can be
1794  * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1795  * that, and returns the selectivity estimate if successful, or -1 if not.
1796  */
1797  if ((isEquality || isInequality) && !is_join_clause)
1798  {
1799  s1 = scalararraysel_containment(root, leftop, rightop,
1800  nominal_element_type,
1801  isEquality, useOr, varRelid);
1802  if (s1 >= 0.0)
1803  return s1;
1804  }
1805 
1806  /*
1807  * Look up the underlying operator's selectivity estimator. Punt if it
1808  * hasn't got one.
1809  */
1810  if (is_join_clause)
1811  oprsel = get_oprjoin(operator);
1812  else
1813  oprsel = get_oprrest(operator);
1814  if (!oprsel)
1815  return (Selectivity) 0.5;
1816  fmgr_info(oprsel, &oprselproc);
1817 
1818  /*
1819  * In the array-containment check above, we must only believe that an
1820  * operator is equality or inequality if it is the default btree equality
1821  * operator (or its negator) for the element type, since those are the
1822  * operators that array containment will use. But in what follows, we can
1823  * be a little laxer, and also believe that any operators using eqsel() or
1824  * neqsel() as selectivity estimator act like equality or inequality.
1825  */
1826  if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1827  isEquality = true;
1828  else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1829  isInequality = true;
1830 
1831  /*
1832  * We consider three cases:
1833  *
1834  * 1. rightop is an Array constant: deconstruct the array, apply the
1835  * operator's selectivity function for each array element, and merge the
1836  * results in the same way that clausesel.c does for AND/OR combinations.
1837  *
1838  * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1839  * function for each element of the ARRAY[] construct, and merge.
1840  *
1841  * 3. otherwise, make a guess ...
1842  */
1843  if (rightop && IsA(rightop, Const))
1844  {
1845  Datum arraydatum = ((Const *) rightop)->constvalue;
1846  bool arrayisnull = ((Const *) rightop)->constisnull;
1847  ArrayType *arrayval;
1848  int16 elmlen;
1849  bool elmbyval;
1850  char elmalign;
1851  int num_elems;
1852  Datum *elem_values;
1853  bool *elem_nulls;
1854  int i;
1855 
1856  if (arrayisnull) /* qual can't succeed if null array */
1857  return (Selectivity) 0.0;
1858  arrayval = DatumGetArrayTypeP(arraydatum);
1860  &elmlen, &elmbyval, &elmalign);
1861  deconstruct_array(arrayval,
1862  ARR_ELEMTYPE(arrayval),
1863  elmlen, elmbyval, elmalign,
1864  &elem_values, &elem_nulls, &num_elems);
1865 
1866  /*
1867  * For generic operators, we assume the probability of success is
1868  * independent for each array element. But for "= ANY" or "<> ALL",
1869  * if the array elements are distinct (which'd typically be the case)
1870  * then the probabilities are disjoint, and we should just sum them.
1871  *
1872  * If we were being really tense we would try to confirm that the
1873  * elements are all distinct, but that would be expensive and it
1874  * doesn't seem to be worth the cycles; it would amount to penalizing
1875  * well-written queries in favor of poorly-written ones. However, we
1876  * do protect ourselves a little bit by checking whether the
1877  * disjointness assumption leads to an impossible (out of range)
1878  * probability; if so, we fall back to the normal calculation.
1879  */
1880  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1881 
1882  for (i = 0; i < num_elems; i++)
1883  {
1884  List *args;
1885  Selectivity s2;
1886 
1887  args = list_make2(leftop,
1888  makeConst(nominal_element_type,
1889  -1,
1890  nominal_element_collation,
1891  elmlen,
1892  elem_values[i],
1893  elem_nulls[i],
1894  elmbyval));
1895  if (is_join_clause)
1896  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1897  clause->inputcollid,
1898  PointerGetDatum(root),
1899  ObjectIdGetDatum(operator),
1900  PointerGetDatum(args),
1901  Int16GetDatum(jointype),
1902  PointerGetDatum(sjinfo)));
1903  else
1904  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1905  clause->inputcollid,
1906  PointerGetDatum(root),
1907  ObjectIdGetDatum(operator),
1908  PointerGetDatum(args),
1909  Int32GetDatum(varRelid)));
1910 
1911  if (useOr)
1912  {
1913  s1 = s1 + s2 - s1 * s2;
1914  if (isEquality)
1915  s1disjoint += s2;
1916  }
1917  else
1918  {
1919  s1 = s1 * s2;
1920  if (isInequality)
1921  s1disjoint += s2 - 1.0;
1922  }
1923  }
1924 
1925  /* accept disjoint-probability estimate if in range */
1926  if ((useOr ? isEquality : isInequality) &&
1927  s1disjoint >= 0.0 && s1disjoint <= 1.0)
1928  s1 = s1disjoint;
1929  }
1930  else if (rightop && IsA(rightop, ArrayExpr) &&
1931  !((ArrayExpr *) rightop)->multidims)
1932  {
1933  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1934  int16 elmlen;
1935  bool elmbyval;
1936  ListCell *l;
1937 
1938  get_typlenbyval(arrayexpr->element_typeid,
1939  &elmlen, &elmbyval);
1940 
1941  /*
1942  * We use the assumption of disjoint probabilities here too, although
1943  * the odds of equal array elements are rather higher if the elements
1944  * are not all constants (which they won't be, else constant folding
1945  * would have reduced the ArrayExpr to a Const). In this path it's
1946  * critical to have the sanity check on the s1disjoint estimate.
1947  */
1948  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1949 
1950  foreach(l, arrayexpr->elements)
1951  {
1952  Node *elem = (Node *) lfirst(l);
1953  List *args;
1954  Selectivity s2;
1955 
1956  /*
1957  * Theoretically, if elem isn't of nominal_element_type we should
1958  * insert a RelabelType, but it seems unlikely that any operator
1959  * estimation function would really care ...
1960  */
1961  args = list_make2(leftop, elem);
1962  if (is_join_clause)
1963  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1964  clause->inputcollid,
1965  PointerGetDatum(root),
1966  ObjectIdGetDatum(operator),
1967  PointerGetDatum(args),
1968  Int16GetDatum(jointype),
1969  PointerGetDatum(sjinfo)));
1970  else
1971  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1972  clause->inputcollid,
1973  PointerGetDatum(root),
1974  ObjectIdGetDatum(operator),
1975  PointerGetDatum(args),
1976  Int32GetDatum(varRelid)));
1977 
1978  if (useOr)
1979  {
1980  s1 = s1 + s2 - s1 * s2;
1981  if (isEquality)
1982  s1disjoint += s2;
1983  }
1984  else
1985  {
1986  s1 = s1 * s2;
1987  if (isInequality)
1988  s1disjoint += s2 - 1.0;
1989  }
1990  }
1991 
1992  /* accept disjoint-probability estimate if in range */
1993  if ((useOr ? isEquality : isInequality) &&
1994  s1disjoint >= 0.0 && s1disjoint <= 1.0)
1995  s1 = s1disjoint;
1996  }
1997  else
1998  {
1999  CaseTestExpr *dummyexpr;
2000  List *args;
2001  Selectivity s2;
2002  int i;
2003 
2004  /*
2005  * We need a dummy rightop to pass to the operator selectivity
2006  * routine. It can be pretty much anything that doesn't look like a
2007  * constant; CaseTestExpr is a convenient choice.
2008  */
2009  dummyexpr = makeNode(CaseTestExpr);
2010  dummyexpr->typeId = nominal_element_type;
2011  dummyexpr->typeMod = -1;
2012  dummyexpr->collation = clause->inputcollid;
2013  args = list_make2(leftop, dummyexpr);
2014  if (is_join_clause)
2015  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2016  clause->inputcollid,
2017  PointerGetDatum(root),
2018  ObjectIdGetDatum(operator),
2019  PointerGetDatum(args),
2020  Int16GetDatum(jointype),
2021  PointerGetDatum(sjinfo)));
2022  else
2023  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2024  clause->inputcollid,
2025  PointerGetDatum(root),
2026  ObjectIdGetDatum(operator),
2027  PointerGetDatum(args),
2028  Int32GetDatum(varRelid)));
2029  s1 = useOr ? 0.0 : 1.0;
2030 
2031  /*
2032  * Arbitrarily assume 10 elements in the eventual array value (see
2033  * also estimate_array_length). We don't risk an assumption of
2034  * disjoint probabilities here.
2035  */
2036  for (i = 0; i < 10; i++)
2037  {
2038  if (useOr)
2039  s1 = s1 + s2 - s1 * s2;
2040  else
2041  s1 = s1 * s2;
2042  }
2043  }
2044 
2045  /* result should be in range, but make sure... */
2046  CLAMP_PROBABILITY(s1);
2047 
2048  return s1;
2049 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
signed short int16
Definition: c.h:255
Definition: fmgr.h:56
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1385
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2433
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:1121
regproc RegProcedure
Definition: c.h:395
#define Int16GetDatum(X)
Definition: postgres.h:457
Definition: nodes.h:509
#define TYPECACHE_EQ_OPR
Definition: typcache.h:110
Datum FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1094
double Selectivity
Definition: nodes.h:638
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:538
#define lsecond(l)
Definition: pg_list.h:116
int32 typeMod
Definition: primnodes.h:936
#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:127
List * elements
Definition: primnodes.h:954
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:191
#define makeNode(_type_)
Definition: nodes.h:557
#define Assert(condition)
Definition: c.h:675
#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:748
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2001
Oid element_typeid
Definition: primnodes.h:953
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3475
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:273
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1714
#define DatumGetArrayTypeP(X)
Definition: array.h:242
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, NULL, 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)
189  NULL, 0,
190  &constval, 1,
192  cmpfunc);
193  else
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)
212  NULL, 0,
213  &constval, 1,
215  cmpfunc);
216  else
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:560
#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:4897
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:638
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define OidIsValid(objectId)
Definition: c.h:538
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
FmgrInfo cmp_proc_finfo
Definition: typcache.h:68
#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:191
#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:4519
#define NULL
Definition: c.h:229
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:116
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 4897 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().

4898 {
4899  if (vardata->acl_ok)
4900  return true;
4901 
4902  if (!OidIsValid(func_oid))
4903  return false;
4904 
4905  if (get_func_leakproof(func_oid))
4906  return true;
4907 
4908  ereport(DEBUG2,
4909  (errmsg_internal("not using statistics because function \"%s\" is not leak-proof",
4910  get_func_name(func_oid))));
4911  return false;
4912 }
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1622
#define OidIsValid(objectId)
Definition: c.h:538
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 155 of file selfuncs.c.

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

PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook

Definition at line 154 of file selfuncs.c.

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