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

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

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

6219 {
6220  List *predExtraQuals = NIL;
6221  ListCell *lc;
6222 
6223  if (index->indpred == NIL)
6224  return indexQuals;
6225 
6226  foreach(lc, index->indpred)
6227  {
6228  Node *predQual = (Node *) lfirst(lc);
6229  List *oneQual = list_make1(predQual);
6230 
6231  if (!predicate_implied_by(oneQual, indexQuals, false))
6232  predExtraQuals = list_concat(predExtraQuals, oneQual);
6233  }
6234  return list_concat(predExtraQuals, indexQuals);
6235 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:528
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
#define list_make1(x1)
Definition: pg_list.h:226
#define lfirst(lc)
Definition: pg_list.h:189
List * indpred
Definition: pathnodes.h:845
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 3247 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().

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

◆ 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:661
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:599
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:4727
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:4727
#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 7334 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().

7338 {
7339  IndexOptInfo *index = path->indexinfo;
7340  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7341  double numPages = index->pages;
7342  RelOptInfo *baserel = index->rel;
7343  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7344  Cost spc_seq_page_cost;
7345  Cost spc_random_page_cost;
7346  double qual_arg_cost;
7347  double qualSelectivity;
7348  BrinStatsData statsData;
7349  double indexRanges;
7350  double minimalRanges;
7351  double estimatedRanges;
7352  double selec;
7353  Relation indexRel;
7354  ListCell *l;
7355  VariableStatData vardata;
7356 
7357  Assert(rte->rtekind == RTE_RELATION);
7358 
7359  /* fetch estimated page cost for the tablespace containing the index */
7361  &spc_random_page_cost,
7362  &spc_seq_page_cost);
7363 
7364  /*
7365  * Obtain some data from the index itself, if possible. Otherwise invent
7366  * some plausible internal statistics based on the relation page count.
7367  */
7368  if (!index->hypothetical)
7369  {
7370  /*
7371  * A lock should have already been obtained on the index in plancat.c.
7372  */
7373  indexRel = index_open(index->indexoid, NoLock);
7374  brinGetStats(indexRel, &statsData);
7375  index_close(indexRel, NoLock);
7376 
7377  /* work out the actual number of ranges in the index */
7378  indexRanges = Max(ceil((double) baserel->pages /
7379  statsData.pagesPerRange), 1.0);
7380  }
7381  else
7382  {
7383  /*
7384  * Assume default number of pages per range, and estimate the number
7385  * of ranges based on that.
7386  */
7387  indexRanges = Max(ceil((double) baserel->pages /
7389 
7391  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7392  }
7393 
7394  /*
7395  * Compute index correlation
7396  *
7397  * Because we can use all index quals equally when scanning, we can use
7398  * the largest correlation (in absolute value) among columns used by the
7399  * query. Start at zero, the worst possible case. If we cannot find any
7400  * correlation statistics, we will keep it as 0.
7401  */
7402  *indexCorrelation = 0;
7403 
7404  foreach(l, path->indexclauses)
7405  {
7406  IndexClause *iclause = lfirst_node(IndexClause, l);
7407  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7408 
7409  /* attempt to lookup stats in relation for this index column */
7410  if (attnum != 0)
7411  {
7412  /* Simple variable -- look to stats for the underlying table */
7414  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7415  {
7416  /*
7417  * The hook took control of acquiring a stats tuple. If it
7418  * did supply a tuple, it'd better have supplied a freefunc.
7419  */
7420  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7421  elog(ERROR,
7422  "no function provided to release variable stats with");
7423  }
7424  else
7425  {
7426  vardata.statsTuple =
7428  ObjectIdGetDatum(rte->relid),
7429  Int16GetDatum(attnum),
7430  BoolGetDatum(false));
7431  vardata.freefunc = ReleaseSysCache;
7432  }
7433  }
7434  else
7435  {
7436  /*
7437  * Looks like we've found an expression column in the index. Let's
7438  * see if there's any stats for it.
7439  */
7440 
7441  /* get the attnum from the 0-based index. */
7442  attnum = iclause->indexcol + 1;
7443 
7444  if (get_index_stats_hook &&
7445  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7446  {
7447  /*
7448  * The hook took control of acquiring a stats tuple. If it
7449  * did supply a tuple, it'd better have supplied a freefunc.
7450  */
7451  if (HeapTupleIsValid(vardata.statsTuple) &&
7452  !vardata.freefunc)
7453  elog(ERROR, "no function provided to release variable stats with");
7454  }
7455  else
7456  {
7458  ObjectIdGetDatum(index->indexoid),
7459  Int16GetDatum(attnum),
7460  BoolGetDatum(false));
7461  vardata.freefunc = ReleaseSysCache;
7462  }
7463  }
7464 
7465  if (HeapTupleIsValid(vardata.statsTuple))
7466  {
7467  AttStatsSlot sslot;
7468 
7469  if (get_attstatsslot(&sslot, vardata.statsTuple,
7470  STATISTIC_KIND_CORRELATION, InvalidOid,
7472  {
7473  double varCorrelation = 0.0;
7474 
7475  if (sslot.nnumbers > 0)
7476  varCorrelation = Abs(sslot.numbers[0]);
7477 
7478  if (varCorrelation > *indexCorrelation)
7479  *indexCorrelation = varCorrelation;
7480 
7481  free_attstatsslot(&sslot);
7482  }
7483  }
7484 
7485  ReleaseVariableStats(vardata);
7486  }
7487 
7488  qualSelectivity = clauselist_selectivity(root, indexQuals,
7489  baserel->relid,
7490  JOIN_INNER, NULL);
7491 
7492  /*
7493  * Now calculate the minimum possible ranges we could match with if all of
7494  * the rows were in the perfect order in the table's heap.
7495  */
7496  minimalRanges = ceil(indexRanges * qualSelectivity);
7497 
7498  /*
7499  * Now estimate the number of ranges that we'll touch by using the
7500  * indexCorrelation from the stats. Careful not to divide by zero (note
7501  * we're using the absolute value of the correlation).
7502  */
7503  if (*indexCorrelation < 1.0e-10)
7504  estimatedRanges = indexRanges;
7505  else
7506  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7507 
7508  /* we expect to visit this portion of the table */
7509  selec = estimatedRanges / indexRanges;
7510 
7511  CLAMP_PROBABILITY(selec);
7512 
7513  *indexSelectivity = selec;
7514 
7515  /*
7516  * Compute the index qual costs, much as in genericcostestimate, to add to
7517  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7518  * support those.
7519  */
7520  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7521 
7522  /*
7523  * Compute the startup cost as the cost to read the whole revmap
7524  * sequentially, including the cost to execute the index quals.
7525  */
7526  *indexStartupCost =
7527  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7528  *indexStartupCost += qual_arg_cost;
7529 
7530  /*
7531  * To read a BRIN index there might be a bit of back and forth over
7532  * regular pages, as revmap might point to them out of sequential order;
7533  * calculate the total cost as reading the whole index in random order.
7534  */
7535  *indexTotalCost = *indexStartupCost +
7536  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7537 
7538  /*
7539  * Charge a small amount per range tuple which we expect to match to. This
7540  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7541  * will set a bit for each page in the range when we find a matching
7542  * range, so we must multiply the charge by the number of pages in the
7543  * range.
7544  */
7545  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7546  statsData.pagesPerRange;
7547 
7548  *indexPages = index->pages;
7549 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1208
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:820
bool hypothetical
Definition: pathnodes.h:858
List * indexclauses
Definition: pathnodes.h:1209
#define Abs(x)
Definition: c.h:933
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:824
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
RelOptInfo * rel
Definition: pathnodes.h:821
#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:374
AttrNumber indexcol
Definition: pathnodes.h:1257
#define lfirst_node(type, lc)
Definition: pg_list.h:192
#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:5916
#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:694
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:5946
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:705
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:977
#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:831
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:662
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1086
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 6239 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().

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

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

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

Referenced by convert_to_scalar().

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

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

Referenced by convert_to_scalar().

4180 {
4181  switch (typid)
4182  {
4183  case BOOLOID:
4184  return (double) DatumGetBool(value);
4185  case INT2OID:
4186  return (double) DatumGetInt16(value);
4187  case INT4OID:
4188  return (double) DatumGetInt32(value);
4189  case INT8OID:
4190  return (double) DatumGetInt64(value);
4191  case FLOAT4OID:
4192  return (double) DatumGetFloat4(value);
4193  case FLOAT8OID:
4194  return (double) DatumGetFloat8(value);
4195  case NUMERICOID:
4196  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4197  return (double)
4199  value));
4200  case OIDOID:
4201  case REGPROCOID:
4202  case REGPROCEDUREOID:
4203  case REGOPEROID:
4204  case REGOPERATOROID:
4205  case REGCLASSOID:
4206  case REGTYPEOID:
4207  case REGCONFIGOID:
4208  case REGDICTIONARYOID:
4209  case REGROLEOID:
4210  case REGNAMESPACEOID:
4211  /* we can treat OIDs as integers... */
4212  return (double) DatumGetObjectId(value);
4213  }
4214 
4215  *failure = true;
4216  return 0;
4217 }
static struct @142 value
#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
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:4337

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

Referenced by convert_bytea_to_scalar().

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

◆ convert_one_string_to_scalar()

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

Definition at line 4320 of file selfuncs.c.

Referenced by convert_string_to_scalar().

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

◆ convert_string_datum()

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

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

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

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

◆ convert_timevalue_to_scalar()

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

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

4544 {
4545  switch (typid)
4546  {
4547  case TIMESTAMPOID:
4548  return DatumGetTimestamp(value);
4549  case TIMESTAMPTZOID:
4550  return DatumGetTimestampTz(value);
4551  case DATEOID:
4553  case INTERVALOID:
4554  {
4556 
4557  /*
4558  * Convert the month part of Interval to days using assumed
4559  * average month length of 365.25/12.0 days. Not too
4560  * accurate, but plenty good enough for our purposes.
4561  */
4562  return interval->time + interval->day * (double) USECS_PER_DAY +
4563  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4564  }
4565  case TIMEOID:
4566  return DatumGetTimeADT(value);
4567  case TIMETZOID:
4568  {
4569  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4570 
4571  /* use GMT-equivalent time */
4572  return (double) (timetz->time + (timetz->zone * 1000000.0));
4573  }
4574  }
4575 
4576  *failure = true;
4577  return 0;
4578 }
#define DatumGetDateADT(X)
Definition: date.h:53
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:29
static struct @142 value
#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
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 4033 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().

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

◆ 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:2177
#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:5247
#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:695
#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:4665
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5276
#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:5881
double rows
Definition: pathnodes.h:669
#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:2180
#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:1057
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:981
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:1057
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:981
uintptr_t Datum
Definition: postgres.h:367
double rows
Definition: pathnodes.h:669
#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:579
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4605
Definition: nodes.h:528
#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:579
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 3723 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().

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

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

Referenced by consider_groupingsets_paths().

3844 {
3845  Size hashentrysize = hash_agg_entry_size(agg_costs->numAggs,
3846  path->pathtarget->width,
3847  agg_costs->transitionSpace);
3848 
3849  /*
3850  * Note that this disregards the effect of fill-factor and growth policy
3851  * of the hash table. That's probably ok, given that the default
3852  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3853  * "double-in-size" growth policies here.
3854  */
3855  return hashentrysize * dNumGroups;
3856 }
PathTarget * pathtarget
Definition: pathnodes.h:1146
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1695
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 3877 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().

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

◆ estimate_num_groups()

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

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

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

◆ examine_simple_variable()

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

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

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

◆ examine_variable()

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

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

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

◆ find_join_input_rel()

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

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

5882 {
5883  RelOptInfo *rel = NULL;
5884 
5885  switch (bms_membership(relids))
5886  {
5887  case BMS_EMPTY_SET:
5888  /* should not happen */
5889  break;
5890  case BMS_SINGLETON:
5891  rel = find_base_rel(root, bms_singleton_member(relids));
5892  break;
5893  case BMS_MULTIPLE:
5894  rel = find_join_rel(root, relids);
5895  break;
5896  }
5897 
5898  if (rel == NULL)
5899  elog(ERROR, "could not find RelOptInfo for given relids");
5900 
5901  return rel;
5902 }
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:579
#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:4605
Definition: nodes.h:528
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 6000 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().

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

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

References datumCopy(), elog, ERROR, ExecClearTuple(), GlobalVisTestFor(), index_beginscan(), index_deform_tuple(), index_endscan(), index_fetch_heap(), index_getnext_tid(), INDEX_MAX_KEYS, index_rescan(), InitNonVacuumableSnapshot, InvalidBuffer, ItemPointerGetBlockNumber, MemoryContextSwitchTo(), 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().

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

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

4668 {
4669  Node *left,
4670  *right;
4671 
4672  if (list_length(args) != 2)
4673  elog(ERROR, "join operator should take two arguments");
4674 
4675  left = (Node *) linitial(args);
4676  right = (Node *) lsecond(args);
4677 
4678  examine_variable(root, left, 0, vardata1);
4679  examine_variable(root, right, 0, vardata2);
4680 
4681  if (vardata1->rel &&
4682  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4683  *join_is_reversed = true; /* var1 is on RHS */
4684  else if (vardata2->rel &&
4685  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4686  *join_is_reversed = true; /* var2 is on LHS */
4687  else
4688  *join_is_reversed = false;
4689 }
RelOptInfo * rel
Definition: selfuncs.h:73
Definition: nodes.h:528
#define lsecond(l)
Definition: pg_list.h:199
Relids syn_lefthand
Definition: pathnodes.h:2178
Relids syn_righthand
Definition: pathnodes.h:2179
#define linitial(l)
Definition: pg_list.h:194
#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:666
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4727
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 5916 of file selfuncs.c.

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

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

5917 {
5918  List *result =