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)
 
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)
 
static double convert_timevalue_to_scalar (Datum value, Oid typid)
 
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 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 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 6046 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity_sub().

◆ CHAR_RANGE_SEL

#define CHAR_RANGE_SEL   0.25

Definition at line 6045 of file selfuncs.c.

Referenced by regex_selectivity_sub().

◆ FIXED_CHAR_SEL

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

Definition at line 6044 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 6047 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity().

◆ PARTIAL_WILDCARD_SEL

#define PARTIAL_WILDCARD_SEL   2.0

Definition at line 6048 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 6858 of file selfuncs.c.

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

Referenced by btcostestimate(), and genericcostestimate().

6859 {
6860  List *predExtraQuals = NIL;
6861  ListCell *lc;
6862 
6863  if (index->indpred == NIL)
6864  return indexQuals;
6865 
6866  foreach(lc, index->indpred)
6867  {
6868  Node *predQual = (Node *) lfirst(lc);
6869  List *oneQual = list_make1(predQual);
6870 
6871  if (!predicate_implied_by(oneQual, indexQuals, false))
6872  predExtraQuals = list_concat(predExtraQuals, oneQual);
6873  }
6874  /* list_concat avoids modifying the passed-in indexQuals list */
6875  return list_concat(predExtraQuals, indexQuals);
6876 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
Definition: nodes.h:512
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:742
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 3280 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().

3282 {
3283  GroupVarInfo *varinfo;
3284  double ndistinct;
3285  bool isdefault;
3286  ListCell *lc;
3287 
3288  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3289 
3290  /* cannot use foreach here because of possible list_delete */
3291  lc = list_head(varinfos);
3292  while (lc)
3293  {
3294  varinfo = (GroupVarInfo *) lfirst(lc);
3295 
3296  /* must advance lc before list_delete possibly pfree's it */
3297  lc = lnext(lc);
3298 
3299  /* Drop exact duplicates */
3300  if (equal(var, varinfo->var))
3301  return varinfos;
3302 
3303  /*
3304  * Drop known-equal vars, but only if they belong to different
3305  * relations (see comments for estimate_num_groups)
3306  */
3307  if (vardata->rel != varinfo->rel &&
3308  exprs_known_equal(root, var, varinfo->var))
3309  {
3310  if (varinfo->ndistinct <= ndistinct)
3311  {
3312  /* Keep older item, forget new one */
3313  return varinfos;
3314  }
3315  else
3316  {
3317  /* Delete the older item */
3318  varinfos = list_delete_ptr(varinfos, varinfo);
3319  }
3320  }
3321  }
3322 
3323  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3324 
3325  varinfo->var = var;
3326  varinfo->rel = vardata->rel;
3327  varinfo->ndistinct = ndistinct;
3328  varinfos = lappend(varinfos, varinfo);
3329  return varinfos;
3330 }
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:1983
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
RelOptInfo * rel
Definition: selfuncs.h:70
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
double ndistinct
Definition: selfuncs.c:3276
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5135
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
Node * var
Definition: selfuncs.c:3274
#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:835
RelOptInfo * rel
Definition: selfuncs.c:3275

◆ booltestsel()

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

Definition at line 1581 of file selfuncs.c.

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

Referenced by clause_selectivity().

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

◆ boolvarsel()

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

Definition at line 1542 of file selfuncs.c.

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

Referenced by clause_selectivity().

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

References Abs, AccessShareLock, Assert, 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(), STATISTIC_KIND_CORRELATION, STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

7964 {
7965  IndexOptInfo *index = path->indexinfo;
7966  List *indexQuals = path->indexquals;
7967  double numPages = index->pages;
7968  RelOptInfo *baserel = index->rel;
7969  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7970  List *qinfos;
7971  Cost spc_seq_page_cost;
7972  Cost spc_random_page_cost;
7973  double qual_arg_cost;
7974  double qualSelectivity;
7975  BrinStatsData statsData;
7976  double indexRanges;
7977  double minimalRanges;
7978  double estimatedRanges;
7979  double selec;
7980  Relation indexRel;
7981  ListCell *l;
7982  VariableStatData vardata;
7983 
7984  Assert(rte->rtekind == RTE_RELATION);
7985 
7986  /* fetch estimated page cost for the tablespace containing the index */
7988  &spc_random_page_cost,
7989  &spc_seq_page_cost);
7990 
7991  /*
7992  * Obtain some data from the index itself.
7993  */
7994  indexRel = index_open(index->indexoid, AccessShareLock);
7995  brinGetStats(indexRel, &statsData);
7996  index_close(indexRel, AccessShareLock);
7997 
7998  /*
7999  * Compute index correlation
8000  *
8001  * Because we can use all index quals equally when scanning, we can use
8002  * the largest correlation (in absolute value) among columns used by the
8003  * query. Start at zero, the worst possible case. If we cannot find any
8004  * correlation statistics, we will keep it as 0.
8005  */
8006  *indexCorrelation = 0;
8007 
8008  qinfos = deconstruct_indexquals(path);
8009  foreach(l, qinfos)
8010  {
8011  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(l);
8012  AttrNumber attnum = index->indexkeys[qinfo->indexcol];
8013 
8014  /* attempt to lookup stats in relation for this index column */
8015  if (attnum != 0)
8016  {
8017  /* Simple variable -- look to stats for the underlying table */
8019  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8020  {
8021  /*
8022  * The hook took control of acquiring a stats tuple. If it
8023  * did supply a tuple, it'd better have supplied a freefunc.
8024  */
8025  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8026  elog(ERROR,
8027  "no function provided to release variable stats with");
8028  }
8029  else
8030  {
8031  vardata.statsTuple =
8033  ObjectIdGetDatum(rte->relid),
8034  Int16GetDatum(attnum),
8035  BoolGetDatum(false));
8036  vardata.freefunc = ReleaseSysCache;
8037  }
8038  }
8039  else
8040  {
8041  /*
8042  * Looks like we've found an expression column in the index. Let's
8043  * see if there's any stats for it.
8044  */
8045 
8046  /* get the attnum from the 0-based index. */
8047  attnum = qinfo->indexcol + 1;
8048 
8049  if (get_index_stats_hook &&
8050  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8051  {
8052  /*
8053  * The hook took control of acquiring a stats tuple. If it
8054  * did supply a tuple, it'd better have supplied a freefunc.
8055  */
8056  if (HeapTupleIsValid(vardata.statsTuple) &&
8057  !vardata.freefunc)
8058  elog(ERROR, "no function provided to release variable stats with");
8059  }
8060  else
8061  {
8063  ObjectIdGetDatum(index->indexoid),
8064  Int16GetDatum(attnum),
8065  BoolGetDatum(false));
8066  vardata.freefunc = ReleaseSysCache;
8067  }
8068  }
8069 
8070  if (HeapTupleIsValid(vardata.statsTuple))
8071  {
8072  AttStatsSlot sslot;
8073 
8074  if (get_attstatsslot(&sslot, vardata.statsTuple,
8077  {
8078  double varCorrelation = 0.0;
8079 
8080  if (sslot.nnumbers > 0)
8081  varCorrelation = Abs(sslot.numbers[0]);
8082 
8083  if (varCorrelation > *indexCorrelation)
8084  *indexCorrelation = varCorrelation;
8085 
8086  free_attstatsslot(&sslot);
8087  }
8088  }
8089 
8090  ReleaseVariableStats(vardata);
8091  }
8092 
8093  qualSelectivity = clauselist_selectivity(root, indexQuals,
8094  baserel->relid,
8095  JOIN_INNER, NULL);
8096 
8097  /* work out the actual number of ranges in the index */
8098  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
8099  1.0);
8100 
8101  /*
8102  * Now calculate the minimum possible ranges we could match with if all of
8103  * the rows were in the perfect order in the table's heap.
8104  */
8105  minimalRanges = ceil(indexRanges * qualSelectivity);
8106 
8107  /*
8108  * Now estimate the number of ranges that we'll touch by using the
8109  * indexCorrelation from the stats. Careful not to divide by zero (note
8110  * we're using the absolute value of the correlation).
8111  */
8112  if (*indexCorrelation < 1.0e-10)
8113  estimatedRanges = indexRanges;
8114  else
8115  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8116 
8117  /* we expect to visit this portion of the table */
8118  selec = estimatedRanges / indexRanges;
8119 
8120  CLAMP_PROBABILITY(selec);
8121 
8122  *indexSelectivity = selec;
8123 
8124  /*
8125  * Compute the index qual costs, much as in genericcostestimate, to add to
8126  * the index costs.
8127  */
8128  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
8129  orderby_operands_eval_cost(root, path);
8130 
8131  /*
8132  * Compute the startup cost as the cost to read the whole revmap
8133  * sequentially, including the cost to execute the index quals.
8134  */
8135  *indexStartupCost =
8136  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8137  *indexStartupCost += qual_arg_cost;
8138 
8139  /*
8140  * To read a BRIN index there might be a bit of back and forth over
8141  * regular pages, as revmap might point to them out of sequential order;
8142  * calculate the total cost as reading the whole index in random order.
8143  */
8144  *indexTotalCost = *indexStartupCost +
8145  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8146 
8147  /*
8148  * Charge a small amount per range tuple which we expect to match to. This
8149  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8150  * will set a bit for each page in the range when we find a matching
8151  * range, so we must multiply the charge by the number of pages in the
8152  * range.
8153  */
8154  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8155  statsData.pagesPerRange;
8156 
8157  *indexPages = index->pages;
8158 }
IndexOptInfo * indexinfo
Definition: relation.h:1119
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
#define Min(x, y)
Definition: c.h:826
#define Int16GetDatum(X)
Definition: postgres.h:457
#define AccessShareLock
Definition: lockdefs.h:36
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
Oid reltablespace
Definition: relation.h:720
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6585
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6490
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6610
#define Abs(x)
Definition: c.h:832
Definition: type.h:89
BlockNumber pages
Definition: relation.h:724
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
List * indexquals
Definition: relation.h:1121
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
#define STATISTIC_KIND_CORRELATION
Definition: pg_statistic.h:231
float4 * numbers
Definition: lsyscache.h:52
double cpu_operator_cost
Definition: costsize.c:108
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:613
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:34
#define Max(x, y)
Definition: c.h:820
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
BlockNumber pages
Definition: relation.h:624
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2928
#define Assert(condition)
Definition: c.h:680
#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:951
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
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:151
double Cost
Definition: nodes.h:643
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1066
BlockNumber revmapNumPages
Definition: brin.h:35
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3044

◆ btcostestimate()

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

Definition at line 6880 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, 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(), STATISTIC_KIND_CORRELATION, STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by bthandler().

6884 {
6885  IndexOptInfo *index = path->indexinfo;
6886  List *qinfos;
6887  GenericCosts costs;
6888  Oid relid;
6889  AttrNumber colnum;
6890  VariableStatData vardata;
6891  double numIndexTuples;
6892  Cost descentCost;
6893  List *indexBoundQuals;
6894  int indexcol;
6895  bool eqQualHere;
6896  bool found_saop;
6897  bool found_is_null_op;
6898  double num_sa_scans;
6899  ListCell *lc;
6900 
6901  /* Do preliminary analysis of indexquals */
6902  qinfos = deconstruct_indexquals(path);
6903 
6904  /*
6905  * For a btree scan, only leading '=' quals plus inequality quals for the
6906  * immediately next attribute contribute to index selectivity (these are
6907  * the "boundary quals" that determine the starting and stopping points of
6908  * the index scan). Additional quals can suppress visits to the heap, so
6909  * it's OK to count them in indexSelectivity, but they should not count
6910  * for estimating numIndexTuples. So we must examine the given indexquals
6911  * to find out which ones count as boundary quals. We rely on the
6912  * knowledge that they are given in index column order.
6913  *
6914  * For a RowCompareExpr, we consider only the first column, just as
6915  * rowcomparesel() does.
6916  *
6917  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6918  * index scans not one, but the ScalarArrayOpExpr's operator can be
6919  * considered to act the same as it normally does.
6920  */
6921  indexBoundQuals = NIL;
6922  indexcol = 0;
6923  eqQualHere = false;
6924  found_saop = false;
6925  found_is_null_op = false;
6926  num_sa_scans = 1;
6927  foreach(lc, qinfos)
6928  {
6929  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6930  RestrictInfo *rinfo = qinfo->rinfo;
6931  Expr *clause = rinfo->clause;
6932  Oid clause_op;
6933  int op_strategy;
6934 
6935  if (indexcol != qinfo->indexcol)
6936  {
6937  /* Beginning of a new column's quals */
6938  if (!eqQualHere)
6939  break; /* done if no '=' qual for indexcol */
6940  eqQualHere = false;
6941  indexcol++;
6942  if (indexcol != qinfo->indexcol)
6943  break; /* no quals at all for indexcol */
6944  }
6945 
6946  if (IsA(clause, ScalarArrayOpExpr))
6947  {
6948  int alength = estimate_array_length(qinfo->other_operand);
6949 
6950  found_saop = true;
6951  /* count up number of SA scans induced by indexBoundQuals only */
6952  if (alength > 1)
6953  num_sa_scans *= alength;
6954  }
6955  else if (IsA(clause, NullTest))
6956  {
6957  NullTest *nt = (NullTest *) clause;
6958 
6959  if (nt->nulltesttype == IS_NULL)
6960  {
6961  found_is_null_op = true;
6962  /* IS NULL is like = for selectivity determination purposes */
6963  eqQualHere = true;
6964  }
6965  }
6966 
6967  /*
6968  * We would need to commute the clause_op if not varonleft, except
6969  * that we only care if it's equality or not, so that refinement is
6970  * unnecessary.
6971  */
6972  clause_op = qinfo->clause_op;
6973 
6974  /* check for equality operator */
6975  if (OidIsValid(clause_op))
6976  {
6977  op_strategy = get_op_opfamily_strategy(clause_op,
6978  index->opfamily[indexcol]);
6979  Assert(op_strategy != 0); /* not a member of opfamily?? */
6980  if (op_strategy == BTEqualStrategyNumber)
6981  eqQualHere = true;
6982  }
6983 
6984  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6985  }
6986 
6987  /*
6988  * If index is unique and we found an '=' clause for each column, we can
6989  * just assume numIndexTuples = 1 and skip the expensive
6990  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6991  * NullTest invalidates that theory, even though it sets eqQualHere.
6992  */
6993  if (index->unique &&
6994  indexcol == index->ncolumns - 1 &&
6995  eqQualHere &&
6996  !found_saop &&
6997  !found_is_null_op)
6998  numIndexTuples = 1.0;
6999  else
7000  {
7001  List *selectivityQuals;
7002  Selectivity btreeSelectivity;
7003 
7004  /*
7005  * If the index is partial, AND the index predicate with the
7006  * index-bound quals to produce a more accurate idea of the number of
7007  * rows covered by the bound conditions.
7008  */
7009  selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
7010 
7011  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
7012  index->rel->relid,
7013  JOIN_INNER,
7014  NULL);
7015  numIndexTuples = btreeSelectivity * index->rel->tuples;
7016 
7017  /*
7018  * As in genericcostestimate(), we have to adjust for any
7019  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
7020  * to integer.
7021  */
7022  numIndexTuples = rint(numIndexTuples / num_sa_scans);
7023  }
7024 
7025  /*
7026  * Now do generic index cost estimation.
7027  */
7028  MemSet(&costs, 0, sizeof(costs));
7029  costs.numIndexTuples = numIndexTuples;
7030 
7031  genericcostestimate(root, path, loop_count, qinfos, &costs);
7032 
7033  /*
7034  * Add a CPU-cost component to represent the costs of initial btree
7035  * descent. We don't charge any I/O cost for touching upper btree levels,
7036  * since they tend to stay in cache, but we still have to do about log2(N)
7037  * comparisons to descend a btree of N leaf tuples. We charge one
7038  * cpu_operator_cost per comparison.
7039  *
7040  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
7041  * ones after the first one are not startup cost so far as the overall
7042  * plan is concerned, so add them only to "total" cost.
7043  */
7044  if (index->tuples > 1) /* avoid computing log(0) */
7045  {
7046  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7047  costs.indexStartupCost += descentCost;
7048  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7049  }
7050 
7051  /*
7052  * Even though we're not charging I/O cost for touching upper btree pages,
7053  * it's still reasonable to charge some CPU cost per page descended
7054  * through. Moreover, if we had no such charge at all, bloated indexes
7055  * would appear to have the same search cost as unbloated ones, at least
7056  * in cases where only a single leaf page is expected to be visited. This
7057  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7058  * touched. The number of such pages is btree tree height plus one (ie,
7059  * we charge for the leaf page too). As above, charge once per SA scan.
7060  */
7061  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
7062  costs.indexStartupCost += descentCost;
7063  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7064 
7065  /*
7066  * If we can get an estimate of the first column's ordering correlation C
7067  * from pg_statistic, estimate the index correlation as C for a
7068  * single-column index, or C * 0.75 for multiple columns. (The idea here
7069  * is that multiple columns dilute the importance of the first column's
7070  * ordering, but don't negate it entirely. Before 8.0 we divided the
7071  * correlation by the number of columns, but that seems too strong.)
7072  */
7073  MemSet(&vardata, 0, sizeof(vardata));
7074 
7075  if (index->indexkeys[0] != 0)
7076  {
7077  /* Simple variable --- look to stats for the underlying table */
7078  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7079 
7080  Assert(rte->rtekind == RTE_RELATION);
7081  relid = rte->relid;
7082  Assert(relid != InvalidOid);
7083  colnum = index->indexkeys[0];
7084 
7086  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7087  {
7088  /*
7089  * The hook took control of acquiring a stats tuple. If it did
7090  * supply a tuple, it'd better have supplied a freefunc.
7091  */
7092  if (HeapTupleIsValid(vardata.statsTuple) &&
7093  !vardata.freefunc)
7094  elog(ERROR, "no function provided to release variable stats with");
7095  }
7096  else
7097  {
7099  ObjectIdGetDatum(relid),
7100  Int16GetDatum(colnum),
7101  BoolGetDatum(rte->inh));
7102  vardata.freefunc = ReleaseSysCache;
7103  }
7104  }
7105  else
7106  {
7107  /* Expression --- maybe there are stats for the index itself */
7108  relid = index->indexoid;
7109  colnum = 1;
7110 
7111  if (get_index_stats_hook &&
7112  (*get_index_stats_hook) (root, relid, colnum, &vardata))
7113  {
7114  /*
7115  * The hook took control of acquiring a stats tuple. If it did
7116  * supply a tuple, it'd better have supplied a freefunc.
7117  */
7118  if (HeapTupleIsValid(vardata.statsTuple) &&
7119  !vardata.freefunc)
7120  elog(ERROR, "no function provided to release variable stats with");
7121  }
7122  else
7123  {
7125  ObjectIdGetDatum(relid),
7126  Int16GetDatum(colnum),
7127  BoolGetDatum(false));
7128  vardata.freefunc = ReleaseSysCache;
7129  }
7130  }
7131 
7132  if (HeapTupleIsValid(vardata.statsTuple))
7133  {
7134  Oid sortop;
7135  AttStatsSlot sslot;
7136 
7137  sortop = get_opfamily_member(index->opfamily[0],
7138  index->opcintype[0],
7139  index->opcintype[0],
7141  if (OidIsValid(sortop) &&
7142  get_attstatsslot(&sslot, vardata.statsTuple,
7145  {
7146  double varCorrelation;
7147 
7148  Assert(sslot.nnumbers == 1);
7149  varCorrelation = sslot.numbers[0];
7150 
7151  if (index->reverse_sort[0])
7152  varCorrelation = -varCorrelation;
7153 
7154  if (index->ncolumns > 1)
7155  costs.indexCorrelation = varCorrelation * 0.75;
7156  else
7157  costs.indexCorrelation = varCorrelation;
7158 
7159  free_attstatsslot(&sslot);
7160  }
7161  }
7162 
7163  ReleaseVariableStats(vardata);
7164 
7165  *indexStartupCost = costs.indexStartupCost;
7166  *indexTotalCost = costs.indexTotalCost;
7167  *indexSelectivity = costs.indexSelectivity;
7168  *indexCorrelation = costs.indexCorrelation;
7169  *indexPages = costs.numIndexPages;
7170 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
IndexOptInfo * indexinfo
Definition: relation.h:1119
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:625
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6858
#define Int16GetDatum(X)
Definition: postgres.h:457
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:877
double Selectivity
Definition: nodes.h:642
double tuples
Definition: relation.h:725
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: relation.h:726
#define OidIsValid(objectId)
Definition: c.h:586
RestrictInfo * rinfo
Definition: selfuncs.h:106
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6490
bool unique
Definition: relation.h:753
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2167
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:138
#define STATISTIC_KIND_CORRELATION
Definition: pg_statistic.h:231
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:108
Cost indexTotalCost
Definition: selfuncs.h:130
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:729
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1842
double indexCorrelation
Definition: selfuncs.h:132
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
NullTestType nulltesttype
Definition: primnodes.h:1188
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:136
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2928
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
Oid * opcintype
Definition: relation.h:733
Cost indexStartupCost
Definition: selfuncs.h:129
Oid * opfamily
Definition: relation.h:732
RTEKind rtekind
Definition: parsenodes.h:951
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:110
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
bool * reverse_sort
Definition: relation.h:735
#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:643
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
Definition: selfuncs.c:6639
double numIndexPages
Definition: selfuncs.h:135
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3044

◆ byte_increment()

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

Definition at line 6214 of file selfuncs.c.

Referenced by make_greater_string().

6215 {
6216  if (*ptr >= 255)
6217  return false;
6218  (*ptr)++;
6219  return true;
6220 }

◆ 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 4442 of file selfuncs.c.

References convert_one_bytea_to_scalar(), DatumGetPointer, i, Min, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by convert_to_scalar().

4448 {
4449  int rangelo,
4450  rangehi,
4451  valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
4452  loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
4453  hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
4454  i,
4455  minlen;
4456  unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
4457  *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
4458  *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4459 
4460  /*
4461  * Assume bytea data is uniformly distributed across all byte values.
4462  */
4463  rangelo = 0;
4464  rangehi = 255;
4465 
4466  /*
4467  * Now strip any common prefix of the three strings.
4468  */
4469  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4470  for (i = 0; i < minlen; i++)
4471  {
4472  if (*lostr != *histr || *lostr != *valstr)
4473  break;
4474  lostr++, histr++, valstr++;
4475  loboundlen--, hiboundlen--, valuelen--;
4476  }
4477 
4478  /*
4479  * Now we can do the conversions.
4480  */
4481  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4482  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4483  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4484 }
#define VARDATA(PTR)
Definition: postgres.h:303
static struct @130 value
#define VARSIZE(PTR)
Definition: postgres.h:304
#define VARHDRSZ
Definition: c.h:503
#define Min(x, y)
Definition: c.h:826
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4487
#define DatumGetPointer(X)
Definition: postgres.h:555
int i

◆ convert_numeric_to_scalar()

static double convert_numeric_to_scalar ( Datum  value,
Oid  typid 
)
static

Definition at line 4150 of file selfuncs.c.

References BOOLOID, DatumGetBool, DatumGetFloat4, DatumGetFloat8, DatumGetInt16, DatumGetInt32, DatumGetInt64, DatumGetObjectId, DirectFunctionCall1, elog, ERROR, FLOAT4OID, FLOAT8OID, INT2OID, INT4OID, INT8OID, numeric_float8_no_overflow(), NUMERICOID, OIDOID, REGCLASSOID, REGCONFIGOID, REGDICTIONARYOID, REGNAMESPACEOID, REGOPERATOROID, REGOPEROID, REGPROCEDUREOID, REGPROCOID, REGROLEOID, and REGTYPEOID.

Referenced by convert_to_scalar().

4151 {
4152  switch (typid)
4153  {
4154  case BOOLOID:
4155  return (double) DatumGetBool(value);
4156  case INT2OID:
4157  return (double) DatumGetInt16(value);
4158  case INT4OID:
4159  return (double) DatumGetInt32(value);
4160  case INT8OID:
4161  return (double) DatumGetInt64(value);
4162  case FLOAT4OID:
4163  return (double) DatumGetFloat4(value);
4164  case FLOAT8OID:
4165  return (double) DatumGetFloat8(value);
4166  case NUMERICOID:
4167  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4168  return (double)
4170  value));
4171  case OIDOID:
4172  case REGPROCOID:
4173  case REGPROCEDUREOID:
4174  case REGOPEROID:
4175  case REGOPERATOROID:
4176  case REGCLASSOID:
4177  case REGTYPEOID:
4178  case REGCONFIGOID:
4179  case REGDICTIONARYOID:
4180  case REGROLEOID:
4181  case REGNAMESPACEOID:
4182  /* we can treat OIDs as integers... */
4183  return (double) DatumGetObjectId(value);
4184  }
4185 
4186  /*
4187  * Can't get here unless someone tries to use scalarineqsel() on an
4188  * operator with one numeric and one non-numeric operand.
4189  */
4190  elog(ERROR, "unsupported type: %u", typid);
4191  return 0;
4192 }
#define REGCLASSOID
Definition: pg_type.h:577
static struct @130 value
#define DatumGetInt32(X)
Definition: postgres.h:478
#define REGROLEOID
Definition: pg_type.h:585
#define OIDOID
Definition: pg_type.h:328
#define NUMERICOID
Definition: pg_type.h:554
#define DatumGetObjectId(X)
Definition: postgres.h:506
#define INT4OID
Definition: pg_type.h:316
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
#define REGTYPEOID
Definition: pg_type.h:581
#define REGOPEROID
Definition: pg_type.h:569
#define ERROR
Definition: elog.h:43
#define DatumGetInt64(X)
Definition: postgres.h:613
#define INT2OID
Definition: pg_type.h:308
#define DatumGetInt16(X)
Definition: postgres.h:450
#define DatumGetBool(X)
Definition: postgres.h:399
#define REGDICTIONARYOID
Definition: pg_type.h:627
#define FLOAT4OID
Definition: pg_type.h:416
#define DatumGetFloat8(X)
Definition: postgres.h:734
#define INT8OID
Definition: pg_type.h:304
#define DatumGetFloat4(X)
Definition: postgres.h:686
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:3194
#define FLOAT8OID
Definition: pg_type.h:419
#define BOOLOID
Definition: pg_type.h:288
#define REGCONFIGOID
Definition: pg_type.h:624
#define elog
Definition: elog.h:219
#define REGPROCEDUREOID
Definition: pg_type.h:565
#define REGNAMESPACEOID
Definition: pg_type.h:589
#define REGOPERATOROID
Definition: pg_type.h:573
#define REGPROCOID
Definition: pg_type.h:320

◆ 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 4487 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

4489 {
4490  double num,
4491  denom,
4492  base;
4493 
4494  if (valuelen <= 0)
4495  return 0.0; /* empty string has scalar value 0 */
4496 
4497  /*
4498  * Since base is 256, need not consider more than about 10 chars (even
4499  * this many seems like overkill)
4500  */
4501  if (valuelen > 10)
4502  valuelen = 10;
4503 
4504  /* Convert initial characters to fraction */
4505  base = rangehi - rangelo + 1;
4506  num = 0.0;
4507  denom = base;
4508  while (valuelen-- > 0)
4509  {
4510  int ch = *value++;
4511 
4512  if (ch < rangelo)
4513  ch = rangelo - 1;
4514  else if (ch > rangehi)
4515  ch = rangehi + 1;
4516  num += ((double) (ch - rangelo)) / denom;
4517  denom *= base;
4518  }
4519 
4520  return num;
4521 }
static struct @130 value

◆ convert_one_string_to_scalar()

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

Definition at line 4295 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4296 {
4297  int slen = strlen(value);
4298  double num,
4299  denom,
4300  base;
4301 
4302  if (slen <= 0)
4303  return 0.0; /* empty string has scalar value 0 */
4304 
4305  /*
4306  * There seems little point in considering more than a dozen bytes from
4307  * the string. Since base is at least 10, that will give us nominal
4308  * resolution of at least 12 decimal digits, which is surely far more
4309  * precision than this estimation technique has got anyway (especially in
4310  * non-C locales). Also, even with the maximum possible base of 256, this
4311  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4312  * overflow on any known machine.
4313  */
4314  if (slen > 12)
4315  slen = 12;
4316 
4317  /* Convert initial characters to fraction */
4318  base = rangehi - rangelo + 1;
4319  num = 0.0;
4320  denom = base;
4321  while (slen-- > 0)
4322  {
4323  int ch = (unsigned char) *value++;
4324 
4325  if (ch < rangelo)
4326  ch = rangelo - 1;
4327  else if (ch > rangehi)
4328  ch = rangehi + 1;
4329  num += ((double) (ch - rangelo)) / denom;
4330  denom *= base;
4331  }
4332 
4333  return num;
4334 }
static struct @130 value

◆ convert_string_datum()

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

Definition at line 4343 of file selfuncs.c.

References Assert, BPCHAROID, CHAROID, DatumGetChar, DatumGetPointer, DEFAULT_COLLATION_OID, elog, ERROR, lc_collate_is_c(), NAMEOID, NameStr, palloc(), pfree(), PG_USED_FOR_ASSERTS_ONLY, pstrdup(), TextDatumGetCString, TEXTOID, val, and VARCHAROID.

Referenced by convert_to_scalar().

4344 {
4345  char *val;
4346 
4347  switch (typid)
4348  {
4349  case CHAROID:
4350  val = (char *) palloc(2);
4351  val[0] = DatumGetChar(value);
4352  val[1] = '\0';
4353  break;
4354  case BPCHAROID:
4355  case VARCHAROID:
4356  case TEXTOID:
4357  val = TextDatumGetCString(value);
4358  break;
4359  case NAMEOID:
4360  {
4362 
4363  val = pstrdup(NameStr(*nm));
4364  break;
4365  }
4366  default:
4367 
4368  /*
4369  * Can't get here unless someone tries to use scalarineqsel() on
4370  * an operator with one string and one non-string operand.
4371  */
4372  elog(ERROR, "unsupported type: %u", typid);
4373  return NULL;
4374  }
4375 
4377  {
4378  char *xfrmstr;
4379  size_t xfrmlen;
4380  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4381 
4382  /*
4383  * XXX: We could guess at a suitable output buffer size and only call
4384  * strxfrm twice if our guess is too small.
4385  *
4386  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4387  * bogus data or set an error. This is not really a problem unless it
4388  * crashes since it will only give an estimation error and nothing
4389  * fatal.
4390  */
4391 #if _MSC_VER == 1400 /* VS.Net 2005 */
4392 
4393  /*
4394  *
4395  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4396  */
4397  {
4398  char x[1];
4399 
4400  xfrmlen = strxfrm(x, val, 0);
4401  }
4402 #else
4403  xfrmlen = strxfrm(NULL, val, 0);
4404 #endif
4405 #ifdef WIN32
4406 
4407  /*
4408  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4409  * of trying to allocate this much memory (and fail), just return the
4410  * original string unmodified as if we were in the C locale.
4411  */
4412  if (xfrmlen == INT_MAX)
4413  return val;
4414 #endif
4415  xfrmstr = (char *) palloc(xfrmlen + 1);
4416  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4417 
4418  /*
4419  * Some systems (e.g., glibc) can return a smaller value from the
4420  * second call than the first; thus the Assert must be <= not ==.
4421  */
4422  Assert(xfrmlen2 <= xfrmlen);
4423  pfree(val);
4424  val = xfrmstr;
4425  }
4426 
4427  return val;
4428 }
#define BPCHAROID
Definition: pg_type.h:504
#define NAMEOID
Definition: pg_type.h:300
static struct @130 value
#define TEXTOID
Definition: pg_type.h:324
char * pstrdup(const char *in)
Definition: mcxt.c:1063
void pfree(void *pointer)
Definition: mcxt.c:936
#define ERROR
Definition: elog.h:43
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1128
Definition: c.h:551
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define VARCHAROID
Definition: pg_type.h:507
#define TextDatumGetCString(d)
Definition: builtins.h:92
#define DatumGetChar(X)
Definition: postgres.h:415
#define CHAROID
Definition: pg_type.h:296
#define Assert(condition)
Definition: c.h:680
#define DatumGetPointer(X)
Definition: postgres.h:555
void * palloc(Size size)
Definition: mcxt.c:835
#define NameStr(name)
Definition: c.h:557
#define elog
Definition: elog.h:219
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:122
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 4215 of file selfuncs.c.

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

4221 {
4222  int rangelo,
4223  rangehi;
4224  char *sptr;
4225 
4226  rangelo = rangehi = (unsigned char) hibound[0];
4227  for (sptr = lobound; *sptr; sptr++)
4228  {
4229  if (rangelo > (unsigned char) *sptr)
4230  rangelo = (unsigned char) *sptr;
4231  if (rangehi < (unsigned char) *sptr)
4232  rangehi = (unsigned char) *sptr;
4233  }
4234  for (sptr = hibound; *sptr; sptr++)
4235  {
4236  if (rangelo > (unsigned char) *sptr)
4237  rangelo = (unsigned char) *sptr;
4238  if (rangehi < (unsigned char) *sptr)
4239  rangehi = (unsigned char) *sptr;
4240  }
4241  /* If range includes any upper-case ASCII chars, make it include all */
4242  if (rangelo <= 'Z' && rangehi >= 'A')
4243  {
4244  if (rangelo > 'A')
4245  rangelo = 'A';
4246  if (rangehi < 'Z')
4247  rangehi = 'Z';
4248  }
4249  /* Ditto lower-case */
4250  if (rangelo <= 'z' && rangehi >= 'a')
4251  {
4252  if (rangelo > 'a')
4253  rangelo = 'a';
4254  if (rangehi < 'z')
4255  rangehi = 'z';
4256  }
4257  /* Ditto digits */
4258  if (rangelo <= '9' && rangehi >= '0')
4259  {
4260  if (rangelo > '0')
4261  rangelo = '0';
4262  if (rangehi < '9')
4263  rangehi = '9';
4264  }
4265 
4266  /*
4267  * If range includes less than 10 chars, assume we have not got enough
4268  * data, and make it include regular ASCII set.
4269  */
4270  if (rangehi - rangelo < 9)
4271  {
4272  rangelo = ' ';
4273  rangehi = 127;
4274  }
4275 
4276  /*
4277  * Now strip any common prefix of the three strings.
4278  */
4279  while (*lobound)
4280  {
4281  if (*lobound != *hibound || *lobound != *value)
4282  break;
4283  lobound++, hibound++, value++;
4284  }
4285 
4286  /*
4287  * Now we can do the conversions.
4288  */
4289  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4290  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4291  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4292 }
static struct @130 value
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4295

◆ convert_timevalue_to_scalar()

static double convert_timevalue_to_scalar ( Datum  value,
Oid  typid 
)
static

Definition at line 4527 of file selfuncs.c.

References abstime_timestamp(), ABSTIMEOID, TimeIntervalData::data, date2timestamp_no_overflow(), DATEOID, DatumGetDateADT, DatumGetIntervalP, DatumGetRelativeTime, DatumGetTimeADT, DatumGetTimeInterval, DatumGetTimestamp, DatumGetTimestampTz, DatumGetTimeTzADTP, Interval::day, DAYS_PER_YEAR, DirectFunctionCall1, elog, ERROR, INTERVALOID, Interval::month, MONTHS_PER_YEAR, RELTIMEOID, TimeIntervalData::status, TimeTzADT::time, Interval::time, TIMEOID, TIMESTAMPOID, TIMESTAMPTZOID, TIMETZOID, TINTERVALOID, USECS_PER_DAY, and TimeTzADT::zone.

Referenced by convert_to_scalar().

4528 {
4529  switch (typid)
4530  {
4531  case TIMESTAMPOID:
4532  return DatumGetTimestamp(value);
4533  case TIMESTAMPTZOID:
4534  return DatumGetTimestampTz(value);
4535  case ABSTIMEOID:
4537  value));
4538  case DATEOID:
4540  case INTERVALOID:
4541  {
4543 
4544  /*
4545  * Convert the month part of Interval to days using assumed
4546  * average month length of 365.25/12.0 days. Not too
4547  * accurate, but plenty good enough for our purposes.
4548  */
4549  return interval->time + interval->day * (double) USECS_PER_DAY +
4550  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4551  }
4552  case RELTIMEOID:
4553  return (DatumGetRelativeTime(value) * 1000000.0);
4554  case TINTERVALOID:
4555  {
4557 
4558  if (tinterval->status != 0)
4559  return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4560  return 0; /* for lack of a better idea */
4561  }
4562  case TIMEOID:
4563  return DatumGetTimeADT(value);
4564  case TIMETZOID:
4565  {
4566  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4567 
4568  /* use GMT-equivalent time */
4569  return (double) (timetz->time + (timetz->zone * 1000000.0));
4570  }
4571  }
4572 
4573  /*
4574  * Can't get here unless someone tries to use scalarineqsel() on an
4575  * operator with one timevalue and one non-timevalue operand.
4576  */
4577  elog(ERROR, "unsupported type: %u", typid);
4578  return 0;
4579 }
#define TIMESTAMPTZOID
Definition: pg_type.h:525
#define TIMEOID
Definition: pg_type.h:514
#define DATEOID
Definition: pg_type.h:511
#define DatumGetDateADT(X)
Definition: date.h:52
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
static struct @130 value
TimeADT time
Definition: date.h:28
#define DatumGetTimeTzADTP(X)
Definition: date.h:54
#define TINTERVALOID
Definition: pg_type.h:428
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:658
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
int32 day
Definition: timestamp.h:47
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define DAYS_PER_YEAR
Definition: timestamp.h:68
#define TIMESTAMPOID
Definition: pg_type.h:519
#define ERROR
Definition: elog.h:43
int32 zone
Definition: date.h:29
#define DatumGetRelativeTime(X)
Definition: nabstime.h:51
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
#define INTERVALOID
Definition: pg_type.h:529
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:53
AbsoluteTime data[2]
Definition: nabstime.h:42
#define TIMETZOID
Definition: pg_type.h:536
#define DatumGetTimeInterval(X)
Definition: nabstime.h:52
#define elog
Definition: elog.h:219
#define ABSTIMEOID
Definition: pg_type.h:422
Definition: date.h:26
#define DatumGetTimestamp(X)
Definition: timestamp.h:27
#define RELTIMEOID
Definition: pg_type.h:425

◆ 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 4032 of file selfuncs.c.

References ABSTIMEOID, BOOLOID, BPCHAROID, BYTEAOID, CHAROID, CIDROID, convert_bytea_to_scalar(), convert_network_to_scalar(), convert_numeric_to_scalar(), convert_string_datum(), convert_string_to_scalar(), convert_timevalue_to_scalar(), DATEOID, FLOAT4OID, FLOAT8OID, INETOID, INT2OID, INT4OID, INT8OID, INTERVALOID, MACADDR8OID, MACADDROID, NAMEOID, NUMERICOID, OIDOID, pfree(), REGCLASSOID, REGCONFIGOID, REGDICTIONARYOID, REGNAMESPACEOID, REGOPERATOROID, REGOPEROID, REGPROCEDUREOID, REGPROCOID, REGROLEOID, REGTYPEOID, RELTIMEOID, TEXTOID, TIMEOID, TIMESTAMPOID, TIMESTAMPTZOID, TIMETZOID, TINTERVALOID, and VARCHAROID.

Referenced by ineq_histogram_selectivity().

4035 {
4036  /*
4037  * Both the valuetypid and the boundstypid should exactly match the
4038  * declared input type(s) of the operator we are invoked for, so we just
4039  * error out if either is not recognized.
4040  *
4041  * XXX The histogram we are interpolating between points of could belong
4042  * to a column that's only binary-compatible with the declared type. In
4043  * essence we are assuming that the semantics of binary-compatible types
4044  * are enough alike that we can use a histogram generated with one type's
4045  * operators to estimate selectivity for the other's. This is outright
4046  * wrong in some cases --- in particular signed versus unsigned
4047  * interpretation could trip us up. But it's useful enough in the
4048  * majority of cases that we do it anyway. Should think about more
4049  * rigorous ways to do it.
4050  */
4051  switch (valuetypid)
4052  {
4053  /*
4054  * Built-in numeric types
4055  */
4056  case BOOLOID:
4057  case INT2OID:
4058  case INT4OID:
4059  case INT8OID:
4060  case FLOAT4OID:
4061  case FLOAT8OID:
4062  case NUMERICOID:
4063  case OIDOID:
4064  case REGPROCOID:
4065  case REGPROCEDUREOID:
4066  case REGOPEROID:
4067  case REGOPERATOROID:
4068  case REGCLASSOID:
4069  case REGTYPEOID:
4070  case REGCONFIGOID:
4071  case REGDICTIONARYOID:
4072  case REGROLEOID:
4073  case REGNAMESPACEOID:
4074  *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
4075  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
4076  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
4077  return true;
4078 
4079  /*
4080  * Built-in string types
4081  */
4082  case CHAROID:
4083  case BPCHAROID:
4084  case VARCHAROID:
4085  case TEXTOID:
4086  case NAMEOID:
4087  {
4088  char *valstr = convert_string_datum(value, valuetypid);
4089  char *lostr = convert_string_datum(lobound, boundstypid);
4090  char *histr = convert_string_datum(hibound, boundstypid);
4091 
4092  convert_string_to_scalar(valstr, scaledvalue,
4093  lostr, scaledlobound,
4094  histr, scaledhibound);
4095  pfree(valstr);
4096  pfree(lostr);
4097  pfree(histr);
4098  return true;
4099  }
4100 
4101  /*
4102  * Built-in bytea type
4103  */
4104  case BYTEAOID:
4105  {
4106  convert_bytea_to_scalar(value, scaledvalue,
4107  lobound, scaledlobound,
4108  hibound, scaledhibound);
4109  return true;
4110  }
4111 
4112  /*
4113  * Built-in time types
4114  */
4115  case TIMESTAMPOID:
4116  case TIMESTAMPTZOID:
4117  case ABSTIMEOID:
4118  case DATEOID:
4119  case INTERVALOID:
4120  case RELTIMEOID:
4121  case TINTERVALOID:
4122  case TIMEOID:
4123  case TIMETZOID:
4124  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
4125  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
4126  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
4127  return true;
4128 
4129  /*
4130  * Built-in network types
4131  */
4132  case INETOID:
4133  case CIDROID:
4134  case MACADDROID:
4135  case MACADDR8OID:
4136  *scaledvalue = convert_network_to_scalar(value, valuetypid);
4137  *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
4138  *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
4139  return true;
4140  }
4141  /* Don't know how to convert */
4142  *scaledvalue = *scaledlobound = *scaledhibound = 0;
4143  return false;
4144 }
#define CIDROID
Definition: pg_type.h:451
#define TIMESTAMPTZOID
Definition: pg_type.h:525
#define TIMEOID
Definition: pg_type.h:514
#define REGCLASSOID
Definition: pg_type.h:577
#define BPCHAROID
Definition: pg_type.h:504
#define DATEOID
Definition: pg_type.h:511
#define NAMEOID
Definition: pg_type.h:300
static struct @130 value
#define REGROLEOID
Definition: pg_type.h:585
#define OIDOID
Definition: pg_type.h:328
#define TEXTOID
Definition: pg_type.h:324
#define INETOID
Definition: pg_type.h:448
#define NUMERICOID
Definition: pg_type.h:554
static double convert_numeric_to_scalar(Datum value, Oid typid)
Definition: selfuncs.c:4150
#define INT4OID
Definition: pg_type.h:316
#define TINTERVALOID
Definition: pg_type.h:428
#define REGTYPEOID
Definition: pg_type.h:581
#define REGOPEROID
Definition: pg_type.h:569
void pfree(void *pointer)
Definition: mcxt.c:936
#define TIMESTAMPOID
Definition: pg_type.h:519
double convert_network_to_scalar(Datum value, Oid typid)
Definition: network.c:907
#define INT2OID
Definition: pg_type.h:308
#define INTERVALOID
Definition: pg_type.h:529
#define REGDICTIONARYOID
Definition: pg_type.h:627
#define VARCHAROID
Definition: pg_type.h:507
#define FLOAT4OID
Definition: pg_type.h:416
#define CHAROID
Definition: pg_type.h:296
#define INT8OID
Definition: pg_type.h:304
static char * convert_string_datum(Datum value, Oid typid)
Definition: selfuncs.c:4343
#define TIMETZOID
Definition: pg_type.h:536
#define FLOAT8OID
Definition: pg_type.h:419
#define BOOLOID
Definition: pg_type.h:288
static double convert_timevalue_to_scalar(Datum value, Oid typid)
Definition: selfuncs.c:4527
#define BYTEAOID
Definition: pg_type.h:292
#define REGCONFIGOID
Definition: pg_type.h:624
#define MACADDR8OID
Definition: pg_type.h:454
static void convert_bytea_to_scalar(Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
Definition: selfuncs.c:4442
#define MACADDROID
Definition: pg_type.h:445
#define REGPROCEDUREOID
Definition: pg_type.h:565
#define ABSTIMEOID
Definition: pg_type.h:422
#define REGNAMESPACEOID
Definition: pg_type.h:589
static void convert_string_to_scalar(char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
Definition: selfuncs.c:4215
#define REGOPERATOROID
Definition: pg_type.h:573
#define REGPROCOID
Definition: pg_type.h:320
#define RELTIMEOID
Definition: pg_type.h:425

◆ deconstruct_indexquals()

List* deconstruct_indexquals ( IndexPath path)

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

6491 {
6492  List *result = NIL;
6493  IndexOptInfo *index = path->indexinfo;
6494  ListCell *lcc,
6495  *lci;
6496 
6497  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6498  {
6499  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6500  int indexcol = lfirst_int(lci);
6501  Expr *clause;
6502  Node *leftop,
6503  *rightop;
6504  IndexQualInfo *qinfo;
6505 
6506  clause = rinfo->clause;
6507 
6508  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6509  qinfo->rinfo = rinfo;
6510  qinfo->indexcol = indexcol;
6511 
6512  if (IsA(clause, OpExpr))
6513  {
6514  qinfo->clause_op = ((OpExpr *) clause)->opno;
6515  leftop = get_leftop(clause);
6516  rightop = get_rightop(clause);
6517  if (match_index_to_operand(leftop, indexcol, index))
6518  {
6519  qinfo->varonleft = true;
6520  qinfo->other_operand = rightop;
6521  }
6522  else
6523  {
6524  Assert(match_index_to_operand(rightop, indexcol, index));
6525  qinfo->varonleft = false;
6526  qinfo->other_operand = leftop;
6527  }
6528  }
6529  else if (IsA(clause, RowCompareExpr))
6530  {
6531  RowCompareExpr *rc = (RowCompareExpr *) clause;
6532 
6533  qinfo->clause_op = linitial_oid(rc->opnos);
6534  /* Examine only first columns to determine left/right sides */
6536  indexcol, index))
6537  {
6538  qinfo->varonleft = true;
6539  qinfo->other_operand = (Node *) rc->rargs;
6540  }
6541  else
6542  {
6544  indexcol, index));
6545  qinfo->varonleft = false;
6546  qinfo->other_operand = (Node *) rc->largs;
6547  }
6548  }
6549  else if (IsA(clause, ScalarArrayOpExpr))
6550  {
6551  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6552 
6553  qinfo->clause_op = saop->opno;
6554  /* index column is always on the left in this case */
6556  indexcol, index));
6557  qinfo->varonleft = true;
6558  qinfo->other_operand = (Node *) lsecond(saop->args);
6559  }
6560  else if (IsA(clause, NullTest))
6561  {
6562  qinfo->clause_op = InvalidOid;
6563  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6564  indexcol, index));
6565  qinfo->varonleft = true;
6566  qinfo->other_operand = NULL;
6567  }
6568  else
6569  {
6570  elog(ERROR, "unsupported indexqual type: %d",
6571  (int) nodeTag(clause));
6572  }
6573 
6574  result = lappend(result, qinfo);
6575  }
6576  return result;
6577 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
IndexOptInfo * indexinfo
Definition: relation.h:1119
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3180
Definition: nodes.h:512
RestrictInfo * rinfo
Definition: selfuncs.h:106
#define lsecond(l)
Definition: pg_list.h:116
Definition: type.h:89
List * indexquals
Definition: relation.h:1121
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
Node * get_leftop(const Expr *clause)
Definition: clauses.c:202
#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:1842
bool varonleft
Definition: selfuncs.h:108
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:680
#define linitial_oid(l)
Definition: pg_list.h:113
#define nodeTag(nodeptr)
Definition: nodes.h:517
Node * get_rightop(const Expr *clause)
Definition: clauses.c:219
List * indexqualcols
Definition: relation.h:1122
void * palloc(Size size)
Definition: mcxt.c:835
Node * other_operand
Definition: selfuncs.h:110
void * arg
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

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

2273 {
2274  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2275  Oid operator = PG_GETARG_OID(1);
2276  List *args = (List *) PG_GETARG_POINTER(2);
2277 
2278 #ifdef NOT_USED
2279  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2280 #endif
2282  double selec;
2283  VariableStatData vardata1;
2284  VariableStatData vardata2;
2285  bool join_is_reversed;
2286  RelOptInfo *inner_rel;
2287 
2288  get_join_variables(root, args, sjinfo,
2289  &vardata1, &vardata2, &join_is_reversed);
2290 
2291  switch (sjinfo->jointype)
2292  {
2293  case JOIN_INNER:
2294  case JOIN_LEFT:
2295  case JOIN_FULL:
2296  selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2297  break;
2298  case JOIN_SEMI:
2299  case JOIN_ANTI:
2300 
2301  /*
2302  * Look up the join's inner relation. min_righthand is sufficient
2303  * information because neither SEMI nor ANTI joins permit any
2304  * reassociation into or out of their RHS, so the righthand will
2305  * always be exactly that set of rels.
2306  */
2307  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2308 
2309  if (!join_is_reversed)
2310  selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
2311  inner_rel);
2312  else
2313  selec = eqjoinsel_semi(get_commutator(operator),
2314  &vardata2, &vardata1,
2315  inner_rel);
2316  break;
2317  default:
2318  /* other values not expected here */
2319  elog(ERROR, "unrecognized join type: %d",
2320  (int) sjinfo->jointype);
2321  selec = 0; /* keep compiler quiet */
2322  break;
2323  }
2324 
2325  ReleaseVariableStats(vardata1);
2326  ReleaseVariableStats(vardata2);
2327 
2328  CLAMP_PROBABILITY(selec);
2329 
2330  PG_RETURN_FLOAT8((float8) selec);
2331 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Relids min_righthand
Definition: relation.h:2015
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:326
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:241
unsigned int Oid
Definition: postgres_ext.h:31
JoinType
Definition: nodes.h:676
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:439
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4666
#define PG_GETARG_OID(n)
Definition: fmgr.h:240
static double eqjoinsel_semi(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2, RelOptInfo *inner_rel)
Definition: selfuncs.c:2557
#define PG_GETARG_INT16(n)
Definition: fmgr.h:236
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:5641
JoinType jointype
Definition: relation.h:2018
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
static double eqjoinsel_inner(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2)
Definition: selfuncs.c:2340
#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 2340 of file selfuncs.c.

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

Referenced by eqjoinsel().

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

◆ eqjoinsel_semi()

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

Definition at line 2557 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool, DEFAULT_COLLATION_OID, 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_KIND_MCV, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by eqjoinsel().

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

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 230 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

231 {
232  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
233 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:326
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:239
double float8
Definition: c.h:439

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

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

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

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

Definition at line 2167 of file selfuncs.c.

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

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

2168 {
2169  /* look through any binary-compatible relabeling of arrayexpr */
2170  arrayexpr = strip_array_coercion(arrayexpr);
2171 
2172  if (arrayexpr && IsA(arrayexpr, Const))
2173  {
2174  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2175  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2176  ArrayType *arrayval;
2177 
2178  if (arrayisnull)
2179  return 0;
2180  arrayval = DatumGetArrayTypeP(arraydatum);
2181  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2182  }
2183  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2184  !((ArrayExpr *) arrayexpr)->multidims)
2185  {
2186  return list_length(((ArrayExpr *) arrayexpr)->elements);
2187  }
2188  else
2189  {
2190  /* default guess --- see also scalararraysel */
2191  return 10;
2192  }
2193 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:279
uintptr_t Datum
Definition: postgres.h:372
static int list_length(const List *l)
Definition: pg_list.h:89
#define ARR_NDIM(a)
Definition: array.h:275
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1815
#define DatumGetArrayTypeP(X)
Definition: array.h:246

◆ estimate_hash_bucket_stats()

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

Definition at line 3761 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

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

◆ estimate_multivariate_ndistinct()

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

Definition at line 3885 of file selfuncs.c.

References Assert, 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, STATS_EXT_NDISTINCT, and GroupVarInfo::var.

Referenced by estimate_num_groups().

3887 {
3888  ListCell *lc;
3889  Bitmapset *attnums = NULL;
3890  int nmatches;
3891  Oid statOid = InvalidOid;
3892  MVNDistinct *stats;
3893  Bitmapset *matched = NULL;
3894 
3895  /* bail out immediately if the table has no extended statistics */
3896  if (!rel->statlist)
3897  return false;
3898 
3899  /* Determine the attnums we're looking for */
3900  foreach(lc, *varinfos)
3901  {
3902  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3903 
3904  Assert(varinfo->rel == rel);
3905 
3906  if (IsA(varinfo->var, Var))
3907  {
3908  attnums = bms_add_member(attnums,
3909  ((Var *) varinfo->var)->varattno);
3910  }
3911  }
3912 
3913  /* look for the ndistinct statistics matching the most vars */
3914  nmatches = 1; /* we require at least two matches */
3915  foreach(lc, rel->statlist)
3916  {
3917  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3918  Bitmapset *shared;
3919  int nshared;
3920 
3921  /* skip statistics of other kinds */
3922  if (info->kind != STATS_EXT_NDISTINCT)
3923  continue;
3924 
3925  /* compute attnums shared by the vars and the statistics object */
3926  shared = bms_intersect(info->keys, attnums);
3927  nshared = bms_num_members(shared);
3928 
3929  /*
3930  * Does this statistics object match more columns than the currently
3931  * best object? If so, use this one instead.
3932  *
3933  * XXX This should break ties using name of the object, or something
3934  * like that, to make the outcome stable.
3935  */
3936  if (nshared > nmatches)
3937  {
3938  statOid = info->statOid;
3939  nmatches = nshared;
3940  matched = shared;
3941  }
3942  }
3943 
3944  /* No match? */
3945  if (statOid == InvalidOid)
3946  return false;
3947  Assert(nmatches > 1 && matched != NULL);
3948 
3949  stats = statext_ndistinct_load(statOid);
3950 
3951  /*
3952  * If we have a match, search it for the specific item that matches (there
3953  * must be one), and construct the output values.
3954  */
3955  if (stats)
3956  {
3957  int i;
3958  List *newlist = NIL;
3959  MVNDistinctItem *item = NULL;
3960 
3961  /* Find the specific item that exactly matches the combination */
3962  for (i = 0; i < stats->nitems; i++)
3963  {
3964  MVNDistinctItem *tmpitem = &stats->items[i];
3965 
3966  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3967  {
3968  item = tmpitem;
3969  break;
3970  }
3971  }
3972 
3973  /* make sure we found an item */
3974  if (!item)
3975  elog(ERROR, "corrupt MVNDistinct entry");
3976 
3977  /* Form the output varinfo list, keeping only unmatched ones */
3978  foreach(lc, *varinfos)
3979  {
3980  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3981  AttrNumber attnum;
3982 
3983  if (!IsA(varinfo->var, Var))
3984  {
3985  newlist = lappend(newlist, varinfo);
3986  continue;
3987  }
3988 
3989  attnum = ((Var *) varinfo->var)->varattno;
3990  if (!bms_is_member(attnum, matched))
3991  newlist = lappend(newlist, varinfo);
3992  }
3993 
3994  *varinfos = newlist;
3995  *ndistinct = item->ndistinct;
3996  return true;
3997  }
3998 
3999  return false;
4000 }
#define NIL
Definition: pg_list.h:69
#define STATS_EXT_NDISTINCT
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
List * statlist
Definition: relation.h:623
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:163
#define ERROR
Definition: elog.h:43
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:649
Node * var
Definition: selfuncs.c:3274
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:296
#define InvalidOid
Definition: postgres_ext.h:36
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:389
#define Assert(condition)
Definition: c.h:680
#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:742
Bitmapset * keys
Definition: relation.h:813
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:464
int16 AttrNumber
Definition: attnum.h:21
RelOptInfo * rel
Definition: selfuncs.c:3275

◆ estimate_num_groups()

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

Definition at line 3398 of file selfuncs.c.

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

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

◆ examine_simple_variable()

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

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

4941 {
4942  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4943 
4944  Assert(IsA(rte, RangeTblEntry));
4945 
4947  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4948  {
4949  /*
4950  * The hook took control of acquiring a stats tuple. If it did supply
4951  * a tuple, it'd better have supplied a freefunc.
4952  */
4953  if (HeapTupleIsValid(vardata->statsTuple) &&
4954  !vardata->freefunc)
4955  elog(ERROR, "no function provided to release variable stats with");
4956  }
4957  else if (rte->rtekind == RTE_RELATION)
4958  {
4959  /*
4960  * Plain table or parent of an inheritance appendrel, so look up the
4961  * column in pg_statistic
4962  */
4964  ObjectIdGetDatum(rte->relid),
4965  Int16GetDatum(var->varattno),
4966  BoolGetDatum(rte->inh));
4967  vardata->freefunc = ReleaseSysCache;
4968 
4969  if (HeapTupleIsValid(vardata->statsTuple))
4970  {
4971  /* check if user has permission to read this column */
4972  vardata->acl_ok =
4974  ACL_SELECT) == ACLCHECK_OK) ||
4976  ACL_SELECT) == ACLCHECK_OK);
4977  }
4978  else
4979  {
4980  /* suppress any possible leakproofness checks later */
4981  vardata->acl_ok = true;
4982  }
4983  }
4984  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4985  {
4986  /*
4987  * Plain subquery (not one that was converted to an appendrel).
4988  */
4989  Query *subquery = rte->subquery;
4990  RelOptInfo *rel;
4991  TargetEntry *ste;
4992 
4993  /*
4994  * Punt if it's a whole-row var rather than a plain column reference.
4995  */
4996  if (var->varattno == InvalidAttrNumber)
4997  return;
4998 
4999  /*
5000  * Punt if subquery uses set operations or GROUP BY, as these will
5001  * mash underlying columns' stats beyond recognition. (Set ops are
5002  * particularly nasty; if we forged ahead, we would return stats
5003  * relevant to only the leftmost subselect...) DISTINCT is also
5004  * problematic, but we check that later because there is a possibility
5005  * of learning something even with it.
5006  */
5007  if (subquery->setOperations ||
5008  subquery->groupClause)
5009  return;
5010 
5011  /*
5012  * OK, fetch RelOptInfo for subquery. Note that we don't change the
5013  * rel returned in vardata, since caller expects it to be a rel of the
5014  * caller's query level. Because we might already be recursing, we
5015  * can't use that rel pointer either, but have to look up the Var's
5016  * rel afresh.
5017  */
5018  rel = find_base_rel(root, var->varno);
5019 
5020  /* If the subquery hasn't been planned yet, we have to punt */
5021  if (rel->subroot == NULL)
5022  return;
5023  Assert(IsA(rel->subroot, PlannerInfo));
5024 
5025  /*
5026  * Switch our attention to the subquery as mangled by the planner. It
5027  * was okay to look at the pre-planning version for the tests above,
5028  * but now we need a Var that will refer to the subroot's live
5029  * RelOptInfos. For instance, if any subquery pullup happened during
5030  * planning, Vars in the targetlist might have gotten replaced, and we
5031  * need to see the replacement expressions.
5032  */
5033  subquery = rel->subroot->parse;
5034  Assert(IsA(subquery, Query));
5035 
5036  /* Get the subquery output expression referenced by the upper Var */
5037  ste = get_tle_by_resno(subquery->targetList, var->varattno);
5038  if (ste == NULL || ste->resjunk)
5039  elog(ERROR, "subquery %s does not have attribute %d",
5040  rte->eref->aliasname, var->varattno);
5041  var = (Var *) ste->expr;
5042 
5043  /*
5044  * If subquery uses DISTINCT, we can't make use of any stats for the
5045  * variable ... but, if it's the only DISTINCT column, we are entitled
5046  * to consider it unique. We do the test this way so that it works
5047  * for cases involving DISTINCT ON.
5048  */
5049  if (subquery->distinctClause)
5050  {
5051  if (list_length(subquery->distinctClause) == 1 &&
5052  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5053  vardata->isunique = true;
5054  /* cannot go further */
5055  return;
5056  }
5057 
5058  /*
5059  * If the sub-query originated from a view with the security_barrier
5060  * attribute, we must not look at the variable's statistics, though it
5061  * seems all right to notice the existence of a DISTINCT clause. So
5062  * stop here.
5063  *
5064  * This is probably a harsher restriction than necessary; it's
5065  * certainly OK for the selectivity estimator (which is a C function,
5066  * and therefore omnipotent anyway) to look at the statistics. But
5067  * many selectivity estimators will happily *invoke the operator
5068  * function* to try to work out a good estimate - and that's not OK.
5069  * So for now, don't dig down for stats.
5070  */
5071  if (rte->security_barrier)
5072  return;
5073 
5074  /* Can only handle a simple Var of subquery's query level */
5075  if (var && IsA(var, Var) &&
5076  var->varlevelsup == 0)
5077  {
5078  /*
5079  * OK, recurse into the subquery. Note that the original setting
5080  * of vardata->isunique (which will surely be false) is left
5081  * unchanged in this situation. That's what we want, since even
5082  * if the underlying column is unique, the subquery may have
5083  * joined to other tables in a way that creates duplicates.
5084  */
5085  examine_simple_variable(rel->subroot, var, vardata);
5086  }
5087  }
5088  else
5089  {
5090  /*
5091  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
5092  * won't see RTE_JOIN here because join alias Vars have already been
5093  * flattened.) There's not much we can do with function outputs, but
5094  * maybe someday try to be smarter about VALUES and/or CTEs.
5095  */
5096  }
5097 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
Query * parse
Definition: relation.h:155
Index varlevelsup
Definition: primnodes.h:173
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4366
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
#define Int16GetDatum(X)
Definition: postgres.h:457
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4939
List * targetList
Definition: parsenodes.h:138
PlannerInfo * subroot
Definition: relation.h:627
bool resjunk
Definition: primnodes.h:1382
List * distinctClause
Definition: parsenodes.h:154
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:188
Index varno
Definition: primnodes.h:166
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:73
bool security_barrier
Definition: parsenodes.h:975
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:680
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1375
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:4480
RTEKind rtekind
Definition: parsenodes.h:951
Node * setOperations
Definition: parsenodes.h:163
Query * subquery
Definition: parsenodes.h:974
List * groupClause
Definition: parsenodes.h:146
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1055
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277

◆ examine_variable()

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

Definition at line 4728 of file selfuncs.c.

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

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

4730 {
4731  Node *basenode;
4732  Relids varnos;
4733  RelOptInfo *onerel;
4734 
4735  /* Make sure we don't return dangling pointers in vardata */
4736  MemSet(vardata, 0, sizeof(VariableStatData));
4737 
4738  /* Save the exposed type of the expression */
4739  vardata->vartype = exprType(node);
4740 
4741  /* Look inside any binary-compatible relabeling */
4742 
4743  if (IsA(node, RelabelType))
4744  basenode = (Node *) ((RelabelType *) node)->arg;
4745  else
4746  basenode = node;
4747 
4748  /* Fast path for a simple Var */
4749 
4750  if (IsA(basenode, Var) &&
4751  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4752  {
4753  Var *var = (Var *) basenode;
4754 
4755  /* Set up result fields other than the stats tuple */
4756  vardata->var = basenode; /* return Var without relabeling */
4757  vardata->rel = find_base_rel(root, var->varno);
4758  vardata->atttype = var->vartype;
4759  vardata->atttypmod = var->vartypmod;
4760  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4761 
4762  /* Try to locate some stats */
4763  examine_simple_variable(root, var, vardata);
4764 
4765  return;
4766  }
4767 
4768  /*
4769  * Okay, it's a more complicated expression. Determine variable
4770  * membership. Note that when varRelid isn't zero, only vars of that
4771  * relation are considered "real" vars.
4772  */
4773  varnos = pull_varnos(basenode);
4774 
4775  onerel = NULL;
4776 
4777  switch (bms_membership(varnos))
4778  {
4779  case BMS_EMPTY_SET:
4780  /* No Vars at all ... must be pseudo-constant clause */
4781  break;
4782  case BMS_SINGLETON:
4783  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4784  {
4785  onerel = find_base_rel(root,
4786  (varRelid ? varRelid : bms_singleton_member(varnos)));
4787  vardata->rel = onerel;
4788  node = basenode; /* strip any relabeling */
4789  }
4790  /* else treat it as a constant */
4791  break;
4792  case BMS_MULTIPLE:
4793  if (varRelid == 0)
4794  {
4795  /* treat it as a variable of a join relation */
4796  vardata->rel = find_join_rel(root, varnos);
4797  node = basenode; /* strip any relabeling */
4798  }
4799  else if (bms_is_member(varRelid, varnos))
4800  {
4801  /* ignore the vars belonging to other relations */
4802  vardata->rel = find_base_rel(root, varRelid);
4803  node = basenode; /* strip any relabeling */
4804  /* note: no point in expressional-index search here */
4805  }
4806  /* else treat it as a constant */
4807  break;
4808  }
4809 
4810  bms_free(varnos);
4811 
4812  vardata->var = node;
4813  vardata->atttype = exprType(node);
4814  vardata->atttypmod = exprTypmod(node);
4815 
4816  if (onerel)
4817  {
4818  /*
4819  * We have an expression in vars of a single relation. Try to match
4820  * it to expressional index columns, in hopes of finding some
4821  * statistics.
4822  *
4823  * XXX it's conceivable that there are multiple matches with different
4824  * index opfamilies; if so, we need to pick one that matches the
4825  * operator we are estimating for. FIXME later.
4826  */
4827  ListCell *ilist;
4828 
4829  foreach(ilist, onerel->indexlist)
4830  {
4831  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4832  ListCell *indexpr_item;
4833  int pos;
4834 
4835  indexpr_item = list_head(index->indexprs);
4836  if (indexpr_item == NULL)
4837  continue; /* no expressions here... */
4838 
4839  for (pos = 0; pos < index->ncolumns; pos++)
4840  {
4841  if (index->indexkeys[pos] == 0)
4842  {
4843  Node *indexkey;
4844 
4845  if (indexpr_item == NULL)
4846  elog(ERROR, "too few entries in indexprs list");
4847  indexkey = (Node *) lfirst(indexpr_item);
4848  if (indexkey && IsA(indexkey, RelabelType))
4849  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4850  if (equal(node, indexkey))
4851  {
4852  /*
4853  * Found a match ... is it a unique index? Tests here
4854  * should match has_unique_index().
4855  */
4856  if (index->unique &&
4857  index->ncolumns == 1 &&
4858  (index->indpred == NIL || index->predOK))
4859  vardata->isunique = true;
4860 
4861  /*
4862  * Has it got stats? We only consider stats for
4863  * non-partial indexes, since partial indexes probably
4864  * don't reflect whole-relation statistics; the above
4865  * check for uniqueness is the only info we take from
4866  * a partial index.
4867  *
4868  * An index stats hook, however, must make its own
4869  * decisions about what to do with partial indexes.
4870  */
4871  if (get_index_stats_hook &&
4872  (*get_index_stats_hook) (root, index->indexoid,
4873  pos + 1, vardata))
4874  {
4875  /*
4876  * The hook took control of acquiring a stats
4877  * tuple. If it did supply a tuple, it'd better
4878  * have supplied a freefunc.
4879  */
4880  if (HeapTupleIsValid(vardata->statsTuple) &&
4881  !vardata->freefunc)
4882  elog(ERROR, "no function provided to release variable stats with");
4883  }
4884  else if (index->indpred == NIL)
4885  {
4886  vardata->statsTuple =
4888  ObjectIdGetDatum(index->indexoid),
4889  Int16GetDatum(pos + 1),
4890  BoolGetDatum(false));
4891  vardata->freefunc = ReleaseSysCache;
4892 
4893  if (HeapTupleIsValid(vardata->statsTuple))
4894  {
4895  /* Get index's table for permission check */
4896  RangeTblEntry *rte;
4897 
4898  rte = planner_rt_fetch(index->rel->relid, root);
4899  Assert(rte->rtekind == RTE_RELATION);
4900 
4901  /*
4902  * For simplicity, we insist on the whole
4903  * table being selectable, rather than trying
4904  * to identify which column(s) the index
4905  * depends on.
4906  */
4907  vardata->acl_ok =
4909  ACL_SELECT) == ACLCHECK_OK);
4910  }
4911  else
4912  {
4913  /* suppress leakproofness checks later */
4914  vardata->acl_ok = true;
4915  }
4916  }
4917  if (vardata->statsTuple)
4918  break;
4919  }
4920  indexpr_item = lnext(indexpr_item);
4921  }
4922  }
4923  if (vardata->statsTuple)
4924  break;
4925  }
4926  }
4927 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
bool predOK
Definition: relation.h:752
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:342
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:457
Definition: nodes.h:512
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:877
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4939
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:753
Definition: type.h:89
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1756
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:170
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int ncolumns
Definition: relation.h:729
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: relation.h:613
Index varno
Definition: primnodes.h:166
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:678
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:73
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:570
List * indexlist
Definition: relation.h:622
#define BoolGetDatum(X)
Definition: postgres.h:408
void bms_free(Bitmapset *a)
Definition: bitmapset.c:245
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4480
RTEKind rtekind
Definition: parsenodes.h:951
void * arg
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
List * indpred
Definition: relation.h:742
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
List * indexprs
Definition: relation.h:741
int32 vartypmod
Definition: primnodes.h:171

◆ find_join_input_rel()

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

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

5642 {
5643  RelOptInfo *rel = NULL;
5644 
5645  switch (bms_membership(relids))
5646  {
5647  case BMS_EMPTY_SET:
5648  /* should not happen */
5649  break;
5650  case BMS_SINGLETON:
5651  rel = find_base_rel(root, bms_singleton_member(relids));
5652  break;
5653  case BMS_MULTIPLE:
5654  rel = find_join_rel(root, relids);
5655  break;
5656  }
5657 
5658  if (rel == NULL)
5659  elog(ERROR, "could not find RelOptInfo for given relids");
5660 
5661  return rel;
5662 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:342
#define ERROR
Definition: elog.h:43
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:678
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:570
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277

◆ genericcostestimate()

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

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

6644 {
6645  IndexOptInfo *index = path->indexinfo;
6646  List *indexQuals = path->indexquals;
6647  List *indexOrderBys = path->indexorderbys;
6648  Cost indexStartupCost;
6649  Cost indexTotalCost;
6650  Selectivity indexSelectivity;
6651  double indexCorrelation;
6652  double numIndexPages;
6653  double numIndexTuples;
6654  double spc_random_page_cost;
6655  double num_sa_scans;
6656  double num_outer_scans;
6657  double num_scans;
6658  double qual_op_cost;
6659  double qual_arg_cost;
6660  List *selectivityQuals;
6661  ListCell *l;
6662 
6663  /*
6664  * If the index is partial, AND the index predicate with the explicitly
6665  * given indexquals to produce a more accurate idea of the index
6666  * selectivity.
6667  */
6668  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6669 
6670  /*
6671  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6672  * index scans that will be performed.
6673  */
6674  num_sa_scans = 1;
6675  foreach(l, indexQuals)
6676  {
6677  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6678 
6679  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6680  {
6681  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6682  int alength = estimate_array_length(lsecond(saop->args));
6683 
6684  if (alength > 1)
6685  num_sa_scans *= alength;
6686  }
6687  }
6688 
6689  /* Estimate the fraction of main-table tuples that will be visited */
6690  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6691  index->rel->relid,
6692  JOIN_INNER,
6693  NULL);
6694 
6695  /*
6696  * If caller didn't give us an estimate, estimate the number of index
6697  * tuples that will be visited. We do it in this rather peculiar-looking
6698  * way in order to get the right answer for partial indexes.
6699  */
6700  numIndexTuples = costs->numIndexTuples;
6701  if (numIndexTuples <= 0.0)
6702  {
6703  numIndexTuples = indexSelectivity * index->rel->tuples;
6704 
6705  /*
6706  * The above calculation counts all the tuples visited across all
6707  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6708  * average per-indexscan number, so adjust. This is a handy place to
6709  * round to integer, too. (If caller supplied tuple estimate, it's
6710  * responsible for handling these considerations.)
6711  */
6712  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6713  }
6714 
6715  /*
6716  * We can bound the number of tuples by the index size in any case. Also,
6717  * always estimate at least one tuple is touched, even when
6718  * indexSelectivity estimate is tiny.
6719  */
6720  if (numIndexTuples > index->tuples)
6721  numIndexTuples = index->tuples;
6722  if (numIndexTuples < 1.0)
6723  numIndexTuples = 1.0;
6724 
6725  /*
6726  * Estimate the number of index pages that will be retrieved.
6727  *
6728  * We use the simplistic method of taking a pro-rata fraction of the total
6729  * number of index pages. In effect, this counts only leaf pages and not
6730  * any overhead such as index metapage or upper tree levels.
6731  *
6732  * In practice access to upper index levels is often nearly free because
6733  * those tend to stay in cache under load; moreover, the cost involved is
6734  * highly dependent on index type. We therefore ignore such costs here
6735  * and leave it to the caller to add a suitable charge if needed.
6736  */
6737  if (index->pages > 1 && index->tuples > 1)
6738  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6739  else
6740  numIndexPages = 1.0;
6741 
6742  /* fetch estimated page cost for tablespace containing index */
6744  &spc_random_page_cost,
6745  NULL);
6746 
6747  /*
6748  * Now compute the disk access costs.
6749  *
6750  * The above calculations are all per-index-scan. However, if we are in a
6751  * nestloop inner scan, we can expect the scan to be repeated (with
6752  * different search keys) for each row of the outer relation. Likewise,
6753  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6754  * the potential for cache effects to reduce the number of disk page
6755  * fetches needed. We want to estimate the average per-scan I/O cost in
6756  * the presence of caching.
6757  *
6758  * We use the Mackert-Lohman formula (see costsize.c for details) to
6759  * estimate the total number of page fetches that occur. While this
6760  * wasn't what it was designed for, it seems a reasonable model anyway.
6761  * Note that we are counting pages not tuples anymore, so we take N = T =
6762  * index size, as if there were one "tuple" per page.
6763  */
6764  num_outer_scans = loop_count;
6765  num_scans = num_sa_scans * num_outer_scans;
6766 
6767  if (num_scans > 1)
6768  {
6769  double pages_fetched;
6770 
6771  /* total page fetches ignoring cache effects */
6772  pages_fetched = numIndexPages * num_scans;
6773 
6774  /* use Mackert and Lohman formula to adjust for cache effects */
6775  pages_fetched = index_pages_fetched(pages_fetched,
6776  index->pages,
6777  (double) index->pages,
6778  root);
6779 
6780  /*
6781  * Now compute the total disk access cost, and then report a pro-rated
6782  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6783  * since that's internal to the indexscan.)
6784  */
6785  indexTotalCost = (pages_fetched * spc_random_page_cost)
6786  / num_outer_scans;
6787  }
6788  else
6789  {
6790  /*
6791  * For a single index scan, we just charge spc_random_page_cost per
6792  * page touched.
6793  */
6794  indexTotalCost = numIndexPages * spc_random_page_cost;
6795  }
6796 
6797  /*
6798  * CPU cost: any complex expressions in the indexquals will need to be
6799  * evaluated once at the start of the scan to reduce them to runtime keys
6800  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6801  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6802  * indexqual operator. Because we have numIndexTuples as a per-scan
6803  * number, we have to multiply by num_sa_scans to get the correct result
6804  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6805  * ORDER BY expressions.
6806  *
6807  * Note: this neglects the possible costs of rechecking lossy operators.
6808  * Detecting that that might be needed seems more expensive than it's
6809  * worth, though, considering all the other inaccuracies here ...
6810  */
6811  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6812  orderby_operands_eval_cost(root, path);
6813  qual_op_cost = cpu_operator_cost *
6814  (list_length(indexQuals) + list_length(indexOrderBys));
6815 
6816  indexStartupCost = qual_arg_cost;
6817  indexTotalCost += qual_arg_cost;
6818  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6819 
6820  /*
6821  * Generic assumption about index correlation: there isn't any.
6822  */
6823  indexCorrelation = 0.0;
6824 
6825  /*
6826  * Return everything to caller.
6827  */
6828  costs->indexStartupCost = indexStartupCost;
6829  costs->indexTotalCost = indexTotalCost;
6830  costs->indexSelectivity = indexSelectivity;
6831  costs->indexCorrelation = indexCorrelation;
6832  costs->numIndexPages = numIndexPages;
6833  costs->numIndexTuples = numIndexTuples;
6834  costs->spc_random_page_cost = spc_random_page_cost;
6835  costs->num_sa_scans = num_sa_scans;
6836 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
IndexOptInfo * indexinfo
Definition: relation.h:1119
double tuples
Definition: relation.h:625
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6858
Oid reltablespace
Definition: relation.h:720
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6585
double Selectivity
Definition: nodes.h:642
double tuples
Definition: relation.h:725
#define lsecond(l)
Definition: pg_list.h:116
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6610
Definition: type.h:89
BlockNumber pages
Definition: relation.h:724
List * indexquals
Definition: relation.h:1121
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2167
RelOptInfo * rel
Definition: relation.h:721
double num_sa_scans
Definition: selfuncs.h:138
double cpu_operator_cost
Definition: costsize.c:108
Cost indexTotalCost
Definition: selfuncs.h:130
double rint(double x)
Definition: rint.c:22
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:613
Expr * clause
Definition: relation.h:1842
double indexCorrelation
Definition: selfuncs.h:132
List * indexorderbys
Definition: relation.h:1123
double spc_random_page_cost
Definition: selfuncs.h:137
double numIndexTuples
Definition: selfuncs.h:136
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Cost indexStartupCost
Definition: selfuncs.h:129
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
Definition: pg_list.h:45
double cpu_index_tuple_cost
Definition: costsize.c:107
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:818
double Cost
Definition: nodes.h:643
double numIndexPages
Definition: selfuncs.h:135

◆ get_actual_variable_range()

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

Definition at line 5402 of file selfuncs.c.

References AccessShareLock, Assert, VariableStatData::atttype, BackwardScanDirection, BTGreaterStrategyNumber, BTLessStrategyNumber, BTREE_AM_OID, 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().

5405 {
5406  bool have_data = false;
5407  RelOptInfo *rel = vardata->rel;
5408  RangeTblEntry *rte;
5409  ListCell *lc;
5410 
5411  /* No hope if no relation or it doesn't have indexes */
5412  if (rel == NULL || rel->indexlist == NIL)
5413  return false;
5414  /* If it has indexes it must be a plain relation */
5415  rte = root->simple_rte_array[rel->relid];
5416  Assert(rte->rtekind == RTE_RELATION);
5417 
5418  /* Search through the indexes to see if any match our problem */
5419  foreach(lc, rel->indexlist)
5420  {
5422  ScanDirection indexscandir;
5423 
5424  /* Ignore non-btree indexes */
5425  if (index->relam != BTREE_AM_OID)
5426  continue;
5427 
5428  /*
5429  * Ignore partial indexes --- we only want stats that cover the entire
5430  * relation.
5431  */
5432  if (index->indpred != NIL)
5433  continue;
5434 
5435  /*
5436  * The index list might include hypothetical indexes inserted by a
5437  * get_relation_info hook --- don't try to access them.
5438  */
5439  if (index->hypothetical)
5440  continue;
5441 
5442  /*
5443  * The first index column must match the desired variable and sort
5444  * operator --- but we can use a descending-order index.
5445  */
5446  if (!match_index_to_operand(vardata->var, 0, index))
5447  continue;
5448  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5449  {
5450  case BTLessStrategyNumber:
5451  if (index->reverse_sort[0])
5452  indexscandir = BackwardScanDirection;
5453  else
5454  indexscandir = ForwardScanDirection;
5455  break;
5457  if (index->reverse_sort[0])
5458  indexscandir = ForwardScanDirection;
5459  else
5460  indexscandir = BackwardScanDirection;
5461  break;
5462  default:
5463  /* index doesn't match the sortop */
5464  continue;
5465  }
5466 
5467  /*
5468  * Found a suitable index to extract data from. We'll need an EState
5469  * and a bunch of other infrastructure.
5470  */
5471  {
5472  EState *estate;
5473  ExprContext *econtext;
5474  MemoryContext tmpcontext;
5475  MemoryContext oldcontext;
5476  Relation heapRel;
5477  Relation indexRel;
5478  IndexInfo *indexInfo;
5479  TupleTableSlot *slot;
5480  int16 typLen;
5481  bool typByVal;
5482  ScanKeyData scankeys[1];
5483  IndexScanDesc index_scan;
5484  HeapTuple tup;
5486  bool isnull[INDEX_MAX_KEYS];
5487  SnapshotData SnapshotNonVacuumable;
5488 
5489  estate = CreateExecutorState();
5490  econtext = GetPerTupleExprContext(estate);
5491  /* Make sure any cruft is generated in the econtext's memory */
5492  tmpcontext = econtext->ecxt_per_tuple_memory;
5493  oldcontext = MemoryContextSwitchTo(tmpcontext);
5494 
5495  /*
5496  * Open the table and index so we can read from them. We should
5497  * already have at least AccessShareLock on the table, but not
5498  * necessarily on the index.
5499  */
5500  heapRel = heap_open(rte->relid, NoLock);
5501  indexRel = index_open(index->indexoid, AccessShareLock);
5502 
5503  /* extract index key information from the index's pg_index info */
5504  indexInfo = BuildIndexInfo(indexRel);
5505 
5506  /* some other stuff */
5507  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
5508  econtext->ecxt_scantuple = slot;
5509  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5510  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5511 
5512  /* set up an IS NOT NULL scan key so that we ignore nulls */
5513  ScanKeyEntryInitialize(&scankeys[0],
5515  1, /* index col to scan */
5516  InvalidStrategy, /* no strategy */
5517  InvalidOid, /* no strategy subtype */
5518  InvalidOid, /* no collation */
5519  InvalidOid, /* no reg proc for this */
5520  (Datum) 0); /* constant */
5521 
5522  have_data = true;
5523 
5524  /* If min is requested ... */
5525  if (min)
5526  {
5527  /*
5528  * In principle, we should scan the index with our current
5529  * active snapshot, which is the best approximation we've got
5530  * to what the query will see when executed. But that won't
5531  * be exact if a new snap is taken before running the query,
5532  * and it can be very expensive if a lot of recently-dead or
5533  * uncommitted rows exist at the beginning or end of the index
5534  * (because we'll laboriously fetch each one and reject it).
5535  * Instead, we use SnapshotNonVacuumable. That will accept
5536  * recently-dead and uncommitted rows as well as normal
5537  * visible rows. On the other hand, it will reject known-dead
5538  * rows, and thus not give a bogus answer when the extreme
5539  * value has been deleted (unless the deletion was quite
5540  * recent); that case motivates not using SnapshotAny here.
5541  *
5542  * A crucial point here is that SnapshotNonVacuumable, with
5543  * RecentGlobalXmin as horizon, yields the inverse of the
5544  * condition that the indexscan will use to decide that index
5545  * entries are killable (see heap_hot_search_buffer()).
5546  * Therefore, if the snapshot rejects a tuple and we have to
5547  * continue scanning past it, we know that the indexscan will
5548  * mark that index entry killed. That means that the next
5549  * get_actual_variable_range() call will not have to visit
5550  * that heap entry. In this way we avoid repetitive work when
5551  * this function is used a lot during planning.
5552  */
5553  index_scan = index_beginscan(heapRel, indexRel,
5554  &SnapshotNonVacuumable,
5555  1, 0);
5556  index_rescan(index_scan, scankeys, 1, NULL, 0);
5557 
5558  /* Fetch first tuple in sortop's direction */
5559  if ((tup = index_getnext(index_scan,
5560  indexscandir)) != NULL)
5561  {
5562  /* Extract the index column values from the heap tuple */
5563  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5564  FormIndexDatum(indexInfo, slot, estate,
5565  values, isnull);
5566 
5567  /* Shouldn't have got a null, but be careful */
5568  if (isnull[0])
5569  elog(ERROR, "found unexpected null value in index \"%s\"",
5570  RelationGetRelationName(indexRel));
5571 
5572  /* Copy the index column value out to caller's context */
5573  MemoryContextSwitchTo(oldcontext);
5574  *min = datumCopy(values[0], typByVal, typLen);
5575  MemoryContextSwitchTo(tmpcontext);
5576  }
5577  else
5578  have_data = false;
5579 
5580  index_endscan(index_scan);
5581  }
5582 
5583  /* If max is requested, and we didn't find the index is empty */
5584  if (max && have_data)
5585  {
5586  index_scan = index_beginscan(heapRel, indexRel,
5587  &SnapshotNonVacuumable,
5588  1, 0);
5589  index_rescan(index_scan, scankeys, 1, NULL, 0);
5590 
5591  /* Fetch first tuple in reverse direction */
5592  if ((tup = index_getnext(index_scan,
5593  -indexscandir)) != NULL)
5594  {
5595  /* Extract the index column values from the heap tuple */
5596  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5597  FormIndexDatum(indexInfo, slot, estate,
5598  values, isnull);
5599 
5600  /* Shouldn't have got a null, but be careful */
5601  if (isnull[0])
5602  elog(ERROR, "found unexpected null value in index \"%s\"",
5603  RelationGetRelationName(indexRel));
5604 
5605  /* Copy the index column value out to caller's context */
5606  MemoryContextSwitchTo(oldcontext);
5607  *max = datumCopy(values[0], typByVal, typLen);
5608  MemoryContextSwitchTo(tmpcontext);
5609  }
5610  else
5611  have_data = false;
5612 
5613  index_endscan(index_scan);
5614  }
5615 
5616  /* Clean everything up */
5618 
5619  index_close(indexRel, AccessShareLock);
5620  heap_close(heapRel, NoLock);
5621 
5622  MemoryContextSwitchTo(oldcontext);
5623  FreeExecutorState(estate);
5624 
5625  /* And we're done */
5626  break;
5627  }
5628  }
5629 
5630  return have_data;
5631 }
signed short int16
Definition: c.h:293
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1774
#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:320
#define InitNonVacuumableSnapshot(snapshotdata, xmin_horizon)
Definition: tqual.h:110
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define RelationGetDescr(relation)
Definition: rel.h:437
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3180
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:214
RelOptInfo * rel
Definition: selfuncs.h:70
#define BTREE_AM_OID
Definition: pg_am.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:734
bool hypothetical
Definition: relation.h:755
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1645
Definition: type.h:89
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:474
#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:216
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
ScanDirection
Definition: sdir.h:22
#define RelationGetRelationName(relation)
Definition: rel.h:445
#define SK_SEARCHNOTNULL
Definition: skey.h:122
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:199
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:81
Index relid
Definition: relation.h:613
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
List * indexlist
Definition: relation.h:622
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:680
#define lfirst(lc)
Definition: pg_list.h:106
#define INDEX_MAX_KEYS
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2020
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:208
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
RTEKind rtekind
Definition: parsenodes.h:951
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:719
bool * reverse_sort
Definition: relation.h:735
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:742
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
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