PostgreSQL Source Code  git master
selfuncs.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <float.h>
#include <math.h>
#include "access/brin.h"
#include "access/gin.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/predtest.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parsetree.h"
#include "statistics/statistics.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/bytea.h"
#include "utils/date.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/index_selfuncs.h"
#include "utils/lsyscache.h"
#include "utils/nabstime.h"
#include "utils/pg_locale.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/snapmgr.h"
#include "utils/spccache.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/tqual.h"
#include "utils/typcache.h"
#include "utils/varlena.h"
Include dependency graph for selfuncs.c:

Go to the source code of this file.

Data Structures

struct  GroupVarInfo
 
struct  GinQualCounts
 

Macros

#define FIXED_CHAR_SEL   0.20 /* about 1/5 */
 
#define CHAR_RANGE_SEL   0.25
 
#define ANY_CHAR_SEL   0.9 /* not 1, since it won't match end-of-string */
 
#define FULL_WILDCARD_SEL   5.0
 
#define PARTIAL_WILDCARD_SEL   2.0
 

Functions

static double eqsel_internal (PG_FUNCTION_ARGS, bool negate)
 
static double var_eq_const (VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
 
static double var_eq_non_const (VariableStatData *vardata, Oid operator, Node *other, bool varonleft, bool negate)
 
static double ineq_histogram_selectivity (PlannerInfo *root, VariableStatData *vardata, FmgrInfo *opproc, bool isgt, bool iseq, Datum constval, Oid consttype)
 
static double eqjoinsel_inner (Oid operator, VariableStatData *vardata1, VariableStatData *vardata2)
 
static double eqjoinsel_semi (Oid operator, VariableStatData *vardata1, VariableStatData *vardata2, RelOptInfo *inner_rel)
 
static bool estimate_multivariate_ndistinct (PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
 
static bool convert_to_scalar (Datum value, Oid valuetypid, double *scaledvalue, Datum lobound, Datum hibound, Oid boundstypid, double *scaledlobound, double *scaledhibound)
 
static double convert_numeric_to_scalar (Datum value, Oid typid, bool *failure)
 
static void convert_string_to_scalar (char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
 
static void convert_bytea_to_scalar (Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
 
static double convert_one_string_to_scalar (char *value, int rangelo, int rangehi)
 
static double convert_one_bytea_to_scalar (unsigned char *value, int valuelen, int rangelo, int rangehi)
 
static char * convert_string_datum (Datum value, Oid typid, bool *failure)
 
static double convert_timevalue_to_scalar (Datum value, Oid typid, bool *failure)
 
static void examine_simple_variable (PlannerInfo *root, Var *var, VariableStatData *vardata)
 
static bool get_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Datum *min, Datum *max)
 
static bool get_actual_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Datum *min, Datum *max)
 
static RelOptInfofind_join_input_rel (PlannerInfo *root, Relids relids)
 
static Selectivity prefix_selectivity (PlannerInfo *root, VariableStatData *vardata, Oid vartype, Oid opfamily, Const *prefixcon)
 
static Selectivity like_selectivity (const char *patt, int pattlen, bool case_insensitive)
 
static Selectivity regex_selectivity (const char *patt, int pattlen, bool case_insensitive, int fixed_prefix_len)
 
static Datum string_to_datum (const char *str, Oid datatype)
 
static Conststring_to_const (const char *str, Oid datatype)
 
static Conststring_to_bytea_const (const char *str, size_t str_len)
 
static Listadd_predicate_to_quals (IndexOptInfo *index, List *indexQuals)
 
Datum eqsel (PG_FUNCTION_ARGS)
 
Datum neqsel (PG_FUNCTION_ARGS)
 
static double scalarineqsel (PlannerInfo *root, Oid operator, bool isgt, bool iseq, VariableStatData *vardata, Datum constval, Oid consttype)
 
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)
 
static Datum scalarineqsel_wrapper (PG_FUNCTION_ARGS, bool isgt, bool iseq)
 
Datum scalarltsel (PG_FUNCTION_ARGS)
 
Datum scalarlesel (PG_FUNCTION_ARGS)
 
Datum scalargtsel (PG_FUNCTION_ARGS)
 
Datum scalargesel (PG_FUNCTION_ARGS)
 
static double patternsel (PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 
Datum regexeqsel (PG_FUNCTION_ARGS)
 
Datum icregexeqsel (PG_FUNCTION_ARGS)
 
Datum likesel (PG_FUNCTION_ARGS)
 
Datum prefixsel (PG_FUNCTION_ARGS)
 
Datum iclikesel (PG_FUNCTION_ARGS)
 
Datum regexnesel (PG_FUNCTION_ARGS)
 
Datum icregexnesel (PG_FUNCTION_ARGS)
 
Datum nlikesel (PG_FUNCTION_ARGS)
 
Datum icnlikesel (PG_FUNCTION_ARGS)
 
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)
 
static Nodestrip_array_coercion (Node *node)
 
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)
 
Datum eqjoinsel (PG_FUNCTION_ARGS)
 
Datum neqjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarltjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarlejoinsel (PG_FUNCTION_ARGS)
 
Datum scalargtjoinsel (PG_FUNCTION_ARGS)
 
Datum scalargejoinsel (PG_FUNCTION_ARGS)
 
static double patternjoinsel (PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 
Datum regexeqjoinsel (PG_FUNCTION_ARGS)
 
Datum icregexeqjoinsel (PG_FUNCTION_ARGS)
 
Datum likejoinsel (PG_FUNCTION_ARGS)
 
Datum prefixjoinsel (PG_FUNCTION_ARGS)
 
Datum iclikejoinsel (PG_FUNCTION_ARGS)
 
Datum regexnejoinsel (PG_FUNCTION_ARGS)
 
Datum icregexnejoinsel (PG_FUNCTION_ARGS)
 
Datum nlikejoinsel (PG_FUNCTION_ARGS)
 
Datum icnlikejoinsel (PG_FUNCTION_ARGS)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
static Listadd_unique_group_var (PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
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)
 
void examine_variable (PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
 
bool statistic_proc_security_check (VariableStatData *vardata, Oid func_oid)
 
double get_variable_numdistinct (VariableStatData *vardata, bool *isdefault)
 
static int pattern_char_isalpha (char c, bool is_multibyte, pg_locale_t locale, bool locale_is_c)
 
static Pattern_Prefix_Status like_fixed_prefix (Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
 
static Pattern_Prefix_Status regex_fixed_prefix (Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
 
Pattern_Prefix_Status pattern_fixed_prefix (Const *patt, Pattern_Type ptype, Oid collation, Const **prefix, Selectivity *rest_selec)
 
static Selectivity regex_selectivity_sub (const char *patt, int pattlen, bool case_insensitive)
 
static bool byte_increment (unsigned char *ptr, int len)
 
Constmake_greater_string (const Const *str_const, FmgrInfo *ltproc, Oid collation)
 
Listdeconstruct_indexquals (IndexPath *path)
 
static Cost other_operands_eval_cost (PlannerInfo *root, List *qinfos)
 
static Cost orderby_operands_eval_cost (PlannerInfo *root, IndexPath *path)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
 
void btcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void hashcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void gistcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void spgcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
static bool gincost_pattern (IndexOptInfo *index, int indexcol, Oid clause_op, Datum query, GinQualCounts *counts)
 
static bool gincost_opexpr (PlannerInfo *root, IndexOptInfo *index, IndexQualInfo *qinfo, GinQualCounts *counts)
 
static bool gincost_scalararrayopexpr (PlannerInfo *root, IndexOptInfo *index, IndexQualInfo *qinfo, double numIndexEntries, GinQualCounts *counts)
 
void gincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void brincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 

Variables

get_relation_stats_hook_type get_relation_stats_hook = NULL
 
get_index_stats_hook_type get_index_stats_hook = NULL
 

Macro Definition Documentation

◆ ANY_CHAR_SEL

#define ANY_CHAR_SEL   0.9 /* not 1, since it won't match end-of-string */

Definition at line 6108 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity_sub().

◆ CHAR_RANGE_SEL

#define CHAR_RANGE_SEL   0.25

Definition at line 6107 of file selfuncs.c.

Referenced by regex_selectivity_sub().

◆ FIXED_CHAR_SEL

#define FIXED_CHAR_SEL   0.20 /* about 1/5 */

Definition at line 6106 of file selfuncs.c.

Referenced by like_selectivity(), regex_selectivity(), and regex_selectivity_sub().

◆ FULL_WILDCARD_SEL

#define FULL_WILDCARD_SEL   5.0

Definition at line 6109 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity().

◆ PARTIAL_WILDCARD_SEL

#define PARTIAL_WILDCARD_SEL   2.0

Definition at line 6110 of file selfuncs.c.

Referenced by regex_selectivity_sub().

Function Documentation

◆ add_predicate_to_quals()

static List * add_predicate_to_quals ( IndexOptInfo index,
List indexQuals 
)
static

Definition at line 6920 of file selfuncs.c.

References IndexOptInfo::indpred, lfirst, list_concat(), list_make1, NIL, and predicate_implied_by().

Referenced by btcostestimate(), and genericcostestimate().

6921 {
6922  List *predExtraQuals = NIL;
6923  ListCell *lc;
6924 
6925  if (index->indpred == NIL)
6926  return indexQuals;
6927 
6928  foreach(lc, index->indpred)
6929  {
6930  Node *predQual = (Node *) lfirst(lc);
6931  List *oneQual = list_make1(predQual);
6932 
6933  if (!predicate_implied_by(oneQual, indexQuals, false))
6934  predExtraQuals = list_concat(predExtraQuals, oneQual);
6935  }
6936  /* list_concat avoids modifying the passed-in indexQuals list */
6937  return list_concat(predExtraQuals, indexQuals);
6938 }
#define NIL
Definition: pg_list.h:69
Definition: nodes.h:517
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define list_make1(x1)
Definition: pg_list.h:139
#define lfirst(lc)
Definition: pg_list.h:106
List * indpred
Definition: relation.h:778
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:149
Definition: pg_list.h:45

◆ add_unique_group_var()

static List* add_unique_group_var ( PlannerInfo root,
List varinfos,
Node var,
VariableStatData vardata 
)
static

Definition at line 3301 of file selfuncs.c.

References equal(), exprs_known_equal(), get_variable_numdistinct(), lappend(), lfirst, list_delete_ptr(), list_head(), lnext, GroupVarInfo::ndistinct, palloc(), VariableStatData::rel, GroupVarInfo::rel, and GroupVarInfo::var.

Referenced by estimate_num_groups().

3303 {
3304  GroupVarInfo *varinfo;
3305  double ndistinct;
3306  bool isdefault;
3307  ListCell *lc;
3308 
3309  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3310 
3311  /* cannot use foreach here because of possible list_delete */
3312  lc = list_head(varinfos);
3313  while (lc)
3314  {
3315  varinfo = (GroupVarInfo *) lfirst(lc);
3316 
3317  /* must advance lc before list_delete possibly pfree's it */
3318  lc = lnext(lc);
3319 
3320  /* Drop exact duplicates */
3321  if (equal(var, varinfo->var))
3322  return varinfos;
3323 
3324  /*
3325  * Drop known-equal vars, but only if they belong to different
3326  * relations (see comments for estimate_num_groups)
3327  */
3328  if (vardata->rel != varinfo->rel &&
3329  exprs_known_equal(root, var, varinfo->var))
3330  {
3331  if (varinfo->ndistinct <= ndistinct)
3332  {
3333  /* Keep older item, forget new one */
3334  return varinfos;
3335  }
3336  else
3337  {
3338  /* Delete the older item */
3339  varinfos = list_delete_ptr(varinfos, varinfo);
3340  }
3341  }
3342  }
3343 
3344  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3345 
3346  varinfo->var = var;
3347  varinfo->rel = vardata->rel;
3348  varinfo->ndistinct = ndistinct;
3349  varinfos = lappend(varinfos, varinfo);
3350  return varinfos;
3351 }
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:1984
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
RelOptInfo * rel
Definition: selfuncs.h:70
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
double ndistinct
Definition: selfuncs.c:3297
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5183
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
Node * var
Definition: selfuncs.c:3295
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
void * palloc(Size size)
Definition: mcxt.c:924
RelOptInfo * rel
Definition: selfuncs.c:3296

◆ booltestsel()

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

Definition at line 1593 of file selfuncs.c.

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

Referenced by clause_selectivity().

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

◆ boolvarsel()

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

Definition at line 1554 of file selfuncs.c.

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

Referenced by clause_selectivity().

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

◆ brincostestimate()

void brincostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 8024 of file selfuncs.c.

References Abs, AccessShareLock, Assert, attnum, ATTSTATSSLOT_NUMBERS, BoolGetDatum, brinGetStats(), CLAMP_PROBABILITY, clauselist_selectivity(), cpu_operator_cost, deconstruct_indexquals(), elog, ERROR, free_attstatsslot(), VariableStatData::freefunc, get_attstatsslot(), get_index_stats_hook, get_relation_stats_hook, get_tablespace_page_costs(), HeapTupleIsValid, index_close(), index_open(), IndexQualInfo::indexcol, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, IndexPath::indexquals, Int16GetDatum, InvalidOid, JOIN_INNER, lfirst, Max, Min, AttStatsSlot::nnumbers, AttStatsSlot::numbers, ObjectIdGetDatum, orderby_operands_eval_cost(), other_operands_eval_cost(), RelOptInfo::pages, IndexOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, IndexOptInfo::reltablespace, BrinStatsData::revmapNumPages, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

8028 {
8029  IndexOptInfo *index = path->indexinfo;
8030  List *indexQuals = path->indexquals;
8031  double numPages = index->pages;
8032  RelOptInfo *baserel = index->rel;
8033  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
8034  List *qinfos;
8035  Cost spc_seq_page_cost;
8036  Cost spc_random_page_cost;
8037  double qual_arg_cost;
8038  double qualSelectivity;
8039  BrinStatsData statsData;
8040  double indexRanges;
8041  double minimalRanges;
8042  double estimatedRanges;
8043  double selec;
8044  Relation indexRel;
8045  ListCell *l;
8046  VariableStatData vardata;
8047 
8048  Assert(rte->rtekind == RTE_RELATION);
8049 
8050  /* fetch estimated page cost for the tablespace containing the index */
8052  &spc_random_page_cost,
8053  &spc_seq_page_cost);
8054 
8055  /*
8056  * Obtain some data from the index itself.
8057  */
8058  indexRel = index_open(index->indexoid, AccessShareLock);
8059  brinGetStats(indexRel, &statsData);
8060  index_close(indexRel, AccessShareLock);
8061 
8062  /*
8063  * Compute index correlation
8064  *
8065  * Because we can use all index quals equally when scanning, we can use
8066  * the largest correlation (in absolute value) among columns used by the
8067  * query. Start at zero, the worst possible case. If we cannot find any
8068  * correlation statistics, we will keep it as 0.
8069  */
8070  *indexCorrelation = 0;
8071 
8072  qinfos = deconstruct_indexquals(path);
8073  foreach(l, qinfos)
8074  {
8075  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(l);
8076  AttrNumber attnum = index->indexkeys[qinfo->indexcol];
8077 
8078  /* attempt to lookup stats in relation for this index column */
8079  if (attnum != 0)
8080  {
8081  /* Simple variable -- look to stats for the underlying table */
8083  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8084  {
8085  /*
8086  * The hook took control of acquiring a stats tuple. If it
8087  * did supply a tuple, it'd better have supplied a freefunc.
8088  */
8089  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8090  elog(ERROR,
8091  "no function provided to release variable stats with");
8092  }
8093  else
8094  {
8095  vardata.statsTuple =
8097  ObjectIdGetDatum(rte->relid),
8098  Int16GetDatum(attnum),
8099  BoolGetDatum(false));
8100  vardata.freefunc = ReleaseSysCache;
8101  }
8102  }
8103  else
8104  {
8105  /*
8106  * Looks like we've found an expression column in the index. Let's
8107  * see if there's any stats for it.
8108  */
8109 
8110  /* get the attnum from the 0-based index. */
8111  attnum = qinfo->indexcol + 1;
8112 
8113  if (get_index_stats_hook &&
8114  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8115  {
8116  /*
8117  * The hook took control of acquiring a stats tuple. If it
8118  * did supply a tuple, it'd better have supplied a freefunc.
8119  */
8120  if (HeapTupleIsValid(vardata.statsTuple) &&
8121  !vardata.freefunc)
8122  elog(ERROR, "no function provided to release variable stats with");
8123  }
8124  else
8125  {
8127  ObjectIdGetDatum(index->indexoid),
8128  Int16GetDatum(attnum),
8129  BoolGetDatum(false));
8130  vardata.freefunc = ReleaseSysCache;
8131  }
8132  }
8133 
8134  if (HeapTupleIsValid(vardata.statsTuple))
8135  {
8136  AttStatsSlot sslot;
8137 
8138  if (get_attstatsslot(&sslot, vardata.statsTuple,
8139  STATISTIC_KIND_CORRELATION, InvalidOid,
8141  {
8142  double varCorrelation = 0.0;
8143 
8144  if (sslot.nnumbers > 0)
8145  varCorrelation = Abs(sslot.numbers[0]);
8146 
8147  if (varCorrelation > *indexCorrelation)
8148  *indexCorrelation = varCorrelation;
8149 
8150  free_attstatsslot(&sslot);
8151  }
8152  }
8153 
8154  ReleaseVariableStats(vardata);
8155  }
8156 
8157  qualSelectivity = clauselist_selectivity(root, indexQuals,
8158  baserel->relid,
8159  JOIN_INNER, NULL);
8160 
8161  /* work out the actual number of ranges in the index */
8162  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
8163  1.0);
8164 
8165  /*
8166  * Now calculate the minimum possible ranges we could match with if all of
8167  * the rows were in the perfect order in the table's heap.
8168  */
8169  minimalRanges = ceil(indexRanges * qualSelectivity);
8170 
8171  /*
8172  * Now estimate the number of ranges that we'll touch by using the
8173  * indexCorrelation from the stats. Careful not to divide by zero (note
8174  * we're using the absolute value of the correlation).
8175  */
8176  if (*indexCorrelation < 1.0e-10)
8177  estimatedRanges = indexRanges;
8178  else
8179  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8180 
8181  /* we expect to visit this portion of the table */
8182  selec = estimatedRanges / indexRanges;
8183 
8184  CLAMP_PROBABILITY(selec);
8185 
8186  *indexSelectivity = selec;
8187 
8188  /*
8189  * Compute the index qual costs, much as in genericcostestimate, to add to
8190  * the index costs.
8191  */
8192  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
8193  orderby_operands_eval_cost(root, path);
8194 
8195  /*
8196  * Compute the startup cost as the cost to read the whole revmap
8197  * sequentially, including the cost to execute the index quals.
8198  */
8199  *indexStartupCost =
8200  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8201  *indexStartupCost += qual_arg_cost;
8202 
8203  /*
8204  * To read a BRIN index there might be a bit of back and forth over
8205  * regular pages, as revmap might point to them out of sequential order;
8206  * calculate the total cost as reading the whole index in random order.
8207  */
8208  *indexTotalCost = *indexStartupCost +
8209  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8210 
8211  /*
8212  * Charge a small amount per range tuple which we expect to match to. This
8213  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8214  * will set a bit for each page in the range when we find a matching
8215  * range, so we must multiply the charge by the number of pages in the
8216  * range.
8217  */
8218  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8219  statsData.pagesPerRange;
8220 
8221  *indexPages = index->pages;
8222 }
IndexOptInfo * indexinfo
Definition: relation.h:1155
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
#define Min(x, y)
Definition: c.h:857
#define Int16GetDatum(X)
Definition: postgres.h:436
#define AccessShareLock
Definition: lockdefs.h:36
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
Oid reltablespace
Definition: relation.h:754
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6647
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6552
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6672
#define Abs(x)
Definition: c.h:863
Definition: type.h:89
BlockNumber pages
Definition: relation.h:758
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
List * indexquals
Definition: relation.h:1157
RelOptInfo * rel
Definition: relation.h:755
#define planner_rt_fetch(rti, root)
Definition: relation.h:344
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
float4 * numbers
Definition: lsyscache.h:52
double cpu_operator_cost
Definition: costsize.c:115
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:155
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:640
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define BoolGetDatum(X)
Definition: postgres.h:387
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:34
int16 attnum
Definition: pg_attribute.h:79
#define Max(x, y)
Definition: c.h:851
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: relation.h:651
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
RTEKind rtekind
Definition: parsenodes.h:962
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
int * indexkeys
Definition: relation.h:765
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:753
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
double Cost
Definition: nodes.h:648
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1077
BlockNumber revmapNumPages
Definition: brin.h:35
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ btcostestimate()

void btcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6942 of file selfuncs.c.

References add_predicate_to_quals(), Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BTEqualStrategyNumber, BTLessStrategyNumber, RestrictInfo::clause, IndexQualInfo::clause_op, clauselist_selectivity(), cpu_operator_cost, deconstruct_indexquals(), elog, ERROR, estimate_array_length(), free_attstatsslot(), VariableStatData::freefunc, genericcostestimate(), get_attstatsslot(), get_index_stats_hook, get_op_opfamily_strategy(), get_opfamily_member(), get_relation_stats_hook, HeapTupleIsValid, IndexQualInfo::indexcol, GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, RangeTblEntry::inh, Int16GetDatum, InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst, MemSet, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, AttStatsSlot::nnumbers, NullTest::nulltesttype, GenericCosts::num_sa_scans, AttStatsSlot::numbers, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, ObjectIdGetDatum, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, IndexQualInfo::other_operand, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, IndexQualInfo::rinfo, rint(), RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by bthandler().

6946 {
6947  IndexOptInfo *index = path->indexinfo;
6948  List *qinfos;
6949  GenericCosts costs;
6950  Oid relid;
6951  AttrNumber colnum;
6952  VariableStatData vardata;
6953  double numIndexTuples;
6954  Cost descentCost;
6955  List *indexBoundQuals;
6956  int indexcol;
6957  bool eqQualHere;
6958  bool found_saop;
6959  bool found_is_null_op;
6960  double num_sa_scans;
6961  ListCell *lc;
6962 
6963  /* Do preliminary analysis of indexquals */
6964  qinfos = deconstruct_indexquals(path);
6965 
6966  /*
6967  * For a btree scan, only leading '=' quals plus inequality quals for the
6968  * immediately next attribute contribute to index selectivity (these are
6969  * the "boundary quals" that determine the starting and stopping points of
6970  * the index scan). Additional quals can suppress visits to the heap, so
6971  * it's OK to count them in indexSelectivity, but they should not count
6972  * for estimating numIndexTuples. So we must examine the given indexquals
6973  * to find out which ones count as boundary quals. We rely on the
6974  * knowledge that they are given in index column order.
6975  *
6976  * For a RowCompareExpr, we consider only the first column, just as
6977  * rowcomparesel() does.
6978  *
6979  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6980  * index scans not one, but the ScalarArrayOpExpr's operator can be
6981  * considered to act the same as it normally does.
6982  */
6983  indexBoundQuals = NIL;
6984  indexcol = 0;
6985  eqQualHere = false;
6986  found_saop = false;
6987  found_is_null_op = false;
6988  num_sa_scans = 1;
6989  foreach(lc, qinfos)
6990  {
6991  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6992  RestrictInfo *rinfo = qinfo->rinfo;
6993  Expr *clause = rinfo->clause;
6994  Oid clause_op;
6995  int op_strategy;
6996 
6997  if (indexcol != qinfo->indexcol)
6998  {
6999  /* Beginning of a new column's quals */
7000  if (!eqQualHere)
7001  break; /* done if no '=' qual for indexcol */
7002  eqQualHere = false;
7003  indexcol++;
7004  if (indexcol != qinfo->indexcol)
7005  break; /* no quals at all for indexcol */
7006  }
7007 
7008  if (IsA(clause, ScalarArrayOpExpr))
7009  {
7010  int alength = estimate_array_length(qinfo->other_operand);
7011 
7012  found_saop = true;
7013  /* count up number of SA scans induced by indexBoundQuals only */
7014  if (alength > 1)
7015  num_sa_scans *= alength;
7016  }
7017  else if (IsA(clause, NullTest))
7018  {
7019  NullTest *nt = (NullTest *) clause;
7020 
7021  if (nt->nulltesttype == IS_NULL)
7022  {
7023  found_is_null_op = true;
7024  /* IS NULL is like = for selectivity determination purposes */
7025  eqQualHere = true;
7026  }
7027  }
7028 
7029  /*
7030  * We would need to commute the clause_op if not varonleft, except
7031  * that we only care if it's equality or not, so that refinement is
7032  * unnecessary.
7033  */
7034  clause_op = qinfo->clause_op;
7035 
7036  /* check for equality operator */
7037  if (OidIsValid(clause_op))
7038  {
7039  op_strategy = get_op_opfamily_strategy(clause_op,
7040  index->opfamily[indexcol]);
7041  Assert(op_strategy != 0); /* not a member of opfamily?? */
7042  if (op_strategy == BTEqualStrategyNumber)
7043  eqQualHere = true;
7044  }
7045 
7046  indexBoundQuals = lappend(indexBoundQuals, rinfo);
7047  }
7048 
7049  /*
7050  * If index is unique and we found an '=' clause for each column, we can
7051  * just assume numIndexTuples = 1 and skip the expensive
7052  * clauselist_selectivity calculations. However, a ScalarArrayOp or
7053  * NullTest invalidates that theory, even though it sets eqQualHere.
7054  */
7055  if (index->unique &&
7056  indexcol == index->nkeycolumns - 1 &&
7057  eqQualHere &&
7058  !found_saop &&
7059  !found_is_null_op)
7060  numIndexTuples = 1.0;
7061  else
7062  {
7063  List *selectivityQuals;
7064  Selectivity btreeSelectivity;
7065 
7066  /*
7067  * If the index is partial, AND the index predicate with the
7068  * index-bound quals to produce a more accurate idea of the number of
7069  * rows covered by the bound conditions.
7070  */
7071  selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
7072 
7073  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
7074  index->rel->relid,
7075  JOIN_INNER,
7076  NULL);
7077  numIndexTuples = btreeSelectivity * index->rel->tuples;
7078 
7079  /*
7080  * As in genericcostestimate(), we have to adjust for any
7081  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
7082  * to integer.
7083  */
7084  numIndexTuples = rint(numIndexTuples / num_sa_scans);
7085  }
7086 
7087  /*
7088  * Now do generic index cost estimation.
7089  */
7090  MemSet(&costs, 0, sizeof(costs));
7091  costs.numIndexTuples = numIndexTuples;
7092 
7093  genericcostestimate(root, path, loop_count, qinfos, &costs);
7094 
7095  /*
7096  * Add a CPU-cost component to represent the costs of initial btree
7097  * descent. We don't charge any I/O cost for touching upper btree levels,
7098  * since they tend to stay in cache, but we still have to do about log2(N)
7099  * comparisons to descend a btree of N leaf tuples. We charge one
7100  * cpu_operator_cost per comparison.
7101  *
7102  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
7103  * ones after the first one are not startup cost so far as the overall
7104  * plan is concerned, so add them only to "total" cost.
7105  */
7106  if (index->tuples > 1) /* avoid computing log(0) */
7107  {
7108  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7109  costs.indexStartupCost += descentCost;
7110  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7111  }
7112 
7113  /*
7114  * Even though we're not charging I/O cost for touching upper btree pages,
7115  * it's still reasonable to charge some CPU cost per page descended
7116  * through. Moreover, if we had no such charge at all, bloated indexes
7117  * would appear to have the same search cost as unbloated ones, at least
7118  * in cases where only a single leaf page is expected to be visited. This
7119  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7120  * touched. The number of such pages is btree tree height plus one (ie,
7121  * we charge for the leaf page too). As above, charge once per SA scan.
7122  */
7123  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
7124  costs.indexStartupCost += descentCost;
7125  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7126 
7127  /*
7128  * If we can get an estimate of the first column's ordering correlation C
7129  * from pg_statistic, estimate the index correlation as C for a
7130  * single-column index, or C * 0.75 for multiple columns. (The idea here
7131  * is that multiple columns dilute the importance of the first column's
7132  * ordering, but don't negate it entirely. Before 8.0 we divided the
7133  * correlation by the number of columns, but that seems too strong.)
7134  */
7135  MemSet(&vardata, 0, sizeof(vardata));
7136 
7137  if (index->indexkeys[0] != 0)
7138  {
7139  /* Simple variable --- look to stats for the underlying table */
7140  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7141 
7142  Assert(rte->rtekind == RTE_RELATION);
7143  relid = rte->relid;
7144  Assert(relid != InvalidOid);
7145  colnum = index->indexkeys[0];
7146 
7148  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7149  {
7150  /*
7151  * The hook took control of acquiring a stats tuple. If it did
7152  * supply a tuple, it'd better have supplied a freefunc.
7153  */
7154  if (HeapTupleIsValid(vardata.statsTuple) &&
7155  !vardata.freefunc)
7156  elog(ERROR, "no function provided to release variable stats with");
7157  }
7158  else
7159  {
7161  ObjectIdGetDatum(relid),
7162  Int16GetDatum(colnum),
7163  BoolGetDatum(rte->inh));
7164  vardata.freefunc = ReleaseSysCache;
7165  }
7166  }
7167  else
7168  {
7169  /* Expression --- maybe there are stats for the index itself */
7170  relid = index->indexoid;
7171  colnum = 1;
7172 
7173  if (get_index_stats_hook &&
7174  (*get_index_stats_hook) (root, relid, colnum, &vardata))
7175  {
7176  /*
7177  * The hook took control of acquiring a stats tuple. If it did
7178  * supply a tuple, it'd better have supplied a freefunc.
7179  */
7180  if (HeapTupleIsValid(vardata.statsTuple) &&
7181  !vardata.freefunc)
7182  elog(ERROR, "no function provided to release variable stats with");
7183  }
7184  else
7185  {
7187  ObjectIdGetDatum(relid),
7188  Int16GetDatum(colnum),
7189  BoolGetDatum(false));
7190  vardata.freefunc = ReleaseSysCache;
7191  }
7192  }
7193 
7194  if (HeapTupleIsValid(vardata.statsTuple))
7195  {
7196  Oid sortop;
7197  AttStatsSlot sslot;
7198 
7199  sortop = get_opfamily_member(index->opfamily[0],
7200  index->opcintype[0],
7201  index->opcintype[0],
7203  if (OidIsValid(sortop) &&
7204  get_attstatsslot(&sslot, vardata.statsTuple,
7205  STATISTIC_KIND_CORRELATION, sortop,
7207  {
7208  double varCorrelation;
7209 
7210  Assert(sslot.nnumbers == 1);
7211  varCorrelation = sslot.numbers[0];
7212 
7213  if (index->reverse_sort[0])
7214  varCorrelation = -varCorrelation;
7215 
7216  if (index->ncolumns > 1)
7217  costs.indexCorrelation = varCorrelation * 0.75;
7218  else
7219  costs.indexCorrelation = varCorrelation;
7220 
7221  free_attstatsslot(&sslot);
7222  }
7223  }
7224 
7225  ReleaseVariableStats(vardata);
7226 
7227  *indexStartupCost = costs.indexStartupCost;
7228  *indexTotalCost = costs.indexTotalCost;
7229  *indexSelectivity = costs.indexSelectivity;
7230  *indexCorrelation = costs.indexCorrelation;
7231  *indexPages = costs.numIndexPages;
7232 }
Selectivity indexSelectivity
Definition: selfuncs.h:134
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
IndexOptInfo * indexinfo
Definition: relation.h:1155
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:652
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6920
#define Int16GetDatum(X)
Definition: postgres.h:436
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:908
double Selectivity
Definition: nodes.h:647
double tuples
Definition: relation.h:759
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: relation.h:760
#define OidIsValid(objectId)
Definition: c.h:605
RestrictInfo * rinfo
Definition: selfuncs.h:109
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6552
bool unique
Definition: relation.h:789
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2179
RelOptInfo * rel
Definition: relation.h:755
#define planner_rt_fetch(rti, root)
Definition: relation.h:344
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
double num_sa_scans
Definition: selfuncs.h:141
float4 * numbers
Definition: lsyscache.h:52
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
double cpu_operator_cost
Definition: costsize.c:115
Cost indexTotalCost
Definition: selfuncs.h:133
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:155
double rint(double x)
Definition: rint.c:22
int ncolumns
Definition: relation.h:763
Index relid
Definition: relation.h:640
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1880
double indexCorrelation
Definition: selfuncs.h:135
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
NullTestType nulltesttype
Definition: primnodes.h:1189
#define BoolGetDatum(X)
Definition: postgres.h:387
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:139
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
int nkeycolumns
Definition: relation.h:764
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
Oid * opcintype
Definition: relation.h:769
Cost indexStartupCost
Definition: selfuncs.h:132
Oid * opfamily
Definition: relation.h:768
RTEKind rtekind
Definition: parsenodes.h:962
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
Node * other_operand
Definition: selfuncs.h:113
int * indexkeys
Definition: relation.h:765
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:753
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
bool * reverse_sort
Definition: relation.h:771
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define BTEqualStrategyNumber
Definition: stratnum.h:31
double Cost
Definition: nodes.h:648
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
Definition: selfuncs.c:6701
double numIndexPages
Definition: selfuncs.h:138
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ byte_increment()

static bool byte_increment ( unsigned char *  ptr,
int  len 
)
static

Definition at line 6276 of file selfuncs.c.

Referenced by make_greater_string().

6277 {
6278  if (*ptr >= 255)
6279  return false;
6280  (*ptr)++;
6281  return true;
6282 }

◆ convert_bytea_to_scalar()

static void convert_bytea_to_scalar ( Datum  value,
double *  scaledvalue,
Datum  lobound,
double *  scaledlobound,
Datum  hibound,
double *  scaledhibound 
)
static

Definition at line 4488 of file selfuncs.c.

References convert_one_bytea_to_scalar(), DatumGetByteaPP, i, Min, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

Referenced by convert_to_scalar().

4494 {
4495  bytea *valuep = DatumGetByteaPP(value);
4496  bytea *loboundp = DatumGetByteaPP(lobound);
4497  bytea *hiboundp = DatumGetByteaPP(hibound);
4498  int rangelo,
4499  rangehi,
4500  valuelen = VARSIZE_ANY_EXHDR(valuep),
4501  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4502  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4503  i,
4504  minlen;
4505  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4506  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4507  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4508 
4509  /*
4510  * Assume bytea data is uniformly distributed across all byte values.
4511  */
4512  rangelo = 0;
4513  rangehi = 255;
4514 
4515  /*
4516  * Now strip any common prefix of the three strings.
4517  */
4518  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4519  for (i = 0; i < minlen; i++)
4520  {
4521  if (*lostr != *histr || *lostr != *valstr)
4522  break;
4523  lostr++, histr++, valstr++;
4524  loboundlen--, hiboundlen--, valuelen--;
4525  }
4526 
4527  /*
4528  * Now we can do the conversions.
4529  */
4530  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4531  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4532  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4533 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:348
#define Min(x, y)
Definition: c.h:857
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4536
#define DatumGetByteaPP(X)
Definition: fmgr.h:260
static struct @131 value
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:341
int i
Definition: c.h:516

◆ convert_numeric_to_scalar()

static double convert_numeric_to_scalar ( Datum  value,
Oid  typid,
bool failure 
)
static

Definition at line 4202 of file selfuncs.c.

References DatumGetBool, DatumGetFloat4, DatumGetFloat8, DatumGetInt16, DatumGetInt32, DatumGetInt64, DatumGetObjectId, DirectFunctionCall1, and numeric_float8_no_overflow().

Referenced by convert_to_scalar().

4203 {
4204  switch (typid)
4205  {
4206  case BOOLOID:
4207  return (double) DatumGetBool(value);
4208  case INT2OID:
4209  return (double) DatumGetInt16(value);
4210  case INT4OID:
4211  return (double) DatumGetInt32(value);
4212  case INT8OID:
4213  return (double) DatumGetInt64(value);
4214  case FLOAT4OID:
4215  return (double) DatumGetFloat4(value);
4216  case FLOAT8OID:
4217  return (double) DatumGetFloat8(value);
4218  case NUMERICOID:
4219  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4220  return (double)
4222  value));
4223  case OIDOID:
4224  case REGPROCOID:
4225  case REGPROCEDUREOID:
4226  case REGOPEROID:
4227  case REGOPERATOROID:
4228  case REGCLASSOID:
4229  case REGTYPEOID:
4230  case REGCONFIGOID:
4231  case REGDICTIONARYOID:
4232  case REGROLEOID:
4233  case REGNAMESPACEOID:
4234  /* we can treat OIDs as integers... */
4235  return (double) DatumGetObjectId(value);
4236  }
4237 
4238  *failure = true;
4239  return 0;
4240 }
#define DatumGetInt32(X)
Definition: postgres.h:457
#define DatumGetObjectId(X)
Definition: postgres.h:485
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:590
#define DatumGetInt64(X)
Definition: postgres.h:592
#define DatumGetInt16(X)
Definition: postgres.h:429
#define DatumGetBool(X)
Definition: postgres.h:378
#define DatumGetFloat8(X)
Definition: postgres.h:713
static struct @131 value
#define DatumGetFloat4(X)
Definition: postgres.h:665
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:3287

◆ convert_one_bytea_to_scalar()

static double convert_one_bytea_to_scalar ( unsigned char *  value,
int  valuelen,
int  rangelo,
int  rangehi 
)
static

Definition at line 4536 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

4538 {
4539  double num,
4540  denom,
4541  base;
4542 
4543  if (valuelen <= 0)
4544  return 0.0; /* empty string has scalar value 0 */
4545 
4546  /*
4547  * Since base is 256, need not consider more than about 10 chars (even
4548  * this many seems like overkill)
4549  */
4550  if (valuelen > 10)
4551  valuelen = 10;
4552 
4553  /* Convert initial characters to fraction */
4554  base = rangehi - rangelo + 1;
4555  num = 0.0;
4556  denom = base;
4557  while (valuelen-- > 0)
4558  {
4559  int ch = *value++;
4560 
4561  if (ch < rangelo)
4562  ch = rangelo - 1;
4563  else if (ch > rangehi)
4564  ch = rangehi + 1;
4565  num += ((double) (ch - rangelo)) / denom;
4566  denom *= base;
4567  }
4568 
4569  return num;
4570 }
static struct @131 value

◆ convert_one_string_to_scalar()

static double convert_one_string_to_scalar ( char *  value,
int  rangelo,
int  rangehi 
)
static

Definition at line 4343 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4344 {
4345  int slen = strlen(value);
4346  double num,
4347  denom,
4348  base;
4349 
4350  if (slen <= 0)
4351  return 0.0; /* empty string has scalar value 0 */
4352 
4353  /*
4354  * There seems little point in considering more than a dozen bytes from
4355  * the string. Since base is at least 10, that will give us nominal
4356  * resolution of at least 12 decimal digits, which is surely far more
4357  * precision than this estimation technique has got anyway (especially in
4358  * non-C locales). Also, even with the maximum possible base of 256, this
4359  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4360  * overflow on any known machine.
4361  */
4362  if (slen > 12)
4363  slen = 12;
4364 
4365  /* Convert initial characters to fraction */
4366  base = rangehi - rangelo + 1;
4367  num = 0.0;
4368  denom = base;
4369  while (slen-- > 0)
4370  {
4371  int ch = (unsigned char) *value++;
4372 
4373  if (ch < rangelo)
4374  ch = rangelo - 1;
4375  else if (ch > rangehi)
4376  ch = rangehi + 1;
4377  num += ((double) (ch - rangelo)) / denom;
4378  denom *= base;
4379  }
4380 
4381  return num;
4382 }
static struct @131 value

◆ convert_string_datum()

static char * convert_string_datum ( Datum  value,
Oid  typid,
bool failure 
)
static

Definition at line 4394 of file selfuncs.c.

References Assert, DatumGetChar, DatumGetPointer, lc_collate_is_c(), NameStr, palloc(), pfree(), PG_USED_FOR_ASSERTS_ONLY, pstrdup(), TextDatumGetCString, and val.

Referenced by convert_to_scalar().

4395 {
4396  char *val;
4397 
4398  switch (typid)
4399  {
4400  case CHAROID:
4401  val = (char *) palloc(2);
4402  val[0] = DatumGetChar(value);
4403  val[1] = '\0';
4404  break;
4405  case BPCHAROID:
4406  case VARCHAROID:
4407  case TEXTOID:
4408  val = TextDatumGetCString(value);
4409  break;
4410  case NAMEOID:
4411  {
4413 
4414  val = pstrdup(NameStr(*nm));
4415  break;
4416  }
4417  default:
4418  *failure = true;
4419  return NULL;
4420  }
4421 
4422  if (!lc_collate_is_c(DEFAULT_COLLATION_OID))
4423  {
4424  char *xfrmstr;
4425  size_t xfrmlen;
4426  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4427 
4428  /*
4429  * XXX: We could guess at a suitable output buffer size and only call
4430  * strxfrm twice if our guess is too small.
4431  *
4432  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4433  * bogus data or set an error. This is not really a problem unless it
4434  * crashes since it will only give an estimation error and nothing
4435  * fatal.
4436  */
4437 #if _MSC_VER == 1400 /* VS.Net 2005 */
4438 
4439  /*
4440  *
4441  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4442  */
4443  {
4444  char x[1];
4445 
4446  xfrmlen = strxfrm(x, val, 0);
4447  }
4448 #else
4449  xfrmlen = strxfrm(NULL, val, 0);
4450 #endif
4451 #ifdef WIN32
4452 
4453  /*
4454  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4455  * of trying to allocate this much memory (and fail), just return the
4456  * original string unmodified as if we were in the C locale.
4457  */
4458  if (xfrmlen == INT_MAX)
4459  return val;
4460 #endif
4461  xfrmstr = (char *) palloc(xfrmlen + 1);
4462  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4463 
4464  /*
4465  * Some systems (e.g., glibc) can return a smaller value from the
4466  * second call than the first; thus the Assert must be <= not ==.
4467  */
4468  Assert(xfrmlen2 <= xfrmlen);
4469  pfree(val);
4470  val = xfrmstr;
4471  }
4472 
4473  return val;
4474 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
void pfree(void *pointer)
Definition: mcxt.c:1031
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1128
Definition: c.h:570
#define TextDatumGetCString(d)
Definition: builtins.h:96
#define DatumGetChar(X)
Definition: postgres.h:394
static struct @131 value
#define Assert(condition)
Definition: c.h:699
#define DatumGetPointer(X)
Definition: postgres.h:534
void * palloc(Size size)
Definition: mcxt.c:924
#define NameStr(name)
Definition: c.h:576
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
long val
Definition: informix.c:689

◆ convert_string_to_scalar()

static void convert_string_to_scalar ( char *  value,
double *  scaledvalue,
char *  lobound,
double *  scaledlobound,
char *  hibound,
double *  scaledhibound 
)
static

Definition at line 4263 of file selfuncs.c.

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

4269 {
4270  int rangelo,
4271  rangehi;
4272  char *sptr;
4273 
4274  rangelo = rangehi = (unsigned char) hibound[0];
4275  for (sptr = lobound; *sptr; sptr++)
4276  {
4277  if (rangelo > (unsigned char) *sptr)
4278  rangelo = (unsigned char) *sptr;
4279  if (rangehi < (unsigned char) *sptr)
4280  rangehi = (unsigned char) *sptr;
4281  }
4282  for (sptr = hibound; *sptr; sptr++)
4283  {
4284  if (rangelo > (unsigned char) *sptr)
4285  rangelo = (unsigned char) *sptr;
4286  if (rangehi < (unsigned char) *sptr)
4287  rangehi = (unsigned char) *sptr;
4288  }
4289  /* If range includes any upper-case ASCII chars, make it include all */
4290  if (rangelo <= 'Z' && rangehi >= 'A')
4291  {
4292  if (rangelo > 'A')
4293  rangelo = 'A';
4294  if (rangehi < 'Z')
4295  rangehi = 'Z';
4296  }
4297  /* Ditto lower-case */
4298  if (rangelo <= 'z' && rangehi >= 'a')
4299  {
4300  if (rangelo > 'a')
4301  rangelo = 'a';
4302  if (rangehi < 'z')
4303  rangehi = 'z';
4304  }
4305  /* Ditto digits */
4306  if (rangelo <= '9' && rangehi >= '0')
4307  {
4308  if (rangelo > '0')
4309  rangelo = '0';
4310  if (rangehi < '9')
4311  rangehi = '9';
4312  }
4313 
4314  /*
4315  * If range includes less than 10 chars, assume we have not got enough
4316  * data, and make it include regular ASCII set.
4317  */
4318  if (rangehi - rangelo < 9)
4319  {
4320  rangelo = ' ';
4321  rangehi = 127;
4322  }
4323 
4324  /*
4325  * Now strip any common prefix of the three strings.
4326  */
4327  while (*lobound)
4328  {
4329  if (*lobound != *hibound || *lobound != *value)
4330  break;
4331  lobound++, hibound++, value++;
4332  }
4333 
4334  /*
4335  * Now we can do the conversions.
4336  */
4337  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4338  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4339  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4340 }
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4343
static struct @131 value

◆ convert_timevalue_to_scalar()

static double convert_timevalue_to_scalar ( Datum  value,
Oid  typid,
bool failure 
)
static

Definition at line 4579 of file selfuncs.c.

References abstime_timestamp(), TimeIntervalData::data, date2timestamp_no_overflow(), DatumGetDateADT, DatumGetIntervalP, DatumGetRelativeTime, DatumGetTimeADT, DatumGetTimeInterval, DatumGetTimestamp, DatumGetTimestampTz, DatumGetTimeTzADTP, Interval::day, DAYS_PER_YEAR, DirectFunctionCall1, Interval::month, MONTHS_PER_YEAR, TimeIntervalData::status, TimeTzADT::time, Interval::time, USECS_PER_DAY, and TimeTzADT::zone.

Referenced by convert_to_scalar().

4580 {
4581  switch (typid)
4582  {
4583  case TIMESTAMPOID:
4584  return DatumGetTimestamp(value);
4585  case TIMESTAMPTZOID:
4586  return DatumGetTimestampTz(value);
4587  case ABSTIMEOID:
4589  value));
4590  case DATEOID:
4592  case INTERVALOID:
4593  {
4595 
4596  /*
4597  * Convert the month part of Interval to days using assumed
4598  * average month length of 365.25/12.0 days. Not too
4599  * accurate, but plenty good enough for our purposes.
4600  */
4601  return interval->time + interval->day * (double) USECS_PER_DAY +
4602  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4603  }
4604  case RELTIMEOID:
4605  return (DatumGetRelativeTime(value) * 1000000.0);
4606  case TINTERVALOID:
4607  {
4609 
4610  if (tinterval->status != 0)
4611  return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4612  return 0; /* for lack of a better idea */
4613  }
4614  case TIMEOID:
4615  return DatumGetTimeADT(value);
4616  case TIMETZOID:
4617  {
4618  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4619 
4620  /* use GMT-equivalent time */
4621  return (double) (timetz->time + (timetz->zone * 1000000.0));
4622  }
4623  }
4624 
4625  *failure = true;
4626  return 0;
4627 }
#define DatumGetDateADT(X)
Definition: date.h:53
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:29
#define DatumGetTimeTzADTP(X)
Definition: date.h:55
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:656
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:590
int32 day
Definition: timestamp.h:47
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define DAYS_PER_YEAR
Definition: timestamp.h:68
int32 zone
Definition: date.h:30
#define DatumGetRelativeTime(X)
Definition: nabstime.h:51
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
TimeOffset time
Definition: timestamp.h:45
#define USECS_PER_DAY
Definition: timestamp.h:91
int32 month
Definition: timestamp.h:48
Datum abstime_timestamp(PG_FUNCTION_ARGS)
Definition: nabstime.c:467
#define DatumGetTimeADT(X)
Definition: date.h:54
static struct @131 value
AbsoluteTime data[2]
Definition: nabstime.h:42
#define DatumGetTimeInterval(X)
Definition: nabstime.h:52
Definition: date.h:27
#define DatumGetTimestamp(X)
Definition: timestamp.h:27

◆ convert_to_scalar()

static bool convert_to_scalar ( Datum  value,
Oid  valuetypid,
double *  scaledvalue,
Datum  lobound,
Datum  hibound,
Oid  boundstypid,
double *  scaledlobound,
double *  scaledhibound 
)
static

Definition at line 4053 of file selfuncs.c.

References convert_bytea_to_scalar(), convert_network_to_scalar(), convert_numeric_to_scalar(), convert_string_datum(), convert_string_to_scalar(), convert_timevalue_to_scalar(), and pfree().

Referenced by ineq_histogram_selectivity().

4056 {
4057  bool failure = false;
4058 
4059  /*
4060  * Both the valuetypid and the boundstypid should exactly match the
4061  * declared input type(s) of the operator we are invoked for. However,
4062  * extensions might try to use scalarineqsel as estimator for operators
4063  * with input type(s) we don't handle here; in such cases, we want to
4064  * return false, not fail. In any case, we mustn't assume that valuetypid
4065  * and boundstypid are identical.
4066  *
4067  * XXX The histogram we are interpolating between points of could belong
4068  * to a column that's only binary-compatible with the declared type. In
4069  * essence we are assuming that the semantics of binary-compatible types
4070  * are enough alike that we can use a histogram generated with one type's
4071  * operators to estimate selectivity for the other's. This is outright
4072  * wrong in some cases --- in particular signed versus unsigned
4073  * interpretation could trip us up. But it's useful enough in the
4074  * majority of cases that we do it anyway. Should think about more
4075  * rigorous ways to do it.
4076  */
4077  switch (valuetypid)
4078  {
4079  /*
4080  * Built-in numeric types
4081  */
4082  case BOOLOID:
4083  case INT2OID:
4084  case INT4OID:
4085  case INT8OID:
4086  case FLOAT4OID:
4087  case FLOAT8OID:
4088  case NUMERICOID:
4089  case OIDOID:
4090  case REGPROCOID:
4091  case REGPROCEDUREOID:
4092  case REGOPEROID:
4093  case REGOPERATOROID:
4094  case REGCLASSOID:
4095  case REGTYPEOID:
4096  case REGCONFIGOID:
4097  case REGDICTIONARYOID:
4098  case REGROLEOID:
4099  case REGNAMESPACEOID:
4100  *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4101  &failure);
4102  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4103  &failure);
4104  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4105  &failure);
4106  return !failure;
4107 
4108  /*
4109  * Built-in string types
4110  */
4111  case CHAROID:
4112  case BPCHAROID:
4113  case VARCHAROID:
4114  case TEXTOID:
4115  case NAMEOID:
4116  {
4117  char *valstr = convert_string_datum(value, valuetypid,
4118  &failure);
4119  char *lostr = convert_string_datum(lobound, boundstypid,
4120  &failure);
4121  char *histr = convert_string_datum(hibound, boundstypid,
4122  &failure);
4123 
4124  /*
4125  * Bail out if any of the values is not of string type. We
4126  * might leak converted strings for the other value(s), but
4127  * that's not worth troubling over.
4128  */
4129  if (failure)
4130  return false;
4131 
4132  convert_string_to_scalar(valstr, scaledvalue,
4133  lostr, scaledlobound,
4134  histr, scaledhibound);
4135  pfree(valstr);
4136  pfree(lostr);
4137  pfree(histr);
4138  return true;
4139  }
4140 
4141  /*
4142  * Built-in bytea type
4143  */
4144  case BYTEAOID:
4145  {
4146  /* We only support bytea vs bytea comparison */
4147  if (boundstypid != BYTEAOID)
4148  return false;
4149  convert_bytea_to_scalar(value, scaledvalue,
4150  lobound, scaledlobound,
4151  hibound, scaledhibound);
4152  return true;
4153  }
4154 
4155  /*
4156  * Built-in time types
4157  */
4158  case TIMESTAMPOID:
4159  case TIMESTAMPTZOID:
4160  case ABSTIMEOID:
4161  case DATEOID:
4162  case INTERVALOID:
4163  case RELTIMEOID:
4164  case TINTERVALOID:
4165  case TIMEOID:
4166  case TIMETZOID:
4167  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4168  &failure);
4169  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4170  &failure);
4171  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4172  &failure);
4173  return !failure;
4174 
4175  /*
4176  * Built-in network types
4177  */
4178  case INETOID:
4179  case CIDROID:
4180  case MACADDROID:
4181  case MACADDR8OID:
4182  *scaledvalue = convert_network_to_scalar(value, valuetypid,
4183  &failure);
4184  *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4185  &failure);
4186  *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4187  &failure);
4188  return !failure;
4189  }
4190  /* Don't know how to convert */
4191  *scaledvalue = *scaledlobound = *scaledhibound = 0;
4192  return false;
4193 }
void pfree(void *pointer)
Definition: mcxt.c:1031
double convert_network_to_scalar(Datum value, Oid typid, bool *failure)
Definition: network.c:910
static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4202
static struct @131 value
static char * convert_string_datum(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4394
static void convert_bytea_to_scalar(Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
Definition: selfuncs.c:4488
static double convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4579
static void convert_string_to_scalar(char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
Definition: selfuncs.c:4263

◆ deconstruct_indexquals()

List* deconstruct_indexquals ( IndexPath path)

Definition at line 6552 of file selfuncs.c.

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

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

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

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

Definition at line 2284 of file selfuncs.c.

References generate_unaccent_rules::args, CLAMP_PROBABILITY, elog, eqjoinsel_inner(), eqjoinsel_semi(), ERROR, find_join_input_rel(), get_commutator(), get_join_variables(), JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, SpecialJoinInfo::jointype, SpecialJoinInfo::min_righthand, PG_GETARG_INT16, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_FLOAT8, and ReleaseVariableStats.

Referenced by neqjoinsel().

2285 {
2286  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2287  Oid operator = PG_GETARG_OID(1);
2288  List *args = (List *) PG_GETARG_POINTER(2);
2289 
2290 #ifdef NOT_USED
2291  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2292 #endif
2294  double selec;
2295  VariableStatData vardata1;
2296  VariableStatData vardata2;
2297  bool join_is_reversed;
2298  RelOptInfo *inner_rel;
2299 
2300  get_join_variables(root, args, sjinfo,
2301  &vardata1, &vardata2, &join_is_reversed);
2302 
2303  switch (sjinfo->jointype)
2304  {
2305  case JOIN_INNER:
2306  case JOIN_LEFT:
2307  case JOIN_FULL:
2308  selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2309  break;
2310  case JOIN_SEMI:
2311  case JOIN_ANTI:
2312 
2313  /*
2314  * Look up the join's inner relation. min_righthand is sufficient
2315  * information because neither SEMI nor ANTI joins permit any
2316  * reassociation into or out of their RHS, so the righthand will
2317  * always be exactly that set of rels.
2318  */
2319  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2320 
2321  if (!join_is_reversed)
2322  selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
2323  inner_rel);
2324  else
2325  selec = eqjoinsel_semi(get_commutator(operator),
2326  &vardata2, &vardata1,
2327  inner_rel);
2328  break;
2329  default:
2330  /* other values not expected here */
2331  elog(ERROR, "unrecognized join type: %d",
2332  (int) sjinfo->jointype);
2333  selec = 0; /* keep compiler quiet */
2334  break;
2335  }
2336 
2337  ReleaseVariableStats(vardata1);
2338  ReleaseVariableStats(vardata2);
2339 
2340  CLAMP_PROBABILITY(selec);
2341 
2342  PG_RETURN_FLOAT8((float8) selec);
2343 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1298
Relids min_righthand
Definition: relation.h:2067
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:331
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:246
unsigned int Oid
Definition: postgres_ext.h:31
JoinType
Definition: nodes.h:681
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:458
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4714
#define PG_GETARG_OID(n)
Definition: fmgr.h:245
static double eqjoinsel_semi(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2, RelOptInfo *inner_rel)
Definition: selfuncs.c:2569
#define PG_GETARG_INT16(n)
Definition: fmgr.h:241
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:5689
JoinType jointype
Definition: relation.h:2070
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
static double eqjoinsel_inner(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2)
Definition: selfuncs.c:2352
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ eqjoinsel_inner()

static double eqjoinsel_inner ( Oid  operator,
VariableStatData vardata1,
VariableStatData vardata2 
)
static

Definition at line 2352 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool, fmgr_info(), free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), get_opcode(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, AttStatsSlot::numbers, AttStatsSlot::nvalues, palloc0(), pfree(), statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by eqjoinsel().

2354 {
2355  double selec;
2356  double nd1;
2357  double nd2;
2358  bool isdefault1;
2359  bool isdefault2;
2360  Oid opfuncoid;
2361  Form_pg_statistic stats1 = NULL;
2362  Form_pg_statistic stats2 = NULL;
2363  bool have_mcvs1 = false;
2364  bool have_mcvs2 = false;
2365  AttStatsSlot sslot1;
2366  AttStatsSlot sslot2;
2367 
2368  nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2369  nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2370 
2371  opfuncoid = get_opcode(operator);
2372 
2373  memset(&sslot1, 0, sizeof(sslot1));
2374  memset(&sslot2, 0, sizeof(sslot2));
2375 
2376  if (HeapTupleIsValid(vardata1->statsTuple))
2377  {
2378  /* note we allow use of nullfrac regardless of security check */
2379  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2380  if (statistic_proc_security_check(vardata1, opfuncoid))
2381  have_mcvs1 = get_attstatsslot(&sslot1, vardata1->statsTuple,
2382  STATISTIC_KIND_MCV, InvalidOid,
2384  }
2385 
2386  if (HeapTupleIsValid(vardata2->statsTuple))
2387  {
2388  /* note we allow use of nullfrac regardless of security check */
2389  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2390  if (statistic_proc_security_check(vardata2, opfuncoid))
2391  have_mcvs2 = get_attstatsslot(&sslot2, vardata2->statsTuple,
2392  STATISTIC_KIND_MCV, InvalidOid,
2394  }
2395 
2396  if (have_mcvs1 && have_mcvs2)
2397  {
2398  /*
2399  * We have most-common-value lists for both relations. Run through
2400  * the lists to see which MCVs actually join to each other with the
2401  * given operator. This allows us to determine the exact join
2402  * selectivity for the portion of the relations represented by the MCV
2403  * lists. We still have to estimate for the remaining population, but
2404  * in a skewed distribution this gives us a big leg up in accuracy.
2405  * For motivation see the analysis in Y. Ioannidis and S.
2406  * Christodoulakis, "On the propagation of errors in the size of join
2407  * results", Technical Report 1018, Computer Science Dept., University
2408  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2409  */
2410  FmgrInfo eqproc;
2411  bool *hasmatch1;
2412  bool *hasmatch2;
2413  double nullfrac1 = stats1->stanullfrac;
2414  double nullfrac2 = stats2->stanullfrac;
2415  double matchprodfreq,
2416  matchfreq1,
2417  matchfreq2,
2418  unmatchfreq1,
2419  unmatchfreq2,
2420  otherfreq1,
2421  otherfreq2,
2422  totalsel1,
2423  totalsel2;
2424  int i,
2425  nmatches;
2426 
2427  fmgr_info(opfuncoid, &eqproc);
2428  hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
2429  hasmatch2 = (bool *) palloc0(sslot2.nvalues * sizeof(bool));
2430 
2431  /*
2432  * Note we assume that each MCV will match at most one member of the
2433  * other MCV list. If the operator isn't really equality, there could
2434  * be multiple matches --- but we don't look for them, both for speed
2435  * and because the math wouldn't add up...
2436  */
2437  matchprodfreq = 0.0;
2438  nmatches = 0;
2439  for (i = 0; i < sslot1.nvalues; i++)
2440  {
2441  int j;
2442 
2443  for (j = 0; j < sslot2.nvalues; j++)
2444  {
2445  if (hasmatch2[j])
2446  continue;
2447  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2448  DEFAULT_COLLATION_OID,
2449  sslot1.values[i],
2450  sslot2.values[j])))
2451  {
2452  hasmatch1[i] = hasmatch2[j] = true;
2453  matchprodfreq += sslot1.numbers[i] * sslot2.numbers[j];
2454  nmatches++;
2455  break;
2456  }
2457  }
2458  }
2459  CLAMP_PROBABILITY(matchprodfreq);
2460  /* Sum up frequencies of matched and unmatched MCVs */
2461  matchfreq1 = unmatchfreq1 = 0.0;
2462  for (i = 0; i < sslot1.nvalues; i++)
2463  {
2464  if (hasmatch1[i])
2465  matchfreq1 += sslot1.numbers[i];
2466  else
2467  unmatchfreq1 += sslot1.numbers[i];
2468  }
2469  CLAMP_PROBABILITY(matchfreq1);
2470  CLAMP_PROBABILITY(unmatchfreq1);
2471  matchfreq2 = unmatchfreq2 = 0.0;
2472  for (i = 0; i < sslot2.nvalues; i++)
2473  {
2474  if (hasmatch2[i])
2475  matchfreq2 += sslot2.numbers[i];
2476  else
2477  unmatchfreq2 += sslot2.numbers[i];
2478  }
2479  CLAMP_PROBABILITY(matchfreq2);
2480  CLAMP_PROBABILITY(unmatchfreq2);
2481  pfree(hasmatch1);
2482  pfree(hasmatch2);
2483 
2484  /*
2485  * Compute total frequency of non-null values that are not in the MCV
2486  * lists.
2487  */
2488  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2489  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2490  CLAMP_PROBABILITY(otherfreq1);
2491  CLAMP_PROBABILITY(otherfreq2);
2492 
2493  /*
2494  * We can estimate the total selectivity from the point of view of
2495  * relation 1 as: the known selectivity for matched MCVs, plus
2496  * unmatched MCVs that are assumed to match against random members of
2497  * relation 2's non-MCV population, plus non-MCV values that are
2498  * assumed to match against random members of relation 2's unmatched
2499  * MCVs plus non-MCV values.
2500  */
2501  totalsel1 = matchprodfreq;
2502  if (nd2 > sslot2.nvalues)
2503  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2.nvalues);
2504  if (nd2 > nmatches)
2505  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2506  (nd2 - nmatches);
2507  /* Same estimate from the point of view of relation 2. */
2508  totalsel2 = matchprodfreq;
2509  if (nd1 > sslot1.nvalues)
2510  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1.nvalues);
2511  if (nd1 > nmatches)
2512  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2513  (nd1 - nmatches);
2514 
2515  /*
2516  * Use the smaller of the two estimates. This can be justified in
2517  * essentially the same terms as given below for the no-stats case: to
2518  * a first approximation, we are estimating from the point of view of
2519  * the relation with smaller nd.
2520  */
2521  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2522  }
2523  else
2524  {
2525  /*
2526  * We do not have MCV lists for both sides. Estimate the join
2527  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2528  * is plausible if we assume that the join operator is strict and the
2529  * non-null values are about equally distributed: a given non-null
2530  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2531  * of rel2, so total join rows are at most
2532  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2533  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2534  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2535  * with MIN() is an upper bound. Using the MIN() means we estimate
2536  * from the point of view of the relation with smaller nd (since the
2537  * larger nd is determining the MIN). It is reasonable to assume that
2538  * most tuples in this rel will have join partners, so the bound is
2539  * probably reasonably tight and should be taken as-is.
2540  *
2541  * XXX Can we be smarter if we have an MCV list for just one side? It
2542  * seems that if we assume equal distribution for the other side, we
2543  * end up with the same answer anyway.
2544  */
2545  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2546  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2547 
2548  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2549  if (nd1 > nd2)
2550  selec /= nd1;
2551  else
2552  selec /= nd2;
2553  }
2554 
2555  free_attstatsslot(&sslot1);
2556  free_attstatsslot(&sslot2);
2557 
2558  return selec;
2559 }
Definition: fmgr.h:56
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5154
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1133
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5183
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
float4 * numbers
Definition: lsyscache.h:52
#define DatumGetBool(X)
Definition: postgres.h:378
void * palloc0(Size size)
Definition: mcxt.c:955
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1079
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ eqjoinsel_semi()

static double eqjoinsel_semi ( Oid  operator,
VariableStatData vardata1,
VariableStatData vardata2,
RelOptInfo inner_rel 
)
static

Definition at line 2569 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool, fmgr_info(), free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), get_opcode(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, Min, AttStatsSlot::numbers, AttStatsSlot::nvalues, OidIsValid, palloc0(), pfree(), VariableStatData::rel, RelOptInfo::rows, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by eqjoinsel().

2572 {
2573  double selec;
2574  double nd1;
2575  double nd2;
2576  bool isdefault1;
2577  bool isdefault2;
2578  Oid opfuncoid;
2579  Form_pg_statistic stats1 = NULL;
2580  bool have_mcvs1 = false;
2581  bool have_mcvs2 = false;
2582  AttStatsSlot sslot1;
2583  AttStatsSlot sslot2;
2584 
2585  nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2586  nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2587 
2588  opfuncoid = OidIsValid(operator) ? get_opcode(operator) : InvalidOid;
2589 
2590  memset(&sslot1, 0, sizeof(sslot1));
2591  memset(&sslot2, 0, sizeof(sslot2));
2592 
2593  /*
2594  * We clamp nd2 to be not more than what we estimate the inner relation's
2595  * size to be. This is intuitively somewhat reasonable since obviously
2596  * there can't be more than that many distinct values coming from the
2597  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2598  * likewise) is that this is the only pathway by which restriction clauses
2599  * applied to the inner rel will affect the join result size estimate,
2600  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2601  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2602  * the selectivity of outer-rel restrictions.
2603  *
2604  * We can apply this clamping both with respect to the base relation from
2605  * which the join variable comes (if there is just one), and to the
2606  * immediate inner input relation of the current join.
2607  *
2608  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2609  * great, maybe, but it didn't come out of nowhere either. This is most
2610  * helpful when the inner relation is empty and consequently has no stats.
2611  */
2612  if (vardata2->rel)
2613  {
2614  if (nd2 >= vardata2->rel->rows)
2615  {
2616  nd2 = vardata2->rel->rows;
2617  isdefault2 = false;
2618  }
2619  }
2620  if (nd2 >= inner_rel->rows)
2621  {
2622  nd2 = inner_rel->rows;
2623  isdefault2 = false;
2624  }
2625 
2626  if (HeapTupleIsValid(vardata1->statsTuple))
2627  {
2628  /* note we allow use of nullfrac regardless of security check */
2629  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2630  if (statistic_proc_security_check(vardata1, opfuncoid))
2631  have_mcvs1 = get_attstatsslot(&sslot1, vardata1->statsTuple,
2632  STATISTIC_KIND_MCV, InvalidOid,
2634  }
2635 
2636  if (HeapTupleIsValid(vardata2->statsTuple) &&
2637  statistic_proc_security_check(vardata2, opfuncoid))
2638  {
2639  have_mcvs2 = get_attstatsslot(&sslot2, vardata2->statsTuple,
2640  STATISTIC_KIND_MCV, InvalidOid,
2642  /* note: currently don't need stanumbers from RHS */
2643  }
2644 
2645  if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2646  {
2647  /*
2648  * We have most-common-value lists for both relations. Run through
2649  * the lists to see which MCVs actually join to each other with the
2650  * given operator. This allows us to determine the exact join
2651  * selectivity for the portion of the relations represented by the MCV
2652  * lists. We still have to estimate for the remaining population, but
2653  * in a skewed distribution this gives us a big leg up in accuracy.
2654  */
2655  FmgrInfo eqproc;
2656  bool *hasmatch1;
2657  bool *hasmatch2;
2658  double nullfrac1 = stats1->stanullfrac;
2659  double matchfreq1,
2660  uncertainfrac,
2661  uncertain;
2662  int i,
2663  nmatches,
2664  clamped_nvalues2;
2665 
2666  /*
2667  * The clamping above could have resulted in nd2 being less than
2668  * sslot2.nvalues; in which case, we assume that precisely the nd2
2669  * most common values in the relation will appear in the join input,
2670  * and so compare to only the first nd2 members of the MCV list. Of
2671  * course this is frequently wrong, but it's the best bet we can make.
2672  */
2673  clamped_nvalues2 = Min(sslot2.nvalues, nd2);
2674 
2675  fmgr_info(opfuncoid, &eqproc);
2676  hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
2677  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2678 
2679  /*
2680  * Note we assume that each MCV will match at most one member of the
2681  * other MCV list. If the operator isn't really equality, there could
2682  * be multiple matches --- but we don't look for them, both for speed
2683  * and because the math wouldn't add up...
2684  */
2685  nmatches = 0;
2686  for (i = 0; i < sslot1.nvalues; i++)
2687  {
2688  int j;
2689 
2690  for (j = 0; j < clamped_nvalues2; j++)
2691  {
2692  if (hasmatch2[j])
2693  continue;
2694  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2695  DEFAULT_COLLATION_OID,
2696  sslot1.values[i],
2697  sslot2.values[j])))
2698  {
2699  hasmatch1[i] = hasmatch2[j] = true;
2700  nmatches++;
2701  break;
2702  }
2703  }
2704  }
2705  /* Sum up frequencies of matched MCVs */
2706  matchfreq1 = 0.0;
2707  for (i = 0; i < sslot1.nvalues; i++)
2708  {
2709  if (hasmatch1[i])
2710  matchfreq1 += sslot1.numbers[i];
2711  }
2712  CLAMP_PROBABILITY(matchfreq1);
2713  pfree(hasmatch1);
2714  pfree(hasmatch2);
2715 
2716  /*
2717  * Now we need to estimate the fraction of relation 1 that has at
2718  * least one join partner. We know for certain that the matched MCVs
2719  * do, so that gives us a lower bound, but we're really in the dark
2720  * about everything else. Our crude approach is: if nd1 <= nd2 then
2721  * assume all non-null rel1 rows have join partners, else assume for
2722  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2723  * can discount the known-matched MCVs from the distinct-values counts
2724  * before doing the division.
2725  *
2726  * Crude as the above is, it's completely useless if we don't have
2727  * reliable ndistinct values for both sides. Hence, if either nd1 or
2728  * nd2 is default, punt and assume half of the uncertain rows have
2729  * join partners.
2730  */
2731  if (!isdefault1 && !isdefault2)
2732  {
2733  nd1 -= nmatches;
2734  nd2 -= nmatches;
2735  if (nd1 <= nd2 || nd2 < 0)
2736  uncertainfrac = 1.0;
2737  else
2738  uncertainfrac = nd2 / nd1;
2739  }
2740  else
2741  uncertainfrac = 0.5;
2742  uncertain = 1.0 - matchfreq1 - nullfrac1;
2743  CLAMP_PROBABILITY(uncertain);
2744  selec = matchfreq1 + uncertainfrac * uncertain;
2745  }
2746  else
2747  {
2748  /*
2749  * Without MCV lists for both sides, we can only use the heuristic
2750  * about nd1 vs nd2.
2751  */
2752  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2753 
2754  if (!isdefault1 && !isdefault2)
2755  {
2756  if (nd1 <= nd2 || nd2 < 0)
2757  selec = 1.0 - nullfrac1;
2758  else
2759  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2760  }
2761  else
2762  selec = 0.5 * (1.0 - nullfrac1);
2763  }
2764 
2765  free_attstatsslot(&sslot1);
2766  free_attstatsslot(&sslot2);
2767 
2768  return selec;
2769 }
Definition: fmgr.h:56
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5154
RelOptInfo * rel
Definition: selfuncs.h:70
#define Min(x, y)
Definition: c.h:857
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1133
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:127
#define OidIsValid(objectId)
Definition: c.h:605
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5183
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
float4 * numbers
Definition: lsyscache.h:52
#define DatumGetBool(X)
Definition: postgres.h:378
void * palloc0(Size size)
Definition: mcxt.c:955
double rows
Definition: relation.h:615
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1079
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2913
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3029

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 231 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

232 {
233  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
234 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:331
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:240
double float8
Definition: c.h:458

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

Definition at line 240 of file selfuncs.c.

References generate_unaccent_rules::args, DEFAULT_EQ_SEL, get_negator(), get_restriction_variable(), IsA, OidIsValid, PG_GETARG_INT32, PG_GETARG_OID, PG_GETARG_POINTER, ReleaseVariableStats, var_eq_const(), and var_eq_non_const().

Referenced by eqsel(), and neqsel().

241 {
243  Oid operator = PG_GETARG_OID(1);
244  List *args = (List *) PG_GETARG_POINTER(2);
245  int varRelid = PG_GETARG_INT32(3);
246  VariableStatData vardata;
247  Node *other;
248  bool varonleft;
249  double selec;
250 
251  /*
252  * When asked about <>, we do the estimation using the corresponding =
253  * operator, then convert to <> via "1.0 - eq_selectivity - nullfrac".
254  */
255  if (negate)
256  {
257  operator = get_negator(operator);
258  if (!OidIsValid(operator))
259  {
260  /* Use default selectivity (should we raise an error instead?) */
261  return 1.0 - DEFAULT_EQ_SEL;
262  }
263  }
264 
265  /*
266  * If expression is not variable = something or something = variable, then
267  * punt and return a default estimate.
268  */
269  if (!get_restriction_variable(root, args, varRelid,
270  &vardata, &other, &varonleft))
271  return negate ? (1.0 - DEFAULT_EQ_SEL) : DEFAULT_EQ_SEL;
272 
273  /*
274  * We can do a lot better if the something is a constant. (Note: the
275  * Const might result from estimation rather than being a simple constant
276  * in the query.)
277  */
278  if (IsA(other, Const))
279  selec = var_eq_const(&vardata, operator,
280  ((Const *) other)->constvalue,
281  ((Const *) other)->constisnull,
282  varonleft, negate);
283  else
284  selec = var_eq_non_const(&vardata, operator, other,
285  varonleft, negate);
286 
287  ReleaseVariableStats(vardata);
288 
289  return selec;
290 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:239
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4654
Definition: nodes.h:517
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:246
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
static double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:298
#define PG_GETARG_OID(n)
Definition: fmgr.h:245
#define DEFAULT_EQ_SEL
Definition: selfuncs.h:34
static double var_eq_non_const(VariableStatData *vardata, Oid operator, Node *other, bool varonleft, bool negate)
Definition: selfuncs.c:450
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
Oid get_negator(Oid opno)
Definition: lsyscache.c:1322
Definition: pg_list.h:45

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

Definition at line 2179 of file selfuncs.c.

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

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

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

◆ estimate_hash_bucket_stats()

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

Definition at line 3782 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

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

◆ estimate_multivariate_ndistinct()

static bool estimate_multivariate_ndistinct ( PlannerInfo root,
RelOptInfo rel,
List **  varinfos,
double *  ndistinct 
)
static

Definition at line 3906 of file selfuncs.c.

References Assert, attnum, MVNDistinctItem::attrs, bms_add_member(), BMS_EQUAL, bms_intersect(), bms_is_member(), bms_num_members(), bms_subset_compare(), elog, ERROR, i, InvalidOid, IsA, MVNDistinct::items, StatisticExtInfo::keys, StatisticExtInfo::kind, lappend(), lfirst, MVNDistinctItem::ndistinct, NIL, MVNDistinct::nitems, GroupVarInfo::rel, statext_ndistinct_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, and GroupVarInfo::var.

Referenced by estimate_num_groups().

3908 {
3909  ListCell *lc;
3910  Bitmapset *attnums = NULL;
3911  int nmatches;
3912  Oid statOid = InvalidOid;
3913  MVNDistinct *stats;
3914  Bitmapset *matched = NULL;
3915 
3916  /* bail out immediately if the table has no extended statistics */
3917  if (!rel->statlist)
3918  return false;
3919 
3920  /* Determine the attnums we're looking for */
3921  foreach(lc, *varinfos)
3922  {
3923  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3924 
3925  Assert(varinfo->rel == rel);
3926 
3927  if (IsA(varinfo->var, Var))
3928  {
3929  attnums = bms_add_member(attnums,
3930  ((Var *) varinfo->var)->varattno);
3931  }
3932  }
3933 
3934  /* look for the ndistinct statistics matching the most vars */
3935  nmatches = 1; /* we require at least two matches */
3936  foreach(lc, rel->statlist)
3937  {
3938  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3939  Bitmapset *shared;
3940  int nshared;
3941 
3942  /* skip statistics of other kinds */
3943  if (info->kind != STATS_EXT_NDISTINCT)
3944  continue;
3945 
3946  /* compute attnums shared by the vars and the statistics object */
3947  shared = bms_intersect(info->keys, attnums);
3948  nshared = bms_num_members(shared);
3949 
3950  /*
3951  * Does this statistics object match more columns than the currently
3952  * best object? If so, use this one instead.
3953  *
3954  * XXX This should break ties using name of the object, or something
3955  * like that, to make the outcome stable.
3956  */
3957  if (nshared > nmatches)
3958  {
3959  statOid = info->statOid;
3960  nmatches = nshared;
3961  matched = shared;
3962  }
3963  }
3964 
3965  /* No match? */
3966  if (statOid == InvalidOid)
3967  return false;
3968  Assert(nmatches > 1 && matched != NULL);
3969 
3970  stats = statext_ndistinct_load(statOid);
3971 
3972  /*
3973  * If we have a match, search it for the specific item that matches (there
3974  * must be one), and construct the output values.
3975  */
3976  if (stats)
3977  {
3978  int i;
3979  List *newlist = NIL;
3980  MVNDistinctItem *item = NULL;
3981 
3982  /* Find the specific item that exactly matches the combination */
3983  for (i = 0; i < stats->nitems; i++)
3984  {
3985  MVNDistinctItem *tmpitem = &stats->items[i];
3986 
3987  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3988  {
3989  item = tmpitem;
3990  break;
3991  }
3992  }
3993 
3994  /* make sure we found an item */
3995  if (!item)
3996  elog(ERROR, "corrupt MVNDistinct entry");
3997 
3998  /* Form the output varinfo list, keeping only unmatched ones */
3999  foreach(lc, *varinfos)
4000  {
4001  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4003 
4004  if (!IsA(varinfo->var, Var))
4005  {
4006  newlist = lappend(newlist, varinfo);
4007  continue;
4008  }
4009 
4010  attnum = ((Var *) varinfo->var)->varattno;
4011  if (!bms_is_member(attnum, matched))
4012  newlist = lappend(newlist, varinfo);
4013  }
4014 
4015  *varinfos = newlist;
4016  *ndistinct = item->ndistinct;
4017  return true;
4018  }
4019 
4020  return false;
4021 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
List * statlist
Definition: relation.h:650
MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:42
double ndistinct
Definition: statistics.h:28
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:164
#define ERROR
Definition: elog.h:43
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:671
Node * var
Definition: selfuncs.c:3295
uint32 nitems
Definition: statistics.h:41
List * lappend(List *list, void *datum)
Definition: list.c:128
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:318
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:411
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * attrs
Definition: statistics.h:29
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
Bitmapset * keys
Definition: relation.h:849
int i
#define elog
Definition: elog.h:219
MVNDistinct * statext_ndistinct_load(Oid mvoid)
Definition: mvdistinct.c:127
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486
int16 AttrNumber
Definition: attnum.h:21
RelOptInfo * rel
Definition: selfuncs.c:3296

◆ estimate_num_groups()

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

Definition at line 3419 of file selfuncs.c.

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

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

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

◆ examine_simple_variable()

static void examine_simple_variable ( PlannerInfo root,
Var var,
VariableStatData vardata 
)
static

Definition at line 4987 of file selfuncs.c.

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, Alias::aliasname, Assert, BoolGetDatum, Query::distinctClause, elog, RangeTblEntry::eref, ERROR, TargetEntry::expr, find_base_rel(), VariableStatData::freefunc, get_relation_stats_hook, get_tle_by_resno(), GetUserId(), Query::groupClause, HeapTupleIsValid, RangeTblEntry::inh, Int16GetDatum, InvalidAttrNumber, InvalidOid, IsA, VariableStatData::isunique, list_length(), ObjectIdGetDatum, PlannerInfo::parse, pg_attribute_aclcheck(), pg_class_aclcheck(), ReleaseSysCache(), RangeTblEntry::relid, TargetEntry::resjunk, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, SearchSysCache3(), RangeTblEntry::security_barrier, Query::setOperations, PlannerInfo::simple_rte_array, STATRELATTINH, VariableStatData::statsTuple, RangeTblEntry::subquery, RelOptInfo::subroot, targetIsInSortList(), Query::targetList, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by examine_variable().

4989 {
4990  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4991 
4992  Assert(IsA(rte, RangeTblEntry));
4993 
4995  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4996  {
4997  /*
4998  * The hook took control of acquiring a stats tuple. If it did supply
4999  * a tuple, it'd better have supplied a freefunc.
5000  */
5001  if (HeapTupleIsValid(vardata->statsTuple) &&
5002  !vardata->freefunc)
5003  elog(ERROR, "no function provided to release variable stats with");
5004  }
5005  else if (rte->rtekind == RTE_RELATION)
5006  {
5007  /*
5008  * Plain table or parent of an inheritance appendrel, so look up the
5009  * column in pg_statistic
5010  */
5012  ObjectIdGetDatum(rte->relid),
5013  Int16GetDatum(var->varattno),
5014  BoolGetDatum(rte->inh));
5015  vardata->freefunc = ReleaseSysCache;
5016 
5017  if (HeapTupleIsValid(vardata->statsTuple))
5018  {
5019  /* check if user has permission to read this column */
5020  vardata->acl_ok =
5022  ACL_SELECT) == ACLCHECK_OK) ||
5024  ACL_SELECT) == ACLCHECK_OK);
5025  }
5026  else
5027  {
5028  /* suppress any possible leakproofness checks later */
5029  vardata->acl_ok = true;
5030  }
5031  }
5032  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
5033  {
5034  /*
5035  * Plain subquery (not one that was converted to an appendrel).
5036  */
5037  Query *subquery = rte->subquery;
5038  RelOptInfo *rel;
5039  TargetEntry *ste;
5040 
5041  /*
5042  * Punt if it's a whole-row var rather than a plain column reference.
5043  */
5044  if (var->varattno == InvalidAttrNumber)
5045  return;
5046 
5047  /*
5048  * Punt if subquery uses set operations or GROUP BY, as these will
5049  * mash underlying columns' stats beyond recognition. (Set ops are
5050  * particularly nasty; if we forged ahead, we would return stats
5051  * relevant to only the leftmost subselect...) DISTINCT is also
5052  * problematic, but we check that later because there is a possibility
5053  * of learning something even with it.
5054  */
5055  if (subquery->setOperations ||
5056  subquery->groupClause)
5057  return;
5058 
5059  /*
5060  * OK, fetch RelOptInfo for subquery. Note that we don't change the
5061  * rel returned in vardata, since caller expects it to be a rel of the
5062  * caller's query level. Because we might already be recursing, we
5063  * can't use that rel pointer either, but have to look up the Var's
5064  * rel afresh.
5065  */
5066  rel = find_base_rel(root, var->varno);
5067 
5068  /* If the subquery hasn't been planned yet, we have to punt */
5069  if (rel->subroot == NULL)
5070  return;
5071  Assert(IsA(rel->subroot, PlannerInfo));
5072 
5073  /*
5074  * Switch our attention to the subquery as mangled by the planner. It
5075  * was okay to look at the pre-planning version for the tests above,
5076  * but now we need a Var that will refer to the subroot's live
5077  * RelOptInfos. For instance, if any subquery pullup happened during
5078  * planning, Vars in the targetlist might have gotten replaced, and we
5079  * need to see the replacement expressions.
5080  */
5081  subquery = rel->subroot->parse;
5082  Assert(IsA(subquery, Query));
5083 
5084  /* Get the subquery output expression referenced by the upper Var */
5085  ste = get_tle_by_resno(subquery->targetList, var->varattno);
5086  if (ste == NULL || ste->resjunk)
5087  elog(ERROR, "subquery %s does not have attribute %d",
5088  rte->eref->aliasname, var->varattno);
5089  var = (Var *) ste->expr;
5090 
5091  /*
5092  * If subquery uses DISTINCT, we can't make use of any stats for the
5093  * variable ... but, if it's the only DISTINCT column, we are entitled
5094  * to consider it unique. We do the test this way so that it works
5095  * for cases involving DISTINCT ON.
5096  */
5097  if (subquery->distinctClause)
5098  {
5099  if (list_length(subquery->distinctClause) == 1 &&
5100  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5101  vardata->isunique = true;
5102  /* cannot go further */
5103  return;
5104  }
5105 
5106  /*
5107  * If the sub-query originated from a view with the security_barrier
5108  * attribute, we must not look at the variable's statistics, though it
5109  * seems all right to notice the existence of a DISTINCT clause. So
5110  * stop here.
5111  *
5112  * This is probably a harsher restriction than necessary; it's
5113  * certainly OK for the selectivity estimator (which is a C function,
5114  * and therefore omnipotent anyway) to look at the statistics. But
5115  * many selectivity estimators will happily *invoke the operator
5116  * function* to try to work out a good estimate - and that's not OK.
5117  * So for now, don't dig down for stats.
5118  */
5119  if (rte->security_barrier)
5120  return;
5121 
5122  /* Can only handle a simple Var of subquery's query level */
5123  if (var && IsA(var, Var) &&
5124  var->varlevelsup == 0)
5125  {
5126  /*
5127  * OK, recurse into the subquery. Note that the original setting
5128  * of vardata->isunique (which will surely be false) is left
5129  * unchanged in this situation. That's what we want, since even
5130  * if the underlying column is unique, the subquery may have
5131  * joined to other tables in a way that creates duplicates.
5132  */
5133  examine_simple_variable(rel->subroot, var, vardata);
5134  }
5135  }
5136  else
5137  {
5138  /*
5139  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
5140  * won't see RTE_JOIN here because join alias Vars have already been
5141  * flattened.) There's not much we can do with function outputs, but
5142  * maybe someday try to be smarter about VALUES and/or CTEs.
5143  */
5144  }
5145 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Query * parse
Definition: relation.h:169
Index varlevelsup
Definition: primnodes.h:174
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4513
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:379
#define Int16GetDatum(X)
Definition: postgres.h:436
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
AttrNumber varattno
Definition: primnodes.h:169
Definition: primnodes.h:164
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4987
List * targetList
Definition: parsenodes.h:140
PlannerInfo * subroot
Definition: relation.h:654
bool resjunk
Definition: primnodes.h:1383
List * distinctClause
Definition: parsenodes.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:155
RangeTblEntry ** simple_rte_array
Definition: relation.h:202
Index varno
Definition: primnodes.h:167
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:75
bool security_barrier
Definition: parsenodes.h:986
#define BoolGetDatum(X)
Definition: postgres.h:387
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:699
char * aliasname
Definition: primnodes.h:43
Expr * expr
Definition: primnodes.h:1376
static int list_length(const List *l)
Definition: pg_list.h:89
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4627
RTEKind rtekind
Definition: parsenodes.h:962
Node * setOperations
Definition: parsenodes.h:165
Query * subquery
Definition: parsenodes.h:985
List * groupClause
Definition: parsenodes.h:148
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1066
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:279

◆ examine_variable()

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

Definition at line 4776 of file selfuncs.c.

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

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

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

◆ find_join_input_rel()

static RelOptInfo * find_join_input_rel ( PlannerInfo root,
Relids  relids 
)
static

Definition at line 5689 of file selfuncs.c.

References BMS_EMPTY_SET, bms_membership(), BMS_MULTIPLE, BMS_SINGLETON, bms_singleton_member(), elog, ERROR, find_base_rel(), and find_join_rel().

Referenced by eqjoinsel().

5690 {
5691  RelOptInfo *rel = NULL;
5692 
5693  switch (bms_membership(relids))
5694  {
5695  case BMS_EMPTY_SET:
5696  /* should not happen */
5697  break;
5698  case BMS_SINGLETON:
5699  rel = find_base_rel(root, bms_singleton_member(relids));
5700  break;
5701  case BMS_MULTIPLE:
5702  rel = find_join_rel(root, relids);
5703  break;
5704  }
5705 
5706  if (rel == NULL)
5707  elog(ERROR, "could not find RelOptInfo for given relids");
5708 
5709  return rel;
5710 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:344
#define ERROR
Definition: elog.h:43
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:700
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:592
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:279

◆ genericcostestimate()

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

Definition at line 6701 of file selfuncs.c.

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

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

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

◆ get_actual_variable_range()

static bool get_actual_variable_range ( PlannerInfo root,
VariableStatData vardata,
Oid  sortop,
Datum min,
Datum max 
)
static

Definition at line 5450 of file selfuncs.c.

References AccessShareLock, Assert, VariableStatData::atttype, BackwardScanDirection, BTGreaterStrategyNumber, BTLessStrategyNumber, BuildIndexInfo(), CreateExecutorState(), datumCopy(), ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, elog, ERROR, ExecDropSingleTupleTableSlot(), ExecStoreTuple(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), get_op_opfamily_strategy(), get_typlenbyval(), GetPerTupleExprContext, heap_close, heap_open(), IndexOptInfo::hypothetical, index_beginscan(), index_close(), index_endscan(), index_getnext(), INDEX_MAX_KEYS, index_open(), index_rescan(), RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indpred, InitNonVacuumableSnapshot, InvalidBuffer, InvalidOid, InvalidStrategy, lfirst, MakeSingleTupleTableSlot(), match_index_to_operand(), MemoryContextSwitchTo(), NIL, NoLock, RecentGlobalXmin, VariableStatData::rel, IndexOptInfo::relam, RelationGetDescr, RelationGetRelationName, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, RTE_RELATION, RangeTblEntry::rtekind, ScanKeyEntryInitialize(), PlannerInfo::simple_rte_array, SK_ISNULL, SK_SEARCHNOTNULL, IndexOptInfo::sortopfamily, values, and VariableStatData::var.

Referenced by get_variable_range(), and ineq_histogram_selectivity().

5453 {
5454  bool have_data = false;
5455  RelOptInfo *rel = vardata->rel;
5456  RangeTblEntry *rte;
5457  ListCell *lc;
5458 
5459  /* No hope if no relation or it doesn't have indexes */
5460  if (rel == NULL || rel->indexlist == NIL)
5461  return false;
5462  /* If it has indexes it must be a plain relation */
5463  rte = root->simple_rte_array[rel->relid];
5464  Assert(rte->rtekind == RTE_RELATION);
5465 
5466  /* Search through the indexes to see if any match our problem */
5467  foreach(lc, rel->indexlist)
5468  {
5470  ScanDirection indexscandir;
5471 
5472  /* Ignore non-btree indexes */
5473  if (index->relam != BTREE_AM_OID)
5474  continue;
5475 
5476  /*
5477  * Ignore partial indexes --- we only want stats that cover the entire
5478  * relation.
5479  */
5480  if (index->indpred != NIL)
5481  continue;
5482 
5483  /*
5484  * The index list might include hypothetical indexes inserted by a
5485  * get_relation_info hook --- don't try to access them.
5486  */
5487  if (index->hypothetical)
5488  continue;
5489 
5490  /*
5491  * The first index column must match the desired variable and sort
5492  * operator --- but we can use a descending-order index.
5493  */
5494  if (!match_index_to_operand(vardata->var, 0, index))
5495  continue;
5496  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5497  {
5498  case BTLessStrategyNumber:
5499  if (index->reverse_sort[0])
5500  indexscandir = BackwardScanDirection;
5501  else
5502  indexscandir = ForwardScanDirection;
5503  break;
5505  if (index->reverse_sort[0])
5506  indexscandir = ForwardScanDirection;
5507  else
5508  indexscandir = BackwardScanDirection;
5509  break;
5510  default:
5511  /* index doesn't match the sortop */
5512  continue;
5513  }
5514 
5515  /*
5516  * Found a suitable index to extract data from. We'll need an EState
5517  * and a bunch of other infrastructure.
5518  */
5519  {
5520  EState *estate;
5521  ExprContext *econtext;
5522  MemoryContext tmpcontext;
5523  MemoryContext oldcontext;
5524  Relation heapRel;
5525  Relation indexRel;
5526  IndexInfo *indexInfo;
5527  TupleTableSlot *slot;
5528  int16 typLen;
5529  bool typByVal;
5530  ScanKeyData scankeys[1];
5531  IndexScanDesc index_scan;
5532  HeapTuple tup;
5534  bool isnull[INDEX_MAX_KEYS];
5535  SnapshotData SnapshotNonVacuumable;
5536 
5537  estate = CreateExecutorState();
5538  econtext = GetPerTupleExprContext(estate);
5539  /* Make sure any cruft is generated in the econtext's memory */
5540  tmpcontext = econtext->ecxt_per_tuple_memory;
5541  oldcontext = MemoryContextSwitchTo(tmpcontext);
5542 
5543  /*
5544  * Open the table and index so we can read from them. We should
5545  * already have at least AccessShareLock on the table, but not
5546  * necessarily on the index.
5547  */
5548  heapRel = heap_open(rte->relid, NoLock);
5549  indexRel = index_open(index->indexoid, AccessShareLock);
5550 
5551  /* extract index key information from the index's pg_index info */
5552  indexInfo = BuildIndexInfo(indexRel);
5553 
5554  /* some other stuff */
5555  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
5556  econtext->ecxt_scantuple = slot;
5557  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5558  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5559 
5560  /* set up an IS NOT NULL scan key so that we ignore nulls */
5561  ScanKeyEntryInitialize(&scankeys[0],
5563  1, /* index col to scan */
5564  InvalidStrategy, /* no strategy */
5565  InvalidOid, /* no strategy subtype */
5566  InvalidOid, /* no collation */
5567  InvalidOid, /* no reg proc for this */
5568  (Datum) 0); /* constant */
5569 
5570  have_data = true;
5571 
5572  /* If min is requested ... */
5573  if (min)
5574  {
5575  /*
5576  * In principle, we should scan the index with our current
5577  * active snapshot, which is the best approximation we've got
5578  * to what the query will see when executed. But that won't
5579  * be exact if a new snap is taken before running the query,
5580  * and it can be very expensive if a lot of recently-dead or
5581  * uncommitted rows exist at the beginning or end of the index
5582  * (because we'll laboriously fetch each one and reject it).
5583  * Instead, we use SnapshotNonVacuumable. That will accept
5584  * recently-dead and uncommitted rows as well as normal
5585  * visible rows. On the other hand, it will reject known-dead
5586  * rows, and thus not give a bogus answer when the extreme
5587  * value has been deleted (unless the deletion was quite
5588  * recent); that case motivates not using SnapshotAny here.
5589  *
5590  * A crucial point here is that SnapshotNonVacuumable, with
5591  * RecentGlobalXmin as horizon, yields the inverse of the
5592  * condition that the indexscan will use to decide that index
5593  * entries are killable (see heap_hot_search_buffer()).
5594  * Therefore, if the snapshot rejects a tuple and we have to
5595  * continue scanning past it, we know that the indexscan will
5596  * mark that index entry killed. That means that the next
5597  * get_actual_variable_range() call will not have to visit
5598  * that heap entry. In this way we avoid repetitive work when
5599  * this function is used a lot during planning.
5600  */
5601  index_scan = index_beginscan(heapRel, indexRel,
5602  &SnapshotNonVacuumable,
5603  1, 0);
5604  index_rescan(index_scan, scankeys, 1, NULL, 0);
5605 
5606  /* Fetch first tuple in sortop's direction */
5607  if ((tup = index_getnext(index_scan,
5608  indexscandir)) != NULL)
5609  {
5610  /* Extract the index column values from the heap tuple */
5611  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5612  FormIndexDatum(indexInfo, slot, estate,
5613  values, isnull);
5614 
5615  /* Shouldn't have got a null, but be careful */
5616  if (isnull[0])
5617  elog(ERROR, "found unexpected null value in index \"%s\"",
5618  RelationGetRelationName(indexRel));
5619 
5620  /* Copy the index column value out to caller's context */
5621  MemoryContextSwitchTo(oldcontext);
5622  *min = datumCopy(values[0], typByVal, typLen);
5623  MemoryContextSwitchTo(tmpcontext);
5624  }
5625  else
5626  have_data = false;
5627 
5628  index_endscan(index_scan);
5629  }
5630 
5631  /* If max is requested, and we didn't find the index is empty */
5632  if (max && have_data)
5633  {
5634  index_scan = index_beginscan(heapRel, indexRel,
5635  &SnapshotNonVacuumable,
5636  1, 0);
5637  index_rescan(index_scan, scankeys, 1, NULL, 0);
5638 
5639  /* Fetch first tuple in reverse direction */
5640  if ((tup = index_getnext(index_scan,
5641  -indexscandir)) != NULL)
5642  {
5643  /* Extract the index column values from the heap tuple */
5644  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5645  FormIndexDatum(indexInfo, slot, estate,
5646  values, isnull);
5647 
5648  /* Shouldn't have got a null, but be careful */
5649  if (isnull[0])
5650  elog(ERROR, "found unexpected null value in index \"%s\"",
5651  RelationGetRelationName(indexRel));
5652 
5653  /* Copy the index column value out to caller's context */
5654  MemoryContextSwitchTo(oldcontext);
5655  *max = datumCopy(values[0], typByVal, typLen);
5656  MemoryContextSwitchTo(tmpcontext);
5657  }
5658  else
5659  have_data = false;
5660 
5661  index_endscan(index_scan);
5662  }
5663 
5664  /* Clean everything up */
5666 
5667  index_close(indexRel, AccessShareLock);
5668  heap_close(heapRel, NoLock);
5669 
5670  MemoryContextSwitchTo(oldcontext);
5671  FreeExecutorState(estate);
5672 
5673  /* And we're done */
5674  break;
5675  }
5676  }
5677 
5678  return have_data;
5679 }
signed short int16
Definition: c.h:312
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2000
#define InvalidStrategy
Definition: stratnum.h:24
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:356
#define InitNonVacuumableSnapshot(snapshotdata, xmin_horizon)
Definition: tqual.h:110
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define RelationGetDescr(relation)
Definition: rel.h:433
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3206
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:226
RelOptInfo * rel
Definition: selfuncs.h:70
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define InvalidBuffer
Definition: buf.h:25
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:310
Oid * sortopfamily
Definition: relation.h:770
bool hypothetical
Definition: relation.h:791
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1745
Definition: type.h:89
void FreeExecutorState(EState *estate)
Definition: execUtils.c:188
#define GetPerTupleExprContext(estate)
Definition: executor.h:489
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:247
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
ScanDirection
Definition: sdir.h:22
#define RelationGetRelationName(relation)
Definition: rel.h:441
#define SK_SEARCHNOTNULL
Definition: skey.h:122
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:232
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:340
#define SK_ISNULL
Definition: skey.h:115
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:80
Index relid
Definition: relation.h:640
RangeTblEntry ** simple_rte_array
Definition: relation.h:202
uintptr_t Datum
Definition: postgres.h:367
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
List * indexlist
Definition: relation.h:649
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
#define INDEX_MAX_KEYS
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2005
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:218
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
RTEKind rtekind
Definition: parsenodes.h:962
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:753
bool * reverse_sort
Definition: relation.h:771
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:778
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
HeapTuple index_getnext(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:659
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:221

◆ get_join_variables()

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

Definition at line 4714 of file selfuncs.c.

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

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

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

◆ get_restriction_variable()

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

Definition at line 4654 of file selfuncs.c.

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

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

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

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

Definition at line 5183 of file selfuncs.c.

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

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

5184 {
5185  double stadistinct;
5186  double stanullfrac = 0.0;
5187  double ntuples;
5188 
5189  *isdefault = false;
5190 
5191  /*
5192  * Determine the stadistinct value to use. There are cases where we can
5193  * get an estimate even without a pg_statistic entry, or can get a better
5194  * value than is in pg_statistic. Grab stanullfrac too if we can find it
5195  * (otherwise, assume no nulls, for lack of any better idea).
5196  */
5197  if (HeapTupleIsValid(vardata->statsTuple))
5198  {
5199  /* Use the pg_statistic entry */
5200  Form_pg_statistic stats;
5201 
5202  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
5203  stadistinct = stats->stadistinct;
5204  stanullfrac = stats->stanullfrac;
5205  }
5206  else if (vardata->vartype == BOOLOID)
5207  {
5208  /*
5209  * Special-case boolean columns: presumably, two distinct values.
5210  *
5211  * Are there any other datatypes we should wire in special estimates
5212  * for?
5213  */
5214  stadistinct = 2.0;
5215  }
5216  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5217  {
5218  /*
5219  * If the Var represents a column of a VALUES RTE, assume it's unique.
5220  * This could of course be very wrong, but it should tend to be true
5221  * in well-written queries. We could consider examining the VALUES'
5222  * contents to get some real statistics; but that only works if the
5223  * entries are all constants, and it would be pretty expensive anyway.
5224  */
5225  stadistinct = -1.0; /* unique (and all non null) */
5226  }
5227  else
5228  {
5229  /*
5230  * We don't keep statistics for system columns, but in some cases we
5231  * can infer distinctness anyway.
5232  */
5233  if (vardata->var && IsA(vardata->var, Var))
5234  {
5235  switch (((Var *) vardata->var)->varattno)
5236  {
5239  stadistinct = -1.0; /* unique (and all non null) */
5240  break;
5242  stadistinct = 1.0; /* only 1 value */
5243  break;
5244  default:
5245  stadistinct = 0.0; /* means "unknown" */
5246  break;
5247  }
5248  }
5249  else
5250  stadistinct = 0.0; /* means "unknown" */
5251 
5252  /*
5253  * XXX consider using estimate_num_groups on expressions?
5254  */
5255  }
5256 
5257  /*
5258  * If there is a unique index or DISTINCT clause for the variable, assume
5259  * it is unique no matter what pg_statistic says; the statistics could be
5260  * out of date, or we might have found a partial unique index that proves
5261  * the var is unique for this query. However, we'd better still believe
5262  * the null-fraction statistic.
5263  */
5264  if (vardata->isunique)
5265  stadistinct = -1.0 * (1.0 - stanullfrac);
5266 
5267  /*
5268  * If we had an absolute estimate, use that.
5269  */
5270  if (stadistinct > 0.0)