PostgreSQL Source Code  git master
selfuncs.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <math.h>
#include "access/brin.h"
#include "access/brin_page.h"
#include "access/gin.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/visibilitymap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_statistic_ext.h"
#include "executor/nodeAgg.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/index_selfuncs.h"
#include "utils/lsyscache.h"
#include "utils/memutils.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/typcache.h"
Include dependency graph for selfuncs.c:

Go to the source code of this file.

Data Structures

struct  GroupVarInfo
 
struct  GinQualCounts
 

Functions

static double eqsel_internal (PG_FUNCTION_ARGS, bool negate)
 
static double eqjoinsel_inner (Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2)
 
static double eqjoinsel_semi (Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2, 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, Oid collid, double *scaledvalue, Datum lobound, Datum hibound, Oid boundstypid, double *scaledlobound, double *scaledhibound)
 
static double convert_numeric_to_scalar (Datum value, Oid typid, bool *failure)
 
static void convert_string_to_scalar (char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
 
static void convert_bytea_to_scalar (Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
 
static double convert_one_string_to_scalar (char *value, int rangelo, int rangehi)
 
static double convert_one_bytea_to_scalar (unsigned char *value, int valuelen, int rangelo, int rangehi)
 
static char * convert_string_datum (Datum value, Oid typid, Oid collid, bool *failure)
 
static double convert_timevalue_to_scalar (Datum value, Oid typid, bool *failure)
 
static void examine_simple_variable (PlannerInfo *root, Var *var, VariableStatData *vardata)
 
static bool get_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
 
static void get_stats_slot_range (AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc, Oid collation, int16 typLen, bool typByVal, Datum *min, Datum *max, bool *p_have_data)
 
static bool get_actual_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
 
static bool get_actual_variable_endpoint (Relation heapRel, Relation indexRel, ScanDirection indexscandir, ScanKey scankeys, int16 typLen, bool typByVal, TupleTableSlot *tableslot, MemoryContext outercontext, Datum *endpointDatum)
 
static RelOptInfofind_join_input_rel (PlannerInfo *root, Relids relids)
 
Datum eqsel (PG_FUNCTION_ARGS)
 
double var_eq_const (VariableStatData *vardata, Oid operator, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
 
double var_eq_non_const (VariableStatData *vardata, Oid operator, Oid collation, Node *other, bool varonleft, bool negate)
 
Datum neqsel (PG_FUNCTION_ARGS)
 
static double scalarineqsel (PlannerInfo *root, Oid operator, bool isgt, bool iseq, Oid collation, VariableStatData *vardata, Datum constval, Oid consttype)
 
double mcv_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
 
double histogram_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
 
double generic_restriction_selectivity (PlannerInfo *root, Oid oproid, Oid collation, List *args, int varRelid, double default_selectivity)
 
double ineq_histogram_selectivity (PlannerInfo *root, VariableStatData *vardata, Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq, Oid collation, Datum constval, Oid consttype)
 
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)
 
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)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
Datum matchingsel (PG_FUNCTION_ARGS)
 
Datum matchingjoinsel (PG_FUNCTION_ARGS)
 
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)
 
double estimate_hashagg_tablesize (Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
 
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)
 
Listget_quals_from_indexclauses (List *indexclauses)
 
Cost index_other_operands_eval_cost (PlannerInfo *root, List *indexquals)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
 
Listadd_predicate_to_index_quals (IndexOptInfo *index, List *indexQuals)
 
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, int indexcol, OpExpr *clause, GinQualCounts *counts)
 
static bool gincost_scalararrayopexpr (PlannerInfo *root, IndexOptInfo *index, int indexcol, ScalarArrayOpExpr *clause, 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
 

Function Documentation

◆ add_predicate_to_index_quals()

List* add_predicate_to_index_quals ( IndexOptInfo index,
List indexQuals 
)

Definition at line 6213 of file selfuncs.c.

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

Referenced by btcostestimate(), genericcostestimate(), and gincostestimate().

6214 {
6215  List *predExtraQuals = NIL;
6216  ListCell *lc;
6217 
6218  if (index->indpred == NIL)
6219  return indexQuals;
6220 
6221  foreach(lc, index->indpred)
6222  {
6223  Node *predQual = (Node *) lfirst(lc);
6224  List *oneQual = list_make1(predQual);
6225 
6226  if (!predicate_implied_by(oneQual, indexQuals, false))
6227  predExtraQuals = list_concat(predExtraQuals, oneQual);
6228  }
6229  return list_concat(predExtraQuals, indexQuals);
6230 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:529
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
#define list_make1(x1)
Definition: pg_list.h:227
#define lfirst(lc)
Definition: pg_list.h:190
List * indpred
Definition: pathnodes.h:844
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50

◆ add_unique_group_var()

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

Definition at line 3244 of file selfuncs.c.

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

Referenced by estimate_num_groups().

3246 {
3247  GroupVarInfo *varinfo;
3248  double ndistinct;
3249  bool isdefault;
3250  ListCell *lc;
3251 
3252  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3253 
3254  foreach(lc, varinfos)
3255  {
3256  varinfo = (GroupVarInfo *) lfirst(lc);
3257 
3258  /* Drop exact duplicates */
3259  if (equal(var, varinfo->var))
3260  return varinfos;
3261 
3262  /*
3263  * Drop known-equal vars, but only if they belong to different
3264  * relations (see comments for estimate_num_groups)
3265  */
3266  if (vardata->rel != varinfo->rel &&
3267  exprs_known_equal(root, var, varinfo->var))
3268  {
3269  if (varinfo->ndistinct <= ndistinct)
3270  {
3271  /* Keep older item, forget new one */
3272  return varinfos;
3273  }
3274  else
3275  {
3276  /* Delete the older item */
3277  varinfos = foreach_delete_current(varinfos, lc);
3278  }
3279  }
3280  }
3281 
3282  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3283 
3284  varinfo->var = var;
3285  varinfo->rel = vardata->rel;
3286  varinfo->ndistinct = ndistinct;
3287  varinfos = lappend(varinfos, varinfo);
3288  return varinfos;
3289 }
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:2113
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3033
RelOptInfo * rel
Definition: selfuncs.h:73
double ndistinct
Definition: selfuncs.c:3240
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5273
Node * var
Definition: selfuncs.c:3238
List * lappend(List *list, void *datum)
Definition: list.c:321
#define lfirst(lc)
Definition: pg_list.h:190
void * palloc(Size size)
Definition: mcxt.c:949
RelOptInfo * rel
Definition: selfuncs.c:3239

◆ booltestsel()

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

Definition at line 1537 of file selfuncs.c.

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

Referenced by clause_selectivity().

1539 {
1540  VariableStatData vardata;
1541  double selec;
1542 
1543  examine_variable(root, arg, varRelid, &vardata);
1544 
1545  if (HeapTupleIsValid(vardata.statsTuple))
1546  {
1547  Form_pg_statistic stats;
1548  double freq_null;
1549  AttStatsSlot sslot;
1550 
1551  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1552  freq_null = stats->stanullfrac;
1553 
1554  if (get_attstatsslot(&sslot, vardata.statsTuple,
1555  STATISTIC_KIND_MCV, InvalidOid,
1557  && sslot.nnumbers > 0)
1558  {
1559  double freq_true;
1560  double freq_false;
1561 
1562  /*
1563  * Get first MCV frequency and derive frequency for true.
1564  */
1565  if (DatumGetBool(sslot.values[0]))
1566  freq_true = sslot.numbers[0];
1567  else
1568  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1569 
1570  /*
1571  * Next derive frequency for false. Then use these as appropriate
1572  * to derive frequency for each case.
1573  */
1574  freq_false = 1.0 - freq_true - freq_null;
1575 
1576  switch (booltesttype)
1577  {
1578  case IS_UNKNOWN:
1579  /* select only NULL values */
1580  selec = freq_null;
1581  break;
1582  case IS_NOT_UNKNOWN:
1583  /* select non-NULL values */
1584  selec = 1.0 - freq_null;
1585  break;
1586  case IS_TRUE:
1587  /* select only TRUE values */
1588  selec = freq_true;
1589  break;
1590  case IS_NOT_TRUE:
1591  /* select non-TRUE values */
1592  selec = 1.0 - freq_true;
1593  break;
1594  case IS_FALSE:
1595  /* select only FALSE values */
1596  selec = freq_false;
1597  break;
1598  case IS_NOT_FALSE:
1599  /* select non-FALSE values */
1600  selec = 1.0 - freq_false;
1601  break;
1602  default:
1603  elog(ERROR, "unrecognized booltesttype: %d",
1604  (int) booltesttype);
1605  selec = 0.0; /* Keep compiler quiet */
1606  break;
1607  }
1608 
1609  free_attstatsslot(&sslot);
1610  }
1611  else
1612  {
1613  /*
1614  * No most-common-value info available. Still have null fraction
1615  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1616  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1617  */
1618  switch (booltesttype)
1619  {
1620  case IS_UNKNOWN:
1621  /* select only NULL values */
1622  selec = freq_null;
1623  break;
1624  case IS_NOT_UNKNOWN:
1625  /* select non-NULL values */
1626  selec = 1.0 - freq_null;
1627  break;
1628  case IS_TRUE:
1629  case IS_FALSE:
1630  /* Assume we select half of the non-NULL values */
1631  selec = (1.0 - freq_null) / 2.0;
1632  break;
1633  case IS_NOT_TRUE:
1634  case IS_NOT_FALSE:
1635  /* Assume we select NULLs plus half of the non-NULLs */
1636  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1637  selec = (freq_null + 1.0) / 2.0;
1638  break;
1639  default:
1640  elog(ERROR, "unrecognized booltesttype: %d",
1641  (int) booltesttype);
1642  selec = 0.0; /* Keep compiler quiet */
1643  break;
1644  }
1645  }
1646  }
1647  else
1648  {
1649  /*
1650  * If we can't get variable statistics for the argument, perhaps
1651  * clause_selectivity can do something with it. We ignore the
1652  * possibility of a NULL value when using clause_selectivity, and just
1653  * assume the value is either TRUE or FALSE.
1654  */
1655  switch (booltesttype)
1656  {
1657  case IS_UNKNOWN:
1658  selec = DEFAULT_UNK_SEL;
1659  break;
1660  case IS_NOT_UNKNOWN:
1661  selec = DEFAULT_NOT_UNK_SEL;
1662  break;
1663  case IS_TRUE:
1664  case IS_NOT_FALSE:
1665  selec = (double) clause_selectivity(root, arg,
1666  varRelid,
1667  jointype, sjinfo);
1668  break;
1669  case IS_FALSE:
1670  case IS_NOT_TRUE:
1671  selec = 1.0 - (double) clause_selectivity(root, arg,
1672  varRelid,
1673  jointype, sjinfo);
1674  break;
1675  default:
1676  elog(ERROR, "unrecognized booltesttype: %d",
1677  (int) booltesttype);
1678  selec = 0.0; /* Keep compiler quiet */
1679  break;
1680  }
1681  }
1682 
1683  ReleaseVariableStats(vardata);
1684 
1685  /* result should be in range, but make sure... */
1686  CLAMP_PROBABILITY(selec);
1687 
1688  return (Selectivity) selec;
1689 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:74
int nnumbers
Definition: lsyscache.h:54
double Selectivity
Definition: nodes.h:662
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:53
#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:600
float4 * numbers
Definition: lsyscache.h:53
#define DatumGetBool(X)
Definition: postgres.h:393
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:52
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4724
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3052
Datum * values
Definition: lsyscache.h:50
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
#define elog(elevel,...)
Definition: elog.h:214
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3169

◆ boolvarsel()

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

Definition at line 1509 of file selfuncs.c.

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

Referenced by clause_selectivity().

1510 {
1511  VariableStatData vardata;
1512  double selec;
1513 
1514  examine_variable(root, arg, varRelid, &vardata);
1515  if (HeapTupleIsValid(vardata.statsTuple))
1516  {
1517  /*
1518  * A boolean variable V is equivalent to the clause V = 't', so we
1519  * compute the selectivity as if that is what we have.
1520  */
1521  selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1522  BoolGetDatum(true), false, true, false);
1523  }
1524  else
1525  {
1526  /* Otherwise, the default estimate is 0.5 */
1527  selec = 0.5;
1528  }
1529  ReleaseVariableStats(vardata);
1530  return selec;
1531 }
HeapTuple statsTuple
Definition: selfuncs.h:74
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4724
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
double var_eq_const(VariableStatData *vardata, Oid operator, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:292

◆ brincostestimate()

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

Definition at line 7329 of file selfuncs.c.

References Abs, Assert, attnum, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BRIN_DEFAULT_PAGES_PER_RANGE, brinGetStats(), CLAMP_PROBABILITY, clauselist_selectivity(), cpu_operator_cost, elog, ERROR, free_attstatsslot(), VariableStatData::freefunc, get_attstatsslot(), get_index_stats_hook, get_quals_from_indexclauses(), get_relation_stats_hook, get_tablespace_page_costs(), HeapTupleIsValid, IndexOptInfo::hypothetical, index_close(), index_open(), index_other_operands_eval_cost(), IndexPath::indexclauses, IndexClause::indexcol, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, Int16GetDatum, InvalidOid, JOIN_INNER, lfirst_node, Max, Min, AttStatsSlot::nnumbers, NoLock, AttStatsSlot::numbers, ObjectIdGetDatum, RelOptInfo::pages, IndexOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reltablespace, REVMAP_PAGE_MAXITEMS, BrinStatsData::revmapNumPages, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

7333 {
7334  IndexOptInfo *index = path->indexinfo;
7335  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7336  double numPages = index->pages;
7337  RelOptInfo *baserel = index->rel;
7338  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7339  Cost spc_seq_page_cost;
7340  Cost spc_random_page_cost;
7341  double qual_arg_cost;
7342  double qualSelectivity;
7343  BrinStatsData statsData;
7344  double indexRanges;
7345  double minimalRanges;
7346  double estimatedRanges;
7347  double selec;
7348  Relation indexRel;
7349  ListCell *l;
7350  VariableStatData vardata;
7351 
7352  Assert(rte->rtekind == RTE_RELATION);
7353 
7354  /* fetch estimated page cost for the tablespace containing the index */
7356  &spc_random_page_cost,
7357  &spc_seq_page_cost);
7358 
7359  /*
7360  * Obtain some data from the index itself, if possible. Otherwise invent
7361  * some plausible internal statistics based on the relation page count.
7362  */
7363  if (!index->hypothetical)
7364  {
7365  /*
7366  * A lock should have already been obtained on the index in plancat.c.
7367  */
7368  indexRel = index_open(index->indexoid, NoLock);
7369  brinGetStats(indexRel, &statsData);
7370  index_close(indexRel, NoLock);
7371 
7372  /* work out the actual number of ranges in the index */
7373  indexRanges = Max(ceil((double) baserel->pages /
7374  statsData.pagesPerRange), 1.0);
7375  }
7376  else
7377  {
7378  /*
7379  * Assume default number of pages per range, and estimate the number
7380  * of ranges based on that.
7381  */
7382  indexRanges = Max(ceil((double) baserel->pages /
7384 
7386  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7387  }
7388 
7389  /*
7390  * Compute index correlation
7391  *
7392  * Because we can use all index quals equally when scanning, we can use
7393  * the largest correlation (in absolute value) among columns used by the
7394  * query. Start at zero, the worst possible case. If we cannot find any
7395  * correlation statistics, we will keep it as 0.
7396  */
7397  *indexCorrelation = 0;
7398 
7399  foreach(l, path->indexclauses)
7400  {
7401  IndexClause *iclause = lfirst_node(IndexClause, l);
7402  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7403 
7404  /* attempt to lookup stats in relation for this index column */
7405  if (attnum != 0)
7406  {
7407  /* Simple variable -- look to stats for the underlying table */
7409  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7410  {
7411  /*
7412  * The hook took control of acquiring a stats tuple. If it
7413  * did supply a tuple, it'd better have supplied a freefunc.
7414  */
7415  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7416  elog(ERROR,
7417  "no function provided to release variable stats with");
7418  }
7419  else
7420  {
7421  vardata.statsTuple =
7423  ObjectIdGetDatum(rte->relid),
7424  Int16GetDatum(attnum),
7425  BoolGetDatum(false));
7426  vardata.freefunc = ReleaseSysCache;
7427  }
7428  }
7429  else
7430  {
7431  /*
7432  * Looks like we've found an expression column in the index. Let's
7433  * see if there's any stats for it.
7434  */
7435 
7436  /* get the attnum from the 0-based index. */
7437  attnum = iclause->indexcol + 1;
7438 
7439  if (get_index_stats_hook &&
7440  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7441  {
7442  /*
7443  * The hook took control of acquiring a stats tuple. If it
7444  * did supply a tuple, it'd better have supplied a freefunc.
7445  */
7446  if (HeapTupleIsValid(vardata.statsTuple) &&
7447  !vardata.freefunc)
7448  elog(ERROR, "no function provided to release variable stats with");
7449  }
7450  else
7451  {
7453  ObjectIdGetDatum(index->indexoid),
7454  Int16GetDatum(attnum),
7455  BoolGetDatum(false));
7456  vardata.freefunc = ReleaseSysCache;
7457  }
7458  }
7459 
7460  if (HeapTupleIsValid(vardata.statsTuple))
7461  {
7462  AttStatsSlot sslot;
7463 
7464  if (get_attstatsslot(&sslot, vardata.statsTuple,
7465  STATISTIC_KIND_CORRELATION, InvalidOid,
7467  {
7468  double varCorrelation = 0.0;
7469 
7470  if (sslot.nnumbers > 0)
7471  varCorrelation = Abs(sslot.numbers[0]);
7472 
7473  if (varCorrelation > *indexCorrelation)
7474  *indexCorrelation = varCorrelation;
7475 
7476  free_attstatsslot(&sslot);
7477  }
7478  }
7479 
7480  ReleaseVariableStats(vardata);
7481  }
7482 
7483  qualSelectivity = clauselist_selectivity(root, indexQuals,
7484  baserel->relid,
7485  JOIN_INNER, NULL);
7486 
7487  /*
7488  * Now calculate the minimum possible ranges we could match with if all of
7489  * the rows were in the perfect order in the table's heap.
7490  */
7491  minimalRanges = ceil(indexRanges * qualSelectivity);
7492 
7493  /*
7494  * Now estimate the number of ranges that we'll touch by using the
7495  * indexCorrelation from the stats. Careful not to divide by zero (note
7496  * we're using the absolute value of the correlation).
7497  */
7498  if (*indexCorrelation < 1.0e-10)
7499  estimatedRanges = indexRanges;
7500  else
7501  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7502 
7503  /* we expect to visit this portion of the table */
7504  selec = estimatedRanges / indexRanges;
7505 
7506  CLAMP_PROBABILITY(selec);
7507 
7508  *indexSelectivity = selec;
7509 
7510  /*
7511  * Compute the index qual costs, much as in genericcostestimate, to add to
7512  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7513  * support those.
7514  */
7515  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7516 
7517  /*
7518  * Compute the startup cost as the cost to read the whole revmap
7519  * sequentially, including the cost to execute the index quals.
7520  */
7521  *indexStartupCost =
7522  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7523  *indexStartupCost += qual_arg_cost;
7524 
7525  /*
7526  * To read a BRIN index there might be a bit of back and forth over
7527  * regular pages, as revmap might point to them out of sequential order;
7528  * calculate the total cost as reading the whole index in random order.
7529  */
7530  *indexTotalCost = *indexStartupCost +
7531  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7532 
7533  /*
7534  * Charge a small amount per range tuple which we expect to match to. This
7535  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7536  * will set a bit for each page in the range when we find a matching
7537  * range, so we must multiply the charge by the number of pages in the
7538  * range.
7539  */
7540  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7541  statsData.pagesPerRange;
7542 
7543  *indexPages = index->pages;
7544 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1207
HeapTuple statsTuple
Definition: selfuncs.h:74
int nnumbers
Definition: lsyscache.h:54
#define Min(x, y)
Definition: c.h:927
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:76
Oid reltablespace
Definition: pathnodes.h:819
bool hypothetical
Definition: pathnodes.h:857
List * indexclauses
Definition: pathnodes.h:1208
#define Abs(x)
Definition: c.h:933
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:823
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
RelOptInfo * rel
Definition: pathnodes.h:820
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
AttrNumber indexcol
Definition: pathnodes.h:1256
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
float4 * numbers
Definition: lsyscache.h:53
double cpu_operator_cost
Definition: costsize.c:115
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5911
#define BRIN_DEFAULT_PAGES_PER_RANGE
Definition: brin.h:38
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:693
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define REVMAP_PAGE_MAXITEMS
Definition: brin_page.h:93
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
int16 attnum
Definition: pg_attribute.h:79
#define Max(x, y)
Definition: c.h:921
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5941
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:704
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3052
#define Assert(condition)
Definition: c.h:745
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:145
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RTEKind rtekind
Definition: parsenodes.h:976
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
e
Definition: preproc-init.c:82
#define elog(elevel,...)
Definition: elog.h:214
int * indexkeys
Definition: pathnodes.h:830
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
double Cost
Definition: nodes.h:663
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1085
BlockNumber revmapNumPages
Definition: brin.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3169

◆ btcostestimate()

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

Definition at line 6234 of file selfuncs.c.

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BTEqualStrategyNumber, BTLessStrategyNumber, RestrictInfo::clause, clauselist_selectivity(), cpu_operator_cost, 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, IndexPath::indexclauses, IndexClause::indexcol, GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, IndexClause::indexquals, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, RangeTblEntry::inh, Int16GetDatum, InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst_node, linitial_oid, lsecond, MemSet, NIL, IndexOptInfo::nkeycolumns, AttStatsSlot::nnumbers, nodeTag, NullTest::nulltesttype, GenericCosts::num_sa_scans, AttStatsSlot::numbers, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, ObjectIdGetDatum, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, OpExpr::opno, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by bthandler().

6238 {
6239  IndexOptInfo *index = path->indexinfo;
6240  GenericCosts costs;
6241  Oid relid;
6242  AttrNumber colnum;
6243  VariableStatData vardata;
6244  double numIndexTuples;
6245  Cost descentCost;
6246  List *indexBoundQuals;
6247  int indexcol;
6248  bool eqQualHere;
6249  bool found_saop;
6250  bool found_is_null_op;
6251  double num_sa_scans;
6252  ListCell *lc;
6253 
6254  /*
6255  * For a btree scan, only leading '=' quals plus inequality quals for the
6256  * immediately next attribute contribute to index selectivity (these are
6257  * the "boundary quals" that determine the starting and stopping points of
6258  * the index scan). Additional quals can suppress visits to the heap, so
6259  * it's OK to count them in indexSelectivity, but they should not count
6260  * for estimating numIndexTuples. So we must examine the given indexquals
6261  * to find out which ones count as boundary quals. We rely on the
6262  * knowledge that they are given in index column order.
6263  *
6264  * For a RowCompareExpr, we consider only the first column, just as
6265  * rowcomparesel() does.
6266  *
6267  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6268  * index scans not one, but the ScalarArrayOpExpr's operator can be
6269  * considered to act the same as it normally does.
6270  */
6271  indexBoundQuals = NIL;
6272  indexcol = 0;
6273  eqQualHere = false;
6274  found_saop = false;
6275  found_is_null_op = false;
6276  num_sa_scans = 1;
6277  foreach(lc, path->indexclauses)
6278  {
6279  IndexClause *iclause = lfirst_node(IndexClause, lc);
6280  ListCell *lc2;
6281 
6282  if (indexcol != iclause->indexcol)
6283  {
6284  /* Beginning of a new column's quals */
6285  if (!eqQualHere)
6286  break; /* done if no '=' qual for indexcol */
6287  eqQualHere = false;
6288  indexcol++;
6289  if (indexcol != iclause->indexcol)
6290  break; /* no quals at all for indexcol */
6291  }
6292 
6293  /* Examine each indexqual associated with this index clause */
6294  foreach(lc2, iclause->indexquals)
6295  {
6296  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6297  Expr *clause = rinfo->clause;
6298  Oid clause_op = InvalidOid;
6299  int op_strategy;
6300 
6301  if (IsA(clause, OpExpr))
6302  {
6303  OpExpr *op = (OpExpr *) clause;
6304 
6305  clause_op = op->opno;
6306  }
6307  else if (IsA(clause, RowCompareExpr))
6308  {
6309  RowCompareExpr *rc = (RowCompareExpr *) clause;
6310 
6311  clause_op = linitial_oid(rc->opnos);
6312  }
6313  else if (IsA(clause, ScalarArrayOpExpr))
6314  {
6315  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6316  Node *other_operand = (Node *) lsecond(saop->args);
6317  int alength = estimate_array_length(other_operand);
6318 
6319  clause_op = saop->opno;
6320  found_saop = true;
6321  /* count number of SA scans induced by indexBoundQuals only */
6322  if (alength > 1)
6323  num_sa_scans *= alength;
6324  }
6325  else if (IsA(clause, NullTest))
6326  {
6327  NullTest *nt = (NullTest *) clause;
6328 
6329  if (nt->nulltesttype == IS_NULL)
6330  {
6331  found_is_null_op = true;
6332  /* IS NULL is like = for selectivity purposes */
6333  eqQualHere = true;
6334  }
6335  }
6336  else
6337  elog(ERROR, "unsupported indexqual type: %d",
6338  (int) nodeTag(clause));
6339 
6340  /* check for equality operator */
6341  if (OidIsValid(clause_op))
6342  {
6343  op_strategy = get_op_opfamily_strategy(clause_op,
6344  index->opfamily[indexcol]);
6345  Assert(op_strategy != 0); /* not a member of opfamily?? */
6346  if (op_strategy == BTEqualStrategyNumber)
6347  eqQualHere = true;
6348  }
6349 
6350  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6351  }
6352  }
6353 
6354  /*
6355  * If index is unique and we found an '=' clause for each column, we can
6356  * just assume numIndexTuples = 1 and skip the expensive
6357  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6358  * NullTest invalidates that theory, even though it sets eqQualHere.
6359  */
6360  if (index->unique &&
6361  indexcol == index->nkeycolumns - 1 &&
6362  eqQualHere &&
6363  !found_saop &&
6364  !found_is_null_op)
6365  numIndexTuples = 1.0;
6366  else
6367  {
6368  List *selectivityQuals;
6369  Selectivity btreeSelectivity;
6370 
6371  /*
6372  * If the index is partial, AND the index predicate with the
6373  * index-bound quals to produce a more accurate idea of the number of
6374  * rows covered by the bound conditions.
6375  */
6376  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6377 
6378  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6379  index->rel->relid,
6380  JOIN_INNER,
6381  NULL);
6382  numIndexTuples = btreeSelectivity * index->rel->tuples;
6383 
6384  /*
6385  * As in genericcostestimate(), we have to adjust for any
6386  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6387  * to integer.
6388  */
6389  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6390  }
6391 
6392  /*
6393  * Now do generic index cost estimation.
6394  */
6395  MemSet(&costs, 0, sizeof(costs));
6396  costs.numIndexTuples = numIndexTuples;
6397 
6398  genericcostestimate(root, path, loop_count, &costs);
6399 
6400  /*
6401  * Add a CPU-cost component to represent the costs of initial btree
6402  * descent. We don't charge any I/O cost for touching upper btree levels,
6403  * since they tend to stay in cache, but we still have to do about log2(N)
6404  * comparisons to descend a btree of N leaf tuples. We charge one
6405  * cpu_operator_cost per comparison.
6406  *
6407  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6408  * ones after the first one are not startup cost so far as the overall
6409  * plan is concerned, so add them only to "total" cost.
6410  */
6411  if (index->tuples > 1) /* avoid computing log(0) */
6412  {
6413  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6414  costs.indexStartupCost += descentCost;
6415  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6416  }
6417 
6418  /*
6419  * Even though we're not charging I/O cost for touching upper btree pages,
6420  * it's still reasonable to charge some CPU cost per page descended
6421  * through. Moreover, if we had no such charge at all, bloated indexes
6422  * would appear to have the same search cost as unbloated ones, at least
6423  * in cases where only a single leaf page is expected to be visited. This
6424  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6425  * touched. The number of such pages is btree tree height plus one (ie,
6426  * we charge for the leaf page too). As above, charge once per SA scan.
6427  */
6428  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6429  costs.indexStartupCost += descentCost;
6430  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6431 
6432  /*
6433  * If we can get an estimate of the first column's ordering correlation C
6434  * from pg_statistic, estimate the index correlation as C for a
6435  * single-column index, or C * 0.75 for multiple columns. (The idea here
6436  * is that multiple columns dilute the importance of the first column's
6437  * ordering, but don't negate it entirely. Before 8.0 we divided the
6438  * correlation by the number of columns, but that seems too strong.)
6439  */
6440  MemSet(&vardata, 0, sizeof(vardata));
6441 
6442  if (index->indexkeys[0] != 0)
6443  {
6444  /* Simple variable --- look to stats for the underlying table */
6445  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6446 
6447  Assert(rte->rtekind == RTE_RELATION);
6448  relid = rte->relid;
6449  Assert(relid != InvalidOid);
6450  colnum = index->indexkeys[0];
6451 
6453  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6454  {
6455  /*
6456  * The hook took control of acquiring a stats tuple. If it did
6457  * supply a tuple, it'd better have supplied a freefunc.
6458  */
6459  if (HeapTupleIsValid(vardata.statsTuple) &&
6460  !vardata.freefunc)
6461  elog(ERROR, "no function provided to release variable stats with");
6462  }
6463  else
6464  {
6466  ObjectIdGetDatum(relid),
6467  Int16GetDatum(colnum),
6468  BoolGetDatum(rte->inh));
6469  vardata.freefunc = ReleaseSysCache;
6470  }
6471  }
6472  else
6473  {
6474  /* Expression --- maybe there are stats for the index itself */
6475  relid = index->indexoid;
6476  colnum = 1;
6477 
6478  if (get_index_stats_hook &&
6479  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6480  {
6481  /*
6482  * The hook took control of acquiring a stats tuple. If it did
6483  * supply a tuple, it'd better have supplied a freefunc.
6484  */
6485  if (HeapTupleIsValid(vardata.statsTuple) &&
6486  !vardata.freefunc)
6487  elog(ERROR, "no function provided to release variable stats with");
6488  }
6489  else
6490  {
6492  ObjectIdGetDatum(relid),
6493  Int16GetDatum(colnum),
6494  BoolGetDatum(false));
6495  vardata.freefunc = ReleaseSysCache;
6496  }
6497  }
6498 
6499  if (HeapTupleIsValid(vardata.statsTuple))
6500  {
6501  Oid sortop;
6502  AttStatsSlot sslot;
6503 
6504  sortop = get_opfamily_member(index->opfamily[0],
6505  index->opcintype[0],
6506  index->opcintype[0],
6508  if (OidIsValid(sortop) &&
6509  get_attstatsslot(&sslot, vardata.statsTuple,
6510  STATISTIC_KIND_CORRELATION, sortop,
6512  {
6513  double varCorrelation;
6514 
6515  Assert(sslot.nnumbers == 1);
6516  varCorrelation = sslot.numbers[0];
6517 
6518  if (index->reverse_sort[0])
6519  varCorrelation = -varCorrelation;
6520 
6521  if (index->nkeycolumns > 1)
6522  costs.indexCorrelation = varCorrelation * 0.75;
6523  else
6524  costs.indexCorrelation = varCorrelation;
6525 
6526  free_attstatsslot(&sslot);
6527  }
6528  }
6529 
6530  ReleaseVariableStats(vardata);
6531 
6532  *indexStartupCost = costs.indexStartupCost;
6533  *indexTotalCost = costs.indexTotalCost;
6534  *indexSelectivity = costs.indexSelectivity;
6535  *indexCorrelation = costs.indexCorrelation;
6536  *indexPages = costs.numIndexPages;
6537 }
Selectivity indexSelectivity
Definition: selfuncs.h:109
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
IndexOptInfo * indexinfo
Definition: pathnodes.h:1207
HeapTuple statsTuple
Definition: selfuncs.h:74
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:705
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:529
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:76
#define MemSet(start, val, len)
Definition: c.h:978
List * indexclauses
Definition: pathnodes.h:1208
double Selectivity
Definition: nodes.h:662
double tuples
Definition: pathnodes.h:824
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: pathnodes.h:825
#define OidIsValid(objectId)
Definition: c.h:651
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
RelOptInfo * rel
Definition: pathnodes.h:820
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
AttrNumber indexcol
Definition: pathnodes.h:1256
double num_sa_scans
Definition: selfuncs.h:116
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5995
float4 * numbers
Definition: lsyscache.h:53
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
double cpu_operator_cost
Definition: costsize.c:115
Cost indexTotalCost
Definition: selfuncs.h:108
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
List * indexquals
Definition: pathnodes.h:1254
Index relid
Definition: pathnodes.h:693
List * lappend(List *list, void *datum)
Definition: list.c:321
Expr * clause
Definition: pathnodes.h:1985
double indexCorrelation
Definition: selfuncs.h:110
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
NullTestType nulltesttype
Definition: primnodes.h:1220
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:114
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3052
#define Assert(condition)
Definition: c.h:745
#define linitial_oid(l)
Definition: pg_list.h:197
int nkeycolumns
Definition: pathnodes.h:829
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:145
Oid * opcintype
Definition: pathnodes.h:834
#define nodeTag(nodeptr)
Definition: nodes.h:534
Cost indexStartupCost
Definition: selfuncs.h:107
Oid * opfamily
Definition: pathnodes.h:833
RTEKind rtekind
Definition: parsenodes.h:976
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:81
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
#define elog(elevel,...)
Definition: elog.h:214
int * indexkeys
Definition: pathnodes.h:830
Oid opno
Definition: primnodes.h:516
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
bool * reverse_sort
Definition: pathnodes.h:836
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define BTEqualStrategyNumber
Definition: stratnum.h:31
double Cost
Definition: nodes.h:663
double numIndexPages
Definition: selfuncs.h:113
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3169
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6213

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

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

Referenced by convert_to_scalar().

4455 {
4456  bytea *valuep = DatumGetByteaPP(value);
4457  bytea *loboundp = DatumGetByteaPP(lobound);
4458  bytea *hiboundp = DatumGetByteaPP(hibound);
4459  int rangelo,
4460  rangehi,
4461  valuelen = VARSIZE_ANY_EXHDR(valuep),
4462  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4463  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4464  i,
4465  minlen;
4466  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4467  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4468  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4469 
4470  /*
4471  * Assume bytea data is uniformly distributed across all byte values.
4472  */
4473  rangelo = 0;
4474  rangehi = 255;
4475 
4476  /*
4477  * Now strip any common prefix of the three strings.
4478  */
4479  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4480  for (i = 0; i < minlen; i++)
4481  {
4482  if (*lostr != *histr || *lostr != *valstr)
4483  break;
4484  lostr++, histr++, valstr++;
4485  loboundlen--, hiboundlen--, valuelen--;
4486  }
4487 
4488  /*
4489  * Now we can do the conversions.
4490  */
4491  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4492  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4493  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4494 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:348
#define Min(x, y)
Definition: c.h:927
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4497
#define DatumGetByteaPP(X)
Definition: fmgr.h:290
static struct @143 value
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:341
int i
Definition: c.h:562

◆ convert_numeric_to_scalar()

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

Definition at line 4176 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4177 {
4178  switch (typid)
4179  {
4180  case BOOLOID:
4181  return (double) DatumGetBool(value);
4182  case INT2OID:
4183  return (double) DatumGetInt16(value);
4184  case INT4OID:
4185  return (double) DatumGetInt32(value);
4186  case INT8OID:
4187  return (double) DatumGetInt64(value);
4188  case FLOAT4OID:
4189  return (double) DatumGetFloat4(value);
4190  case FLOAT8OID:
4191  return (double) DatumGetFloat8(value);
4192  case NUMERICOID:
4193  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4194  return (double)
4196  value));
4197  case OIDOID:
4198  case REGPROCOID:
4199  case REGPROCEDUREOID:
4200  case REGOPEROID:
4201  case REGOPERATOROID:
4202  case REGCLASSOID:
4203  case REGTYPEOID:
4204  case REGCONFIGOID:
4205  case REGDICTIONARYOID:
4206  case REGROLEOID:
4207  case REGNAMESPACEOID:
4208  /* we can treat OIDs as integers... */
4209  return (double) DatumGetObjectId(value);
4210  }
4211 
4212  *failure = true;
4213  return 0;
4214 }
#define DatumGetInt32(X)
Definition: postgres.h:472
#define DatumGetObjectId(X)
Definition: postgres.h:500
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:624
static float4 DatumGetFloat4(Datum X)
Definition: postgres.h:664
#define DatumGetInt64(X)
Definition: postgres.h:607
#define DatumGetInt16(X)
Definition: postgres.h:444
#define DatumGetBool(X)
Definition: postgres.h:393
#define DatumGetFloat8(X)
Definition: postgres.h:714
static struct @143 value
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:3632

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

Referenced by convert_bytea_to_scalar().

4499 {
4500  double num,
4501  denom,
4502  base;
4503 
4504  if (valuelen <= 0)
4505  return 0.0; /* empty string has scalar value 0 */
4506 
4507  /*
4508  * Since base is 256, need not consider more than about 10 chars (even
4509  * this many seems like overkill)
4510  */
4511  if (valuelen > 10)
4512  valuelen = 10;
4513 
4514  /* Convert initial characters to fraction */
4515  base = rangehi - rangelo + 1;
4516  num = 0.0;
4517  denom = base;
4518  while (valuelen-- > 0)
4519  {
4520  int ch = *value++;
4521 
4522  if (ch < rangelo)
4523  ch = rangelo - 1;
4524  else if (ch > rangehi)
4525  ch = rangehi + 1;
4526  num += ((double) (ch - rangelo)) / denom;
4527  denom *= base;
4528  }
4529 
4530  return num;
4531 }
static struct @143 value

◆ convert_one_string_to_scalar()

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

Definition at line 4317 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4318 {
4319  int slen = strlen(value);
4320  double num,
4321  denom,
4322  base;
4323 
4324  if (slen <= 0)
4325  return 0.0; /* empty string has scalar value 0 */
4326 
4327  /*
4328  * There seems little point in considering more than a dozen bytes from
4329  * the string. Since base is at least 10, that will give us nominal
4330  * resolution of at least 12 decimal digits, which is surely far more
4331  * precision than this estimation technique has got anyway (especially in
4332  * non-C locales). Also, even with the maximum possible base of 256, this
4333  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4334  * overflow on any known machine.
4335  */
4336  if (slen > 12)
4337  slen = 12;
4338 
4339  /* Convert initial characters to fraction */
4340  base = rangehi - rangelo + 1;
4341  num = 0.0;
4342  denom = base;
4343  while (slen-- > 0)
4344  {
4345  int ch = (unsigned char) *value++;
4346 
4347  if (ch < rangelo)
4348  ch = rangelo - 1;
4349  else if (ch > rangehi)
4350  ch = rangehi + 1;
4351  num += ((double) (ch - rangelo)) / denom;
4352  denom *= base;
4353  }
4354 
4355  return num;
4356 }
static struct @143 value

◆ convert_string_datum()

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

Definition at line 4368 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4369 {
4370  char *val;
4371 
4372  switch (typid)
4373  {
4374  case CHAROID:
4375  val = (char *) palloc(2);
4376  val[0] = DatumGetChar(value);
4377  val[1] = '\0';
4378  break;
4379  case BPCHAROID:
4380  case VARCHAROID:
4381  case TEXTOID:
4382  val = TextDatumGetCString(value);
4383  break;
4384  case NAMEOID:
4385  {
4387 
4388  val = pstrdup(NameStr(*nm));
4389  break;
4390  }
4391  default:
4392  *failure = true;
4393  return NULL;
4394  }
4395 
4396  if (!lc_collate_is_c(collid))
4397  {
4398  char *xfrmstr;
4399  size_t xfrmlen;
4400  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4401 
4402  /*
4403  * XXX: We could guess at a suitable output buffer size and only call
4404  * strxfrm twice if our guess is too small.
4405  *
4406  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4407  * bogus data or set an error. This is not really a problem unless it
4408  * crashes since it will only give an estimation error and nothing
4409  * fatal.
4410  */
4411  xfrmlen = strxfrm(NULL, val, 0);
4412 #ifdef WIN32
4413 
4414  /*
4415  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4416  * of trying to allocate this much memory (and fail), just return the
4417  * original string unmodified as if we were in the C locale.
4418  */
4419  if (xfrmlen == INT_MAX)
4420  return val;
4421 #endif
4422  xfrmstr = (char *) palloc(xfrmlen + 1);
4423  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4424 
4425  /*
4426  * Some systems (e.g., glibc) can return a smaller value from the
4427  * second call than the first; thus the Assert must be <= not ==.
4428  */
4429  Assert(xfrmlen2 <= xfrmlen);
4430  pfree(val);
4431  val = xfrmstr;
4432  }
4433 
4434  return val;
4435 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
void pfree(void *pointer)
Definition: mcxt.c:1056
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1356
Definition: c.h:616
#define TextDatumGetCString(d)
Definition: builtins.h:88
#define DatumGetChar(X)
Definition: postgres.h:409
static struct @143 value
#define Assert(condition)
Definition: c.h:745
#define DatumGetPointer(X)
Definition: postgres.h:549
void * palloc(Size size)
Definition: mcxt.c:949
#define NameStr(name)
Definition: c.h:622
long val
Definition: informix.c:664
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:121

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

4243 {
4244  int rangelo,
4245  rangehi;
4246  char *sptr;
4247 
4248  rangelo = rangehi = (unsigned char) hibound[0];
4249  for (sptr = lobound; *sptr; sptr++)
4250  {
4251  if (rangelo > (unsigned char) *sptr)
4252  rangelo = (unsigned char) *sptr;
4253  if (rangehi < (unsigned char) *sptr)
4254  rangehi = (unsigned char) *sptr;
4255  }
4256  for (sptr = hibound; *sptr; sptr++)
4257  {
4258  if (rangelo > (unsigned char) *sptr)
4259  rangelo = (unsigned char) *sptr;
4260  if (rangehi < (unsigned char) *sptr)
4261  rangehi = (unsigned char) *sptr;
4262  }
4263  /* If range includes any upper-case ASCII chars, make it include all */
4264  if (rangelo <= 'Z' && rangehi >= 'A')
4265  {
4266  if (rangelo > 'A')
4267  rangelo = 'A';
4268  if (rangehi < 'Z')
4269  rangehi = 'Z';
4270  }
4271  /* Ditto lower-case */
4272  if (rangelo <= 'z' && rangehi >= 'a')
4273  {
4274  if (rangelo > 'a')
4275  rangelo = 'a';
4276  if (rangehi < 'z')
4277  rangehi = 'z';
4278  }
4279  /* Ditto digits */
4280  if (rangelo <= '9' && rangehi >= '0')
4281  {
4282  if (rangelo > '0')
4283  rangelo = '0';
4284  if (rangehi < '9')
4285  rangehi = '9';
4286  }
4287 
4288  /*
4289  * If range includes less than 10 chars, assume we have not got enough
4290  * data, and make it include regular ASCII set.
4291  */
4292  if (rangehi - rangelo < 9)
4293  {
4294  rangelo = ' ';
4295  rangehi = 127;
4296  }
4297 
4298  /*
4299  * Now strip any common prefix of the three strings.
4300  */
4301  while (*lobound)
4302  {
4303  if (*lobound != *hibound || *lobound != *value)
4304  break;
4305  lobound++, hibound++, value++;
4306  }
4307 
4308  /*
4309  * Now we can do the conversions.
4310  */
4311  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4312  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4313  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4314 }
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4317
static struct @143 value

◆ convert_timevalue_to_scalar()

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

Definition at line 4540 of file selfuncs.c.

References date2timestamp_no_overflow(), DatumGetDateADT, DatumGetIntervalP, DatumGetTimeADT, DatumGetTimestamp, DatumGetTimestampTz, DatumGetTimeTzADTP, Interval::day, DAYS_PER_YEAR, Interval::month, MONTHS_PER_YEAR, TimeTzADT::time, Interval::time, USECS_PER_DAY, and TimeTzADT::zone.

Referenced by convert_to_scalar().

4541 {
4542  switch (typid)
4543  {
4544  case TIMESTAMPOID:
4545  return DatumGetTimestamp(value);
4546  case TIMESTAMPTZOID:
4547  return DatumGetTimestampTz(value);
4548  case DATEOID:
4550  case INTERVALOID:
4551  {
4553 
4554  /*
4555  * Convert the month part of Interval to days using assumed
4556  * average month length of 365.25/12.0 days. Not too
4557  * accurate, but plenty good enough for our purposes.
4558  */
4559  return interval->time + interval->day * (double) USECS_PER_DAY +
4560  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
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  *failure = true;
4574  return 0;
4575 }
#define DatumGetDateADT(X)
Definition: date.h:53
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:29
#define DatumGetTimeTzADTP(X)
Definition: date.h:55
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:708
int32 day
Definition: timestamp.h:47
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define DAYS_PER_YEAR
Definition: timestamp.h:68
int32 zone
Definition: date.h:30
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
TimeOffset time
Definition: timestamp.h:45
#define USECS_PER_DAY
Definition: timestamp.h:91
int32 month
Definition: timestamp.h:48
#define DatumGetTimeADT(X)
Definition: date.h:54
static struct @143 value
Definition: date.h:27
#define DatumGetTimestamp(X)
Definition: timestamp.h:27

◆ convert_to_scalar()

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

Definition at line 4030 of file selfuncs.c.

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

Referenced by ineq_histogram_selectivity().

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

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

Definition at line 2237 of file selfuncs.c.

References generate_unaccent_rules::args, ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, elog, eqjoinsel_inner(), eqjoinsel_semi(), ERROR, find_join_input_rel(), free_attstatsslot(), get_attstatsslot(), get_commutator(), get_join_variables(), get_opcode(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, InvalidOid, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, SpecialJoinInfo::jointype, Min, SpecialJoinInfo::min_righthand, OidIsValid, PG_GET_COLLATION, PG_GETARG_INT16, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_FLOAT8, ReleaseVariableStats, RelOptInfo::rows, statistic_proc_security_check(), and VariableStatData::statsTuple.

Referenced by neqjoinsel().

2238 {
2239  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2240  Oid operator = PG_GETARG_OID(1);
2241  List *args = (List *) PG_GETARG_POINTER(2);
2242 
2243 #ifdef NOT_USED
2244  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2245 #endif
2247  Oid collation = PG_GET_COLLATION();
2248  double selec;
2249  double selec_inner;
2250  VariableStatData vardata1;
2251  VariableStatData vardata2;
2252  double nd1;
2253  double nd2;
2254  bool isdefault1;
2255  bool isdefault2;
2256  Oid opfuncoid;
2257  AttStatsSlot sslot1;
2258  AttStatsSlot sslot2;
2259  Form_pg_statistic stats1 = NULL;
2260  Form_pg_statistic stats2 = NULL;
2261  bool have_mcvs1 = false;
2262  bool have_mcvs2 = false;
2263  bool join_is_reversed;
2264  RelOptInfo *inner_rel;
2265 
2266  get_join_variables(root, args, sjinfo,
2267  &vardata1, &vardata2, &join_is_reversed);
2268 
2269  nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2270  nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2271 
2272  opfuncoid = get_opcode(operator);
2273 
2274  memset(&sslot1, 0, sizeof(sslot1));
2275  memset(&sslot2, 0, sizeof(sslot2));
2276 
2277  if (HeapTupleIsValid(vardata1.statsTuple))
2278  {
2279  /* note we allow use of nullfrac regardless of security check */
2280  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2281  if (statistic_proc_security_check(&vardata1, opfuncoid))
2282  have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2283  STATISTIC_KIND_MCV, InvalidOid,
2285  }
2286 
2287  if (HeapTupleIsValid(vardata2.statsTuple))
2288  {
2289  /* note we allow use of nullfrac regardless of security check */
2290  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2291  if (statistic_proc_security_check(&vardata2, opfuncoid))
2292  have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2293  STATISTIC_KIND_MCV, InvalidOid,
2295  }
2296 
2297  /* We need to compute the inner-join selectivity in all cases */
2298  selec_inner = eqjoinsel_inner(opfuncoid, collation,
2299  &vardata1, &vardata2,
2300  nd1, nd2,
2301  isdefault1, isdefault2,
2302  &sslot1, &sslot2,
2303  stats1, stats2,
2304  have_mcvs1, have_mcvs2);
2305 
2306  switch (sjinfo->jointype)
2307  {
2308  case JOIN_INNER:
2309  case JOIN_LEFT:
2310  case JOIN_FULL:
2311  selec = selec_inner;
2312  break;
2313  case JOIN_SEMI:
2314  case JOIN_ANTI:
2315 
2316  /*
2317  * Look up the join's inner relation. min_righthand is sufficient
2318  * information because neither SEMI nor ANTI joins permit any
2319  * reassociation into or out of their RHS, so the righthand will
2320  * always be exactly that set of rels.
2321  */
2322  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2323 
2324  if (!join_is_reversed)
2325  selec = eqjoinsel_semi(opfuncoid, collation,
2326  &vardata1, &vardata2,
2327  nd1, nd2,
2328  isdefault1, isdefault2,
2329  &sslot1, &sslot2,
2330  stats1, stats2,
2331  have_mcvs1, have_mcvs2,
2332  inner_rel);
2333  else
2334  {
2335  Oid commop = get_commutator(operator);
2336  Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2337 
2338  selec = eqjoinsel_semi(commopfuncoid, collation,
2339  &vardata2, &vardata1,
2340  nd2, nd1,
2341  isdefault2, isdefault1,
2342  &sslot2, &sslot1,
2343  stats2, stats1,
2344  have_mcvs2, have_mcvs1,
2345  inner_rel);
2346  }
2347 
2348  /*
2349  * We should never estimate the output of a semijoin to be more
2350  * rows than we estimate for an inner join with the same input
2351  * rels and join condition; it's obviously impossible for that to
2352  * happen. The former estimate is N1 * Ssemi while the latter is
2353  * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2354  * this is worthwhile because of the shakier estimation rules we
2355  * use in eqjoinsel_semi, particularly in cases where it has to
2356  * punt entirely.
2357  */
2358  selec = Min(selec, inner_rel->rows * selec_inner);
2359  break;
2360  default:
2361  /* other values not expected here */
2362  elog(ERROR, "unrecognized join type: %d",
2363  (int) sjinfo->jointype);
2364  selec = 0; /* keep compiler quiet */
2365  break;
2366  }
2367 
2368  free_attstatsslot(&sslot1);
2369  free_attstatsslot(&sslot2);
2370 
2371  ReleaseVariableStats(vardata1);
2372  ReleaseVariableStats(vardata2);
2373 
2374  CLAMP_PROBABILITY(selec);
2375 
2376  PG_RETURN_FLOAT8((float8) selec);
2377 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1421
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Relids min_righthand
Definition: pathnodes.h:2176
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:74
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5244
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:365
#define Min(x, y)
Definition: c.h:927
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define OidIsValid(objectId)
Definition: c.h:651
#define PG_GET_COLLATION()
Definition: fmgr.h:198
JoinType
Definition: nodes.h:696
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
static double eqjoinsel_inner(Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2)
Definition: selfuncs.c:2386
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:498
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4662
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5273
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
static double eqjoinsel_semi(Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2, RelOptInfo *inner_rel)
Definition: selfuncs.c:2583
#define PG_GETARG_INT16(n)
Definition: fmgr.h:271
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:5876
double rows
Definition: pathnodes.h:668
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3052
JoinType jointype
Definition: pathnodes.h:2179
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
#define elog(elevel,...)
Definition: elog.h:214
Definition: pg_list.h:50
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3169

◆ eqjoinsel_inner()

static double eqjoinsel_inner ( Oid  opfuncoid,
Oid  collation,
VariableStatData vardata1,
VariableStatData vardata2,
double  nd1,
double  nd2,
bool  isdefault1,
bool  isdefault2,
AttStatsSlot sslot1,
AttStatsSlot sslot2,
Form_pg_statistic  stats1,
Form_pg_statistic  stats2,
bool  have_mcvs1,
bool  have_mcvs2 
)
static

Definition at line 2386 of file selfuncs.c.

References CLAMP_PROBABILITY, DatumGetBool, fmgr_info(), FunctionCallInvoke, i, InitFunctionCallInfoData, LOCAL_FCINFO, AttStatsSlot::numbers, AttStatsSlot::nvalues, palloc0(), pfree(), and AttStatsSlot::values.

Referenced by eqjoinsel().

2393 {
2394  double selec;
2395 
2396  if (have_mcvs1 && have_mcvs2)
2397  {
2398  /*
2399  * We have most-common-value lists for both relations. Run through
2400  * the lists to see which MCVs actually join to each other with the
2401  * given operator. This allows us to determine the exact join
2402  * selectivity for the portion of the relations represented by the MCV
2403  * lists. We still have to estimate for the remaining population, but
2404  * in a skewed distribution this gives us a big leg up in accuracy.
2405  * For motivation see the analysis in Y. Ioannidis and S.
2406  * Christodoulakis, "On the propagation of errors in the size of join
2407  * results", Technical Report 1018, Computer Science Dept., University
2408  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2409  */
2410  LOCAL_FCINFO(fcinfo, 2);
2411  FmgrInfo eqproc;
2412  bool *hasmatch1;
2413  bool *hasmatch2;
2414  double nullfrac1 = stats1->stanullfrac;
2415  double nullfrac2 = stats2->stanullfrac;
2416  double matchprodfreq,
2417  matchfreq1,
2418  matchfreq2,
2419  unmatchfreq1,
2420  unmatchfreq2,
2421  otherfreq1,
2422  otherfreq2,
2423  totalsel1,
2424  totalsel2;
2425  int i,
2426  nmatches;
2427 
2428  fmgr_info(opfuncoid, &eqproc);
2429 
2430  /*
2431  * Save a few cycles by setting up the fcinfo struct just once. Using
2432  * FunctionCallInvoke directly also avoids failure if the eqproc
2433  * returns NULL, though really equality functions should never do
2434  * that.
2435  */
2436  InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2437  NULL, NULL);
2438  fcinfo->args[0].isnull = false;
2439  fcinfo->args[1].isnull = false;
2440 
2441  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2442  hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2443 
2444  /*
2445  * Note we assume that each MCV will match at most one member of the
2446  * other MCV list. If the operator isn't really equality, there could
2447  * be multiple matches --- but we don't look for them, both for speed
2448  * and because the math wouldn't add up...
2449  */
2450  matchprodfreq = 0.0;
2451  nmatches = 0;
2452  for (i = 0; i < sslot1->nvalues; i++)
2453  {
2454  int j;
2455 
2456  fcinfo->args[0].value = sslot1->values[i];
2457 
2458  for (j = 0; j < sslot2->nvalues; j++)
2459  {
2460  Datum fresult;
2461 
2462  if (hasmatch2[j])
2463  continue;
2464  fcinfo->args[1].value = sslot2->values[j];
2465  fcinfo->isnull = false;
2466  fresult = FunctionCallInvoke(fcinfo);
2467  if (!fcinfo->isnull && DatumGetBool(fresult))
2468  {
2469  hasmatch1[i] = hasmatch2[j] = true;
2470  matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2471  nmatches++;
2472  break;
2473  }
2474  }
2475  }
2476  CLAMP_PROBABILITY(matchprodfreq);
2477  /* Sum up frequencies of matched and unmatched MCVs */
2478  matchfreq1 = unmatchfreq1 = 0.0;
2479  for (i = 0; i < sslot1->nvalues; i++)
2480  {
2481  if (hasmatch1[i])
2482  matchfreq1 += sslot1->numbers[i];
2483  else
2484  unmatchfreq1 += sslot1->numbers[i];
2485  }
2486  CLAMP_PROBABILITY(matchfreq1);
2487  CLAMP_PROBABILITY(unmatchfreq1);
2488  matchfreq2 = unmatchfreq2 = 0.0;
2489  for (i = 0; i < sslot2->nvalues; i++)
2490  {
2491  if (hasmatch2[i])
2492  matchfreq2 += sslot2->numbers[i];
2493  else
2494  unmatchfreq2 += sslot2->numbers[i];
2495  }
2496  CLAMP_PROBABILITY(matchfreq2);
2497  CLAMP_PROBABILITY(unmatchfreq2);
2498  pfree(hasmatch1);
2499  pfree(hasmatch2);
2500 
2501  /*
2502  * Compute total frequency of non-null values that are not in the MCV
2503  * lists.
2504  */
2505  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2506  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2507  CLAMP_PROBABILITY(otherfreq1);
2508  CLAMP_PROBABILITY(otherfreq2);
2509 
2510  /*
2511  * We can estimate the total selectivity from the point of view of
2512  * relation 1 as: the known selectivity for matched MCVs, plus
2513  * unmatched MCVs that are assumed to match against random members of
2514  * relation 2's non-MCV population, plus non-MCV values that are
2515  * assumed to match against random members of relation 2's unmatched
2516  * MCVs plus non-MCV values.
2517  */
2518  totalsel1 = matchprodfreq;
2519  if (nd2 > sslot2->nvalues)
2520  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2521  if (nd2 > nmatches)
2522  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2523  (nd2 - nmatches);
2524  /* Same estimate from the point of view of relation 2. */
2525  totalsel2 = matchprodfreq;
2526  if (nd1 > sslot1->nvalues)
2527  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2528  if (nd1 > nmatches)
2529  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2530  (nd1 - nmatches);
2531 
2532  /*
2533  * Use the smaller of the two estimates. This can be justified in
2534  * essentially the same terms as given below for the no-stats case: to
2535  * a first approximation, we are estimating from the point of view of
2536  * the relation with smaller nd.
2537  */
2538  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2539  }
2540  else
2541  {
2542  /*
2543  * We do not have MCV lists for both sides. Estimate the join
2544  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2545  * is plausible if we assume that the join operator is strict and the
2546  * non-null values are about equally distributed: a given non-null
2547  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2548  * of rel2, so total join rows are at most
2549  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2550  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2551  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2552  * with MIN() is an upper bound. Using the MIN() means we estimate
2553  * from the point of view of the relation with smaller nd (since the
2554  * larger nd is determining the MIN). It is reasonable to assume that
2555  * most tuples in this rel will have join partners, so the bound is
2556  * probably reasonably tight and should be taken as-is.
2557  *
2558  * XXX Can we be smarter if we have an MCV list for just one side? It
2559  * seems that if we assume equal distribution for the other side, we
2560  * end up with the same answer anyway.
2561  */
2562  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2563  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2564 
2565  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2566  if (nd1 > nd2)
2567  selec /= nd1;
2568  else
2569  selec /= nd2;
2570  }
2571 
2572  return selec;
2573 }
Definition: fmgr.h:56
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
void pfree(void *pointer)
Definition: mcxt.c:1056
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
float4 * numbers
Definition: lsyscache.h:53
#define DatumGetBool(X)
Definition: postgres.h:393
void * palloc0(Size size)
Definition: mcxt.c:980
uintptr_t Datum
Definition: postgres.h:367
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
Datum * values
Definition: lsyscache.h:50
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
int i

◆ eqjoinsel_semi()

static double eqjoinsel_semi ( Oid  opfuncoid,
Oid  collation,
VariableStatData vardata1,
VariableStatData vardata2,
double  nd1,
double  nd2,
bool  isdefault1,
bool  isdefault2,
AttStatsSlot sslot1,
AttStatsSlot sslot2,
Form_pg_statistic  stats1,
Form_pg_statistic  stats2,
bool  have_mcvs1,
bool  have_mcvs2,
RelOptInfo inner_rel 
)
static

Definition at line 2583 of file selfuncs.c.

References CLAMP_PROBABILITY, DatumGetBool, fmgr_info(), FunctionCallInvoke, i, InitFunctionCallInfoData, LOCAL_FCINFO, Min, AttStatsSlot::numbers, AttStatsSlot::nvalues, OidIsValid, palloc0(), pfree(), VariableStatData::rel, RelOptInfo::rows, and AttStatsSlot::values.

Referenced by eqjoinsel().

2591 {
2592  double selec;
2593 
2594  /*
2595  * We clamp nd2 to be not more than what we estimate the inner relation's
2596  * size to be. This is intuitively somewhat reasonable since obviously
2597  * there can't be more than that many distinct values coming from the
2598  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2599  * likewise) is that this is the only pathway by which restriction clauses
2600  * applied to the inner rel will affect the join result size estimate,
2601  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2602  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2603  * the selectivity of outer-rel restrictions.
2604  *
2605  * We can apply this clamping both with respect to the base relation from
2606  * which the join variable comes (if there is just one), and to the
2607  * immediate inner input relation of the current join.
2608  *
2609  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2610  * great, maybe, but it didn't come out of nowhere either. This is most
2611  * helpful when the inner relation is empty and consequently has no stats.
2612  */
2613  if (vardata2->rel)
2614  {
2615  if (nd2 >= vardata2->rel->rows)
2616  {
2617  nd2 = vardata2->rel->rows;
2618  isdefault2 = false;
2619  }
2620  }
2621  if (nd2 >= inner_rel->rows)
2622  {
2623  nd2 = inner_rel->rows;
2624  isdefault2 = false;
2625  }
2626 
2627  if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2628  {
2629  /*
2630  * We have most-common-value lists for both relations. Run through
2631  * the lists to see which MCVs actually join to each other with the
2632  * given operator. This allows us to determine the exact join
2633  * selectivity for the portion of the relations represented by the MCV
2634  * lists. We still have to estimate for the remaining population, but
2635  * in a skewed distribution this gives us a big leg up in accuracy.
2636  */
2637  LOCAL_FCINFO(fcinfo, 2);
2638  FmgrInfo eqproc;
2639  bool *hasmatch1;
2640  bool *hasmatch2;
2641  double nullfrac1 = stats1->stanullfrac;
2642  double matchfreq1,
2643  uncertainfrac,
2644  uncertain;
2645  int i,
2646  nmatches,
2647  clamped_nvalues2;
2648 
2649  /*
2650  * The clamping above could have resulted in nd2 being less than
2651  * sslot2->nvalues; in which case, we assume that precisely the nd2
2652  * most common values in the relation will appear in the join input,
2653  * and so compare to only the first nd2 members of the MCV list. Of
2654  * course this is frequently wrong, but it's the best bet we can make.
2655  */
2656  clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2657 
2658  fmgr_info(opfuncoid, &eqproc);
2659 
2660  /*
2661  * Save a few cycles by setting up the fcinfo struct just once. Using
2662  * FunctionCallInvoke directly also avoids failure if the eqproc
2663  * returns NULL, though really equality functions should never do
2664  * that.
2665  */
2666  InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2667  NULL, NULL);
2668  fcinfo->args[0].isnull = false;
2669  fcinfo->args[1].isnull = false;
2670 
2671  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2672  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2673 
2674  /*
2675  * Note we assume that each MCV will match at most one member of the
2676  * other MCV list. If the operator isn't really equality, there could
2677  * be multiple matches --- but we don't look for them, both for speed
2678  * and because the math wouldn't add up...
2679  */
2680  nmatches = 0;
2681  for (i = 0; i < sslot1->nvalues; i++)
2682  {
2683  int j;
2684 
2685  fcinfo->args[0].value = sslot1->values[i];
2686 
2687  for (j = 0; j < clamped_nvalues2; j++)
2688  {
2689  Datum fresult;
2690 
2691  if (hasmatch2[j])
2692  continue;
2693  fcinfo->args[1].value = sslot2->values[j];
2694  fcinfo->isnull = false;
2695  fresult = FunctionCallInvoke(fcinfo);
2696  if (!fcinfo->isnull && DatumGetBool(fresult))
2697  {
2698  hasmatch1[i] = hasmatch2[j] = true;
2699  nmatches++;
2700  break;
2701  }
2702  }
2703  }
2704  /* Sum up frequencies of matched MCVs */
2705  matchfreq1 = 0.0;
2706  for (i = 0; i < sslot1->nvalues; i++)
2707  {
2708  if (hasmatch1[i])
2709  matchfreq1 += sslot1->numbers[i];
2710  }
2711  CLAMP_PROBABILITY(matchfreq1);
2712  pfree(hasmatch1);
2713  pfree(hasmatch2);
2714 
2715  /*
2716  * Now we need to estimate the fraction of relation 1 that has at
2717  * least one join partner. We know for certain that the matched MCVs
2718  * do, so that gives us a lower bound, but we're really in the dark
2719  * about everything else. Our crude approach is: if nd1 <= nd2 then
2720  * assume all non-null rel1 rows have join partners, else assume for
2721  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2722  * can discount the known-matched MCVs from the distinct-values counts
2723  * before doing the division.
2724  *
2725  * Crude as the above is, it's completely useless if we don't have
2726  * reliable ndistinct values for both sides. Hence, if either nd1 or
2727  * nd2 is default, punt and assume half of the uncertain rows have
2728  * join partners.
2729  */
2730  if (!isdefault1 && !isdefault2)
2731  {
2732  nd1 -= nmatches;
2733  nd2 -= nmatches;
2734  if (nd1 <= nd2 || nd2 < 0)
2735  uncertainfrac = 1.0;
2736  else
2737  uncertainfrac = nd2 / nd1;
2738  }
2739  else
2740  uncertainfrac = 0.5;
2741  uncertain = 1.0 - matchfreq1 - nullfrac1;
2742  CLAMP_PROBABILITY(uncertain);
2743  selec = matchfreq1 + uncertainfrac * uncertain;
2744  }
2745  else
2746  {
2747  /*
2748  * Without MCV lists for both sides, we can only use the heuristic
2749  * about nd1 vs nd2.
2750  */
2751  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2752 
2753  if (!isdefault1 && !isdefault2)
2754  {
2755  if (nd1 <= nd2 || nd2 < 0)
2756  selec = 1.0 - nullfrac1;
2757  else
2758  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2759  }
2760  else
2761  selec = 0.5 * (1.0 - nullfrac1);
2762  }
2763 
2764  return selec;
2765 }
Definition: fmgr.h:56
RelOptInfo * rel
Definition: selfuncs.h:73
#define Min(x, y)
Definition: c.h:927
#define OidIsValid(objectId)
Definition: c.h:651
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
void pfree(void *pointer)
Definition: mcxt.c:1056
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
float4 * numbers
Definition: lsyscache.h:53
#define DatumGetBool(X)
Definition: postgres.h:393
void * palloc0(Size size)
Definition: mcxt.c:980
uintptr_t Datum
Definition: postgres.h:367
double rows
Definition: pathnodes.h:668
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
Datum * values
Definition: lsyscache.h:50
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
int i

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 224 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

225 {
226  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
227 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:365
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:233
double float8
Definition: c.h:498

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

Definition at line 233 of file selfuncs.c.

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

Referenced by eqsel(), and neqsel().

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

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

Definition at line 2132 of file selfuncs.c.

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

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

2133 {
2134  /* look through any binary-compatible relabeling of arrayexpr */
2135  arrayexpr = strip_array_coercion(arrayexpr);
2136 
2137  if (arrayexpr && IsA(arrayexpr, Const))
2138  {
2139  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2140  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2141  ArrayType *arrayval;
2142 
2143  if (arrayisnull)
2144  return 0;
2145  arrayval = DatumGetArrayTypeP(arraydatum);
2146  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2147  }
2148  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2149  !((ArrayExpr *) arrayexpr)->multidims)
2150  {
2151  return list_length(((ArrayExpr *) arrayexpr)->elements);
2152  }
2153  else
2154  {
2155  /* default guess --- see also scalararraysel */
2156  return 10;
2157  }
2158 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:282
uintptr_t Datum
Definition: postgres.h:367
static int list_length(const List *l)
Definition: pg_list.h:169
#define ARR_NDIM(a)
Definition: array.h:278
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1780
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ estimate_hash_bucket_stats()

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

Definition at line 3720 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

3723 {
3724  VariableStatData vardata;
3725  double estfract,
3726  ndistinct,
3727  stanullfrac,
3728  avgfreq;
3729  bool isdefault;
3730  AttStatsSlot sslot;
3731 
3732  examine_variable(root, hashkey, 0, &vardata);
3733 
3734  /* Look up the frequency of the most common value, if available */
3735  *mcv_freq = 0.0;
3736 
3737  if (HeapTupleIsValid(vardata.statsTuple))
3738  {
3739  if (get_attstatsslot(&sslot, vardata.statsTuple,
3740  STATISTIC_KIND_MCV, InvalidOid,
3742  {
3743  /*
3744  * The first MCV stat is for the most common value.
3745  */
3746  if (sslot.nnumbers > 0)
3747  *mcv_freq = sslot.numbers[0];
3748  free_attstatsslot(&sslot);
3749  }
3750  }
3751 
3752  /* Get number of distinct values */
3753  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3754 
3755  /*
3756  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3757  * mcv_freq is known to be even higher than that, use it instead.
3758  */
3759  if (isdefault)
3760  {
3761  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3762  ReleaseVariableStats(vardata);
3763  return;
3764  }
3765 
3766  /* Get fraction that are null */
3767  if (HeapTupleIsValid(vardata.statsTuple))
3768  {
3769  Form_pg_statistic stats;
3770 
3771  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3772  stanullfrac = stats->stanullfrac;
3773  }
3774  else
3775  stanullfrac = 0.0;
3776 
3777  /* Compute avg freq of all distinct data values in raw relation */
3778  avgfreq = (1.0 - stanullfrac) / ndistinct;
3779 
3780  /*
3781  * Adjust ndistinct to account for restriction clauses. Observe we are
3782  * assuming that the data distribution is affected uniformly by the
3783  * restriction clauses!
3784  *
3785  * XXX Possibly better way, but much more expensive: multiply by
3786  * selectivity of rel's restriction clauses that mention the target Var.
3787  */
3788  if (vardata.rel && vardata.rel->tuples > 0)
3789  {
3790  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3791  ndistinct = clamp_row_est(ndistinct);
3792  }
3793 
3794  /*
3795  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3796  * number of buckets is less than the expected number of distinct values;
3797  * otherwise it is 1/ndistinct.
3798  */
3799  if (ndistinct > nbuckets)
3800  estfract = 1.0 / nbuckets;
3801  else
3802  estfract = 1.0 / ndistinct;
3803 
3804  /*
3805  * Adjust estimated bucketsize upward to account for skewed distribution.
3806  */
3807  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3808  estfract *= *mcv_freq / avgfreq;
3809 
3810  /*
3811  * Clamp bucketsize to sane range (the above adjustment could easily
3812  * produce an out-of-range result). We set the lower bound a little above
3813  * zero, since zero isn't a very sane result.
3814  */
3815  if (estfract < 1.0e-6)
3816  estfract = 1.0e-6;
3817  else if (estfract > 1.0)
3818  estfract = 1.0;
3819 
3820  *bucketsize_frac = (Selectivity) estfract;
3821 
3822  ReleaseVariableStats(vardata);
3823 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
HeapTuple statsTuple
Definition: selfuncs.h:74
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:705
RelOptInfo * rel
Definition: selfuncs.h:73
double Selectivity
Definition: nodes.h:662
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5273
float4 * numbers
Definition: lsyscache.h:53
double rows
Definition: pathnodes.h:668
#define InvalidOid
Definition: postgres_ext.h:36
#define Max(x, y)
Definition: c.h:921
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4724
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3052
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
e
Definition: preproc-init.c:82
double clamp_row_est(double nrows)
Definition: costsize.c:190
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3169

◆ estimate_hashagg_tablesize()

double estimate_hashagg_tablesize ( Path path,
const AggClauseCosts agg_costs,
double  dNumGroups 
)

Definition at line 3839 of file selfuncs.c.

References hash_agg_entry_size(), AggClauseCosts::numAggs, Path::pathtarget, AggClauseCosts::transitionSpace, and PathTarget::width.

Referenced by add_paths_to_grouping_rel(), consider_groupingsets_paths(), and create_partial_grouping_paths().

3841 {
3842  Size hashentrysize = hash_agg_entry_size(agg_costs->numAggs,
3843  path->pathtarget->width,
3844  agg_costs->transitionSpace);
3845 
3846  /*
3847  * Note that this disregards the effect of fill-factor and growth policy
3848  * of the hash table. That's probably ok, given that the default
3849  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3850  * "double-in-size" growth policies here.
3851  */
3852  return hashentrysize * dNumGroups;
3853 }
PathTarget * pathtarget
Definition: pathnodes.h:1145
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1680
size_t Size
Definition: c.h:473
Size transitionSpace
Definition: pathnodes.h:64

◆ estimate_multivariate_ndistinct()

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

Definition at line 3874 of file selfuncs.c.

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

Referenced by estimate_num_groups().

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

◆ estimate_num_groups()

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

Definition at line 3357 of file selfuncs.c.

References add_unique_group_var(), Assert, clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), expression_returns_set_rows(), exprType(), for_each_cell, HeapTupleIsValid, i, IS_SIMPLE_REL, VariableStatData::isunique, lappend(), lfirst, linitial, list_length(), list_member_int(), list_second_cell(), 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(), cost_incremental_sort(), create_distinct_paths(), create_unique_path(), estimate_path_cost_size(), get_number_of_groups(), and recurse_set_operations().

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

◆ examine_simple_variable()

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

Definition at line 4997 of file selfuncs.c.

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, Alias::aliasname, PlannerInfo::append_rel_array, Assert, BoolGetDatum, RangeTblEntry::checkAsUser, 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(), NIL, AppendRelInfo::num_child_cols, ObjectIdGetDatum, AppendRelInfo::parent_colnos, AppendRelInfo::parent_relid, PlannerInfo::parse, pg_attribute_aclcheck(), pg_class_aclcheck(), planner_rt_fetch, ReleaseSysCache(), RangeTblEntry::relid, TargetEntry::resjunk, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, SearchSysCache3(), RangeTblEntry::security_barrier, RangeTblEntry::securityQuals, 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().

4999 {
5000  RangeTblEntry *rte = root->simple_rte_array[var->varno];
5001 
5002  Assert(IsA(rte, RangeTblEntry));
5003 
5005  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
5006  {
5007  /*
5008  * The hook took control of acquiring a stats tuple. If it did supply
5009  * a tuple, it'd better have supplied a freefunc.
5010  */
5011  if (HeapTupleIsValid(vardata->statsTuple) &&
5012  !vardata->freefunc)
5013  elog(ERROR, "no function provided to release variable stats with");
5014  }
5015  else if (rte->rtekind == RTE_RELATION)
5016  {
5017  /*
5018  * Plain table or parent of an inheritance appendrel, so look up the
5019  * column in pg_statistic
5020  */
5022  ObjectIdGetDatum(rte->relid),
5023  Int16GetDatum(var->varattno),
5024  BoolGetDatum(rte->inh));
5025  vardata->freefunc = ReleaseSysCache;
5026 
5027  if (HeapTupleIsValid(vardata->statsTuple))
5028  {
5029  Oid userid;
5030 
5031  /*
5032  * Check if user has permission to read this column. We require
5033  * all rows to be accessible, so there must be no securityQuals
5034  * from security barrier views or RLS policies. Use checkAsUser
5035  * if it's set, in case we're accessing the table via a view.
5036  */
5037  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5038 
5039  vardata->acl_ok =
5040  rte->securityQuals == NIL &&
5041  ((pg_class_aclcheck(rte->relid, userid,
5042  ACL_SELECT) == ACLCHECK_OK) ||
5043  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
5044  ACL_SELECT) == ACLCHECK_OK));
5045 
5046  /*
5047  * If the user doesn't have permissions to access an inheritance
5048  * child relation or specifically this attribute, check the
5049  * permissions of the table/column actually mentioned in the
5050  * query, since most likely the user does have that permission
5051  * (else the query will fail at runtime), and if the user can read
5052  * the column there then he can get the values of the child table
5053  * too. To do that, we must find out which of the root parent's
5054  * attributes the child relation's attribute corresponds to.
5055  */
5056  if (!vardata->acl_ok && var->varattno > 0 &&
5057  root->append_rel_array != NULL)
5058  {
5059  AppendRelInfo *appinfo;
5060  Index varno = var->varno;
5061  int varattno = var->varattno;
5062  bool found = false;
5063 
5064  appinfo = root->append_rel_array[varno];
5065 
5066  /*
5067  * Partitions are mapped to their immediate parent, not the
5068  * root parent, so must be ready to walk up multiple
5069  * AppendRelInfos. But stop if we hit a parent that is not
5070  * RTE_RELATION --- that's a flattened UNION ALL subquery, not
5071  * an inheritance parent.
5072  */
5073  while (appinfo &&
5074  planner_rt_fetch(appinfo->parent_relid,
5075  root)->rtekind == RTE_RELATION)
5076  {
5077  int parent_varattno;
5078 
5079  found = false;
5080  if (varattno <= 0 || varattno > appinfo->num_child_cols)
5081  break; /* safety check */
5082  parent_varattno = appinfo->parent_colnos[varattno - 1];
5083  if (parent_varattno == 0)
5084  break; /* Var is local to child */
5085 
5086  varno = appinfo->parent_relid;
5087  varattno = parent_varattno;
5088  found = true;
5089 
5090  /* If the parent is itself a child, continue up. */
5091  appinfo = root->append_rel_array[varno];
5092  }
5093 
5094  /*
5095  * In rare cases, the Var may be local to the child table, in
5096  * which case, we've got to live with having no access to this
5097  * column's stats.
5098  */
5099  if (!found)
5100  return;
5101 
5102  /* Repeat the access check on this parent rel & column */
5103  rte = planner_rt_fetch(varno, root);
5104  Assert(rte->rtekind == RTE_RELATION);
5105 
5106  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5107 
5108  vardata->acl_ok =
5109  rte->securityQuals == NIL &&
5110  ((pg_class_aclcheck(rte->relid, userid,
5111  ACL_SELECT) == ACLCHECK_OK) ||
5112  (pg_attribute_aclcheck(rte->relid, varattno, userid,
5113  ACL_SELECT) == ACLCHECK_OK));
5114  }
5115  }
5116  else
5117  {
5118  /* suppress any possible leakproofness checks later */
5119  vardata->acl_ok = true;
5120  }
5121  }
5122  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
5123  {
5124  /*
5125  * Plain subquery (not one that was converted to an appendrel).
5126  */
5127  Query *subquery = rte->subquery;
5128  RelOptInfo *rel;
5129  TargetEntry *ste;
5130 
5131  /*
5132  * Punt if it's a whole-row var rather than a plain column reference.
5133  */
5134  if (var->varattno == InvalidAttrNumber)
5135  return;
5136 
5137  /*
5138  * Punt if subquery uses set operations or GROUP BY, as these will
5139  * mash underlying columns' stats beyond recognition. (Set ops are
5140  * particularly nasty; if we forged ahead, we would return stats
5141  * relevant to only the leftmost subselect...) DISTINCT is also
5142  * problematic, but we check that later because there is a possibility
5143  * of learning something even with it.
5144  */
5145  if (subquery->setOperations ||
5146  subquery->groupClause)
5147  return;
5148 
5149  /*
5150  * OK, fetch RelOptInfo for subquery. Note that we don't change the
5151  * rel returned in vardata, since caller expects it to be a rel of the
5152  * caller's query level. Because we might already be recursing, we
5153  * can't use that rel pointer either, but have to look up the Var's
5154  * rel afresh.
5155  */
5156  rel = find_base_rel(root, var->varno);
5157 
5158  /* If the subquery hasn't been planned yet, we have to punt */
5159  if (rel->subroot == NULL)
5160  return;
5161  Assert(IsA(rel->subroot, PlannerInfo));
5162 
5163  /*
5164  * Switch our attention to the subquery as mangled by the planner. It
5165  * was okay to look at the pre-planning version for the tests above,
5166  * but now we need a Var that will refer to the subroot's live
5167  * RelOptInfos. For instance, if any subquery pullup happened during
5168  * planning, Vars in the targetlist might have gotten replaced, and we
5169  * need to see the replacement expressions.
5170  */
5171  subquery = rel->subroot->parse;
5172  Assert(IsA(subquery, Query));
5173 
5174  /* Get the subquery output expression referenced by the upper Var */
5175  ste = get_tle_by_resno(subquery->targetList, var->varattno);
5176  if (ste == NULL || ste->resjunk)
5177  elog(ERROR, "subquery %s does not have attribute %d",
5178  rte->eref->aliasname, var->varattno);
5179  var = (Var *) ste->expr;
5180 
5181  /*
5182  * If subquery uses DISTINCT, we can't make use of any stats for the
5183  * variable ... but, if it's the only DISTINCT column, we are entitled
5184  * to consider it unique. We do the test this way so that it works
5185  * for cases involving DISTINCT ON.
5186  */
5187  if (subquery->distinctClause)
5188  {
5189  if (list_length(subquery->distinctClause) == 1 &&
5190  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5191  vardata->isunique = true;
5192  /* cannot go further */
5193  return;
5194  }
5195 
5196  /*
5197  * If the sub-query originated from a view with the security_barrier
5198  * attribute, we must not look at the variable's statistics, though it
5199  * seems all right to notice the existence of a DISTINCT clause. So
5200  * stop here.
5201  *
5202  * This is probably a harsher restriction than necessary; it's
5203  * certainly OK for the selectivity estimator (which is a C function,
5204  * and therefore omnipotent anyway) to look at the statistics. But
5205  * many selectivity estimators will happily *invoke the operator
5206  * function* to try to work out a good estimate - and that's not OK.
5207  * So for now, don't dig down for stats.
5208  */
5209  if (rte->security_barrier)
5210  return;
5211 
5212  /* Can only handle a simple Var of subquery's query level */
5213  if (var && IsA(var, Var) &&
5214  var->varlevelsup == 0)
5215  {
5216  /*
5217  * OK, recurse into the subquery. Note that the original setting
5218  * of vardata->isunique (which will surely be false) is left
5219  * unchanged in this situation. That's what we want, since even
5220  * if the underlying column is unique, the subquery may have
5221  * joined to other tables in a way that creates duplicates.
5222  */
5223  examine_simple_variable(rel->subroot, var, vardata);
5224  }
5225  }
5226  else
5227  {
5228  /*
5229  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
5230  * won't see RTE_JOIN here because join alias Vars have already been
5231  * flattened.) There's not much we can do with function outputs, but
5232  * maybe someday try to be smarter about VALUES and/or CTEs.
5233  */
5234  }
5235 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Query * parse
Definition: pathnodes.h:179
Index varlevelsup
Definition: primnodes.h:191
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4449
int num_child_cols
Definition: pathnodes.h:2265
HeapTuple statsTuple
Definition: selfuncs.h:74
Oid GetUserId(void)
Definition: miscinit.c:448
AttrNumber * parent_colnos
Definition: pathnodes.h:2266
List * securityQuals
Definition: parsenodes.h:1125
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:76
AttrNumber varattno
Definition: primnodes.h:186
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4997
List * targetList
Definition: parsenodes.h:140
PlannerInfo * subroot
Definition: pathnodes.h:709
bool resjunk
Definition: primnodes.h:1414
List * distinctClause
Definition: parsenodes.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:211
Index varno
Definition: primnodes.h:184
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ACL_SELECT
Definition: parsenodes.h:75
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:219
unsigned int Index
Definition: c.h:482
bool security_barrier
Definition: parsenodes.h:1012
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1407
static int list_length(const List *l)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4563
RTEKind rtekind
Definition: parsenodes.h:976
Node * setOperations
Definition: parsenodes.h:166
Query * subquery
Definition: parsenodes.h:1011
List * groupClause
Definition: parsenodes.h:148
#define elog(elevel,...)
Definition: elog.h:214
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1115
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
Index parent_relid
Definition: pathnodes.h:2229

◆ examine_variable()

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

Definition at line 4724 of file selfuncs.c.

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, PlannerInfo::append_rel_array, arg, Assert, VariableStatData::atttype, VariableStatData::atttypmod, BMS_EMPTY_SET, bms_free(), bms_is_member(), bms_membership(), BMS_MULTIPLE, BMS_SINGLETON, bms_singleton_member(), BoolGetDatum, RangeTblEntry::checkAsUser, elog, equal(), ERROR, examine_simple_variable(), exprType(), exprTypmod(), find_base_rel(), find_join_rel(), VariableStatData::freefunc, get_index_stats_hook, GetUserId(), has_unique_index(), HeapTupleIsValid, IndexOptInfo::indexkeys, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, IndexOptInfo::indpred, Int16GetDatum, IsA, VariableStatData::isunique, lfirst, list_head(), lnext(), MemSet, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, ObjectIdGetDatum, AppendRelInfo::parent_relid, pg_class_aclcheck(), planner_rt_fetch, IndexOptInfo::predOK, pull_varnos(), VariableStatData::rel, IndexOptInfo::rel, ReleaseSysCache(), RelOptInfo::relid, RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), RangeTblEntry::securityQuals, 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().

4726 {
4727  Node *basenode;
4728  Relids varnos;
4729  RelOptInfo *onerel;
4730 
4731  /* Make sure we don't return dangling pointers in vardata */
4732  MemSet(vardata, 0, sizeof(VariableStatData));
4733 
4734  /* Save the exposed type of the expression */
4735  vardata->vartype = exprType(node);
4736 
4737  /* Look inside any binary-compatible relabeling */
4738 
4739  if (IsA(node, RelabelType))
4740  basenode = (Node *) ((RelabelType *) node)->arg;
4741  else
4742  basenode = node;
4743 
4744  /* Fast path for a simple Var */
4745 
4746  if (IsA(basenode, Var) &&
4747  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4748  {
4749  Var *var = (Var *) basenode;
4750 
4751  /* Set up result fields other than the stats tuple */
4752  vardata->var = basenode; /* return Var without relabeling */
4753  vardata->rel = find_base_rel(root, var->varno);
4754  vardata->atttype = var->vartype;
4755  vardata->atttypmod = var->vartypmod;
4756  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4757 
4758  /* Try to locate some stats */
4759  examine_simple_variable(root, var, vardata);
4760 
4761  return;
4762  }
4763 
4764  /*
4765  * Okay, it's a more complicated expression. Determine variable
4766  * membership. Note that when varRelid isn't zero, only vars of that
4767  * relation are considered "real" vars.
4768  */
4769  varnos = pull_varnos(basenode);
4770 
4771  onerel = NULL;
4772 
4773  switch (bms_membership(varnos))
4774  {
4775  case BMS_EMPTY_SET:
4776  /* No Vars at all ... must be pseudo-constant clause */
4777  break;
4778  case BMS_SINGLETON:
4779  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4780  {
4781  onerel = find_base_rel(root,
4782  (varRelid ? varRelid : bms_singleton_member(varnos)));
4783  vardata->rel = onerel;
4784  node = basenode; /* strip any relabeling */
4785  }
4786  /* else treat it as a constant */
4787  break;
4788  case BMS_MULTIPLE:
4789  if (varRelid == 0)
4790  {
4791  /* treat it as a variable of a join relation */
4792  vardata->rel = find_join_rel(root, varnos);
4793  node = basenode; /* strip any relabeling */
4794  }
4795  else if (bms_is_member(varRelid, varnos))
4796  {
4797  /* ignore the vars belonging to other relations */
4798  vardata->rel = find_base_rel(root, varRelid);
4799  node = basenode; /* strip any relabeling */
4800  /* note: no point in expressional-index search here */
4801  }
4802  /* else treat it as a constant */
4803  break;
4804  }
4805 
4806  bms_free(varnos);
4807 
4808  vardata->var = node;
4809  vardata->atttype = exprType(node);
4810  vardata->atttypmod = exprTypmod(node);
4811 
4812  if (onerel)
4813  {
4814  /*
4815  * We have an expression in vars of a single relation. Try to match
4816  * it to expressional index columns, in hopes of finding some
4817  * statistics.
4818  *
4819  * Note that we consider all index columns including INCLUDE columns,
4820  * since there could be stats for such columns. But the test for
4821  * uniqueness needs to be warier.
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->nkeycolumns == 1 &&
4858  pos == 0 &&
4859  (index->indpred == NIL || index->predOK))
4860  vardata->isunique = true;
4861 
4862  /*
4863  * Has it got stats? We only consider stats for
4864  * non-partial indexes, since partial indexes probably
4865  * don't reflect whole-relation statistics; the above
4866  * check for uniqueness is the only info we take from
4867  * a partial index.
4868  *
4869  * An index stats hook, however, must make its own
4870  * decisions about what to do with partial indexes.
4871  */
4872  if (get_index_stats_hook &&
4873  (*get_index_stats_hook) (root, index->indexoid,
4874  pos + 1, vardata))
4875  {
4876  /*
4877  * The hook took control of acquiring a stats
4878  * tuple. If it did supply a tuple, it'd better
4879  * have supplied a freefunc.
4880  */
4881  if (HeapTupleIsValid(vardata->statsTuple) &&
4882  !vardata->freefunc)
4883  elog(ERROR, "no function provided to release variable stats with");
4884  }
4885  else if (index->indpred == NIL)
4886  {
4887  vardata->statsTuple =
4889  ObjectIdGetDatum(index->indexoid),
4890  Int16GetDatum(pos + 1),
4891  BoolGetDatum(false));
4892  vardata->freefunc = ReleaseSysCache;
4893 
4894  if (HeapTupleIsValid(vardata->statsTuple))
4895  {
4896  /* Get index's table for permission check */
4897  RangeTblEntry *rte;
4898  Oid userid;
4899 
4900  rte = planner_rt_fetch(index->rel->relid, root);
4901  Assert(rte->rtekind == RTE_RELATION);
4902 
4903  /*
4904  * Use checkAsUser if it's set, in case we're
4905  * accessing the table via a view.
4906  */
4907  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4908 
4909  /*
4910  * For simplicity, we insist on the whole
4911  * table being selectable, rather than trying
4912  * to identify which column(s) the index
4913  * depends on. Also require all rows to be
4914  * selectable --- there must be no
4915  * securityQuals from security barrier views
4916  * or RLS policies.
4917  */
4918  vardata->acl_ok =
4919  rte->securityQuals == NIL &&
4920  (pg_class_aclcheck(rte->relid, userid,
4921  ACL_SELECT) == ACLCHECK_OK);
4922 
4923  /*
4924  * If the user doesn't have permissions to
4925  * access an inheritance child relation, check
4926  * the permissions of the table actually
4927  * mentioned in the query, since most likely
4928  * the user does have that permission. Note
4929  * that whole-table select privilege on the
4930  * parent doesn't quite guarantee that the
4931  * user could read all columns of the child.
4932  * But in practice it's unlikely that any
4933  * interesting security violation could result
4934  * from allowing access to the expression
4935  * index's stats, so we allow it anyway. See
4936  * similar code in examine_simple_variable()
4937  * for additional comments.
4938  */
4939  if (!vardata->acl_ok &&
4940  root->append_rel_array != NULL)
4941  {
4942  AppendRelInfo *appinfo;
4943  Index varno = index->rel->relid;
4944 
4945  appinfo = root->append_rel_array[varno];
4946  while (appinfo &&
4947  planner_rt_fetch(appinfo->parent_relid,
4948  root)->rtekind == RTE_RELATION)
4949  {
4950  varno = appinfo->parent_relid;
4951  appinfo = root->append_rel_array[varno];
4952  }
4953  if (varno != index->rel->relid)
4954  {
4955  /* Repeat access check on this rel */
4956  rte = planner_rt_fetch(varno, root);
4957  Assert(rte->rtekind == RTE_RELATION);
4958 
4959  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4960 
4961  vardata->acl_ok =
4962  rte->securityQuals == NIL &&
4963  (pg_class_aclcheck(rte->relid,
4964  userid,
4965  ACL_SELECT) == ACLCHECK_OK);
4966  }
4967  }
4968  }
4969  else
4970  {
4971  /* suppress leakproofness checks later */
4972  vardata->acl_ok = true;
4973  }
4974  }
4975  if (vardata->statsTuple)
4976  break;
4977  }
4978  indexpr_item = lnext(index->indexprs, indexpr_item);
4979  }
4980  }
4981  if (vardata->statsTuple)
4982  break;
4983  }
4984  }
4985 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:439
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3033
HeapTuple statsTuple
Definition: selfuncs.h:74
Oid GetUserId(void)
Definition: miscinit.c:448
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
List * securityQuals
Definition: parsenodes.h:1125
RelOptInfo * rel
Definition: selfuncs.h:73
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:529
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:76
#define MemSet(start, val, len)
Definition: c.h:978
AttrNumber varattno
Definition: primnodes.h:186
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4997
int32 atttypmod
Definition: selfuncs.h:79
Definition: type.h:89
RelOptInfo * rel
Definition: pathnodes.h:820
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2027
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:188
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: pathnodes.h:693
Index varno
Definition: primnodes.h:184
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ACL_SELECT
Definition: parsenodes.h:75
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:219
unsigned int Index
Definition: c.h:482
List * indexlist
Definition: pathnodes.h:702
#define BoolGetDatum(X)
Definition: postgres.h:402
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int nkeycolumns
Definition: pathnodes.h:829
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:145
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4563
RTEKind rtekind
Definition: parsenodes.h:976
#define elog(elevel,...)
Definition: elog.h:214
void * arg
int * indexkeys
Definition: pathnodes.h:830
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
Index parent_relid
Definition: pathnodes.h:2229
List * indpred
Definition: pathnodes.h:844
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
List * indexprs
Definition: pathnodes.h:843
int32 vartypmod
Definition: primnodes.h:189

◆ find_join_input_rel()

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

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

5877 {
5878  RelOptInfo *rel = NULL;
5879 
5880  switch (bms_membership(relids))
5881  {
5882  case BMS_EMPTY_SET:
5883  /* should not happen */
5884  break;
5885  case BMS_SINGLETON:
5886  rel = find_base_rel(root, bms_singleton_member(relids));
5887  break;
5888  case BMS_MULTIPLE:
5889  rel = find_join_rel(root, relids);
5890  break;
5891  }
5892 
5893  if (rel == NULL)
5894  elog(ERROR, "could not find RelOptInfo for given relids");
5895 
5896  return rel;
5897 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:439
#define ERROR
Definition: elog.h:43
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
#define elog(elevel,...)
Definition: elog.h:214
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374

◆ generic_restriction_selectivity()

double generic_restriction_selectivity ( PlannerInfo root,
Oid  oproid,
Oid  collation,
List args,
int  varRelid,
double  default_selectivity 
)

Definition at line 911 of file selfuncs.c.

References CLAMP_PROBABILITY, fmgr_info(), get_opcode(), get_restriction_variable(), GETSTRUCT, HeapTupleIsValid, histogram_selectivity(), IsA, mcv_selectivity(), ReleaseVariableStats, and VariableStatData::statsTuple.

Referenced by ltreeparentsel(), and matchingsel().

914 {
915  double selec;
916  VariableStatData vardata;
917  Node *other;
918  bool varonleft;
919 
920  /*
921  * If expression is not variable OP something or something OP variable,
922  * then punt and return the default estimate.
923  */
924  if (!get_restriction_variable(root, args, varRelid,
925  &vardata, &other, &varonleft))
926  return default_selectivity;
927 
928  /*
929  * If the something is a NULL constant, assume operator is strict and
930  * return zero, ie, operator will never return TRUE.
931  */
932  if (IsA(other, Const) &&
933  ((Const *) other)->constisnull)
934  {
935  ReleaseVariableStats(vardata);
936  return 0.0;
937  }
938 
939  if (IsA(other, Const))
940  {
941  /* Variable is being compared to a known non-null constant */
942  Datum constval = ((Const *) other)->constvalue;
943  FmgrInfo opproc;
944  double mcvsum;
945  double mcvsel;
946  double nullfrac;
947  int hist_size;
948 
949  fmgr_info(get_opcode(oproid), &opproc);
950 
951  /*
952  * Calculate the selectivity for the column's most common values.
953  */
954  mcvsel = mcv_selectivity(&vardata, &opproc, collation,
955  constval, varonleft,
956  &mcvsum);
957 
958  /*
959  * If the histogram is large enough, see what fraction of it matches
960  * the query, and assume that's representative of the non-MCV
961  * population. Otherwise use the default selectivity for the non-MCV
962  * population.
963  */
964  selec = histogram_selectivity(&vardata, &opproc, collation,
965  constval, varonleft,
966  10, 1, &hist_size);
967  if (selec < 0)
968  {
969  /* Nope, fall back on default */
970  selec = default_selectivity;
971  }
972  else if (hist_size < 100)
973  {
974  /*
975  * For histogram sizes from 10 to 100, we combine the histogram
976  * and default selectivities, putting increasingly more trust in
977  * the histogram for larger sizes.
978  */
979  double hist_weight = hist_size / 100.0;
980 
981  selec = selec * hist_weight +
982  default_selectivity * (1.0 - hist_weight);
983  }
984 
985  /* In any case, don't believe extremely small or large estimates. */
986  if (selec < 0.0001)
987  selec = 0.0001;
988  else if (selec > 0.9999)
989  selec = 0.9999;
990 
991  /* Don't forget to account for nulls. */
992  if (HeapTupleIsValid(vardata.statsTuple))
993  nullfrac = ((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
994  else
995  nullfrac = 0.0;
996 
997  /*
998  * Now merge the results from the MCV and histogram calculations,
999  * realizing that the histogram covers only the non-null values that
1000  * are not listed in MCV.
1001  */
1002  selec *= 1.0 - nullfrac - mcvsum;
1003  selec += mcvsel;
1004  }
1005  else
1006  {
1007  /* Comparison value is not constant, so we can't do anything */
1008  selec = default_selectivity;
1009  }
1010 
1011  ReleaseVariableStats(vardata);
1012 
1013  /* result should be in range, but make sure... */
1014  CLAMP_PROBABILITY(selec);
1015 
1016  return selec;
1017 }
Definition: fmgr.h:56
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
HeapTuple statsTuple
Definition: selfuncs.h:74
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4602
Definition: nodes.h:529
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
uintptr_t Datum
Definition: postgres.h:367
double mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
Definition: selfuncs.c:729
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
double histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
Definition: selfuncs.c:820
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84

◆ genericcostestimate()

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

Definition at line 5995 of file selfuncs.c.

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

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

5999 {
6000  IndexOptInfo *index = path->indexinfo;
6001  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6002  List *indexOrderBys = path->indexorderbys;
6003  Cost indexStartupCost;
6004  Cost indexTotalCost;
6005  Selectivity indexSelectivity;
6006  double indexCorrelation;
6007  double numIndexPages;
6008  double numIndexTuples;
6009  double spc_random_page_cost;
6010  double num_sa_scans;
6011  double num_outer_scans;
6012  double num_scans;
6013  double qual_op_cost;
6014  double qual_arg_cost;
6015  List *selectivityQuals;
6016  ListCell *l;
6017 
6018  /*
6019  * If the index is partial, AND the index predicate with the explicitly
6020  * given indexquals to produce a more accurate idea of the index
6021  * selectivity.
6022  */
6023  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6024 
6025  /*
6026  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6027  * index scans that will be performed.
6028  */
6029  num_sa_scans = 1;
6030  foreach(l, indexQuals)
6031  {
6032  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6033 
6034  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6035  {
6036  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6037  int alength = estimate_array_length(lsecond(saop->args));
6038 
6039  if (alength > 1)
6040  num_sa_scans *= alength;
6041  }
6042  }
6043 
6044  /* Estimate the fraction of main-table tuples that will be visited */
6045  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6046  index->rel->relid,
6047  JOIN_INNER,
6048  NULL);
6049 
6050  /*
6051  * If caller didn't give us an estimate, estimate the number of index
6052  * tuples that will be visited. We do it in this rather peculiar-looking
6053  * way in order to get the right answer for partial indexes.
6054  */
6055  numIndexTuples = costs->numIndexTuples;
6056  if (numIndexTuples <= 0.0)
6057  {
6058  numIndexTuples = indexSelectivity * index->rel->tuples;
6059 
6060  /*
6061  * The above calculation counts all the tuples visited across all
6062  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6063  * average per-indexscan number, so adjust. This is a handy place to
6064  * round to integer, too. (If caller supplied tuple estimate, it's
6065  * responsible for handling these considerations.)
6066  */
6067  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6068  }
6069 
6070  /*
6071  * We can bound the number of tuples by the index size in any case. Also,
6072  * always estimate at least one tuple is touched, even when
6073  * indexSelectivity estimate is tiny.
6074  */
6075  if (numIndexTuples > index->tuples)
6076  numIndexTuples = index->tuples;
6077  if (numIndexTuples < 1.0)
6078  numIndexTuples = 1.0;
6079 
6080  /*
6081  * Estimate the number of index pages that will be retrieved.
6082  *
6083  * We use the simplistic method of taking a pro-rata fraction of the total
6084  * number of index pages. In effect, this counts only leaf pages and not
6085  * any overhead such as index metapage or upper tree levels.
6086  *
6087  * In practice access to upper index levels is often nearly free because
6088  * those tend to stay in cache under load; moreover, the cost involved is
6089  * highly dependent on index type. We therefore ignore such costs here
6090  * and leave it to the caller to add a suitable charge if needed.
6091  */
6092  if (index->pages > 1 && index->tuples > 1)
6093  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6094  else
6095  numIndexPages = 1.0;
6096 
6097  /* fetch estimated page cost for tablespace containing index */
6099  &spc_random_page_cost,
6100  NULL);
6101 
6102  /*
6103  * Now compute the disk access costs.
6104  *
6105  * The above calculations are all per-index-scan. However, if we are in a
6106  * nestloop inner scan, we can expect the scan to be repeated (with
6107  * different search keys) for each row of the outer relation. Likewise,
6108  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6109  * the potential for cache effects to reduce the number of disk page
6110  * fetches needed. We want to estimate the average per-scan I/O cost in
6111  * the presence of caching.
6112  *
6113  * We use the Mackert-Lohman formula (see costsize.c for details) to
6114  * estimate the total number of page fetches that occur. While this
6115  * wasn't what it was designed for, it seems a reasonable model anyway.
6116  * Note that we are counting pages not tuples anymore, so we take N = T =
6117  * index size, as if there were one "tuple" per page.
6118  */
6119  num_outer_scans = loop_count;
6120  num_scans = num_sa_scans * num_outer_scans;
6121 
6122  if (num_scans > 1)
6123  {
6124  double pages_fetched;
6125 
6126  /* total page fetches ignoring cache effects */
6127  pages_fetched = numIndexPages * num_scans;
6128 
6129  /* use Mackert and Lohman formula to adjust for cache effects */
6130  pages_fetched = index_pages_fetched(pages_fetched,
6131  index->pages,
6132  (double) index->pages,
6133  root);
6134 
6135  /*
6136  * Now compute the total disk access cost, and then report a pro-rated
6137  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6138  * since that's internal to the indexscan.)
6139  */
6140  indexTotalCost = (pages_fetched * spc_random_page_cost)
6141  / num_outer_scans;
6142  }
6143  else
6144  {
6145  /*
6146  * For a single index scan, we just charge spc_random_page_cost per
6147  * page touched.
6148  */
6149  indexTotalCost = numIndexPages * spc_random_page_cost;
6150  }
6151 
6152  /*
6153  * CPU cost: any complex expressions in the indexquals will need to be
6154  * evaluated once at the start of the scan to reduce them to runtime keys
6155  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6156  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6157  * indexqual operator. Because we have numIndexTuples as a per-scan
6158  * number, we have to multiply by num_sa_scans to get the correct result
6159  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6160  * ORDER BY expressions.
6161  *
6162  * Note: this neglects the possible costs of rechecking lossy operators.
6163  * Detecting that that might be needed seems more expensive than it's
6164  * worth, though, considering all the other inaccuracies here ...
6165  */
6166  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
6167  index_other_operands_eval_cost(root, indexOrderBys);
6168  qual_op_cost = cpu_operator_cost *
6169  (list_length(indexQuals) + list_length(indexOrderBys));
6170 
6171  indexStartupCost = qual_arg_cost;
6172  indexTotalCost += qual_arg_cost;
6173  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6174 
6175  /*
6176  * Generic assumption about index correlation: there isn't any.
6177  */
6178  indexCorrelation = 0.0;
6179 
6180  /*
6181  * Return everything to caller.
6182  */
6183  costs->indexStartupCost = indexStartupCost;
6184  costs->indexTotalCost = indexTotalCost;
6185  costs->indexSelectivity = indexSelectivity;
6186  costs->indexCorrelation = indexCorrelation;
6187  costs->numIndexPages = numIndexPages;
6188  costs->numIndexTuples = numIndexTuples;
6189  costs->spc_random_page_cost = spc_random_page_cost;
6190  costs->num_sa_scans = num_sa_scans;
6191 }
Selectivity indexSelectivity
Definition: selfuncs.h:109
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
IndexOptInfo * indexinfo
Definition: pathnodes.h:1207
double tuples
Definition: pathnodes.h:705
Oid reltablespace
Definition: pathnodes.h:819
List * indexclauses
Definition: pathnodes.h:1208
double Selectivity
Definition: nodes.h:662
double tuples
Definition: pathnodes.h:824
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:823
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
RelOptInfo * rel
Definition: pathnodes.h:820
double num_sa_scans
Definition: selfuncs.h:116
double cpu_operator_cost
Definition: costsize.c:115
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5911
Cost indexTotalCost
Definition: selfuncs.h:108
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:693
Expr * clause
Definition: pathnodes.h:1985
double indexCorrelation
Definition: selfuncs.h:110
List * indexorderbys
Definition: pathnodes.h:1209
double spc_random_page_cost
Definition: selfuncs.h:115
double numIndexTuples
Definition: selfuncs.h:114
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5941
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
Cost indexStartupCost
Definition: selfuncs.h:107
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
double cpu_index_tuple_cost
Definition: costsize.c:114
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:828
double Cost
Definition: nodes.h:663
double numIndexPages
Definition: selfuncs.h:113
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6213

◆ get_actual_variable_endpoint()

static bool get_actual_variable_endpoint ( Relation  heapRel,
Relation  indexRel,
ScanDirection  indexscandir,
ScanKey  scankeys,
int16  typLen,
bool  typByVal,
TupleTableSlot tableslot,
MemoryContext  outercontext,
Datum endpointDatum 
)
static

Definition at line 5749 of file selfuncs.c.

References datumCopy(), elog, ERROR, ExecClearTuple(), index_beginscan(), index_deform_tuple(), index_endscan(), index_fetch_heap(), index_getnext_tid(), INDEX_MAX_KEYS, index_rescan(), InitNonVacuumableSnapshot, InvalidBuffer, ItemPointerGetBlockNumber, MemoryContextSwitchTo(), RecentGlobalXmin, RelationGetRelationName, ReleaseBuffer(), values, VM_ALL_VISIBLE, IndexScanDescData::xs_itup, IndexScanDescData::xs_itupdesc, IndexScanDescData::xs_recheck, and IndexScanDescData::xs_want_itup.

Referenced by get_actual_variable_range().

5758 {
5759  bool have_data = false;
5760  SnapshotData SnapshotNonVacuumable;
5761  IndexScanDesc index_scan;
5762  Buffer vmbuffer = InvalidBuffer;
5763  ItemPointer tid;
5765  bool isnull[INDEX_MAX_KEYS];
5766  MemoryContext oldcontext;
5767 
5768  /*
5769  * We use the index-only-scan machinery for this. With mostly-static
5770  * tables that's a win because it avoids a heap visit. It's also a win
5771  * for dynamic data, but the reason is less obvious; read on for details.
5772  *
5773  * In principle, we should scan the index with our current active
5774  * snapshot, which is the best approximation we've got to what the query
5775  * will see when executed. But that won't be exact if a new snap is taken
5776  * before running the query, and it can be very expensive if a lot of
5777  * recently-dead or uncommitted rows exist at the beginning or end of the
5778  * index (because we'll laboriously fetch each one and reject it).
5779  * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
5780  * and uncommitted rows as well as normal visible rows. On the other
5781  * hand, it will reject known-dead rows, and thus not give a bogus answer
5782  * when the extreme value has been deleted (unless the deletion was quite
5783  * recent); that case motivates not using SnapshotAny here.
5784  *
5785  * A crucial point here is that SnapshotNonVacuumable, with
5786  * RecentGlobalXmin as horizon, yields the inverse of the condition that
5787  * the indexscan will use to decide that index entries are killable (see
5788  * heap_hot_search_buffer()). Therefore, if the snapshot rejects a tuple
5789  * (or more precisely, all tuples of a HOT chain) and we have to continue
5790  * scanning past it, we know that the indexscan will mark that index entry
5791  * killed. That means that the next get_actual_variable_endpoint() call
5792  * will not have to re-consider that index entry. In this way we avoid
5793  * repetitive work when this function is used a lot during planning.
5794  *
5795  * But using SnapshotNonVacuumable creates a hazard of its own. In a
5796  * recently-created index, some index entries may point at "broken" HOT
5797  * chains in which not all the tuple versions contain data matching the
5798  * index entry. The live tuple version(s) certainly do match the index,
5799  * but SnapshotNonVacuumable can accept recently-dead tuple versions that
5800  * don't match. Hence, if we took data from the selected heap tuple, we
5801  * might get a bogus answer that's not close to the index extremal value,
5802  * or could even be NULL. We avoid this hazard because we take the data
5803  * from the index entry not the heap.
5804  */
5805  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5806 
5807  index_scan = index_beginscan(heapRel, indexRel,
5808  &SnapshotNonVacuumable,
5809  1, 0);
5810  /* Set it up for index-only scan */
5811  index_scan->xs_want_itup = true;
5812  index_rescan(index_scan, scankeys, 1, NULL, 0);
5813 
5814  /* Fetch first/next tuple in specified direction */
5815  while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
5816  {
5817  if (!VM_ALL_VISIBLE(heapRel,
5819  &vmbuffer))
5820  {
5821  /* Rats, we have to visit the heap to check visibility */
5822  if (!index_fetch_heap(index_scan, tableslot))
5823  continue; /* no visible tuple, try next index entry */
5824 
5825  /* We don't actually need the heap tuple for anything */
5826  ExecClearTuple(tableslot);
5827 
5828  /*
5829  * We don't care whether there's more than one visible tuple in
5830  * the HOT chain; if any are visible, that's good enough.
5831  */
5832  }
5833 
5834  /*
5835  * We expect that btree will return data in IndexTuple not HeapTuple
5836  * format. It's not lossy either.
5837  */
5838  if (!index_scan->xs_itup)
5839  elog(ERROR, "no data returned for index-only scan");
5840  if (index_scan->xs_recheck)
5841  elog(ERROR, "unexpected recheck indication from btree");
5842 
5843  /* OK to deconstruct the index tuple */
5844  index_deform_tuple(index_scan->xs_itup,
5845  index_scan->xs_itupdesc,
5846  values, isnull);
5847 
5848  /* Shouldn't have got a null, but be careful */
5849  if (isnull[0])
5850  elog(ERROR, "found unexpected null value in index \"%s\"",
5851  RelationGetRelationName(indexRel));
5852 
5853  /* Copy the index column value out to caller's context */
5854  oldcontext = MemoryContextSwitchTo(outercontext);
5855  *endpointDatum = datumCopy(values[0], typByVal, typLen);
5856  MemoryContextSwitchTo(oldcontext);
5857  have_data = true;
5858  break;
5859  }
5860 
5861  if (vmbuffer != InvalidBuffer)
5862  ReleaseBuffer(vmbuffer);
5863  index_endscan(index_scan);
5864 
5865  return have_data;
5866 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
IndexTuple xs_itup
Definition: relscan.h:127
struct TupleDescData * xs_itupdesc
Definition: relscan.h:128
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:295
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3483
#define InitNonVacuumableSnapshot(snapshotdata, xmin_horizon)
Definition: snapmgr.h:83
ItemPointer index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:515
#define ERROR
Definition: elog.h:43
TransactionId RecentGlobalXmin
Definition: snapmgr.c:168
#define RelationGetRelationName(relation)
Definition: rel.h:490
void index_deform_tuple(IndexTuple tup, TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:434
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:321
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
uintptr_t Datum
Definition: postgres.h:367
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:32
#define INDEX_MAX_KEYS
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define elog(elevel,...)
Definition: elog.h:214
bool index_fetch_heap(IndexScanDesc scan, TupleTableSlot *slot)
Definition: indexam.c:572
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
int Buffer
Definition: buf.h:23
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:203

◆ get_actual_variable_range()

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

Definition at line 5576 of file selfuncs.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, VariableStatData::atttype, BackwardScanDirection, BTGreaterStrategyNumber, BTLessStrategyNumber, CurrentMemoryContext, ExecDropSingleTupleTableSlot(), ForwardScanDirection, get_actual_variable_endpoint(), get_op_opfamily_strategy(), get_typlenbyval(), IndexOptInfo::hypothetical, index_close(), index_open(), IndexOptInfo::indexcollations, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indpred, InvalidOid, InvalidStrategy, lfirst, match_index_to_operand(), MemoryContextDelete(), MemoryContextSwitchTo(), NIL, NoLock, VariableStatData::rel, IndexOptInfo::relam, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, RTE_RELATION, RangeTblEntry::rtekind, ScanKeyEntryInitialize(), PlannerInfo::simple_rte_array, SK_ISNULL, SK_SEARCHNOTNULL, IndexOptInfo::sortopfamily, table_close(), table_open(), table_slot_create(), and VariableStatData::var.

Referenced by get_variable_range(), and ineq_histogram_selectivity().

5579 {
5580  bool have_data = false;
5581  RelOptInfo *rel = vardata->rel;
5582  RangeTblEntry *rte;
5583  ListCell *lc;
5584 
5585  /* No hope if no relation or it doesn't have indexes */
5586  if (rel == NULL || rel->indexlist == NIL)
5587  return false;
5588  /* If it has indexes it must be a plain relation */
5589  rte = root->simple_rte_array[rel->relid];
5590  Assert(rte->rtekind == RTE_RELATION);
5591 
5592  /* Search through the indexes to see if any match our problem */
5593  foreach(lc, rel->indexlist)
5594  {
5596  ScanDirection indexscandir;
5597 
5598  /* Ignore non-btree indexes */
5599  if (index->relam != BTREE_AM_OID)
5600  continue;
5601 
5602  /*
5603  * Ignore partial indexes --- we only want stats that cover the entire
5604  * relation.
5605  */
5606  if (index->indpred != NIL)
5607  continue;
5608 
5609  /*
5610  * The index list might include hypothetical indexes inserted by a
5611  * get_relation_info hook --- don't try to access them.
5612  */
5613  if (index->hypothetical)
5614  continue;
5615 
5616  /*
5617  * The first index column must match the desired variable, sortop, and
5618  * collation --- but we can use a descending-order index.
5619  */
5620  if (collation != index->indexcollations[0])
5621  continue; /* test first 'cause it's cheapest */
5622  if (!match_index_to_operand(vardata->var, 0, index))
5623  continue;
5624  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5625  {
5626  case BTLessStrategyNumber:
5627  if (index->reverse_sort[0])
5628  indexscandir = BackwardScanDirection;
5629  else
5630  indexscandir = ForwardScanDirection;
5631  break;
5633  if (index->reverse_sort[0])
5634  indexscandir = ForwardScanDirection;
5635  else
5636  indexscandir = BackwardScanDirection;
5637  break;
5638  default:
5639  /* index doesn't match the sortop */
5640  continue;
5641  }
5642 
5643  /*
5644  * Found a suitable index to extract data from. Set up some data that
5645  * can be used by both invocations of get_actual_variable_endpoint.
5646  */
5647  {
5648  MemoryContext tmpcontext;
5649  MemoryContext oldcontext;
5650  Relation heapRel;
5651  Relation indexRel;
5652  TupleTableSlot *slot;
5653  int16 typLen;
5654  bool typByVal;
5655  ScanKeyData scankeys[1];
5656 
5657  /* Make sure any cruft gets recycled when we're done */
5659  "get_actual_variable_range workspace",
5661  oldcontext = MemoryContextSwitchTo(tmpcontext);
5662 
5663  /*
5664  * Open the table and index so we can read from them. We should
5665  * already have some type of lock on each.
5666  */
5667  heapRel = table_open(rte->relid, NoLock);
5668  indexRel = index_open(index->indexoid, NoLock);
5669 
5670  /* build some stuff needed for indexscan execution */
5671  slot = table_slot_create(heapRel, NULL);
5672  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5673 
5674  /* set up an IS NOT NULL scan key so that we ignore nulls */
5675  ScanKeyEntryInitialize(&scankeys[0],
5677  1, /* index col to scan */
5678  InvalidStrategy, /* no strategy */
5679  InvalidOid, /* no strategy subtype */
5680  InvalidOid, /* no collation */
5681  InvalidOid, /* no reg proc for this */
5682  (Datum) 0); /* constant */
5683 
5684  /* If min is requested ... */
5685  if (min)
5686  {
5687  have_data = get_actual_variable_endpoint(heapRel,
5688  indexRel,
5689  indexscandir,
5690  scankeys,
5691  typLen,
5692  typByVal,
5693  slot,
5694  oldcontext,
5695  min);
5696  }
5697  else
5698  {
5699  /* If min not requested, assume index is nonempty */
5700  have_data = true;
5701  }
5702 
5703  /* If max is requested, and we didn't find the index is empty */
5704  if (max && have_data)
5705  {
5706  /* scan in the opposite direction; all else is the same */
5707  have_data = get_actual_variable_endpoint(heapRel,
5708  indexRel,
5709  -indexscandir,
5710  scankeys,
5711  typLen,
5712  typByVal,
5713  slot,
5714  oldcontext,
5715  max);
5716  }
5717 
5718  /* Clean everything up */
5720 
5721  index_close(indexRel, NoLock);
5722  table_close(heapRel, NoLock);
5723 
5724  MemoryContextSwitchTo(oldcontext);
5725  MemoryContextDelete(tmpcontext);
5726 
5727  /* And we're done */
5728  break;
5729  }
5730  }
5731 
5732  return have_data;
5733 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:77
signed short int16
Definition: c.h:361
#define InvalidStrategy
Definition: stratnum.h:24
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
Oid * indexcollations
Definition: pathnodes.h:832
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3719
RelOptInfo * rel
Definition: selfuncs.h:73
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Oid * sortopfamily
Definition: pathnodes.h:835
bool hypothetical
Definition: pathnodes.h:857
Definition: type.h:89
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#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:1224
ScanDirection
Definition: sdir.h:22
#define SK_SEARCHNOTNULL
Definition: skey.h:122
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define SK_ISNULL
Definition: skey.h:115
Index relid
Definition: pathnodes.h:693
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:211
uintptr_t Datum
Definition: postgres.h:367
List * indexlist
Definition: pathnodes.h:702
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2139
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RTEKind rtekind
Definition: parsenodes.h:976
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:81
static bool get_actual_variable_endpoint(Relation heapRel, Relation indexRel, ScanDirection indexscandir, ScanKey scankeys, int16 typLen, bool typByVal, TupleTableSlot *tableslot, MemoryContext outercontext, Datum *endpointDatum)
Definition: selfuncs.c:5749
bool * reverse_sort
Definition: pathnodes.h:836
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: pathnodes.h:844
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ get_join_variables()

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

Definition at line 4662 of file selfuncs.c.

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

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

4665 {
4666  Node *left,
4667  *right;
4668 
4669  if (list_length(args) != 2)
4670  elog(ERROR, "join operator should take two arguments");
4671 
4672  left = (Node *) linitial(args);
4673  right = (Node *) lsecond(args);
4674 
4675  examine_variable(root, left, 0, vardata1);
4676  examine_variable(root, right, 0, vardata2);
4677 
4678  if (vardata1->rel &&
4679  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4680  *join_is_reversed = true; /* var1 is on RHS */
4681  else if (vardata2->rel &&
4682  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4683  *join_is_reversed = true; /* var2 is on LHS */
4684  else
4685  *join_is_reversed = false;
4686 }
RelOptInfo * rel
Definition: selfuncs.h:73
Definition: nodes.h:529
#define lsecond(l)
Definition: pg_list.h:200
Relids syn_lefthand
Definition: pathnodes.h:2177
Relids syn_righthand
Definition: pathnodes.h:2178
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Relids relids
Definition: pathnodes.h:665
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4724
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:214

◆ get_quals_from_indexclauses()

List* get_quals_from_indexclauses ( List indexclauses)

Definition at line 5911 of file selfuncs.c.

References IndexClause::indexquals, lappend(), lfirst_node, and NIL.

Referenced by brincostestimate(), genericcostestimate(), and gincostestimate().

5912 {
5913  List *result = NIL;
5914  ListCell *lc;
5915