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

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

Definition at line 141 of file selfuncs.h.

Enumeration Type Documentation

Enumerator
Pattern_Prefix_None 
Pattern_Prefix_Partial 
Pattern_Prefix_Exact 

Definition at line 93 of file selfuncs.h.

Enumerator
Pattern_Type_Like 
Pattern_Type_Like_IC 
Pattern_Type_Regex 
Pattern_Type_Regex_IC 

Definition at line 87 of file selfuncs.h.

Function Documentation

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

Definition at line 1494 of file selfuncs.c.

References VariableStatData::atttype, VariableStatData::atttypmod, 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, NULL, ReleaseVariableStats, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and values.

Referenced by clause_selectivity().

1496 {
1497  VariableStatData vardata;
1498  double selec;
1499 
1500  examine_variable(root, arg, varRelid, &vardata);
1501 
1502  if (HeapTupleIsValid(vardata.statsTuple))
1503  {
1504  Form_pg_statistic stats;
1505  double freq_null;
1506  Datum *values;
1507  int nvalues;
1508  float4 *numbers;
1509  int nnumbers;
1510 
1511  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1512  freq_null = stats->stanullfrac;
1513 
1514  if (get_attstatsslot(vardata.statsTuple,
1515  vardata.atttype, vardata.atttypmod,
1517  NULL,
1518  &values, &nvalues,
1519  &numbers, &nnumbers)
1520  && nnumbers > 0)
1521  {
1522  double freq_true;
1523  double freq_false;
1524 
1525  /*
1526  * Get first MCV frequency and derive frequency for true.
1527  */
1528  if (DatumGetBool(values[0]))
1529  freq_true = numbers[0];
1530  else
1531  freq_true = 1.0 - numbers[0] - freq_null;
1532 
1533  /*
1534  * Next derive frequency for false. Then use these as appropriate
1535  * to derive frequency for each case.
1536  */
1537  freq_false = 1.0 - freq_true - freq_null;
1538 
1539  switch (booltesttype)
1540  {
1541  case IS_UNKNOWN:
1542  /* select only NULL values */
1543  selec = freq_null;
1544  break;
1545  case IS_NOT_UNKNOWN:
1546  /* select non-NULL values */
1547  selec = 1.0 - freq_null;
1548  break;
1549  case IS_TRUE:
1550  /* select only TRUE values */
1551  selec = freq_true;
1552  break;
1553  case IS_NOT_TRUE:
1554  /* select non-TRUE values */
1555  selec = 1.0 - freq_true;
1556  break;
1557  case IS_FALSE:
1558  /* select only FALSE values */
1559  selec = freq_false;
1560  break;
1561  case IS_NOT_FALSE:
1562  /* select non-FALSE values */
1563  selec = 1.0 - freq_false;
1564  break;
1565  default:
1566  elog(ERROR, "unrecognized booltesttype: %d",
1567  (int) booltesttype);
1568  selec = 0.0; /* Keep compiler quiet */
1569  break;
1570  }
1571 
1572  free_attstatsslot(vardata.atttype, values, nvalues,
1573  numbers, nnumbers);
1574  }
1575  else
1576  {
1577  /*
1578  * No most-common-value info available. Still have null fraction
1579  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1580  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1581  */
1582  switch (booltesttype)
1583  {
1584  case IS_UNKNOWN:
1585  /* select only NULL values */
1586  selec = freq_null;
1587  break;
1588  case IS_NOT_UNKNOWN:
1589  /* select non-NULL values */
1590  selec = 1.0 - freq_null;
1591  break;
1592  case IS_TRUE:
1593  case IS_FALSE:
1594  /* Assume we select half of the non-NULL values */
1595  selec = (1.0 - freq_null) / 2.0;
1596  break;
1597  case IS_NOT_TRUE:
1598  case IS_NOT_FALSE:
1599  /* Assume we select NULLs plus half of the non-NULLs */
1600  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1601  selec = (freq_null + 1.0) / 2.0;
1602  break;
1603  default:
1604  elog(ERROR, "unrecognized booltesttype: %d",
1605  (int) booltesttype);
1606  selec = 0.0; /* Keep compiler quiet */
1607  break;
1608  }
1609  }
1610  }
1611  else
1612  {
1613  /*
1614  * If we can't get variable statistics for the argument, perhaps
1615  * clause_selectivity can do something with it. We ignore the
1616  * possibility of a NULL value when using clause_selectivity, and just
1617  * assume the value is either TRUE or FALSE.
1618  */
1619  switch (booltesttype)
1620  {
1621  case IS_UNKNOWN:
1622  selec = DEFAULT_UNK_SEL;
1623  break;
1624  case IS_NOT_UNKNOWN:
1625  selec = DEFAULT_NOT_UNK_SEL;
1626  break;
1627  case IS_TRUE:
1628  case IS_NOT_FALSE:
1629  selec = (double) clause_selectivity(root, arg,
1630  varRelid,
1631  jointype, sjinfo);
1632  break;
1633  case IS_FALSE:
1634  case IS_NOT_TRUE:
1635  selec = 1.0 - (double) clause_selectivity(root, arg,
1636  varRelid,
1637  jointype, sjinfo);
1638  break;
1639  default:
1640  elog(ERROR, "unrecognized booltesttype: %d",
1641  (int) booltesttype);
1642  selec = 0.0; /* Keep compiler quiet */
1643  break;
1644  }
1645  }
1646 
1647  ReleaseVariableStats(vardata);
1648 
1649  /* result should be in range, but make sure... */
1650  CLAMP_PROBABILITY(selec);
1651 
1652  return (Selectivity) selec;
1653 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
double Selectivity
Definition: nodes.h:631
bool get_attstatsslot(HeapTuple statstuple, Oid atttype, int32 atttypmod, int reqkind, Oid reqop, Oid *actualop, Datum **values, int *nvalues, float4 **numbers, int *nnumbers)
Definition: lsyscache.c:2854
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
int32 atttypmod
Definition: selfuncs.h:76
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:50
#define ERROR
Definition: elog.h:43
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:483
#define DatumGetBool(X)
Definition: postgres.h:401
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:49
float float4
Definition: c.h:377
uintptr_t Datum
Definition: postgres.h:374
#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:4391
#define NULL
Definition: c.h:226
static Datum values[MAXATTR]
Definition: bootstrap.c:162
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
#define elog
Definition: elog.h:219
void free_attstatsslot(Oid atttype, Datum *values, int nvalues, float4 *numbers, int nnumbers)
Definition: lsyscache.c:2978
Selectivity boolvarsel ( PlannerInfo root,
Node arg,
int  varRelid 
)

Definition at line 1455 of file selfuncs.c.

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

Referenced by clause_selectivity().

1456 {
1457  VariableStatData vardata;
1458  double selec;
1459 
1460  examine_variable(root, arg, varRelid, &vardata);
1461  if (HeapTupleIsValid(vardata.statsTuple))
1462  {
1463  /*
1464  * A boolean variable V is equivalent to the clause V = 't', so we
1465  * compute the selectivity as if that is what we have.
1466  */
1467  selec = var_eq_const(&vardata, BooleanEqualOperator,
1468  BoolGetDatum(true), false, true);
1469  }
1470  else if (is_funcclause(arg))
1471  {
1472  /*
1473  * If we have no stats and it's a function call, estimate 0.3333333.
1474  * This seems a pretty unprincipled choice, but Postgres has been
1475  * using that estimate for function calls since 1992. The hoariness
1476  * of this behavior suggests that we should not be in too much hurry
1477  * to use another value.
1478  */
1479  selec = 0.3333333;
1480  }
1481  else
1482  {
1483  /* Otherwise, the default estimate is 0.5 */
1484  selec = 0.5;
1485  }
1486  ReleaseVariableStats(vardata);
1487  return selec;
1488 }
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:264
#define BoolGetDatum(X)
Definition: postgres.h:410
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4391
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
List* deconstruct_indexquals ( IndexPath path)

Definition at line 6063 of file selfuncs.c.

References arg, ScalarArrayOpExpr::args, Assert, castNode, 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, lfirst_int, linitial, linitial_oid, lsecond, match_index_to_operand(), NIL, nodeTag, NULL, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, IndexQualInfo::other_operand, palloc(), RowCompareExpr::rargs, IndexQualInfo::rinfo, and IndexQualInfo::varonleft.

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

6064 {
6065  List *result = NIL;
6066  IndexOptInfo *index = path->indexinfo;
6067  ListCell *lcc,
6068  *lci;
6069 
6070  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6071  {
6072  RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(lcc));
6073  int indexcol = lfirst_int(lci);
6074  Expr *clause;
6075  Node *leftop,
6076  *rightop;
6077  IndexQualInfo *qinfo;
6078 
6079  clause = rinfo->clause;
6080 
6081  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6082  qinfo->rinfo = rinfo;
6083  qinfo->indexcol = indexcol;
6084 
6085  if (IsA(clause, OpExpr))
6086  {
6087  qinfo->clause_op = ((OpExpr *) clause)->opno;
6088  leftop = get_leftop(clause);
6089  rightop = get_rightop(clause);
6090  if (match_index_to_operand(leftop, indexcol, index))
6091  {
6092  qinfo->varonleft = true;
6093  qinfo->other_operand = rightop;
6094  }
6095  else
6096  {
6097  Assert(match_index_to_operand(rightop, indexcol, index));
6098  qinfo->varonleft = false;
6099  qinfo->other_operand = leftop;
6100  }
6101  }
6102  else if (IsA(clause, RowCompareExpr))
6103  {
6104  RowCompareExpr *rc = (RowCompareExpr *) clause;
6105 
6106  qinfo->clause_op = linitial_oid(rc->opnos);
6107  /* Examine only first columns to determine left/right sides */
6109  indexcol, index))
6110  {
6111  qinfo->varonleft = true;
6112  qinfo->other_operand = (Node *) rc->rargs;
6113  }
6114  else
6115  {
6117  indexcol, index));
6118  qinfo->varonleft = false;
6119  qinfo->other_operand = (Node *) rc->largs;
6120  }
6121  }
6122  else if (IsA(clause, ScalarArrayOpExpr))
6123  {
6124  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6125 
6126  qinfo->clause_op = saop->opno;
6127  /* index column is always on the left in this case */
6129  indexcol, index));
6130  qinfo->varonleft = true;
6131  qinfo->other_operand = (Node *) lsecond(saop->args);
6132  }
6133  else if (IsA(clause, NullTest))
6134  {
6135  qinfo->clause_op = InvalidOid;
6136  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6137  indexcol, index));
6138  qinfo->varonleft = true;
6139  qinfo->other_operand = NULL;
6140  }
6141  else
6142  {
6143  elog(ERROR, "unsupported indexqual type: %d",
6144  (int) nodeTag(clause));
6145  }
6146 
6147  result = lappend(result, qinfo);
6148  }
6149  return result;
6150 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
IndexOptInfo * indexinfo
Definition: relation.h:972
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3161
Definition: nodes.h:508
RestrictInfo * rinfo
Definition: selfuncs.h:105
#define lsecond(l)
Definition: pg_list.h:114
Definition: type.h:90
List * indexquals
Definition: relation.h:974
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
Node * get_leftop(const Expr *clause)
Definition: clauses.c:198
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1637
bool varonleft
Definition: selfuncs.h:107
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
#define linitial_oid(l)
Definition: pg_list.h:112
#define nodeTag(nodeptr)
Definition: nodes.h:513
Node * get_rightop(const Expr *clause)
Definition: clauses.c:215
List * indexqualcols
Definition: relation.h:975
void * palloc(Size size)
Definition: mcxt.c:891
Node * other_operand
Definition: selfuncs.h:109
void * arg
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
int estimate_array_length ( Node arrayexpr)

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

2079 {
2080  /* look through any binary-compatible relabeling of arrayexpr */
2081  arrayexpr = strip_array_coercion(arrayexpr);
2082 
2083  if (arrayexpr && IsA(arrayexpr, Const))
2084  {
2085  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2086  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2087  ArrayType *arrayval;
2088 
2089  if (arrayisnull)
2090  return 0;
2091  arrayval = DatumGetArrayTypeP(arraydatum);
2092  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2093  }
2094  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2095  !((ArrayExpr *) arrayexpr)->multidims)
2096  {
2097  return list_length(((ArrayExpr *) arrayexpr)->elements);
2098  }
2099  else
2100  {
2101  /* default guess --- see also scalararraysel */
2102  return 10;
2103  }
2104 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
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:374
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:1735
#define DatumGetArrayTypeP(X)
Definition: array.h:242
Selectivity estimate_hash_bucketsize ( PlannerInfo root,
Node hashkey,
double  nbuckets 
)

Definition at line 3554 of file selfuncs.c.

References VariableStatData::atttype, VariableStatData::atttypmod, clamp_row_est(), examine_variable(), free_attstatsslot(), get_attstatsslot(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, InvalidOid, NULL, VariableStatData::rel, ReleaseVariableStats, RelOptInfo::rows, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by final_cost_hashjoin().

3555 {
3556  VariableStatData vardata;
3557  double estfract,
3558  ndistinct,
3559  stanullfrac,
3560  mcvfreq,
3561  avgfreq;
3562  bool isdefault;
3563  float4 *numbers;
3564  int nnumbers;
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(vardata.statsTuple,
3624  vardata.atttype, vardata.atttypmod,
3626  NULL,
3627  NULL, NULL,
3628  &numbers, &nnumbers))
3629  {
3630  /*
3631  * The first MCV stat is for the most common value.
3632  */
3633  if (nnumbers > 0)
3634  mcvfreq = numbers[0];
3635  free_attstatsslot(vardata.atttype, NULL, 0,
3636  numbers, nnumbers);
3637  }
3638  }
3639 
3640  /*
3641  * Adjust estimated bucketsize upward to account for skewed distribution.
3642  */
3643  if (avgfreq > 0.0 && mcvfreq > avgfreq)
3644  estfract *= mcvfreq / avgfreq;
3645 
3646  /*
3647  * Clamp bucketsize to sane range (the above adjustment could easily
3648  * produce an out-of-range result). We set the lower bound a little above
3649  * zero, since zero isn't a very sane result.
3650  */
3651  if (estfract < 1.0e-6)
3652  estfract = 1.0e-6;
3653  else if (estfract > 1.0)
3654  estfract = 1.0;
3655 
3656  ReleaseVariableStats(vardata);
3657 
3658  return (Selectivity) estfract;
3659 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
double tuples
Definition: relation.h:529
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:631
bool get_attstatsslot(HeapTuple statstuple, Oid atttype, int32 atttypmod, int reqkind, Oid reqop, Oid *actualop, Datum **values, int *nvalues, float4 **numbers, int *nnumbers)
Definition: lsyscache.c:2854
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
int32 atttypmod
Definition: selfuncs.h:76
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4735
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
float float4
Definition: c.h:377
double rows
Definition: relation.h:493
#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:4391
#define NULL
Definition: c.h:226
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
e
Definition: preproc-init.c:82
double clamp_row_est(double nrows)
Definition: costsize.c:172
void free_attstatsslot(Oid atttype, Datum *values, int nvalues, float4 *numbers, int nnumbers)
Definition: lsyscache.c:2978
double estimate_num_groups ( PlannerInfo root,
List groupExprs,
double  input_rows,
List **  pgset 
)

Definition at line 3272 of file selfuncs.c.

References add_unique_group_var(), Assert, BOOLOID, clamp_row_est(), contain_volatile_functions(), examine_variable(), exprType(), for_each_cell, HeapTupleIsValid, i, 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, RELOPT_BASEREL, RelOptInfo::reloptkind, 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().

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

Definition at line 4391 of file selfuncs.c.

References arg, 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, 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, IndexOptInfo::predOK, pull_varnos(), VariableStatData::rel, ReleaseSysCache(), 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().

4393 {
4394  Node *basenode;
4395  Relids varnos;
4396  RelOptInfo *onerel;
4397 
4398  /* Make sure we don't return dangling pointers in vardata */
4399  MemSet(vardata, 0, sizeof(VariableStatData));
4400 
4401  /* Save the exposed type of the expression */
4402  vardata->vartype = exprType(node);
4403 
4404  /* Look inside any binary-compatible relabeling */
4405 
4406  if (IsA(node, RelabelType))
4407  basenode = (Node *) ((RelabelType *) node)->arg;
4408  else
4409  basenode = node;
4410 
4411  /* Fast path for a simple Var */
4412 
4413  if (IsA(basenode, Var) &&
4414  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4415  {
4416  Var *var = (Var *) basenode;
4417 
4418  /* Set up result fields other than the stats tuple */
4419  vardata->var = basenode; /* return Var without relabeling */
4420  vardata->rel = find_base_rel(root, var->varno);
4421  vardata->atttype = var->vartype;
4422  vardata->atttypmod = var->vartypmod;
4423  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4424 
4425  /* Try to locate some stats */
4426  examine_simple_variable(root, var, vardata);
4427 
4428  return;
4429  }
4430 
4431  /*
4432  * Okay, it's a more complicated expression. Determine variable
4433  * membership. Note that when varRelid isn't zero, only vars of that
4434  * relation are considered "real" vars.
4435  */
4436  varnos = pull_varnos(basenode);
4437 
4438  onerel = NULL;
4439 
4440  switch (bms_membership(varnos))
4441  {
4442  case BMS_EMPTY_SET:
4443  /* No Vars at all ... must be pseudo-constant clause */
4444  break;
4445  case BMS_SINGLETON:
4446  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4447  {
4448  onerel = find_base_rel(root,
4449  (varRelid ? varRelid : bms_singleton_member(varnos)));
4450  vardata->rel = onerel;
4451  node = basenode; /* strip any relabeling */
4452  }
4453  /* else treat it as a constant */
4454  break;
4455  case BMS_MULTIPLE:
4456  if (varRelid == 0)
4457  {
4458  /* treat it as a variable of a join relation */
4459  vardata->rel = find_join_rel(root, varnos);
4460  node = basenode; /* strip any relabeling */
4461  }
4462  else if (bms_is_member(varRelid, varnos))
4463  {
4464  /* ignore the vars belonging to other relations */
4465  vardata->rel = find_base_rel(root, varRelid);
4466  node = basenode; /* strip any relabeling */
4467  /* note: no point in expressional-index search here */
4468  }
4469  /* else treat it as a constant */
4470  break;
4471  }
4472 
4473  bms_free(varnos);
4474 
4475  vardata->var = node;
4476  vardata->atttype = exprType(node);
4477  vardata->atttypmod = exprTypmod(node);
4478 
4479  if (onerel)
4480  {
4481  /*
4482  * We have an expression in vars of a single relation. Try to match
4483  * it to expressional index columns, in hopes of finding some
4484  * statistics.
4485  *
4486  * XXX it's conceivable that there are multiple matches with different
4487  * index opfamilies; if so, we need to pick one that matches the
4488  * operator we are estimating for. FIXME later.
4489  */
4490  ListCell *ilist;
4491 
4492  foreach(ilist, onerel->indexlist)
4493  {
4494  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4495  ListCell *indexpr_item;
4496  int pos;
4497 
4498  indexpr_item = list_head(index->indexprs);
4499  if (indexpr_item == NULL)
4500  continue; /* no expressions here... */
4501 
4502  for (pos = 0; pos < index->ncolumns; pos++)
4503  {
4504  if (index->indexkeys[pos] == 0)
4505  {
4506  Node *indexkey;
4507 
4508  if (indexpr_item == NULL)
4509  elog(ERROR, "too few entries in indexprs list");
4510  indexkey = (Node *) lfirst(indexpr_item);
4511  if (indexkey && IsA(indexkey, RelabelType))
4512  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4513  if (equal(node, indexkey))
4514  {
4515  /*
4516  * Found a match ... is it a unique index? Tests here
4517  * should match has_unique_index().
4518  */
4519  if (index->unique &&
4520  index->ncolumns == 1 &&
4521  (index->indpred == NIL || index->predOK))
4522  vardata->isunique = true;
4523 
4524  /*
4525  * Has it got stats? We only consider stats for
4526  * non-partial indexes, since partial indexes probably
4527  * don't reflect whole-relation statistics; the above
4528  * check for uniqueness is the only info we take from
4529  * a partial index.
4530  *
4531  * An index stats hook, however, must make its own
4532  * decisions about what to do with partial indexes.
4533  */
4534  if (get_index_stats_hook &&
4535  (*get_index_stats_hook) (root, index->indexoid,
4536  pos + 1, vardata))
4537  {
4538  /*
4539  * The hook took control of acquiring a stats
4540  * tuple. If it did supply a tuple, it'd better
4541  * have supplied a freefunc.
4542  */
4543  if (HeapTupleIsValid(vardata->statsTuple) &&
4544  !vardata->freefunc)
4545  elog(ERROR, "no function provided to release variable stats with");
4546  }
4547  else if (index->indpred == NIL)
4548  {
4549  vardata->statsTuple =
4551  ObjectIdGetDatum(index->indexoid),
4552  Int16GetDatum(pos + 1),
4553  BoolGetDatum(false));
4554  vardata->freefunc = ReleaseSysCache;
4555  }
4556  if (vardata->statsTuple)
4557  break;
4558  }
4559  indexpr_item = lnext(indexpr_item);
4560  }
4561  }
4562  if (vardata->statsTuple)
4563  break;
4564  }
4565  }
4566 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
bool predOK
Definition: relation.h:620
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:284
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2870
HeapTuple statsTuple
Definition: selfuncs.h:71
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:273
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:459
Definition: nodes.h:508
#define MemSet(start, val, len)
Definition: c.h:853
AttrNumber varattno
Definition: primnodes.h:146
Definition: primnodes.h:141
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4578
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:621
Definition: type.h:90
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1649
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:148
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int ncolumns
Definition: relation.h:598
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index varno
Definition: primnodes.h:144
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:604
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:496
List * indexlist
Definition: relation.h:527
#define BoolGetDatum(X)
Definition: postgres.h:410
void bms_free(Bitmapset *a)
Definition: bitmapset.c:200
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#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:149
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:153
void * arg
int * indexkeys
Definition: relation.h:599
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:588
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
List * indpred
Definition: relation.h:611
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
List * indexprs
Definition: relation.h:610
int32 vartypmod
Definition: primnodes.h:149
void genericcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
List qinfos,
GenericCosts costs 
)

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

6217 {
6218  IndexOptInfo *index = path->indexinfo;
6219  List *indexQuals = path->indexquals;
6220  List *indexOrderBys = path->indexorderbys;
6221  Cost indexStartupCost;
6222  Cost indexTotalCost;
6223  Selectivity indexSelectivity;
6224  double indexCorrelation;
6225  double numIndexPages;
6226  double numIndexTuples;
6227  double spc_random_page_cost;
6228  double num_sa_scans;
6229  double num_outer_scans;
6230  double num_scans;
6231  double qual_op_cost;
6232  double qual_arg_cost;
6233  List *selectivityQuals;
6234  ListCell *l;
6235 
6236  /*
6237  * If the index is partial, AND the index predicate with the explicitly
6238  * given indexquals to produce a more accurate idea of the index
6239  * selectivity.
6240  */
6241  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6242 
6243  /*
6244  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6245  * index scans that will be performed.
6246  */
6247  num_sa_scans = 1;
6248  foreach(l, indexQuals)
6249  {
6250  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6251 
6252  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6253  {
6254  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6255  int alength = estimate_array_length(lsecond(saop->args));
6256 
6257  if (alength > 1)
6258  num_sa_scans *= alength;
6259  }
6260  }
6261 
6262  /* Estimate the fraction of main-table tuples that will be visited */
6263  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6264  index->rel->relid,
6265  JOIN_INNER,
6266  NULL);
6267 
6268  /*
6269  * If caller didn't give us an estimate, estimate the number of index
6270  * tuples that will be visited. We do it in this rather peculiar-looking
6271  * way in order to get the right answer for partial indexes.
6272  */
6273  numIndexTuples = costs->numIndexTuples;
6274  if (numIndexTuples <= 0.0)
6275  {
6276  numIndexTuples = indexSelectivity * index->rel->tuples;
6277 
6278  /*
6279  * The above calculation counts all the tuples visited across all
6280  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6281  * average per-indexscan number, so adjust. This is a handy place to
6282  * round to integer, too. (If caller supplied tuple estimate, it's
6283  * responsible for handling these considerations.)
6284  */
6285  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6286  }
6287 
6288  /*
6289  * We can bound the number of tuples by the index size in any case. Also,
6290  * always estimate at least one tuple is touched, even when
6291  * indexSelectivity estimate is tiny.
6292  */
6293  if (numIndexTuples > index->tuples)
6294  numIndexTuples = index->tuples;
6295  if (numIndexTuples < 1.0)
6296  numIndexTuples = 1.0;
6297 
6298  /*
6299  * Estimate the number of index pages that will be retrieved.
6300  *
6301  * We use the simplistic method of taking a pro-rata fraction of the total
6302  * number of index pages. In effect, this counts only leaf pages and not
6303  * any overhead such as index metapage or upper tree levels.
6304  *
6305  * In practice access to upper index levels is often nearly free because
6306  * those tend to stay in cache under load; moreover, the cost involved is
6307  * highly dependent on index type. We therefore ignore such costs here
6308  * and leave it to the caller to add a suitable charge if needed.
6309  */
6310  if (index->pages > 1 && index->tuples > 1)
6311  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6312  else
6313  numIndexPages = 1.0;
6314 
6315  /* fetch estimated page cost for tablespace containing index */
6317  &spc_random_page_cost,
6318  NULL);
6319 
6320  /*
6321  * Now compute the disk access costs.
6322  *
6323  * The above calculations are all per-index-scan. However, if we are in a
6324  * nestloop inner scan, we can expect the scan to be repeated (with
6325  * different search keys) for each row of the outer relation. Likewise,
6326  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6327  * the potential for cache effects to reduce the number of disk page
6328  * fetches needed. We want to estimate the average per-scan I/O cost in
6329  * the presence of caching.
6330  *
6331  * We use the Mackert-Lohman formula (see costsize.c for details) to
6332  * estimate the total number of page fetches that occur. While this
6333  * wasn't what it was designed for, it seems a reasonable model anyway.
6334  * Note that we are counting pages not tuples anymore, so we take N = T =
6335  * index size, as if there were one "tuple" per page.
6336  */
6337  num_outer_scans = loop_count;
6338  num_scans = num_sa_scans * num_outer_scans;
6339 
6340  if (num_scans > 1)
6341  {
6342  double pages_fetched;
6343 
6344  /* total page fetches ignoring cache effects */
6345  pages_fetched = numIndexPages * num_scans;
6346 
6347  /* use Mackert and Lohman formula to adjust for cache effects */
6348  pages_fetched = index_pages_fetched(pages_fetched,
6349  index->pages,
6350  (double) index->pages,
6351  root);
6352 
6353  /*
6354  * Now compute the total disk access cost, and then report a pro-rated
6355  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6356  * since that's internal to the indexscan.)
6357  */
6358  indexTotalCost = (pages_fetched * spc_random_page_cost)
6359  / num_outer_scans;
6360  }
6361  else
6362  {
6363  /*
6364  * For a single index scan, we just charge spc_random_page_cost per
6365  * page touched.
6366  */
6367  indexTotalCost = numIndexPages * spc_random_page_cost;
6368  }
6369 
6370  /*
6371  * CPU cost: any complex expressions in the indexquals will need to be
6372  * evaluated once at the start of the scan to reduce them to runtime keys
6373  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6374  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6375  * indexqual operator. Because we have numIndexTuples as a per-scan
6376  * number, we have to multiply by num_sa_scans to get the correct result
6377  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6378  * ORDER BY expressions.
6379  *
6380  * Note: this neglects the possible costs of rechecking lossy operators.
6381  * Detecting that that might be needed seems more expensive than it's
6382  * worth, though, considering all the other inaccuracies here ...
6383  */
6384  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6385  orderby_operands_eval_cost(root, path);
6386  qual_op_cost = cpu_operator_cost *
6387  (list_length(indexQuals) + list_length(indexOrderBys));
6388 
6389  indexStartupCost = qual_arg_cost;
6390  indexTotalCost += qual_arg_cost;
6391  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6392 
6393  /*
6394  * Generic assumption about index correlation: there isn't any.
6395  */
6396  indexCorrelation = 0.0;
6397 
6398  /*
6399  * Return everything to caller.
6400  */
6401  costs->indexStartupCost = indexStartupCost;
6402  costs->indexTotalCost = indexTotalCost;
6403  costs->indexSelectivity = indexSelectivity;
6404  costs->indexCorrelation = indexCorrelation;
6405  costs->numIndexPages = numIndexPages;
6406  costs->numIndexTuples = numIndexTuples;
6407  costs->spc_random_page_cost = spc_random_page_cost;
6408  costs->num_sa_scans = num_sa_scans;
6409 }
Selectivity indexSelectivity
Definition: selfuncs.h:130
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
IndexOptInfo * indexinfo
Definition: relation.h:972
double tuples
Definition: relation.h:529
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6431
Oid reltablespace
Definition: relation.h:589
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6158
double Selectivity
Definition: nodes.h:631
double tuples
Definition: relation.h:594
#define lsecond(l)
Definition: pg_list.h:114
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6183
Definition: type.h:90
BlockNumber pages
Definition: relation.h:593
List * indexquals
Definition: relation.h:974
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2078
RelOptInfo * rel
Definition: relation.h:590
double num_sa_scans
Definition: selfuncs.h:137
double cpu_operator_cost
Definition: costsize.c:108
Cost indexTotalCost
Definition: selfuncs.h:129
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:178
Index relid
Definition: relation.h:518
Expr * clause
Definition: relation.h:1637
double indexCorrelation
Definition: selfuncs.h:131
List * indexorderbys
Definition: relation.h:976
double spc_random_page_cost
Definition: selfuncs.h:136
double numIndexTuples
Definition: selfuncs.h:135
#define NULL
Definition: c.h:226
#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:128
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
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:738
double Cost
Definition: nodes.h:632
double numIndexPages
Definition: selfuncs.h:134
void get_join_variables ( PlannerInfo root,
List args,
SpecialJoinInfo sjinfo,
VariableStatData vardata1,
VariableStatData vardata2,
bool join_is_reversed 
)

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

4335 {
4336  Node *left,
4337  *right;
4338 
4339  if (list_length(args) != 2)
4340  elog(ERROR, "join operator should take two arguments");
4341 
4342  left = (Node *) linitial(args);
4343  right = (Node *) lsecond(args);
4344 
4345  examine_variable(root, left, 0, vardata1);
4346  examine_variable(root, right, 0, vardata2);
4347 
4348  if (vardata1->rel &&
4349  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4350  *join_is_reversed = true; /* var1 is on RHS */
4351  else if (vardata2->rel &&
4352  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4353  *join_is_reversed = true; /* var2 is on LHS */
4354  else
4355  *join_is_reversed = false;
4356 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:508
#define lsecond(l)
Definition: pg_list.h:114
Relids syn_lefthand
Definition: relation.h:1809
Relids syn_righthand
Definition: relation.h:1810
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:307
Relids relids
Definition: relation.h:490
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4391
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 4272 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().

4275 {
4276  Node *left,
4277  *right;
4278  VariableStatData rdata;
4279 
4280  /* Fail if not a binary opclause (probably shouldn't happen) */
4281  if (list_length(args) != 2)
4282  return false;
4283 
4284  left = (Node *) linitial(args);
4285  right = (Node *) lsecond(args);
4286 
4287  /*
4288  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4289  * relations will be treated as pseudoconstants.
4290  */
4291  examine_variable(root, left, varRelid, vardata);
4292  examine_variable(root, right, varRelid, &rdata);
4293 
4294  /*
4295  * If one side is a variable and the other not, we win.
4296  */
4297  if (vardata->rel && rdata.rel == NULL)
4298  {
4299  *varonleft = true;
4300  *other = estimate_expression_value(root, rdata.var);
4301  /* Assume we need no ReleaseVariableStats(rdata) here */
4302  return true;
4303  }
4304 
4305  if (vardata->rel == NULL && rdata.rel)
4306  {
4307  *varonleft = false;
4308  *other = estimate_expression_value(root, vardata->var);
4309  /* Assume we need no ReleaseVariableStats(*vardata) here */
4310  *vardata = rdata;
4311  return true;
4312  }
4313 
4314  /* Ooops, clause has wrong structure (probably var op var) */
4315  ReleaseVariableStats(*vardata);
4316  ReleaseVariableStats(rdata);
4317 
4318  return false;
4319 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2399
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:508
#define lsecond(l)
Definition: pg_list.h:114
#define linitial(l)
Definition: pg_list.h:110
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4391
#define NULL
Definition: c.h:226
static int list_length(const List *l)
Definition: pg_list.h:89
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

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

4736 {
4737  double stadistinct;
4738  double stanullfrac = 0.0;
4739  double ntuples;
4740 
4741  *isdefault = false;
4742 
4743  /*
4744  * Determine the stadistinct value to use. There are cases where we can
4745  * get an estimate even without a pg_statistic entry, or can get a better
4746  * value than is in pg_statistic. Grab stanullfrac too if we can find it
4747  * (otherwise, assume no nulls, for lack of any better idea).
4748  */
4749  if (HeapTupleIsValid(vardata->statsTuple))
4750  {
4751  /* Use the pg_statistic entry */
4752  Form_pg_statistic stats;
4753 
4754  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4755  stadistinct = stats->stadistinct;
4756  stanullfrac = stats->stanullfrac;
4757  }
4758  else if (vardata->vartype == BOOLOID)
4759  {
4760  /*
4761  * Special-case boolean columns: presumably, two distinct values.
4762  *
4763  * Are there any other datatypes we should wire in special estimates
4764  * for?
4765  */
4766  stadistinct = 2.0;
4767  }
4768  else
4769  {
4770  /*
4771  * We don't keep statistics for system columns, but in some cases we
4772  * can infer distinctness anyway.
4773  */
4774  if (vardata->var && IsA(vardata->var, Var))
4775  {
4776  switch (((Var *) vardata->var)->varattno)
4777  {
4780  stadistinct = -1.0; /* unique (and all non null) */
4781  break;
4783  stadistinct = 1.0; /* only 1 value */
4784  break;
4785  default:
4786  stadistinct = 0.0; /* means "unknown" */
4787  break;
4788  }
4789  }
4790  else
4791  stadistinct = 0.0; /* means "unknown" */
4792 
4793  /*
4794  * XXX consider using estimate_num_groups on expressions?
4795  */
4796  }
4797 
4798  /*
4799  * If there is a unique index or DISTINCT clause for the variable, assume
4800  * it is unique no matter what pg_statistic says; the statistics could be
4801  * out of date, or we might have found a partial unique index that proves
4802  * the var is unique for this query. However, we'd better still believe
4803  * the null-fraction statistic.
4804  */
4805  if (vardata->isunique)
4806  stadistinct = -1.0 * (1.0 - stanullfrac);
4807 
4808  /*
4809  * If we had an absolute estimate, use that.
4810  */
4811  if (stadistinct > 0.0)
4812  return clamp_row_est(stadistinct);
4813 
4814  /*
4815  * Otherwise we need to get the relation size; punt if not available.
4816  */
4817  if (vardata->rel == NULL)
4818  {
4819  *isdefault = true;
4820  return DEFAULT_NUM_DISTINCT;
4821  }
4822  ntuples = vardata->rel->tuples;
4823  if (ntuples <= 0.0)
4824  {
4825  *isdefault = true;
4826  return DEFAULT_NUM_DISTINCT;
4827  }
4828 
4829  /*
4830  * If we had a relative estimate, use that.
4831  */
4832  if (stadistinct < 0.0)
4833  return clamp_row_est(-stadistinct * ntuples);
4834 
4835  /*
4836  * With no data, estimate ndistinct = ntuples if the table is small, else
4837  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
4838  * that the behavior isn't discontinuous.
4839  */
4840  if (ntuples < DEFAULT_NUM_DISTINCT)
4841  return clamp_row_est(ntuples);
4842 
4843  *isdefault = true;
4844  return DEFAULT_NUM_DISTINCT;
4845 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#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:529
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: primnodes.h:141
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:226
#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:172
double histogram_selectivity ( VariableStatData vardata,
FmgrInfo opproc,
Datum  constval,
bool  varonleft,
int  min_hist_size,
int  n_skip,
int *  hist_size 
)

Definition at line 684 of file selfuncs.c.

References Assert, VariableStatData::atttype, VariableStatData::atttypmod, DatumGetBool, DEFAULT_COLLATION_OID, free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), HeapTupleIsValid, i, InvalidOid, NULL, STATISTIC_KIND_HISTOGRAM, VariableStatData::statsTuple, and values.

Referenced by ltreeparentsel(), and patternsel().

688 {
689  double result;
690  Datum *values;
691  int nvalues;
692 
693  /* check sanity of parameters */
694  Assert(n_skip >= 0);
695  Assert(min_hist_size > 2 * n_skip);
696 
697  if (HeapTupleIsValid(vardata->statsTuple) &&
698  get_attstatsslot(vardata->statsTuple,
699  vardata->atttype, vardata->atttypmod,
701  NULL,
702  &values, &nvalues,
703  NULL, NULL))
704  {
705  *hist_size = nvalues;
706  if (nvalues >= min_hist_size)
707  {
708  int nmatch = 0;
709  int i;
710 
711  for (i = n_skip; i < nvalues - n_skip; i++)
712  {
713  if (varonleft ?
716  values[i],
717  constval)) :
720  constval,
721  values[i])))
722  nmatch++;
723  }
724  result = ((double) nmatch) / ((double) (nvalues - 2 * n_skip));
725  }
726  else
727  result = -1;
728  free_attstatsslot(vardata->atttype, values, nvalues, NULL, 0);
729  }
730  else
731  {
732  *hist_size = 0;
733  result = -1;
734  }
735 
736  return result;
737 }
HeapTuple statsTuple
Definition: selfuncs.h:71
#define STATISTIC_KIND_HISTOGRAM
Definition: pg_statistic.h:222
bool get_attstatsslot(HeapTuple statstuple, Oid atttype, int32 atttypmod, int reqkind, Oid reqop, Oid *actualop, Datum **values, int *nvalues, float4 **numbers, int *nnumbers)
Definition: lsyscache.c:2854
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1306
int32 atttypmod
Definition: selfuncs.h:76
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:68
#define DatumGetBool(X)
Definition: postgres.h:401
uintptr_t Datum
Definition: postgres.h:374
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static Datum values[MAXATTR]
Definition: bootstrap.c:162
int i
void free_attstatsslot(Oid atttype, Datum *values, int nvalues, float4 *numbers, int nnumbers)
Definition: lsyscache.c:2978
Const* make_greater_string ( const Const str_const,
FmgrInfo ltproc,
Oid  collation 
)

Definition at line 5836 of file selfuncs.c.

References byte_increment(), BYTEAOID, Const::consttype, Const::constvalue, DatumGetBool, DatumGetByteaP, 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, VARHDRSZ, VARSIZE, and varstr_cmp().

Referenced by prefix_quals(), and prefix_selectivity().

5837 {
5838  Oid datatype = str_const->consttype;
5839  char *workstr;
5840  int len;
5841  Datum cmpstr;
5842  text *cmptxt = NULL;
5843  mbcharacter_incrementer charinc;
5844 
5845  /*
5846  * Get a modifiable copy of the prefix string in C-string format, and set
5847  * up the string we will compare to as a Datum. In C locale this can just
5848  * be the given prefix string, otherwise we need to add a suffix. Types
5849  * NAME and BYTEA sort bytewise so they don't need a suffix either.
5850  */
5851  if (datatype == NAMEOID)
5852  {
5854  str_const->constvalue));
5855  len = strlen(workstr);
5856  cmpstr = str_const->constvalue;
5857  }
5858  else if (datatype == BYTEAOID)
5859  {
5860  bytea *bstr = DatumGetByteaP(str_const->constvalue);
5861 
5862  len = VARSIZE(bstr) - VARHDRSZ;
5863  workstr = (char *) palloc(len);
5864  memcpy(workstr, VARDATA(bstr), len);
5865  if ((Pointer) bstr != DatumGetPointer(str_const->constvalue))
5866  pfree(bstr);
5867  cmpstr = str_const->constvalue;
5868  }
5869  else
5870  {
5871  workstr = TextDatumGetCString(str_const->constvalue);
5872  len = strlen(workstr);
5873  if (lc_collate_is_c(collation) || len == 0)
5874  cmpstr = str_const->constvalue;
5875  else
5876  {
5877  /* If first time through, determine the suffix to use */
5878  static char suffixchar = 0;
5879  static Oid suffixcollation = 0;
5880 
5881  if (!suffixchar || suffixcollation != collation)
5882  {
5883  char *best;
5884 
5885  best = "Z";
5886  if (varstr_cmp(best, 1, "z", 1, collation) < 0)
5887  best = "z";
5888  if (varstr_cmp(best, 1, "y", 1, collation) < 0)
5889  best = "y";
5890  if (varstr_cmp(best, 1, "9", 1, collation) < 0)
5891  best = "9";
5892  suffixchar = *best;
5893  suffixcollation = collation;
5894  }
5895 
5896  /* And build the string to compare to */
5897  cmptxt = (text *) palloc(VARHDRSZ + len + 1);
5898  SET_VARSIZE(cmptxt, VARHDRSZ + len + 1);
5899  memcpy(VARDATA(cmptxt), workstr, len);
5900  *(VARDATA(cmptxt) + len) = suffixchar;
5901  cmpstr = PointerGetDatum(cmptxt);
5902  }
5903  }
5904 
5905  /* Select appropriate character-incrementer function */
5906  if (datatype == BYTEAOID)
5907  charinc = byte_increment;
5908  else
5910 
5911  /* And search ... */
5912  while (len > 0)
5913  {
5914  int charlen;
5915  unsigned char *lastchar;
5916 
5917  /* Identify the last character --- for bytea, just the last byte */
5918  if (datatype == BYTEAOID)
5919  charlen = 1;
5920  else
5921  charlen = len - pg_mbcliplen(workstr, len, len - 1);
5922  lastchar = (unsigned char *) (workstr + len - charlen);
5923 
5924  /*
5925  * Try to generate a larger string by incrementing the last character
5926  * (for BYTEA, we treat each byte as a character).
5927  *
5928  * Note: the incrementer function is expected to return true if it's
5929  * generated a valid-per-the-encoding new character, otherwise false.
5930  * The contents of the character on false return are unspecified.
5931  */
5932  while (charinc(lastchar, charlen))
5933  {
5934  Const *workstr_const;
5935 
5936  if (datatype == BYTEAOID)
5937  workstr_const = string_to_bytea_const(workstr, len);
5938  else
5939  workstr_const = string_to_const(workstr, datatype);
5940 
5941  if (DatumGetBool(FunctionCall2Coll(ltproc,
5942  collation,
5943  cmpstr,
5944  workstr_const->constvalue)))
5945  {
5946  /* Successfully made a string larger than cmpstr */
5947  if (cmptxt)
5948  pfree(cmptxt);
5949  pfree(workstr);
5950  return workstr_const;
5951  }
5952 
5953  /* No good, release unusable value and try again */
5954  pfree(DatumGetPointer(workstr_const->constvalue));
5955  pfree(workstr_const);
5956  }
5957 
5958  /*
5959  * No luck here, so truncate off the last character and try to
5960  * increment the next one.
5961  */
5962  len -= charlen;
5963  workstr[len] = '\0';
5964  }
5965 
5966  /* Failed... */
5967  if (cmptxt)
5968  pfree(cmptxt);
5969  pfree(workstr);
5970 
5971  return NULL;
5972 }
Datum constvalue
Definition: primnodes.h:174
#define NAMEOID
Definition: pg_type.h:300
#define VARDATA(PTR)
Definition: postgres.h:305
#define VARSIZE(PTR)
Definition: postgres.h:306
#define PointerGetDatum(X)
Definition: postgres.h:564
#define VARHDRSZ
Definition: c.h:441
static Const * string_to_bytea_const(const char *str, size_t str_len)
Definition: selfuncs.c:6043
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:555
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1306
unsigned int Oid
Definition: postgres_ext.h:31
static bool byte_increment(unsigned char *ptr, int len)
Definition: selfuncs.c:5786
static Const * string_to_const(const char *str, Oid datatype)
Definition: selfuncs.c:6000
Oid consttype
Definition: primnodes.h:170
void pfree(void *pointer)
Definition: mcxt.c:992
char * Pointer
Definition: c.h:242
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1122
#define DatumGetCString(X)
Definition: postgres.h:574
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:831
#define DatumGetByteaP(X)
Definition: fmgr.h:246
#define DatumGetBool(X)
Definition: postgres.h:401
#define TextDatumGetCString(d)
Definition: builtins.h:91
uintptr_t Datum
Definition: postgres.h:374
bool(* mbcharacter_incrementer)(unsigned char *mbstr, int len)
Definition: pg_wchar.h:350
#define NULL
Definition: c.h:226
int varstr_cmp(char *arg1, int len1, char *arg2, int len2, Oid collid)
Definition: varlena.c:1384
#define BYTEAOID
Definition: pg_type.h:292
#define DatumGetPointer(X)
Definition: postgres.h:557
void * palloc(Size size)
Definition: mcxt.c:891
mbcharacter_incrementer pg_database_encoding_character_incrementer(void)
Definition: wchar.c:1842
Definition: c.h:435
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:330
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 606 of file selfuncs.c.

References VariableStatData::atttype, VariableStatData::atttypmod, DatumGetBool, DEFAULT_COLLATION_OID, free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), HeapTupleIsValid, i, InvalidOid, NULL, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and values.

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

609 {
610  double mcv_selec,
611  sumcommon;
612  Datum *values;
613  int nvalues;
614  float4 *numbers;
615  int nnumbers;
616  int i;
617 
618  mcv_selec = 0.0;
619  sumcommon = 0.0;
620 
621  if (HeapTupleIsValid(vardata->statsTuple) &&
622  get_attstatsslot(vardata->statsTuple,
623  vardata->atttype, vardata->atttypmod,
625  NULL,
626  &values, &nvalues,
627  &numbers, &nnumbers))
628  {
629  for (i = 0; i < nvalues; i++)
630  {
631  if (varonleft ?
634  values[i],
635  constval)) :
638  constval,
639  values[i])))
640  mcv_selec += numbers[i];
641  sumcommon += numbers[i];
642  }
643  free_attstatsslot(vardata->atttype, values, nvalues,
644  numbers, nnumbers);
645  }
646 
647  *sumcommonp = sumcommon;
648  return mcv_selec;
649 }
HeapTuple statsTuple
Definition: selfuncs.h:71
bool get_attstatsslot(HeapTuple statstuple, Oid atttype, int32 atttypmod, int reqkind, Oid reqop, Oid *actualop, Datum **values, int *nvalues, float4 **numbers, int *nnumbers)
Definition: lsyscache.c:2854
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1306
int32 atttypmod
Definition: selfuncs.h:76
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:68
#define DatumGetBool(X)
Definition: postgres.h:401
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
float float4
Definition: c.h:377
uintptr_t Datum
Definition: postgres.h:374
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
static Datum values[MAXATTR]
Definition: bootstrap.c:162
int i
void free_attstatsslot(Oid atttype, Datum *values, int nvalues, float4 *numbers, int nnumbers)
Definition: lsyscache.c:2978
void mergejoinscansel ( PlannerInfo root,
Node clause,
Oid  opfamily,
int  strategy,
bool  nulls_first,
Selectivity leftstart,
Selectivity leftend,
Selectivity rightstart,
Selectivity rightend 
)

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

2852 {
2853  Node *left,
2854  *right;
2855  VariableStatData leftvar,
2856  rightvar;
2857  int op_strategy;
2858  Oid op_lefttype;
2859  Oid op_righttype;
2860  Oid opno,
2861  lsortop,
2862  rsortop,
2863  lstatop,
2864  rstatop,
2865  ltop,
2866  leop,
2867  revltop,
2868  revleop;
2869  bool isgt;
2870  Datum leftmin,
2871  leftmax,
2872  rightmin,
2873  rightmax;
2874  double selec;
2875 
2876  /* Set default results if we can't figure anything out. */
2877  /* XXX should default "start" fraction be a bit more than 0? */
2878  *leftstart = *rightstart = 0.0;
2879  *leftend = *rightend = 1.0;
2880 
2881  /* Deconstruct the merge clause */
2882  if (!is_opclause(clause))
2883  return; /* shouldn't happen */
2884  opno = ((OpExpr *) clause)->opno;
2885  left = get_leftop((Expr *) clause);
2886  right = get_rightop((Expr *) clause);
2887  if (!right)
2888  return; /* shouldn't happen */
2889 
2890  /* Look for stats for the inputs */
2891  examine_variable(root, left, 0, &leftvar);
2892  examine_variable(root, right, 0, &rightvar);
2893 
2894  /* Extract the operator's declared left/right datatypes */
2895  get_op_opfamily_properties(opno, opfamily, false,
2896  &op_strategy,
2897  &op_lefttype,
2898  &op_righttype);
2899  Assert(op_strategy == BTEqualStrategyNumber);
2900 
2901  /*
2902  * Look up the various operators we need. If we don't find them all, it
2903  * probably means the opfamily is broken, but we just fail silently.
2904  *
2905  * Note: we expect that pg_statistic histograms will be sorted by the '<'
2906  * operator, regardless of which sort direction we are considering.
2907  */
2908  switch (strategy)
2909  {
2910  case BTLessStrategyNumber:
2911  isgt = false;
2912  if (op_lefttype == op_righttype)
2913  {
2914  /* easy case */
2915  ltop = get_opfamily_member(opfamily,
2916  op_lefttype, op_righttype,
2918  leop = get_opfamily_member(opfamily,
2919  op_lefttype, op_righttype,
2921  lsortop = ltop;
2922  rsortop = ltop;
2923  lstatop = lsortop;
2924  rstatop = rsortop;
2925  revltop = ltop;
2926  revleop = leop;
2927  }
2928  else
2929  {
2930  ltop = get_opfamily_member(opfamily,
2931  op_lefttype, op_righttype,
2933  leop = get_opfamily_member(opfamily,
2934  op_lefttype, op_righttype,
2936  lsortop = get_opfamily_member(opfamily,
2937  op_lefttype, op_lefttype,
2939  rsortop = get_opfamily_member(opfamily,
2940  op_righttype, op_righttype,
2942  lstatop = lsortop;
2943  rstatop = rsortop;
2944  revltop = get_opfamily_member(opfamily,
2945  op_righttype, op_lefttype,
2947  revleop = get_opfamily_member(opfamily,
2948  op_righttype, op_lefttype,
2950  }
2951  break;
2953  /* descending-order case */
2954  isgt = true;
2955  if (op_lefttype == op_righttype)
2956  {
2957  /* easy case */
2958  ltop = get_opfamily_member(opfamily,
2959  op_lefttype, op_righttype,
2961  leop = get_opfamily_member(opfamily,
2962  op_lefttype, op_righttype,
2964  lsortop = ltop;
2965  rsortop = ltop;
2966  lstatop = get_opfamily_member(opfamily,
2967  op_lefttype, op_lefttype,
2969  rstatop = lstatop;
2970  revltop = ltop;
2971  revleop = leop;
2972  }
2973  else
2974  {
2975  ltop = get_opfamily_member(opfamily,
2976  op_lefttype, op_righttype,
2978  leop = get_opfamily_member(opfamily,
2979  op_lefttype, op_righttype,
2981  lsortop = get_opfamily_member(opfamily,
2982  op_lefttype, op_lefttype,
2984  rsortop = get_opfamily_member(opfamily,
2985  op_righttype, op_righttype,
2987  lstatop = get_opfamily_member(opfamily,
2988  op_lefttype, op_lefttype,
2990  rstatop = get_opfamily_member(opfamily,
2991  op_righttype, op_righttype,
2993  revltop = get_opfamily_member(opfamily,
2994  op_righttype, op_lefttype,
2996  revleop = get_opfamily_member(opfamily,
2997  op_righttype, op_lefttype,
2999  }
3000  break;
3001  default:
3002  goto fail; /* shouldn't get here */
3003  }
3004 
3005  if (!OidIsValid(lsortop) ||
3006  !OidIsValid(rsortop) ||
3007  !OidIsValid(lstatop) ||
3008  !OidIsValid(rstatop) ||
3009  !OidIsValid(ltop) ||
3010  !OidIsValid(leop) ||
3011  !OidIsValid(revltop) ||
3012  !OidIsValid(revleop))
3013  goto fail; /* insufficient info in catalogs */
3014 
3015  /* Try to get ranges of both inputs */
3016  if (!isgt)
3017  {
3018  if (!get_variable_range(root, &leftvar, lstatop,
3019  &leftmin, &leftmax))
3020  goto fail; /* no range available from stats */
3021  if (!get_variable_range(root, &rightvar, rstatop,
3022  &rightmin, &rightmax))
3023  goto fail; /* no range available from stats */
3024  }
3025  else
3026  {
3027  /* need to swap the max and min */
3028  if (!get_variable_range(root, &leftvar, lstatop,
3029  &leftmax, &leftmin))
3030  goto fail; /* no range available from stats */
3031  if (!get_variable_range(root, &rightvar, rstatop,
3032  &rightmax, &rightmin))
3033  goto fail; /* no range available from stats */
3034  }
3035 
3036  /*
3037  * Now, the fraction of the left variable that will be scanned is the
3038  * fraction that's <= the right-side maximum value. But only believe
3039  * non-default estimates, else stick with our 1.0.
3040  */
3041  selec = scalarineqsel(root, leop, isgt, &leftvar,
3042  rightmax, op_righttype);
3043  if (selec != DEFAULT_INEQ_SEL)
3044  *leftend = selec;
3045 
3046  /* And similarly for the right variable. */
3047  selec = scalarineqsel(root, revleop, isgt, &rightvar,
3048  leftmax, op_lefttype);
3049  if (selec != DEFAULT_INEQ_SEL)
3050  *rightend = selec;
3051 
3052  /*
3053  * Only one of the two "end" fractions can really be less than 1.0;
3054  * believe the smaller estimate and reset the other one to exactly 1.0. If
3055  * we get exactly equal estimates (as can easily happen with self-joins),
3056  * believe neither.
3057  */
3058  if (*leftend > *rightend)
3059  *leftend = 1.0;
3060  else if (*leftend < *rightend)
3061  *rightend = 1.0;
3062  else
3063  *leftend = *rightend = 1.0;
3064 
3065  /*
3066  * Also, the fraction of the left variable that will be scanned before the
3067  * first join pair is found is the fraction that's < the right-side
3068  * minimum value. But only believe non-default estimates, else stick with
3069  * our own default.
3070  */
3071  selec = scalarineqsel(root, ltop, isgt, &leftvar,
3072  rightmin, op_righttype);
3073  if (selec != DEFAULT_INEQ_SEL)
3074  *leftstart = selec;
3075 
3076  /* And similarly for the right variable. */
3077  selec = scalarineqsel(root, revltop, isgt, &rightvar,
3078  leftmin, op_lefttype);
3079  if (selec != DEFAULT_INEQ_SEL)
3080  *rightstart = selec;
3081 
3082  /*
3083  * Only one of the two "start" fractions can really be more than zero;
3084  * believe the larger estimate and reset the other one to exactly 0.0. If
3085  * we get exactly equal estimates (as can easily happen with self-joins),
3086  * believe neither.
3087  */
3088  if (*leftstart < *rightstart)
3089  *leftstart = 0.0;
3090  else if (*leftstart > *rightstart)
3091  *rightstart = 0.0;
3092  else
3093  *leftstart = *rightstart = 0.0;
3094 
3095  /*
3096  * If the sort order is nulls-first, we're going to have to skip over any
3097  * nulls too. These would not have been counted by scalarineqsel, and we
3098  * can safely add in this fraction regardless of whether we believe
3099  * scalarineqsel's results or not. But be sure to clamp the sum to 1.0!
3100  */
3101  if (nulls_first)
3102  {
3103  Form_pg_statistic stats;
3104 
3105  if (HeapTupleIsValid(leftvar.statsTuple))
3106  {
3107  stats = (Form_pg_statistic) GETSTRUCT(leftvar.statsTuple);
3108  *leftstart += stats->stanullfrac;
3109  CLAMP_PROBABILITY(*leftstart);
3110  *leftend += stats->stanullfrac;
3111  CLAMP_PROBABILITY(*leftend);
3112  }
3113  if (HeapTupleIsValid(rightvar.statsTuple))
3114  {
3115  stats = (Form_pg_statistic) GETSTRUCT(rightvar.statsTuple);
3116  *rightstart += stats->stanullfrac;
3117  CLAMP_PROBABILITY(*rightstart);
3118  *rightend += stats->stanullfrac;
3119  CLAMP_PROBABILITY(*rightend);
3120  }
3121  }
3122 
3123  /* Disbelieve start >= end, just in case that can happen */
3124  if (*leftstart >= *leftend)
3125  {
3126  *leftstart = 0.0;
3127  *leftend = 1.0;
3128  }
3129  if (*rightstart >= *rightend)
3130  {
3131  *rightstart = 0.0;
3132  *rightend = 1.0;
3133  }
3134 
3135 fail:
3136  ReleaseVariableStats(leftvar);
3137  ReleaseVariableStats(rightvar);
3138 }
#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:508
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:534
static double scalarineqsel(PlannerInfo *root, Oid operator, bool isgt, VariableStatData *vardata, Datum constval, Oid consttype)
Definition: selfuncs.c:532
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define is_opclause(clause)
Definition: clauses.h:20
Node * get_leftop(const Expr *clause)
Definition: clauses.c:198
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
uintptr_t Datum
Definition: postgres.h:374
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4391
#define Assert(condition)
Definition: c.h:671
Node * get_rightop(const Expr *clause)
Definition: clauses.c:215
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
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:4857
#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 1659 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().

1661 {
1662  VariableStatData vardata;
1663  double selec;
1664 
1665  examine_variable(root, arg, varRelid, &vardata);
1666 
1667  if (HeapTupleIsValid(vardata.statsTuple))
1668  {
1669  Form_pg_statistic stats;
1670  double freq_null;
1671 
1672  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1673  freq_null = stats->stanullfrac;
1674 
1675  switch (nulltesttype)
1676  {
1677  case IS_NULL:
1678 
1679  /*
1680  * Use freq_null directly.
1681  */
1682  selec = freq_null;
1683  break;
1684  case IS_NOT_NULL:
1685 
1686  /*
1687  * Select not unknown (not null) values. Calculate from
1688  * freq_null.
1689  */
1690  selec = 1.0 - freq_null;
1691  break;
1692  default:
1693  elog(ERROR, "unrecognized nulltesttype: %d",
1694  (int) nulltesttype);
1695  return (Selectivity) 0; /* keep compiler quiet */
1696  }
1697  }
1698  else
1699  {
1700  /*
1701  * No ANALYZE stats available, so make a guess
1702  */
1703  switch (nulltesttype)
1704  {
1705  case IS_NULL:
1706  selec = DEFAULT_UNK_SEL;
1707  break;
1708  case IS_NOT_NULL:
1709  selec = DEFAULT_NOT_UNK_SEL;
1710  break;
1711  default:
1712  elog(ERROR, "unrecognized nulltesttype: %d",
1713  (int) nulltesttype);
1714  return (Selectivity) 0; /* keep compiler quiet */
1715  }
1716  }
1717 
1718  ReleaseVariableStats(vardata);
1719 
1720  /* result should be in range, but make sure... */
1721  CLAMP_PROBABILITY(selec);
1722 
1723  return (Selectivity) selec;
1724 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
double Selectivity
Definition: nodes.h:631
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:4391
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
#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 5471 of file selfuncs.c.

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

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

5473 {
5474  Pattern_Prefix_Status result;
5475 
5476  switch (ptype)
5477  {
5478  case Pattern_Type_Like:
5479  result = like_fixed_prefix(patt, false, collation,
5480  prefix, rest_selec);
5481  break;
5482  case Pattern_Type_Like_IC:
5483  result = like_fixed_prefix(patt, true, collation,
5484  prefix, rest_selec);
5485  break;
5486  case Pattern_Type_Regex:
5487  result = regex_fixed_prefix(patt, false, collation,
5488  prefix, rest_selec);
5489  break;
5490  case Pattern_Type_Regex_IC:
5491  result = regex_fixed_prefix(patt, true, collation,
5492  prefix, rest_selec);
5493  break;
5494  default:
5495  elog(ERROR, "unrecognized ptype: %d", (int) ptype);
5496  result = Pattern_Prefix_None; /* keep compiler quiet */
5497  break;
5498  }
5499  return result;
5500 }
static Pattern_Prefix_Status regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5403
static Pattern_Prefix_Status like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
Definition: selfuncs.c:5294
#define ERROR
Definition: elog.h:43
#define elog
Definition: elog.h:219
Pattern_Prefix_Status
Definition: selfuncs.h:93
Selectivity rowcomparesel ( PlannerInfo root,
RowCompareExpr clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

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

2119 {
2120  Selectivity s1;
2121  Oid opno = linitial_oid(clause->opnos);
2122  Oid inputcollid = linitial_oid(clause->inputcollids);
2123  List *opargs;
2124  bool is_join_clause;
2125 
2126  /* Build equivalent arg list for single operator */
2127  opargs = list_make2(linitial(clause->largs), linitial(clause->rargs));
2128 
2129  /*
2130  * Decide if it's a join clause. This should match clausesel.c's
2131  * treat_as_join_clause(), except that we intentionally consider only the
2132  * leading columns and not the rest of the clause.
2133  */
2134  if (varRelid != 0)
2135  {
2136  /*
2137  * Caller is forcing restriction mode (eg, because we are examining an
2138  * inner indexscan qual).
2139  */
2140  is_join_clause = false;
2141  }
2142  else if (sjinfo == NULL)
2143  {
2144  /*
2145  * It must be a restriction clause, since it's being evaluated at a
2146  * scan node.
2147  */
2148  is_join_clause = false;
2149  }
2150  else
2151  {
2152  /*
2153  * Otherwise, it's a join if there's more than one relation used.
2154  */
2155  is_join_clause = (NumRelids((Node *) opargs) > 1);
2156  }
2157 
2158  if (is_join_clause)
2159  {
2160  /* Estimate selectivity for a join clause. */
2161  s1 = join_selectivity(root, opno,
2162  opargs,
2163  inputcollid,
2164  jointype,
2165  sjinfo);
2166  }
2167  else
2168  {
2169  /* Estimate selectivity for a restriction clause. */
2170  s1 = restriction_selectivity(root, opno,
2171  opargs,
2172  inputcollid,
2173  varRelid);
2174  }
2175 
2176  return s1;
2177 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1568
Definition: nodes.h:508
double Selectivity
Definition: nodes.h:631
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial(l)
Definition: pg_list.h:110
char * s1
#define NULL
Definition: c.h:226
#define linitial_oid(l)
Definition: pg_list.h:112
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1605
List * inputcollids
Definition: primnodes.h:1010
Definition: pg_list.h:45
int NumRelids(Node *clause)
Definition: clauses.c:2183
Selectivity scalararraysel ( PlannerInfo root,
ScalarArrayOpExpr clause,
bool  is_join_clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

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

1765 {
1766  Oid operator = clause->opno;
1767  bool useOr = clause->useOr;
1768  bool isEquality = false;
1769  bool isInequality = false;
1770  Node *leftop;
1771  Node *rightop;
1772  Oid nominal_element_type;
1773  Oid nominal_element_collation;
1774  TypeCacheEntry *typentry;
1775  RegProcedure oprsel;
1776  FmgrInfo oprselproc;
1777  Selectivity s1;
1778  Selectivity s1disjoint;
1779 
1780  /* First, deconstruct the expression */
1781  Assert(list_length(clause->args) == 2);
1782  leftop = (Node *) linitial(clause->args);
1783  rightop = (Node *) lsecond(clause->args);
1784 
1785  /* aggressively reduce both sides to constants */
1786  leftop = estimate_expression_value(root, leftop);
1787  rightop = estimate_expression_value(root, rightop);
1788 
1789  /* get nominal (after relabeling) element type of rightop */
1790  nominal_element_type = get_base_element_type(exprType(rightop));
1791  if (!OidIsValid(nominal_element_type))
1792  return (Selectivity) 0.5; /* probably shouldn't happen */
1793  /* get nominal collation, too, for generating constants */
1794  nominal_element_collation = exprCollation(rightop);
1795 
1796  /* look through any binary-compatible relabeling of rightop */
1797  rightop = strip_array_coercion(rightop);
1798 
1799  /*
1800  * Detect whether the operator is the default equality or inequality
1801  * operator of the array element type.
1802  */
1803  typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
1804  if (OidIsValid(typentry->eq_opr))
1805  {
1806  if (operator == typentry->eq_opr)
1807  isEquality = true;
1808  else if (get_negator(operator) == typentry->eq_opr)
1809  isInequality = true;
1810  }
1811 
1812  /*
1813  * If it is equality or inequality, we might be able to estimate this as a
1814  * form of array containment; for instance "const = ANY(column)" can be
1815  * treated as "ARRAY[const] <@ column". scalararraysel_containment tries
1816  * that, and returns the selectivity estimate if successful, or -1 if not.
1817  */
1818  if ((isEquality || isInequality) && !is_join_clause)
1819  {
1820  s1 = scalararraysel_containment(root, leftop, rightop,
1821  nominal_element_type,
1822  isEquality, useOr, varRelid);
1823  if (s1 >= 0.0)
1824  return s1;
1825  }
1826 
1827  /*
1828  * Look up the underlying operator's selectivity estimator. Punt if it
1829  * hasn't got one.
1830  */
1831  if (is_join_clause)
1832  oprsel = get_oprjoin(operator);
1833  else
1834  oprsel = get_oprrest(operator);
1835  if (!oprsel)
1836  return (Selectivity) 0.5;
1837  fmgr_info(oprsel, &oprselproc);
1838 
1839  /*
1840  * In the array-containment check above, we must only believe that an
1841  * operator is equality or inequality if it is the default btree equality
1842  * operator (or its negator) for the element type, since those are the
1843  * operators that array containment will use. But in what follows, we can
1844  * be a little laxer, and also believe that any operators using eqsel() or
1845  * neqsel() as selectivity estimator act like equality or inequality.
1846  */
1847  if (oprsel == F_EQSEL || oprsel == F_EQJOINSEL)
1848  isEquality = true;
1849  else if (oprsel == F_NEQSEL || oprsel == F_NEQJOINSEL)
1850  isInequality = true;
1851 
1852  /*
1853  * We consider three cases:
1854  *
1855  * 1. rightop is an Array constant: deconstruct the array, apply the
1856  * operator's selectivity function for each array element, and merge the
1857  * results in the same way that clausesel.c does for AND/OR combinations.
1858  *
1859  * 2. rightop is an ARRAY[] construct: apply the operator's selectivity
1860  * function for each element of the ARRAY[] construct, and merge.
1861  *
1862  * 3. otherwise, make a guess ...
1863  */
1864  if (rightop && IsA(rightop, Const))
1865  {
1866  Datum arraydatum = ((Const *) rightop)->constvalue;
1867  bool arrayisnull = ((Const *) rightop)->constisnull;
1868  ArrayType *arrayval;
1869  int16 elmlen;
1870  bool elmbyval;
1871  char elmalign;
1872  int num_elems;
1873  Datum *elem_values;
1874  bool *elem_nulls;
1875  int i;
1876 
1877  if (arrayisnull) /* qual can't succeed if null array */
1878  return (Selectivity) 0.0;
1879  arrayval = DatumGetArrayTypeP(arraydatum);
1881  &elmlen, &elmbyval, &elmalign);
1882  deconstruct_array(arrayval,
1883  ARR_ELEMTYPE(arrayval),
1884  elmlen, elmbyval, elmalign,
1885  &elem_values, &elem_nulls, &num_elems);
1886 
1887  /*
1888  * For generic operators, we assume the probability of success is
1889  * independent for each array element. But for "= ANY" or "<> ALL",
1890  * if the array elements are distinct (which'd typically be the case)
1891  * then the probabilities are disjoint, and we should just sum them.
1892  *
1893  * If we were being really tense we would try to confirm that the
1894  * elements are all distinct, but that would be expensive and it
1895  * doesn't seem to be worth the cycles; it would amount to penalizing
1896  * well-written queries in favor of poorly-written ones. However, we
1897  * do protect ourselves a little bit by checking whether the
1898  * disjointness assumption leads to an impossible (out of range)
1899  * probability; if so, we fall back to the normal calculation.
1900  */
1901  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1902 
1903  for (i = 0; i < num_elems; i++)
1904  {
1905  List *args;
1906  Selectivity s2;
1907 
1908  args = list_make2(leftop,
1909  makeConst(nominal_element_type,
1910  -1,
1911  nominal_element_collation,
1912  elmlen,
1913  elem_values[i],
1914  elem_nulls[i],
1915  elmbyval));
1916  if (is_join_clause)
1917  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1918  clause->inputcollid,
1919  PointerGetDatum(root),
1920  ObjectIdGetDatum(operator),
1921  PointerGetDatum(args),
1922  Int16GetDatum(jointype),
1923  PointerGetDatum(sjinfo)));
1924  else
1925  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1926  clause->inputcollid,
1927  PointerGetDatum(root),
1928  ObjectIdGetDatum(operator),
1929  PointerGetDatum(args),
1930  Int32GetDatum(varRelid)));
1931 
1932  if (useOr)
1933  {
1934  s1 = s1 + s2 - s1 * s2;
1935  if (isEquality)
1936  s1disjoint += s2;
1937  }
1938  else
1939  {
1940  s1 = s1 * s2;
1941  if (isInequality)
1942  s1disjoint += s2 - 1.0;
1943  }
1944  }
1945 
1946  /* accept disjoint-probability estimate if in range */
1947  if ((useOr ? isEquality : isInequality) &&
1948  s1disjoint >= 0.0 && s1disjoint <= 1.0)
1949  s1 = s1disjoint;
1950  }
1951  else if (rightop && IsA(rightop, ArrayExpr) &&
1952  !((ArrayExpr *) rightop)->multidims)
1953  {
1954  ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1955  int16 elmlen;
1956  bool elmbyval;
1957  ListCell *l;
1958 
1959  get_typlenbyval(arrayexpr->element_typeid,
1960  &elmlen, &elmbyval);
1961 
1962  /*
1963  * We use the assumption of disjoint probabilities here too, although
1964  * the odds of equal array elements are rather higher if the elements
1965  * are not all constants (which they won't be, else constant folding
1966  * would have reduced the ArrayExpr to a Const). In this path it's
1967  * critical to have the sanity check on the s1disjoint estimate.
1968  */
1969  s1 = s1disjoint = (useOr ? 0.0 : 1.0);
1970 
1971  foreach(l, arrayexpr->elements)
1972  {
1973  Node *elem = (Node *) lfirst(l);
1974  List *args;
1975  Selectivity s2;
1976 
1977  /*
1978  * Theoretically, if elem isn't of nominal_element_type we should
1979  * insert a RelabelType, but it seems unlikely that any operator
1980  * estimation function would really care ...
1981  */
1982  args = list_make2(leftop, elem);
1983  if (is_join_clause)
1984  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
1985  clause->inputcollid,
1986  PointerGetDatum(root),
1987  ObjectIdGetDatum(operator),
1988  PointerGetDatum(args),
1989  Int16GetDatum(jointype),
1990  PointerGetDatum(sjinfo)));
1991  else
1992  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
1993  clause->inputcollid,
1994  PointerGetDatum(root),
1995  ObjectIdGetDatum(operator),
1996  PointerGetDatum(args),
1997  Int32GetDatum(varRelid)));
1998 
1999  if (useOr)
2000  {
2001  s1 = s1 + s2 - s1 * s2;
2002  if (isEquality)
2003  s1disjoint += s2;
2004  }
2005  else
2006  {
2007  s1 = s1 * s2;
2008  if (isInequality)
2009  s1disjoint += s2 - 1.0;
2010  }
2011  }
2012 
2013  /* accept disjoint-probability estimate if in range */
2014  if ((useOr ? isEquality : isInequality) &&
2015  s1disjoint >= 0.0 && s1disjoint <= 1.0)
2016  s1 = s1disjoint;
2017  }
2018  else
2019  {
2020  CaseTestExpr *dummyexpr;
2021  List *args;
2022  Selectivity s2;
2023  int i;
2024 
2025  /*
2026  * We need a dummy rightop to pass to the operator selectivity
2027  * routine. It can be pretty much anything that doesn't look like a
2028  * constant; CaseTestExpr is a convenient choice.
2029  */
2030  dummyexpr = makeNode(CaseTestExpr);
2031  dummyexpr->typeId = nominal_element_type;
2032  dummyexpr->typeMod = -1;
2033  dummyexpr->collation = clause->inputcollid;
2034  args = list_make2(leftop, dummyexpr);
2035  if (is_join_clause)
2036  s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
2037  clause->inputcollid,
2038  PointerGetDatum(root),
2039  ObjectIdGetDatum(operator),
2040  PointerGetDatum(args),
2041  Int16GetDatum(jointype),
2042  PointerGetDatum(sjinfo)));
2043  else
2044  s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
2045  clause->inputcollid,
2046  PointerGetDatum(root),
2047  ObjectIdGetDatum(operator),
2048  PointerGetDatum(args),
2049  Int32GetDatum(varRelid)));
2050  s1 = useOr ? 0.0 : 1.0;
2051 
2052  /*
2053  * Arbitrarily assume 10 elements in the eventual array value (see
2054  * also estimate_array_length). We don't risk an assumption of
2055  * disjoint probabilities here.
2056  */
2057  for (i = 0; i < 10; i++)
2058  {
2059  if (useOr)
2060  s1 = s1 + s2 - s1 * s2;
2061  else
2062  s1 = s1 * s2;
2063  }
2064  }
2065 
2066  /* result should be in range, but make sure... */
2067  CLAMP_PROBABILITY(s1);
2068 
2069  return s1;
2070 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
signed short int16
Definition: c.h:252
Definition: fmgr.h:53
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1353
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2399
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:1989
#define PointerGetDatum(X)
Definition: postgres.h:564
Datum FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1380
regproc RegProcedure
Definition: c.h:392
#define Int16GetDatum(X)
Definition: postgres.h:459
Definition: nodes.h:508
#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:1353
double Selectivity
Definition: nodes.h:631
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:534
#define lsecond(l)
Definition: pg_list.h:114
int32 typeMod
Definition: primnodes.h:913
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define linitial(l)
Definition: pg_list.h:110
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
char * s1
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:159
List * elements
Definition: primnodes.h:931
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1329
char * s2
#define DatumGetFloat8(X)
Definition: postgres.h:736
uintptr_t Datum
Definition: postgres.h:374
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:191
#define makeNode(_type_)
Definition: nodes.h:556
#define Assert(condition)
Definition: c.h:671
#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:745
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:1969
Oid element_typeid
Definition: primnodes.h:930
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:2525
#define Int32GetDatum(X)
Definition: postgres.h:487
int i
Oid get_negator(Oid opno)
Definition: lsyscache.c:1305
Definition: pg_list.h:45
#define ARR_ELEMTYPE(a)
Definition: array.h:273
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1735
#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 VariableStatData::atttypmod, 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(), NULL, OID_ARRAY_CONTAINED_OP, OID_ARRAY_CONTAINS_OP, OidIsValid, VariableStatData::rel, ReleaseVariableStats, STATISTIC_KIND_DECHIST, STATISTIC_KIND_MCELEM, VariableStatData::statsTuple, TYPECACHE_CMP_PROC_FINFO, and 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  {
138  Form_pg_statistic stats;
139  Datum *values;
140  int nvalues;
141  float4 *numbers;
142  int nnumbers;
143  float4 *hist;
144  int nhist;
145 
146  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
147 
148  /* MCELEM will be an array of same type as element */
149  if (get_attstatsslot(vardata.statsTuple,
150  elemtype, vardata.atttypmod,
152  NULL,
153  &values, &nvalues,
154  &numbers, &nnumbers))
155  {
156  /* For ALL case, also get histogram of distinct-element counts */
157  if (useOr ||
158  !get_attstatsslot(vardata.statsTuple,
159  elemtype, vardata.atttypmod,
161  NULL,
162  NULL, NULL,
163  &hist, &nhist))
164  {
165  hist = NULL;
166  nhist = 0;
167  }
168 
169  /*
170  * For = ANY, estimate as var @> ARRAY[const].
171  *
172  * For = ALL, estimate as var <@ ARRAY[const].
173  */
174  if (useOr)
175  selec = mcelem_array_contain_overlap_selec(values, nvalues,
176  numbers, nnumbers,
177  &constval, 1,
179  cmpfunc);
180  else
181  selec = mcelem_array_contained_selec(values, nvalues,
182  numbers, nnumbers,
183  &constval, 1,
184  hist, nhist,
186  cmpfunc);
187 
188  if (hist)
189  free_attstatsslot(elemtype, NULL, 0, hist, nhist);
190  free_attstatsslot(elemtype, values, nvalues, numbers, nnumbers);
191  }
192  else
193  {
194  /* No most-common-elements info, so do without */
195  if (useOr)
197  NULL, 0,
198  &constval, 1,
200  cmpfunc);
201  else
203  NULL, 0,
204  &constval, 1,
205  NULL, 0,
207  cmpfunc);
208  }
209 
210  /*
211  * MCE stats count only non-null rows, so adjust for null rows.
212  */
213  selec *= (1.0 - stats->stanullfrac);
214  }
215  else
216  {
217  /* No stats at all, so do without */
218  if (useOr)
220  NULL, 0,
221  &constval, 1,
223  cmpfunc);
224  else
226  NULL, 0,
227  &constval, 1,
228  NULL, 0,
230  cmpfunc);
231  /* we assume no nulls here, so no stanullfrac correction */
232  }
233 
234  ReleaseVariableStats(vardata);
235 
236  /*
237  * If the operator is <>, invert the results.
238  */
239  if (!isEquality)
240  selec = 1.0 - selec;
241 
242  CLAMP_PROBABILITY(selec);
243 
244  return selec;
245 }
Definition: fmgr.h:53
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:631
bool get_attstatsslot(HeapTuple statstuple, Oid atttype, int32 atttypmod, int reqkind, Oid reqop, Oid *actualop, Datum **values, int *nvalues, float4 **numbers, int *nnumbers)
Definition: lsyscache.c:2854
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define OidIsValid(objectId)
Definition: c.h:534
int32 atttypmod
Definition: selfuncs.h:76
#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:1548
#define STATISTIC_KIND_DECHIST
Definition: pg_statistic.h:270
#define OID_ARRAY_CONTAINED_OP
Definition: pg_operator.h:1551
float float4
Definition: c.h:377
uintptr_t Datum
Definition: postgres.h:374
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:56
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4391
#define NULL
Definition: c.h:226
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)
static Datum values[MAXATTR]
Definition: bootstrap.c:162
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
#define STATISTIC_KIND_MCELEM
Definition: pg_statistic.h:257
#define TYPECACHE_CMP_PROC_FINFO
Definition: typcache.h:116
void free_attstatsslot(Oid atttype, Datum *values, int nvalues, float4 *numbers, int nnumbers)
Definition: lsyscache.c:2978
static Selectivity mcelem_array_contain_overlap_selec(Datum *mcelem, int nmcelem, float4 *numbers, int nnumbers, Datum *array_data, int nitems, Oid operator, FmgrInfo *cmpfunc)

Variable Documentation

PGDLLIMPORT get_index_stats_hook_type get_index_stats_hook

Definition at line 149 of file selfuncs.c.

Referenced by btcostestimate(), and examine_variable().

PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook

Definition at line 148 of file selfuncs.c.

Referenced by btcostestimate(), and examine_simple_variable().