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, EstimationInfo *estinfo)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
double estimate_hashagg_tablesize (PlannerInfo *root, 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)
 
static void ReleaseDummy (HeapTuple tuple)
 
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 6570 of file selfuncs.c.

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

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

6571 {
6572  List *predExtraQuals = NIL;
6573  ListCell *lc;
6574 
6575  if (index->indpred == NIL)
6576  return indexQuals;
6577 
6578  foreach(lc, index->indpred)
6579  {
6580  Node *predQual = (Node *) lfirst(lc);
6581  List *oneQual = list_make1(predQual);
6582 
6583  if (!predicate_implied_by(oneQual, indexQuals, false))
6584  predExtraQuals = list_concat(predExtraQuals, oneQual);
6585  }
6586  return list_concat(predExtraQuals, indexQuals);
6587 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
#define list_make1(x1)
Definition: pg_list.h:206
#define lfirst(lc)
Definition: pg_list.h:169
List * indpred
Definition: pathnodes.h:856
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 3248 of file selfuncs.c.

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

Referenced by estimate_num_groups().

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

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:654
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:42
HeapTuple statsTuple
Definition: selfuncs.h:91
int nnumbers
Definition: lsyscache.h:57
double Selectivity
Definition: nodes.h:672
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:135
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:56
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
#define ERROR
Definition: elog.h:46
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:690
float4 * numbers
Definition: lsyscache.h:56
#define DatumGetBool(X)
Definition: postgres.h:437
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:55
#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:4954
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3177
Datum * values
Definition: lsyscache.h:53
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
#define elog(elevel,...)
Definition: elog.h:232
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3294

◆ 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_ext().

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:91
#define BoolGetDatum(X)
Definition: postgres.h:446
#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:4954
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
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 7686 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().

7690 {
7691  IndexOptInfo *index = path->indexinfo;
7692  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7693  double numPages = index->pages;
7694  RelOptInfo *baserel = index->rel;
7695  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7696  Cost spc_seq_page_cost;
7697  Cost spc_random_page_cost;
7698  double qual_arg_cost;
7699  double qualSelectivity;
7700  BrinStatsData statsData;
7701  double indexRanges;
7702  double minimalRanges;
7703  double estimatedRanges;
7704  double selec;
7705  Relation indexRel;
7706  ListCell *l;
7707  VariableStatData vardata;
7708 
7709  Assert(rte->rtekind == RTE_RELATION);
7710 
7711  /* fetch estimated page cost for the tablespace containing the index */
7713  &spc_random_page_cost,
7714  &spc_seq_page_cost);
7715 
7716  /*
7717  * Obtain some data from the index itself, if possible. Otherwise invent
7718  * some plausible internal statistics based on the relation page count.
7719  */
7720  if (!index->hypothetical)
7721  {
7722  /*
7723  * A lock should have already been obtained on the index in plancat.c.
7724  */
7725  indexRel = index_open(index->indexoid, NoLock);
7726  brinGetStats(indexRel, &statsData);
7727  index_close(indexRel, NoLock);
7728 
7729  /* work out the actual number of ranges in the index */
7730  indexRanges = Max(ceil((double) baserel->pages /
7731  statsData.pagesPerRange), 1.0);
7732  }
7733  else
7734  {
7735  /*
7736  * Assume default number of pages per range, and estimate the number
7737  * of ranges based on that.
7738  */
7739  indexRanges = Max(ceil((double) baserel->pages /
7741 
7743  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7744  }
7745 
7746  /*
7747  * Compute index correlation
7748  *
7749  * Because we can use all index quals equally when scanning, we can use
7750  * the largest correlation (in absolute value) among columns used by the
7751  * query. Start at zero, the worst possible case. If we cannot find any
7752  * correlation statistics, we will keep it as 0.
7753  */
7754  *indexCorrelation = 0;
7755 
7756  foreach(l, path->indexclauses)
7757  {
7758  IndexClause *iclause = lfirst_node(IndexClause, l);
7759  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7760 
7761  /* attempt to lookup stats in relation for this index column */
7762  if (attnum != 0)
7763  {
7764  /* Simple variable -- look to stats for the underlying table */
7766  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7767  {
7768  /*
7769  * The hook took control of acquiring a stats tuple. If it
7770  * did supply a tuple, it'd better have supplied a freefunc.
7771  */
7772  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7773  elog(ERROR,
7774  "no function provided to release variable stats with");
7775  }
7776  else
7777  {
7778  vardata.statsTuple =
7780  ObjectIdGetDatum(rte->relid),
7781  Int16GetDatum(attnum),
7782  BoolGetDatum(false));
7783  vardata.freefunc = ReleaseSysCache;
7784  }
7785  }
7786  else
7787  {
7788  /*
7789  * Looks like we've found an expression column in the index. Let's
7790  * see if there's any stats for it.
7791  */
7792 
7793  /* get the attnum from the 0-based index. */
7794  attnum = iclause->indexcol + 1;
7795 
7796  if (get_index_stats_hook &&
7797  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7798  {
7799  /*
7800  * The hook took control of acquiring a stats tuple. If it
7801  * did supply a tuple, it'd better have supplied a freefunc.
7802  */
7803  if (HeapTupleIsValid(vardata.statsTuple) &&
7804  !vardata.freefunc)
7805  elog(ERROR, "no function provided to release variable stats with");
7806  }
7807  else
7808  {
7810  ObjectIdGetDatum(index->indexoid),
7811  Int16GetDatum(attnum),
7812  BoolGetDatum(false));
7813  vardata.freefunc = ReleaseSysCache;
7814  }
7815  }
7816 
7817  if (HeapTupleIsValid(vardata.statsTuple))
7818  {
7819  AttStatsSlot sslot;
7820 
7821  if (get_attstatsslot(&sslot, vardata.statsTuple,
7822  STATISTIC_KIND_CORRELATION, InvalidOid,
7824  {
7825  double varCorrelation = 0.0;
7826 
7827  if (sslot.nnumbers > 0)
7828  varCorrelation = Abs(sslot.numbers[0]);
7829 
7830  if (varCorrelation > *indexCorrelation)
7831  *indexCorrelation = varCorrelation;
7832 
7833  free_attstatsslot(&sslot);
7834  }
7835  }
7836 
7837  ReleaseVariableStats(vardata);
7838  }
7839 
7840  qualSelectivity = clauselist_selectivity(root, indexQuals,
7841  baserel->relid,
7842  JOIN_INNER, NULL);
7843 
7844  /*
7845  * Now calculate the minimum possible ranges we could match with if all of
7846  * the rows were in the perfect order in the table's heap.
7847  */
7848  minimalRanges = ceil(indexRanges * qualSelectivity);
7849 
7850  /*
7851  * Now estimate the number of ranges that we'll touch by using the
7852  * indexCorrelation from the stats. Careful not to divide by zero (note
7853  * we're using the absolute value of the correlation).
7854  */
7855  if (*indexCorrelation < 1.0e-10)
7856  estimatedRanges = indexRanges;
7857  else
7858  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7859 
7860  /* we expect to visit this portion of the table */
7861  selec = estimatedRanges / indexRanges;
7862 
7863  CLAMP_PROBABILITY(selec);
7864 
7865  *indexSelectivity = selec;
7866 
7867  /*
7868  * Compute the index qual costs, much as in genericcostestimate, to add to
7869  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7870  * support those.
7871  */
7872  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7873 
7874  /*
7875  * Compute the startup cost as the cost to read the whole revmap
7876  * sequentially, including the cost to execute the index quals.
7877  */
7878  *indexStartupCost =
7879  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7880  *indexStartupCost += qual_arg_cost;
7881 
7882  /*
7883  * To read a BRIN index there might be a bit of back and forth over
7884  * regular pages, as revmap might point to them out of sequential order;
7885  * calculate the total cost as reading the whole index in random order.
7886  */
7887  *indexTotalCost = *indexStartupCost +
7888  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7889 
7890  /*
7891  * Charge a small amount per range tuple which we expect to match to. This
7892  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7893  * will set a bit for each page in the range when we find a matching
7894  * range, so we must multiply the charge by the number of pages in the
7895  * range.
7896  */
7897  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7898  statsData.pagesPerRange;
7899 
7900  *indexPages = index->pages;
7901 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
HeapTuple statsTuple
Definition: selfuncs.h:91
int nnumbers
Definition: lsyscache.h:57
#define Min(x, y)
Definition: c.h:986
#define Int16GetDatum(X)
Definition: postgres.h:495
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:93
Oid reltablespace
Definition: pathnodes.h:831
bool hypothetical
Definition: pathnodes.h:869
List * indexclauses
Definition: pathnodes.h:1238
#define Abs(x)
Definition: c.h:992
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:835
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
RelOptInfo * rel
Definition: pathnodes.h:832
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
AttrNumber indexcol
Definition: pathnodes.h:1286
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NoLock
Definition: lockdefs.h:34
float4 * numbers
Definition: lsyscache.h:56
double cpu_operator_cost
Definition: costsize.c:123
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:6268
#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:181
Index relid
Definition: pathnodes.h:704
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define REVMAP_PAGE_MAXITEMS
Definition: brin_page.h:93
#define BoolGetDatum(X)
Definition: postgres.h:446
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
int16 attnum
Definition: pg_attribute.h:83
#define Max(x, y)
Definition: c.h:980
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6298
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:715
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3177
#define Assert(condition)
Definition: c.h:804
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:995
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
e
Definition: preproc-init.c:82
#define elog(elevel,...)
Definition: elog.h:232
int * indexkeys
Definition: pathnodes.h:842
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
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:673
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1227
BlockNumber revmapNumPages
Definition: brin.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3294

◆ btcostestimate()

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

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

6595 {
6596  IndexOptInfo *index = path->indexinfo;
6597  GenericCosts costs;
6598  Oid relid;
6599  AttrNumber colnum;
6600  VariableStatData vardata;
6601  double numIndexTuples;
6602  Cost descentCost;
6603  List *indexBoundQuals;
6604  int indexcol;
6605  bool eqQualHere;
6606  bool found_saop;
6607  bool found_is_null_op;
6608  double num_sa_scans;
6609  ListCell *lc;
6610 
6611  /*
6612  * For a btree scan, only leading '=' quals plus inequality quals for the
6613  * immediately next attribute contribute to index selectivity (these are
6614  * the "boundary quals" that determine the starting and stopping points of
6615  * the index scan). Additional quals can suppress visits to the heap, so
6616  * it's OK to count them in indexSelectivity, but they should not count
6617  * for estimating numIndexTuples. So we must examine the given indexquals
6618  * to find out which ones count as boundary quals. We rely on the
6619  * knowledge that they are given in index column order.
6620  *
6621  * For a RowCompareExpr, we consider only the first column, just as
6622  * rowcomparesel() does.
6623  *
6624  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6625  * index scans not one, but the ScalarArrayOpExpr's operator can be
6626  * considered to act the same as it normally does.
6627  */
6628  indexBoundQuals = NIL;
6629  indexcol = 0;
6630  eqQualHere = false;
6631  found_saop = false;
6632  found_is_null_op = false;
6633  num_sa_scans = 1;
6634  foreach(lc, path->indexclauses)
6635  {
6636  IndexClause *iclause = lfirst_node(IndexClause, lc);
6637  ListCell *lc2;
6638 
6639  if (indexcol != iclause->indexcol)
6640  {
6641  /* Beginning of a new column's quals */
6642  if (!eqQualHere)
6643  break; /* done if no '=' qual for indexcol */
6644  eqQualHere = false;
6645  indexcol++;
6646  if (indexcol != iclause->indexcol)
6647  break; /* no quals at all for indexcol */
6648  }
6649 
6650  /* Examine each indexqual associated with this index clause */
6651  foreach(lc2, iclause->indexquals)
6652  {
6653  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6654  Expr *clause = rinfo->clause;
6655  Oid clause_op = InvalidOid;
6656  int op_strategy;
6657 
6658  if (IsA(clause, OpExpr))
6659  {
6660  OpExpr *op = (OpExpr *) clause;
6661 
6662  clause_op = op->opno;
6663  }
6664  else if (IsA(clause, RowCompareExpr))
6665  {
6666  RowCompareExpr *rc = (RowCompareExpr *) clause;
6667 
6668  clause_op = linitial_oid(rc->opnos);
6669  }
6670  else if (IsA(clause, ScalarArrayOpExpr))
6671  {
6672  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6673  Node *other_operand = (Node *) lsecond(saop->args);
6674  int alength = estimate_array_length(other_operand);
6675 
6676  clause_op = saop->opno;
6677  found_saop = true;
6678  /* count number of SA scans induced by indexBoundQuals only */
6679  if (alength > 1)
6680  num_sa_scans *= alength;
6681  }
6682  else if (IsA(clause, NullTest))
6683  {
6684  NullTest *nt = (NullTest *) clause;
6685 
6686  if (nt->nulltesttype == IS_NULL)
6687  {
6688  found_is_null_op = true;
6689  /* IS NULL is like = for selectivity purposes */
6690  eqQualHere = true;
6691  }
6692  }
6693  else
6694  elog(ERROR, "unsupported indexqual type: %d",
6695  (int) nodeTag(clause));
6696 
6697  /* check for equality operator */
6698  if (OidIsValid(clause_op))
6699  {
6700  op_strategy = get_op_opfamily_strategy(clause_op,
6701  index->opfamily[indexcol]);
6702  Assert(op_strategy != 0); /* not a member of opfamily?? */
6703  if (op_strategy == BTEqualStrategyNumber)
6704  eqQualHere = true;
6705  }
6706 
6707  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6708  }
6709  }
6710 
6711  /*
6712  * If index is unique and we found an '=' clause for each column, we can
6713  * just assume numIndexTuples = 1 and skip the expensive
6714  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6715  * NullTest invalidates that theory, even though it sets eqQualHere.
6716  */
6717  if (index->unique &&
6718  indexcol == index->nkeycolumns - 1 &&
6719  eqQualHere &&
6720  !found_saop &&
6721  !found_is_null_op)
6722  numIndexTuples = 1.0;
6723  else
6724  {
6725  List *selectivityQuals;
6726  Selectivity btreeSelectivity;
6727 
6728  /*
6729  * If the index is partial, AND the index predicate with the
6730  * index-bound quals to produce a more accurate idea of the number of
6731  * rows covered by the bound conditions.
6732  */
6733  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6734 
6735  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6736  index->rel->relid,
6737  JOIN_INNER,
6738  NULL);
6739  numIndexTuples = btreeSelectivity * index->rel->tuples;
6740 
6741  /*
6742  * As in genericcostestimate(), we have to adjust for any
6743  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6744  * to integer.
6745  */
6746  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6747  }
6748 
6749  /*
6750  * Now do generic index cost estimation.
6751  */
6752  MemSet(&costs, 0, sizeof(costs));
6753  costs.numIndexTuples = numIndexTuples;
6754 
6755  genericcostestimate(root, path, loop_count, &costs);
6756 
6757  /*
6758  * Add a CPU-cost component to represent the costs of initial btree
6759  * descent. We don't charge any I/O cost for touching upper btree levels,
6760  * since they tend to stay in cache, but we still have to do about log2(N)
6761  * comparisons to descend a btree of N leaf tuples. We charge one
6762  * cpu_operator_cost per comparison.
6763  *
6764  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6765  * ones after the first one are not startup cost so far as the overall
6766  * plan is concerned, so add them only to "total" cost.
6767  */
6768  if (index->tuples > 1) /* avoid computing log(0) */
6769  {
6770  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6771  costs.indexStartupCost += descentCost;
6772  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6773  }
6774 
6775  /*
6776  * Even though we're not charging I/O cost for touching upper btree pages,
6777  * it's still reasonable to charge some CPU cost per page descended
6778  * through. Moreover, if we had no such charge at all, bloated indexes
6779  * would appear to have the same search cost as unbloated ones, at least
6780  * in cases where only a single leaf page is expected to be visited. This
6781  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6782  * touched. The number of such pages is btree tree height plus one (ie,
6783  * we charge for the leaf page too). As above, charge once per SA scan.
6784  */
6785  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6786  costs.indexStartupCost += descentCost;
6787  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6788 
6789  /*
6790  * If we can get an estimate of the first column's ordering correlation C
6791  * from pg_statistic, estimate the index correlation as C for a
6792  * single-column index, or C * 0.75 for multiple columns. (The idea here
6793  * is that multiple columns dilute the importance of the first column's
6794  * ordering, but don't negate it entirely. Before 8.0 we divided the
6795  * correlation by the number of columns, but that seems too strong.)
6796  */
6797  MemSet(&vardata, 0, sizeof(vardata));
6798 
6799  if (index->indexkeys[0] != 0)
6800  {
6801  /* Simple variable --- look to stats for the underlying table */
6802  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6803 
6804  Assert(rte->rtekind == RTE_RELATION);
6805  relid = rte->relid;
6806  Assert(relid != InvalidOid);
6807  colnum = index->indexkeys[0];
6808 
6810  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6811  {
6812  /*
6813  * The hook took control of acquiring a stats tuple. If it did
6814  * supply a tuple, it'd better have supplied a freefunc.
6815  */
6816  if (HeapTupleIsValid(vardata.statsTuple) &&
6817  !vardata.freefunc)
6818  elog(ERROR, "no function provided to release variable stats with");
6819  }
6820  else
6821  {
6823  ObjectIdGetDatum(relid),
6824  Int16GetDatum(colnum),
6825  BoolGetDatum(rte->inh));
6826  vardata.freefunc = ReleaseSysCache;
6827  }
6828  }
6829  else
6830  {
6831  /* Expression --- maybe there are stats for the index itself */
6832  relid = index->indexoid;
6833  colnum = 1;
6834 
6835  if (get_index_stats_hook &&
6836  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6837  {
6838  /*
6839  * The hook took control of acquiring a stats tuple. If it did
6840  * supply a tuple, it'd better have supplied a freefunc.
6841  */
6842  if (HeapTupleIsValid(vardata.statsTuple) &&
6843  !vardata.freefunc)
6844  elog(ERROR, "no function provided to release variable stats with");
6845  }
6846  else
6847  {
6849  ObjectIdGetDatum(relid),
6850  Int16GetDatum(colnum),
6851  BoolGetDatum(false));
6852  vardata.freefunc = ReleaseSysCache;
6853  }
6854  }
6855 
6856  if (HeapTupleIsValid(vardata.statsTuple))
6857  {
6858  Oid sortop;
6859  AttStatsSlot sslot;
6860 
6861  sortop = get_opfamily_member(index->opfamily[0],
6862  index->opcintype[0],
6863  index->opcintype[0],
6865  if (OidIsValid(sortop) &&
6866  get_attstatsslot(&sslot, vardata.statsTuple,
6867  STATISTIC_KIND_CORRELATION, sortop,
6869  {
6870  double varCorrelation;
6871 
6872  Assert(sslot.nnumbers == 1);
6873  varCorrelation = sslot.numbers[0];
6874 
6875  if (index->reverse_sort[0])
6876  varCorrelation = -varCorrelation;
6877 
6878  if (index->nkeycolumns > 1)
6879  costs.indexCorrelation = varCorrelation * 0.75;
6880  else
6881  costs.indexCorrelation = varCorrelation;
6882 
6883  free_attstatsslot(&sslot);
6884  }
6885  }
6886 
6887  ReleaseVariableStats(vardata);
6888 
6889  *indexStartupCost = costs.indexStartupCost;
6890  *indexTotalCost = costs.indexTotalCost;
6891  *indexSelectivity = costs.indexSelectivity;
6892  *indexCorrelation = costs.indexCorrelation;
6893  *indexPages = costs.numIndexPages;
6894 }
Selectivity indexSelectivity
Definition: selfuncs.h:126
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
HeapTuple statsTuple
Definition: selfuncs.h:91
int nnumbers
Definition: lsyscache.h:57
double tuples
Definition: pathnodes.h:716
#define Int16GetDatum(X)
Definition: postgres.h:495
Definition: nodes.h:539
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:93
#define MemSet(start, val, len)
Definition: c.h:1008
List * indexclauses
Definition: pathnodes.h:1238
double Selectivity
Definition: nodes.h:672
double tuples
Definition: pathnodes.h:836
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: pathnodes.h:837
#define OidIsValid(objectId)
Definition: c.h:710
#define lsecond(l)
Definition: pg_list.h:179
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
RelOptInfo * rel
Definition: pathnodes.h:832
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
AttrNumber indexcol
Definition: pathnodes.h:1286
double num_sa_scans
Definition: selfuncs.h:133
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:6352
float4 * numbers
Definition: lsyscache.h:56
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
double cpu_operator_cost
Definition: costsize.c:123
Cost indexTotalCost
Definition: selfuncs.h:125
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
List * indexquals
Definition: pathnodes.h:1284
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
double indexCorrelation
Definition: selfuncs.h:127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
NullTestType nulltesttype
Definition: primnodes.h:1266
#define BoolGetDatum(X)
Definition: postgres.h:446
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:131
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3177
#define Assert(condition)
Definition: c.h:804
#define linitial_oid(l)
Definition: pg_list.h:176
int nkeycolumns
Definition: pathnodes.h:841
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:145
Oid * opcintype
Definition: pathnodes.h:846
#define nodeTag(nodeptr)
Definition: nodes.h:544
Cost indexStartupCost
Definition: selfuncs.h:124
Oid * opfamily
Definition: pathnodes.h:845
RTEKind rtekind
Definition: parsenodes.h:995
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:81
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
#define elog(elevel,...)
Definition: elog.h:232
int * indexkeys
Definition: pathnodes.h:842
Oid opno
Definition: primnodes.h:542
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
bool * reverse_sort
Definition: pathnodes.h:848
#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:673
double numIndexPages
Definition: selfuncs.h:130
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3294
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6570

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

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

Referenced by convert_to_scalar().

4678 {
4679  bytea *valuep = DatumGetByteaPP(value);
4680  bytea *loboundp = DatumGetByteaPP(lobound);
4681  bytea *hiboundp = DatumGetByteaPP(hibound);
4682  int rangelo,
4683  rangehi,
4684  valuelen = VARSIZE_ANY_EXHDR(valuep),
4685  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4686  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4687  i,
4688  minlen;
4689  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4690  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4691  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4692 
4693  /*
4694  * Assume bytea data is uniformly distributed across all byte values.
4695  */
4696  rangelo = 0;
4697  rangehi = 255;
4698 
4699  /*
4700  * Now strip any common prefix of the three strings.
4701  */
4702  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4703  for (i = 0; i < minlen; i++)
4704  {
4705  if (*lostr != *histr || *lostr != *valstr)
4706  break;
4707  lostr++, histr++, valstr++;
4708  loboundlen--, hiboundlen--, valuelen--;
4709  }
4710 
4711  /*
4712  * Now we can do the conversions.
4713  */
4714  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4715  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4716  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4717 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:361
#define Min(x, y)
Definition: c.h:986
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4720
#define DatumGetByteaPP(X)
Definition: fmgr.h:291
static struct @143 value
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:354
int i
Definition: c.h:621

◆ convert_numeric_to_scalar()

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

Definition at line 4399 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4400 {
4401  switch (typid)
4402  {
4403  case BOOLOID:
4404  return (double) DatumGetBool(value);
4405  case INT2OID:
4406  return (double) DatumGetInt16(value);
4407  case INT4OID:
4408  return (double) DatumGetInt32(value);
4409  case INT8OID:
4410  return (double) DatumGetInt64(value);
4411  case FLOAT4OID:
4412  return (double) DatumGetFloat4(value);
4413  case FLOAT8OID:
4414  return (double) DatumGetFloat8(value);
4415  case NUMERICOID:
4416  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4417  return (double)
4419  value));
4420  case OIDOID:
4421  case REGPROCOID:
4422  case REGPROCEDUREOID:
4423  case REGOPEROID:
4424  case REGOPERATOROID:
4425  case REGCLASSOID:
4426  case REGTYPEOID:
4427  case REGCONFIGOID:
4428  case REGDICTIONARYOID:
4429  case REGROLEOID:
4430  case REGNAMESPACEOID:
4431  /* we can treat OIDs as integers... */
4432  return (double) DatumGetObjectId(value);
4433  }
4434 
4435  *failure = true;
4436  return 0;
4437 }
#define DatumGetInt32(X)
Definition: postgres.h:516
#define DatumGetObjectId(X)
Definition: postgres.h:544
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
static float4 DatumGetFloat4(Datum X)
Definition: postgres.h:708
#define DatumGetInt64(X)
Definition: postgres.h:651
#define DatumGetInt16(X)
Definition: postgres.h:488
#define DatumGetBool(X)
Definition: postgres.h:437
#define DatumGetFloat8(X)
Definition: postgres.h:758
static struct @143 value
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:4469

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

Referenced by convert_bytea_to_scalar().

4722 {
4723  double num,
4724  denom,
4725  base;
4726 
4727  if (valuelen <= 0)
4728  return 0.0; /* empty string has scalar value 0 */
4729 
4730  /*
4731  * Since base is 256, need not consider more than about 10 chars (even
4732  * this many seems like overkill)
4733  */
4734  if (valuelen > 10)
4735  valuelen = 10;
4736 
4737  /* Convert initial characters to fraction */
4738  base = rangehi - rangelo + 1;
4739  num = 0.0;
4740  denom = base;
4741  while (valuelen-- > 0)
4742  {
4743  int ch = *value++;
4744 
4745  if (ch < rangelo)
4746  ch = rangelo - 1;
4747  else if (ch > rangehi)
4748  ch = rangehi + 1;
4749  num += ((double) (ch - rangelo)) / denom;
4750  denom *= base;
4751  }
4752 
4753  return num;
4754 }
static struct @143 value

◆ convert_one_string_to_scalar()

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

Definition at line 4540 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4541 {
4542  int slen = strlen(value);
4543  double num,
4544  denom,
4545  base;
4546 
4547  if (slen <= 0)
4548  return 0.0; /* empty string has scalar value 0 */
4549 
4550  /*
4551  * There seems little point in considering more than a dozen bytes from
4552  * the string. Since base is at least 10, that will give us nominal
4553  * resolution of at least 12 decimal digits, which is surely far more
4554  * precision than this estimation technique has got anyway (especially in
4555  * non-C locales). Also, even with the maximum possible base of 256, this
4556  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4557  * overflow on any known machine.
4558  */
4559  if (slen > 12)
4560  slen = 12;
4561 
4562  /* Convert initial characters to fraction */
4563  base = rangehi - rangelo + 1;
4564  num = 0.0;
4565  denom = base;
4566  while (slen-- > 0)
4567  {
4568  int ch = (unsigned char) *value++;
4569 
4570  if (ch < rangelo)
4571  ch = rangelo - 1;
4572  else if (ch > rangehi)
4573  ch = rangehi + 1;
4574  num += ((double) (ch - rangelo)) / denom;
4575  denom *= base;
4576  }
4577 
4578  return num;
4579 }
static struct @143 value

◆ convert_string_datum()

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

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

4592 {
4593  char *val;
4594 
4595  switch (typid)
4596  {
4597  case CHAROID:
4598  val = (char *) palloc(2);
4599  val[0] = DatumGetChar(value);
4600  val[1] = '\0';
4601  break;
4602  case BPCHAROID:
4603  case VARCHAROID:
4604  case TEXTOID:
4605  val = TextDatumGetCString(value);
4606  break;
4607  case NAMEOID:
4608  {
4610 
4611  val = pstrdup(NameStr(*nm));
4612  break;
4613  }
4614  default:
4615  *failure = true;
4616  return NULL;
4617  }
4618 
4619  if (!lc_collate_is_c(collid))
4620  {
4621  char *xfrmstr;
4622  size_t xfrmlen;
4623  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4624 
4625  /*
4626  * XXX: We could guess at a suitable output buffer size and only call
4627  * strxfrm twice if our guess is too small.
4628  *
4629  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4630  * bogus data or set an error. This is not really a problem unless it
4631  * crashes since it will only give an estimation error and nothing
4632  * fatal.
4633  */
4634  xfrmlen = strxfrm(NULL, val, 0);
4635 #ifdef WIN32
4636 
4637  /*
4638  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4639  * of trying to allocate this much memory (and fail), just return the
4640  * original string unmodified as if we were in the C locale.
4641  */
4642  if (xfrmlen == INT_MAX)
4643  return val;
4644 #endif
4645  xfrmstr = (char *) palloc(xfrmlen + 1);
4646  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4647 
4648  /*
4649  * Some systems (e.g., glibc) can return a smaller value from the
4650  * second call than the first; thus the Assert must be <= not ==.
4651  */
4652  Assert(xfrmlen2 <= xfrmlen);
4653  pfree(val);
4654  val = xfrmstr;
4655  }
4656 
4657  return val;
4658 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void pfree(void *pointer)
Definition: mcxt.c:1169
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1321
Definition: c.h:675
#define TextDatumGetCString(d)
Definition: builtins.h:83
#define DatumGetChar(X)
Definition: postgres.h:453
static struct @143 value
#define Assert(condition)
Definition: c.h:804
#define DatumGetPointer(X)
Definition: postgres.h:593
void * palloc(Size size)
Definition: mcxt.c:1062
#define NameStr(name)
Definition: c.h:681
long val
Definition: informix.c:664
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

4466 {
4467  int rangelo,
4468  rangehi;
4469  char *sptr;
4470 
4471  rangelo = rangehi = (unsigned char) hibound[0];
4472  for (sptr = lobound; *sptr; sptr++)
4473  {
4474  if (rangelo > (unsigned char) *sptr)
4475  rangelo = (unsigned char) *sptr;
4476  if (rangehi < (unsigned char) *sptr)
4477  rangehi = (unsigned char) *sptr;
4478  }
4479  for (sptr = hibound; *sptr; sptr++)
4480  {
4481  if (rangelo > (unsigned char) *sptr)
4482  rangelo = (unsigned char) *sptr;
4483  if (rangehi < (unsigned char) *sptr)
4484  rangehi = (unsigned char) *sptr;
4485  }
4486  /* If range includes any upper-case ASCII chars, make it include all */
4487  if (rangelo <= 'Z' && rangehi >= 'A')
4488  {
4489  if (rangelo > 'A')
4490  rangelo = 'A';
4491  if (rangehi < 'Z')
4492  rangehi = 'Z';
4493  }
4494  /* Ditto lower-case */
4495  if (rangelo <= 'z' && rangehi >= 'a')
4496  {
4497  if (rangelo > 'a')
4498  rangelo = 'a';
4499  if (rangehi < 'z')
4500  rangehi = 'z';
4501  }
4502  /* Ditto digits */
4503  if (rangelo <= '9' && rangehi >= '0')
4504  {
4505  if (rangelo > '0')
4506  rangelo = '0';
4507  if (rangehi < '9')
4508  rangehi = '9';
4509  }
4510 
4511  /*
4512  * If range includes less than 10 chars, assume we have not got enough
4513  * data, and make it include regular ASCII set.
4514  */
4515  if (rangehi - rangelo < 9)
4516  {
4517  rangelo = ' ';
4518  rangehi = 127;
4519  }
4520 
4521  /*
4522  * Now strip any common prefix of the three strings.
4523  */
4524  while (*lobound)
4525  {
4526  if (*lobound != *hibound || *lobound != *value)
4527  break;
4528  lobound++, hibound++, value++;
4529  }
4530 
4531  /*
4532  * Now we can do the conversions.
4533  */
4534  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4535  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4536  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4537 }
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4540
static struct @143 value

◆ convert_timevalue_to_scalar()

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

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

4764 {
4765  switch (typid)
4766  {
4767  case TIMESTAMPOID:
4768  return DatumGetTimestamp(value);
4769  case TIMESTAMPTZOID:
4770  return DatumGetTimestampTz(value);
4771  case DATEOID:
4773  case INTERVALOID:
4774  {
4776 
4777  /*
4778  * Convert the month part of Interval to days using assumed
4779  * average month length of 365.25/12.0 days. Not too
4780  * accurate, but plenty good enough for our purposes.
4781  */
4782  return interval->time + interval->day * (double) USECS_PER_DAY +
4783  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4784  }
4785  case TIMEOID:
4786  return DatumGetTimeADT(value);
4787  case TIMETZOID:
4788  {
4789  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4790 
4791  /* use GMT-equivalent time */
4792  return (double) (timetz->time + (timetz->zone * 1000000.0));
4793  }
4794  }
4795 
4796  *failure = true;
4797  return 0;
4798 }
#define DatumGetDateADT(X)
Definition: date.h:53
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:29
#define DatumGetTimeTzADTP(X)
Definition: date.h:55
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:725
int32 day
Definition: timestamp.h:47
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define DAYS_PER_YEAR
Definition: timestamp.h:68
int32 zone
Definition: date.h:30
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
TimeOffset time
Definition: timestamp.h:45
#define USECS_PER_DAY
Definition: timestamp.h:91
int32 month
Definition: timestamp.h:48
#define DatumGetTimeADT(X)
Definition: date.h:54
static struct @143 value
Definition: date.h:27
#define DatumGetTimestamp(X)
Definition: timestamp.h:27

◆ convert_to_scalar()

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

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

4256 {
4257  bool failure = false;
4258 
4259  /*
4260  * Both the valuetypid and the boundstypid should exactly match the
4261  * declared input type(s) of the operator we are invoked for. However,
4262  * extensions might try to use scalarineqsel as estimator for operators
4263  * with input type(s) we don't handle here; in such cases, we want to
4264  * return false, not fail. In any case, we mustn't assume that valuetypid
4265  * and boundstypid are identical.
4266  *
4267  * XXX The histogram we are interpolating between points of could belong
4268  * to a column that's only binary-compatible with the declared type. In
4269  * essence we are assuming that the semantics of binary-compatible types
4270  * are enough alike that we can use a histogram generated with one type's
4271  * operators to estimate selectivity for the other's. This is outright
4272  * wrong in some cases --- in particular signed versus unsigned
4273  * interpretation could trip us up. But it's useful enough in the
4274  * majority of cases that we do it anyway. Should think about more
4275  * rigorous ways to do it.
4276  */
4277  switch (valuetypid)
4278  {
4279  /*
4280  * Built-in numeric types
4281  */
4282  case BOOLOID:
4283  case INT2OID:
4284  case INT4OID:
4285  case INT8OID:
4286  case FLOAT4OID:
4287  case FLOAT8OID:
4288  case NUMERICOID:
4289  case OIDOID:
4290  case REGPROCOID:
4291  case REGPROCEDUREOID:
4292  case REGOPEROID:
4293  case REGOPERATOROID:
4294  case REGCLASSOID:
4295  case REGTYPEOID:
4296  case REGCONFIGOID:
4297  case REGDICTIONARYOID:
4298  case REGROLEOID:
4299  case REGNAMESPACEOID:
4300  *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4301  &failure);
4302  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4303  &failure);
4304  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4305  &failure);
4306  return !failure;
4307 
4308  /*
4309  * Built-in string types
4310  */
4311  case CHAROID:
4312  case BPCHAROID:
4313  case VARCHAROID:
4314  case TEXTOID:
4315  case NAMEOID:
4316  {
4317  char *valstr = convert_string_datum(value, valuetypid,
4318  collid, &failure);
4319  char *lostr = convert_string_datum(lobound, boundstypid,
4320  collid, &failure);
4321  char *histr = convert_string_datum(hibound, boundstypid,
4322  collid, &failure);
4323 
4324  /*
4325  * Bail out if any of the values is not of string type. We
4326  * might leak converted strings for the other value(s), but
4327  * that's not worth troubling over.
4328  */
4329  if (failure)
4330  return false;
4331 
4332  convert_string_to_scalar(valstr, scaledvalue,
4333  lostr, scaledlobound,
4334  histr, scaledhibound);
4335  pfree(valstr);
4336  pfree(lostr);
4337  pfree(histr);
4338  return true;
4339  }
4340 
4341  /*
4342  * Built-in bytea type
4343  */
4344  case BYTEAOID:
4345  {
4346  /* We only support bytea vs bytea comparison */
4347  if (boundstypid != BYTEAOID)
4348  return false;
4349  convert_bytea_to_scalar(value, scaledvalue,
4350  lobound, scaledlobound,
4351  hibound, scaledhibound);
4352  return true;
4353  }
4354 
4355  /*
4356  * Built-in time types
4357  */
4358  case TIMESTAMPOID:
4359  case TIMESTAMPTZOID:
4360  case DATEOID:
4361  case INTERVALOID:
4362  case TIMEOID:
4363  case TIMETZOID:
4364  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4365  &failure);
4366  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4367  &failure);
4368  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4369  &failure);
4370  return !failure;
4371 
4372  /*
4373  * Built-in network types
4374  */
4375  case INETOID:
4376  case CIDROID:
4377  case MACADDROID:
4378  case MACADDR8OID:
4379  *scaledvalue = convert_network_to_scalar(value, valuetypid,
4380  &failure);
4381  *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4382  &failure);
4383  *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4384  &failure);
4385  return !failure;
4386  }
4387  /* Don't know how to convert */
4388  *scaledvalue = *scaledlobound = *scaledhibound = 0;
4389  return false;
4390 }
static char * convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
Definition: selfuncs.c:4591
void pfree(void *pointer)
Definition: mcxt.c:1169
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:4399
static struct @143 value
static void convert_bytea_to_scalar(Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
Definition: selfuncs.c:4672
static double convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4763
static void convert_string_to_scalar(char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
Definition: selfuncs.c:4460

◆ 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:1480
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Relids min_righthand
Definition: pathnodes.h:2242
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:42
HeapTuple statsTuple
Definition: selfuncs.h:91
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5599
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define Min(x, y)
Definition: c.h:986
#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:135
#define OidIsValid(objectId)
Definition: c.h:710
#define PG_GET_COLLATION()
Definition: fmgr.h:198
JoinType
Definition: nodes.h:706
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:43
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:46
double float8
Definition: c.h:565
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4885
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5628
#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:6233
double rows
Definition: pathnodes.h:679
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3177
JoinType jointype
Definition: pathnodes.h:2245
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:101
#define elog(elevel,...)
Definition: elog.h:232
Definition: pg_list.h:50
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3294

◆ 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:63
void pfree(void *pointer)
Definition: mcxt.c:1169
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
float4 * numbers
Definition: lsyscache.h:56
#define DatumGetBool(X)
Definition: postgres.h:437
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
Datum * values
Definition: lsyscache.h:53
#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:90
#define Min(x, y)
Definition: c.h:986
#define OidIsValid(objectId)
Definition: c.h:710
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
void pfree(void *pointer)
Definition: mcxt.c:1169
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
float4 * numbers
Definition: lsyscache.h:56
#define DatumGetBool(X)
Definition: postgres.h:437
void * palloc0(Size size)
Definition: mcxt.c:1093
uintptr_t Datum
Definition: postgres.h:411
double rows
Definition: pathnodes.h:679
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
Datum * values
Definition: lsyscache.h:53
#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:367
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:233
double float8
Definition: c.h:565

◆ 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:590
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4825
Definition: nodes.h:539
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#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:101
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:1504
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:590
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:76
#define ARR_DIMS(a)
Definition: array.h:287
uintptr_t Datum
Definition: postgres.h:411
static int list_length(const List *l)
Definition: pg_list.h:149
#define ARR_NDIM(a)
Definition: array.h:283
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1780
#define DatumGetArrayTypeP(X)
Definition: array.h:254

◆ estimate_hash_bucket_stats()

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

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

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

◆ estimate_hashagg_tablesize()

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

Definition at line 3870 of file selfuncs.c.

References PlannerInfo::aggtransinfos, hash_agg_entry_size(), list_length(), Path::pathtarget, AggClauseCosts::transitionSpace, and PathTarget::width.

Referenced by consider_groupingsets_paths().

3872 {
3873  Size hashentrysize;
3874 
3875  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3876  path->pathtarget->width,
3877  agg_costs->transitionSpace);
3878 
3879  /*
3880  * Note that this disregards the effect of fill-factor and growth policy
3881  * of the hash table. That's probably ok, given that the default
3882  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3883  * "double-in-size" growth policies here.
3884  */
3885  return hashentrysize * dNumGroups;
3886 }
PathTarget * pathtarget
Definition: pathnodes.h:1175
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1695
List * aggtransinfos
Definition: pathnodes.h:357
size_t Size
Definition: c.h:540
static int list_length(const List *l)
Definition: pg_list.h:149
Size transitionSpace
Definition: pathnodes.h:60

◆ estimate_multivariate_ndistinct()

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

Definition at line 3907 of file selfuncs.c.

References Assert, attnum, MVNDistinctItem::attributes, AttrNumberIsForUserDefinedAttr, bms_add_member(), bms_is_member(), bms_num_members(), elog, equal(), ERROR, StatisticExtInfo::exprs, i, idx(), InvalidOid, IsA, MVNDistinct::items, StatisticExtInfo::keys, StatisticExtInfo::kind, lappend(), lfirst, list_length(), MVNDistinctItem::nattributes, MVNDistinctItem::ndistinct, NIL, MVNDistinct::nitems, GroupVarInfo::rel, statext_ndistinct_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, and GroupVarInfo::var.

Referenced by estimate_num_groups().

3909 {
3910  ListCell *lc;
3911  int nmatches_vars;
3912  int nmatches_exprs;
3913  Oid statOid = InvalidOid;
3914  MVNDistinct *stats;
3915  StatisticExtInfo *matched_info = NULL;
3916 
3917  /* bail out immediately if the table has no extended statistics */
3918  if (!rel->statlist)
3919  return false;
3920 
3921  /* look for the ndistinct statistics matching the most vars */
3922  nmatches_vars = 0; /* we require at least two matches */
3923  nmatches_exprs = 0;
3924  foreach(lc, rel->statlist)
3925  {
3926  ListCell *lc2;
3927  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3928  int nshared_vars = 0;
3929  int nshared_exprs = 0;
3930 
3931  /* skip statistics of other kinds */
3932  if (info->kind != STATS_EXT_NDISTINCT)
3933  continue;
3934 
3935  /*
3936  * Determine how many expressions (and variables in non-matched
3937  * expressions) match. We'll then use these numbers to pick the
3938  * statistics object that best matches the clauses.
3939  */
3940  foreach(lc2, *varinfos)
3941  {
3942  ListCell *lc3;
3943  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
3945 
3946  Assert(varinfo->rel == rel);
3947 
3948  /* simple Var, search in statistics keys directly */
3949  if (IsA(varinfo->var, Var))
3950  {
3951  attnum = ((Var *) varinfo->var)->varattno;
3952 
3953  /*
3954  * Ignore system attributes - we don't support statistics on
3955  * them, so can't match them (and it'd fail as the values are
3956  * negative).
3957  */
3958  if (!AttrNumberIsForUserDefinedAttr(attnum))
3959  continue;
3960 
3961  if (bms_is_member(attnum, info->keys))
3962  nshared_vars++;
3963 
3964  continue;
3965  }
3966 
3967  /* expression - see if it's in the statistics */
3968  foreach(lc3, info->exprs)
3969  {
3970  Node *expr = (Node *) lfirst(lc3);
3971 
3972  if (equal(varinfo->var, expr))
3973  {
3974  nshared_exprs++;
3975  break;
3976  }
3977  }
3978  }
3979 
3980  if (nshared_vars + nshared_exprs < 2)
3981  continue;
3982 
3983  /*
3984  * Does this statistics object match more columns than the currently
3985  * best object? If so, use this one instead.
3986  *
3987  * XXX This should break ties using name of the object, or something
3988  * like that, to make the outcome stable.
3989  */
3990  if ((nshared_exprs > nmatches_exprs) ||
3991  (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
3992  {
3993  statOid = info->statOid;
3994  nmatches_vars = nshared_vars;
3995  nmatches_exprs = nshared_exprs;
3996  matched_info = info;
3997  }
3998  }
3999 
4000  /* No match? */
4001  if (statOid == InvalidOid)
4002  return false;
4003 
4004  Assert(nmatches_vars + nmatches_exprs > 1);
4005 
4006  stats = statext_ndistinct_load(statOid);
4007 
4008  /*
4009  * If we have a match, search it for the specific item that matches (there
4010  * must be one), and construct the output values.
4011  */
4012  if (stats)
4013  {
4014  int i;
4015  List *newlist = NIL;
4016  MVNDistinctItem *item = NULL;
4017  ListCell *lc2;
4018  Bitmapset *matched = NULL;
4019  AttrNumber attnum_offset;
4020 
4021  /*
4022  * How much we need to offset the attnums? If there are no
4023  * expressions, no offset is needed. Otherwise offset enough to move
4024  * the lowest one (which is equal to number of expressions) to 1.
4025  */
4026  if (matched_info->exprs)
4027  attnum_offset = (list_length(matched_info->exprs) + 1);
4028  else
4029  attnum_offset = 0;
4030 
4031  /* see what actually matched */
4032  foreach(lc2, *varinfos)
4033  {
4034  ListCell *lc3;
4035  int idx;
4036  bool found = false;
4037 
4038  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4039 
4040  /*
4041  * Process a simple Var expression, by matching it to keys
4042  * directly. If there's a matching expression, we'll try matching
4043  * it later.
4044  */
4045  if (IsA(varinfo->var, Var))
4046  {
4047  AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4048 
4049  /*
4050  * Ignore expressions on system attributes. Can't rely on the
4051  * bms check for negative values.
4052  */
4053  if (!AttrNumberIsForUserDefinedAttr(attnum))
4054  continue;
4055 
4056  /* Is the variable covered by the statistics? */
4057  if (!bms_is_member(attnum, matched_info->keys))
4058  continue;
4059 
4060  attnum = attnum + attnum_offset;
4061 
4062  /* ensure sufficient offset */
4064 
4065  matched = bms_add_member(matched, attnum);
4066 
4067  found = true;
4068  }
4069 
4070  /*
4071  * XXX Maybe we should allow searching the expressions even if we
4072  * found an attribute matching the expression? That would handle
4073  * trivial expressions like "(a)" but it seems fairly useless.
4074  */
4075  if (found)
4076  continue;
4077 
4078  /* expression - see if it's in the statistics */
4079  idx = 0;
4080  foreach(lc3, matched_info->exprs)
4081  {
4082  Node *expr = (Node *) lfirst(lc3);
4083 
4084  if (equal(varinfo->var, expr))
4085  {
4086  AttrNumber attnum = -(idx + 1);
4087 
4088  attnum = attnum + attnum_offset;
4089 
4090  /* ensure sufficient offset */
4092 
4093  matched = bms_add_member(matched, attnum);
4094 
4095  /* there should be just one matching expression */
4096  break;
4097  }
4098 
4099  idx++;
4100  }
4101  }
4102 
4103  /* Find the specific item that exactly matches the combination */
4104  for (i = 0; i < stats->nitems; i++)
4105  {
4106  int j;
4107  MVNDistinctItem *tmpitem = &stats->items[i];
4108 
4109  if (tmpitem->nattributes != bms_num_members(matched))
4110  continue;
4111 
4112  /* assume it's the right item */
4113  item = tmpitem;
4114 
4115  /* check that all item attributes/expressions fit the match */
4116  for (j = 0; j < tmpitem->nattributes; j++)
4117  {
4118  AttrNumber attnum = tmpitem->attributes[j];
4119 
4120  /*
4121  * Thanks to how we constructed the matched bitmap above, we
4122  * can just offset all attnums the same way.
4123  */
4124  attnum = attnum + attnum_offset;
4125 
4126  if (!bms_is_member(attnum, matched))
4127  {
4128  /* nah, it's not this item */
4129  item = NULL;
4130  break;
4131  }
4132  }
4133 
4134  /*
4135  * If the item has all the matched attributes, we know it's the
4136  * right one - there can't be a better one. matching more.
4137  */
4138  if (item)
4139  break;
4140  }
4141 
4142  /*
4143  * Make sure we found an item. There has to be one, because ndistinct
4144  * statistics includes all combinations of attributes.
4145  */
4146  if (!item)
4147  elog(ERROR, "corrupt MVNDistinct entry");
4148 
4149  /* Form the output varinfo list, keeping only unmatched ones */
4150  foreach(lc, *varinfos)
4151  {
4152  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4153  ListCell *lc3;
4154  bool found = false;
4155 
4156  /*
4157  * Let's look at plain variables first, because it's the most
4158  * common case and the check is quite cheap. We can simply get the
4159  * attnum and check (with an offset) matched bitmap.
4160  */
4161  if (IsA(varinfo->var, Var))
4162  {
4163  AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4164 
4165  /*
4166  * If it's a system attribute, we're done. We don't support
4167  * extended statistics on system attributes, so it's clearly
4168  * not matched. Just keep the expression and continue.
4169  */
4170  if (!AttrNumberIsForUserDefinedAttr(attnum))
4171  {
4172  newlist = lappend(newlist, varinfo);
4173  continue;
4174  }
4175 
4176  /* apply the same offset as above */
4177  attnum += attnum_offset;
4178 
4179  /* if it's not matched, keep the varinfo */
4180  if (!bms_is_member(attnum, matched))
4181  newlist = lappend(newlist, varinfo);
4182 
4183  /* The rest of the loop deals with complex expressions. */
4184  continue;
4185  }
4186 
4187  /*
4188  * Process complex expressions, not just simple Vars.
4189  *
4190  * First, we search for an exact match of an expression. If we
4191  * find one, we can just discard the whole GroupExprInfo, with all
4192  * the variables we extracted from it.
4193  *
4194  * Otherwise we inspect the individual vars, and try matching it
4195  * to variables in the item.
4196  */
4197  foreach(lc3, matched_info->exprs)
4198  {
4199  Node *expr = (Node *) lfirst(lc3);
4200 
4201  if (equal(varinfo->var, expr))
4202  {
4203  found = true;
4204  break;
4205  }
4206  }
4207 
4208  /* found exact match, skip */
4209  if (found)
4210  continue;
4211 
4212  newlist = lappend(newlist, varinfo);
4213  }
4214 
4215  *varinfos = newlist;
4216  *ndistinct = item->ndistinct;
4217  return true;
4218  }
4219 
4220  return false;
4221 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * statlist
Definition: pathnodes.h:714
MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:39
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
double ndistinct
Definition: statistics.h:28
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
Definition: nodes.h:539
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
#define ERROR
Definition: elog.h:46
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:646
Node * var
Definition: selfuncs.c:3241
uint32 nitems
Definition: statistics.h:38
List * lappend(List *list, void *datum)
Definition: list.c:336
AttrNumber * attributes
Definition: statistics.h:30
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:83
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
Bitmapset * keys
Definition: pathnodes.h:931
#define elog(elevel,...)
Definition: elog.h:232
int i
MVNDistinct * statext_ndistinct_load(Oid mvoid)
Definition: mvdistinct.c:149
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,
EstimationInfo estinfo 
)

Definition at line 3368 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(), EstimationInfo::flags, for_each_from, HeapTupleIsValid, i, IS_SIMPLE_REL, GroupVarInfo::isdefault, VariableStatData::isunique, lappend(), lfirst, linitial, list_length(), list_member_int(), GroupVarInfo::ndistinct, NIL, pull_var_clause(), PVC_RECURSE_AGGREGATES, PVC_RECURSE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, GroupVarInfo::rel, ReleaseVariableStats, RelOptInfo::rows, SELFLAG_USED_DEFAULT, VariableStatData::statsTuple, and RelOptInfo::tuples.

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

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

◆ examine_simple_variable()

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

Definition at line 5351 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, Query::groupingSets, 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().

5353 {
5354  RangeTblEntry *rte = root->simple_rte_array[var->varno];
5355 
5356  Assert(IsA(rte, RangeTblEntry));
5357 
5359  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
5360  {
5361  /*
5362  * The hook took control of acquiring a stats tuple. If it did supply
5363  * a tuple, it'd better have supplied a freefunc.
5364  */
5365  if (HeapTupleIsValid(vardata->statsTuple) &&
5366  !vardata->freefunc)
5367  elog(ERROR, "no function provided to release variable stats with");
5368  }
5369  else if (rte->rtekind == RTE_RELATION)
5370  {
5371  /*
5372  * Plain table or parent of an inheritance appendrel, so look up the
5373  * column in pg_statistic
5374  */
5376  ObjectIdGetDatum(rte->relid),
5377  Int16GetDatum(var->varattno),
5378  BoolGetDatum(rte->inh));
5379  vardata->freefunc = ReleaseSysCache;
5380 
5381  if (HeapTupleIsValid(vardata->statsTuple))
5382  {
5383  Oid userid;
5384 
5385  /*
5386  * Check if user has permission to read this column. We require
5387  * all rows to be accessible, so there must be no securityQuals
5388  * from security barrier views or RLS policies. Use checkAsUser
5389  * if it's set, in case we're accessing the table via a view.
5390  */
5391  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5392 
5393  vardata->acl_ok =
5394  rte->securityQuals == NIL &&
5395  ((pg_class_aclcheck(rte->relid, userid,
5396  ACL_SELECT) == ACLCHECK_OK) ||
5397  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
5398  ACL_SELECT) == ACLCHECK_OK));
5399 
5400  /*
5401  * If the user doesn't have permissions to access an inheritance
5402  * child relation or specifically this attribute, check the
5403  * permissions of the table/column actually mentioned in the
5404  * query, since most likely the user does have that permission
5405  * (else the query will fail at runtime), and if the user can read
5406  * the column there then he can get the values of the child table
5407  * too. To do that, we must find out which of the root parent's
5408  * attributes the child relation's attribute corresponds to.
5409  */
5410  if (!vardata->acl_ok && var->varattno > 0 &&
5411  root->append_rel_array != NULL)
5412  {
5413  AppendRelInfo *appinfo;
5414  Index varno = var->varno;
5415  int varattno = var->varattno;
5416  bool found = false;
5417 
5418  appinfo = root->append_rel_array[varno];
5419 
5420  /*
5421  * Partitions are mapped to their immediate parent, not the
5422  * root parent, so must be ready to walk up multiple
5423  * AppendRelInfos. But stop if we hit a parent that is not
5424  * RTE_RELATION --- that's a flattened UNION ALL subquery, not
5425  * an inheritance parent.
5426  */
5427  while (appinfo &&
5428  planner_rt_fetch(appinfo->parent_relid,
5429  root)->rtekind == RTE_RELATION)
5430  {
5431  int parent_varattno;
5432 
5433  found = false;
5434  if (varattno <= 0 || varattno > appinfo->num_child_cols)
5435  break; /* safety check */
5436  parent_varattno = appinfo->parent_colnos[varattno - 1];
5437  if (parent_varattno == 0)
5438  break; /* Var is local to child */
5439 
5440  varno = appinfo->parent_relid;
5441  varattno = parent_varattno;
5442  found = true;
5443 
5444  /* If the parent is itself a child, continue up. */
5445  appinfo = root->append_rel_array[varno];
5446  }
5447 
5448  /*
5449  * In rare cases, the Var may be local to the child table, in
5450  * which case, we've got to live with having no access to this
5451  * column's stats.
5452  */
5453  if (!found)
5454  return;
5455 
5456  /* Repeat the access check on this parent rel & column */
5457  rte = planner_rt_fetch(varno, root);
5458  Assert(rte->rtekind == RTE_RELATION);
5459 
5460  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5461 
5462  vardata->acl_ok =
5463  rte->securityQuals == NIL &&
5464  ((pg_class_aclcheck(rte->relid, userid,
5465  ACL_SELECT) == ACLCHECK_OK) ||
5466  (pg_attribute_aclcheck(rte->relid, varattno, userid,
5467  ACL_SELECT) == ACLCHECK_OK));
5468  }
5469  }
5470  else
5471  {
5472  /* suppress any possible leakproofness checks later */
5473  vardata->acl_ok = true;
5474  }
5475  }
5476  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
5477  {
5478  /*
5479  * Plain subquery (not one that was converted to an appendrel).
5480  */
5481  Query *subquery = rte->subquery;
5482  RelOptInfo *rel;
5483  TargetEntry *ste;
5484 
5485  /*
5486  * Punt if it's a whole-row var rather than a plain column reference.
5487  */
5488  if (var->varattno == InvalidAttrNumber)
5489  return;
5490 
5491  /*
5492  * Punt if subquery uses set operations or GROUP BY, as these will
5493  * mash underlying columns' stats beyond recognition. (Set ops are
5494  * particularly nasty; if we forged ahead, we would return stats
5495  * relevant to only the leftmost subselect...) DISTINCT is also
5496  * problematic, but we check that later because there is a possibility
5497  * of learning something even with it.
5498  */
5499  if (subquery->setOperations ||
5500  subquery->groupClause ||
5501  subquery->groupingSets)
5502  return;
5503 
5504  /*
5505  * OK, fetch RelOptInfo for subquery. Note that we don't change the
5506  * rel returned in vardata, since caller expects it to be a rel of the
5507  * caller's query level. Because we might already be recursing, we
5508  * can't use that rel pointer either, but have to look up the Var's
5509  * rel afresh.
5510  */
5511  rel = find_base_rel(root, var->varno);
5512 
5513  /* If the subquery hasn't been planned yet, we have to punt */
5514  if (rel->subroot == NULL)
5515  return;
5516  Assert(IsA(rel->subroot, PlannerInfo));
5517 
5518  /*
5519  * Switch our attention to the subquery as mangled by the planner. It
5520  * was okay to look at the pre-planning version for the tests above,
5521  * but now we need a Var that will refer to the subroot's live
5522  * RelOptInfos. For instance, if any subquery pullup happened during
5523  * planning, Vars in the targetlist might have gotten replaced, and we
5524  * need to see the replacement expressions.
5525  */
5526  subquery = rel->subroot->parse;
5527  Assert(IsA(subquery, Query));
5528 
5529  /* Get the subquery output expression referenced by the upper Var */
5530  ste = get_tle_by_resno(subquery->targetList, var->varattno);
5531  if (ste == NULL || ste->resjunk)
5532  elog(ERROR, "subquery %s does not have attribute %d",
5533  rte->eref->aliasname, var->varattno);
5534  var = (Var *) ste->expr;
5535 
5536  /*
5537  * If subquery uses DISTINCT, we can't make use of any stats for the
5538  * variable ... but, if it's the only DISTINCT column, we are entitled
5539  * to consider it unique. We do the test this way so that it works
5540  * for cases involving DISTINCT ON.
5541  */
5542  if (subquery->distinctClause)
5543  {
5544  if (list_length(subquery->distinctClause) == 1 &&
5545  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5546  vardata->isunique = true;
5547  /* cannot go further */
5548  return;
5549  }
5550 
5551  /*
5552  * If the sub-query originated from a view with the security_barrier
5553  * attribute, we must not look at the variable's statistics, though it
5554  * seems all right to notice the existence of a DISTINCT clause. So
5555  * stop here.
5556  *
5557  * This is probably a harsher restriction than necessary; it's
5558  * certainly OK for the selectivity estimator (which is a C function,
5559  * and therefore omnipotent anyway) to look at the statistics. But
5560  * many selectivity estimators will happily *invoke the operator
5561  * function* to try to work out a good estimate - and that's not OK.
5562  * So for now, don't dig down for stats.
5563  */
5564  if (rte->security_barrier)
5565  return;
5566 
5567  /* Can only handle a simple Var of subquery's query level */
5568  if (var && IsA(var, Var) &&
5569  var->varlevelsup == 0)
5570  {
5571  /*
5572  * OK, recurse into the subquery. Note that the original setting
5573  * of vardata->isunique (which will surely be false) is left
5574  * unchanged in this situation. That's what we want, since even
5575  * if the underlying column is unique, the subquery may have
5576  * joined to other tables in a way that creates duplicates.
5577  */
5578  examine_simple_variable(rel->subroot, var, vardata);
5579  }
5580  }
5581  else
5582  {
5583  /*
5584  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
5585  * won't see RTE_JOIN here because join alias Vars have already been
5586  * flattened.) There's not much we can do with function outputs, but
5587  * maybe someday try to be smarter about VALUES and/or CTEs.
5588  */
5589  }
5590 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Query * parse
Definition: pathnodes.h:161
Index varlevelsup
Definition: primnodes.h:196
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4551
int num_child_cols
Definition: pathnodes.h:2331
HeapTuple statsTuple
Definition: selfuncs.h:91
Oid GetUserId(void)
Definition: miscinit.c:478
AttrNumber * parent_colnos
Definition: pathnodes.h:2332
List * securityQuals
Definition: parsenodes.h:1151
#define Int16GetDatum(X)
Definition: postgres.h:495
List * groupingSets
Definition: parsenodes.h:161
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:93
AttrNumber varattno
Definition: primnodes.h:191
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5351
List * targetList
Definition: parsenodes.h:150
PlannerInfo * subroot
Definition: pathnodes.h:720
bool resjunk
Definition: primnodes.h:1461
List * distinctClause
Definition: parsenodes.h:167
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:144
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:193
Index varno
Definition: primnodes.h:189
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ACL_SELECT
Definition: parsenodes.h:83
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:201
unsigned int Index
Definition: c.h:549
bool security_barrier
Definition: parsenodes.h:1031
#define BoolGetDatum(X)
Definition: postgres.h:446
#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:804
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1454
static int list_length(const List *l)
Definition: pg_list.h:149
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4680
RTEKind rtekind
Definition: parsenodes.h:995
Node * setOperations
Definition: parsenodes.h:177
Query * subquery
Definition: parsenodes.h:1030
List * groupClause
Definition: parsenodes.h:158
#define elog(elevel,...)
Definition: elog.h:232
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1141
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
Index parent_relid
Definition: pathnodes.h:2295

◆ examine_variable()

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

Definition at line 4954 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(), StatisticExtInfo::exprs, 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, StatisticExtInfo::kind, 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, ReleaseDummy(), ReleaseSysCache(), RelOptInfo::relid, RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), RangeTblEntry::securityQuals, statext_expressions_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, 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().

4956 {
4957  Node *basenode;
4958  Relids varnos;
4959  RelOptInfo *onerel;
4960 
4961  /* Make sure we don't return dangling pointers in vardata */
4962  MemSet(vardata, 0, sizeof(VariableStatData));
4963 
4964  /* Save the exposed type of the expression */
4965  vardata->vartype = exprType(node);
4966 
4967  /* Look inside any binary-compatible relabeling */
4968 
4969  if (IsA(node, RelabelType))
4970  basenode = (Node *) ((RelabelType *) node)->arg;
4971  else
4972  basenode = node;
4973 
4974  /* Fast path for a simple Var */
4975 
4976  if (IsA(basenode, Var) &&
4977  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4978  {
4979  Var *var = (Var *) basenode;
4980 
4981  /* Set up result fields other than the stats tuple */
4982  vardata->var = basenode; /* return Var without relabeling */
4983  vardata->rel = find_base_rel(root, var->varno);
4984  vardata->atttype = var->vartype;
4985  vardata->atttypmod = var->vartypmod;
4986  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4987 
4988  /* Try to locate some stats */
4989  examine_simple_variable(root, var, vardata);
4990 
4991  return;
4992  }
4993 
4994  /*
4995  * Okay, it's a more complicated expression. Determine variable
4996  * membership. Note that when varRelid isn't zero, only vars of that
4997  * relation are considered "real" vars.
4998  */
4999  varnos = pull_varnos(root, basenode);
5000 
5001  onerel = NULL;
5002 
5003  switch (bms_membership(varnos))
5004  {
5005  case BMS_EMPTY_SET:
5006  /* No Vars at all ... must be pseudo-constant clause */
5007  break;
5008  case BMS_SINGLETON:
5009  if (varRelid == 0 || bms_is_member(varRelid, varnos))
5010  {
5011  onerel = find_base_rel(root,
5012  (varRelid ? varRelid : bms_singleton_member(varnos)));
5013  vardata->rel = onerel;
5014  node = basenode; /* strip any relabeling */
5015  }
5016  /* else treat it as a constant */
5017  break;
5018  case BMS_MULTIPLE:
5019  if (varRelid == 0)
5020  {
5021  /* treat it as a variable of a join relation */
5022  vardata->rel = find_join_rel(root, varnos);
5023  node = basenode; /* strip any relabeling */
5024  }
5025  else if (bms_is_member(varRelid, varnos))
5026  {
5027  /* ignore the vars belonging to other relations */
5028  vardata->rel = find_base_rel(root, varRelid);
5029  node = basenode; /* strip any relabeling */
5030  /* note: no point in expressional-index search here */
5031  }
5032  /* else treat it as a constant */
5033  break;
5034  }
5035 
5036  bms_free(varnos);
5037 
5038  vardata->var = node;
5039  vardata->atttype = exprType(node);
5040  vardata->atttypmod = exprTypmod(node);
5041 
5042  if (onerel)
5043  {
5044  /*
5045  * We have an expression in vars of a single relation. Try to match
5046  * it to expressional index columns, in hopes of finding some
5047  * statistics.
5048  *
5049  * Note that we consider all index columns including INCLUDE columns,
5050  * since there could be stats for such columns. But the test for
5051  * uniqueness needs to be warier.
5052  *
5053  * XXX it's conceivable that there are multiple matches with different
5054  * index opfamilies; if so, we need to pick one that matches the
5055  * operator we are estimating for. FIXME later.
5056  */
5057  ListCell *ilist;
5058  ListCell *slist;
5059 
5060  foreach(ilist, onerel->indexlist)
5061  {
5062  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5063  ListCell *indexpr_item;
5064  int pos;
5065 
5066  indexpr_item = list_head(index->indexprs);
5067  if (indexpr_item == NULL)
5068  continue; /* no expressions here... */
5069 
5070  for (pos = 0; pos < index->ncolumns; pos++)
5071  {
5072  if (index->indexkeys[pos] == 0)
5073  {
5074  Node *indexkey;
5075 
5076  if (indexpr_item == NULL)
5077  elog(ERROR, "too few entries in indexprs list");
5078  indexkey = (Node *) lfirst(indexpr_item);
5079  if (indexkey && IsA(indexkey, RelabelType))
5080  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5081  if (equal(node, indexkey))
5082  {
5083  /*
5084  * Found a match ... is it a unique index? Tests here
5085  * should match has_unique_index().
5086  */
5087  if (index->unique &&
5088  index->nkeycolumns == 1 &&
5089  pos == 0 &&
5090  (index->indpred == NIL || index->predOK))
5091  vardata->isunique = true;
5092 
5093  /*
5094  * Has it got stats? We only consider stats for
5095  * non-partial indexes, since partial indexes probably
5096  * don't reflect whole-relation statistics; the above
5097  * check for uniqueness is the only info we take from
5098  * a partial index.
5099  *
5100  * An index stats hook, however, must make its own
5101  * decisions about what to do with partial indexes.
5102  */
5103  if (get_index_stats_hook &&
5104  (*get_index_stats_hook) (root, index->indexoid,
5105  pos + 1, vardata))
5106  {
5107  /*
5108  * The hook took control of acquiring a stats
5109  * tuple. If it did supply a tuple, it'd better
5110  * have supplied a freefunc.
5111  */
5112  if (HeapTupleIsValid(vardata->statsTuple) &&
5113  !vardata->freefunc)
5114  elog(ERROR, "no function provided to release variable stats with");
5115  }
5116  else if (index->indpred == NIL)
5117  {
5118  vardata->statsTuple =
5120  ObjectIdGetDatum(index->indexoid),
5121  Int16GetDatum(pos + 1),
5122  BoolGetDatum(false));
5123  vardata->freefunc = ReleaseSysCache;
5124 
5125  if (HeapTupleIsValid(vardata->statsTuple))
5126  {
5127  /* Get index's table for permission check */
5128  RangeTblEntry *rte;
5129  Oid userid;
5130 
5131  rte = planner_rt_fetch(index->rel->relid, root);
5132  Assert(rte->rtekind == RTE_RELATION);
5133 
5134  /*
5135  * Use checkAsUser if it's set, in case we're
5136  * accessing the table via a view.
5137  */
5138  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5139 
5140  /*
5141  * For simplicity, we insist on the whole
5142  * table being selectable, rather than trying
5143  * to identify which column(s) the index
5144  * depends on. Also require all rows to be
5145  * selectable --- there must be no
5146  * securityQuals from security barrier views
5147  * or RLS policies.
5148  */
5149  vardata->acl_ok =
5150  rte->securityQuals == NIL &&
5151  (pg_class_aclcheck(rte->relid, userid,
5152  ACL_SELECT) == ACLCHECK_OK);
5153 
5154  /*
5155  * If the user doesn't have permissions to
5156  * access an inheritance child relation, check
5157  * the permissions of the table actually
5158  * mentioned in the query, since most likely
5159  * the user does have that permission. Note
5160  * that whole-table select privilege on the
5161  * parent doesn't quite guarantee that the
5162  * user could read all columns of the child.
5163  * But in practice it's unlikely that any
5164  * interesting security violation could result
5165  * from allowing access to the expression
5166  * index's stats, so we allow it anyway. See
5167  * similar code in examine_simple_variable()
5168  * for additional comments.
5169  */
5170  if (!vardata->acl_ok &&
5171  root->append_rel_array != NULL)
5172  {
5173  AppendRelInfo *appinfo;
5174  Index varno = index->rel->relid;
5175 
5176  appinfo = root->append_rel_array[varno];
5177  while (appinfo &&
5178  planner_rt_fetch(appinfo->parent_relid,
5179  root)->rtekind == RTE_RELATION)
5180  {
5181  varno = appinfo->parent_relid;
5182  appinfo = root->append_rel_array[varno];
5183  }
5184  if (varno != index->rel->relid)
5185  {
5186  /* Repeat access check on this rel */
5187  rte = planner_rt_fetch(varno, root);
5188  Assert(rte->rtekind == RTE_RELATION);
5189 
5190  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5191 
5192  vardata->acl_ok =
5193  rte->securityQuals == NIL &&
5194  (pg_class_aclcheck(rte->relid,
5195  userid,
5196  ACL_SELECT) == ACLCHECK_OK);
5197  }
5198  }
5199  }
5200  else
5201  {
5202  /* suppress leakproofness checks later */
5203  vardata->acl_ok = true;
5204  }
5205  }
5206  if (vardata->statsTuple)
5207  break;
5208  }
5209  indexpr_item = lnext(index->indexprs, indexpr_item);
5210  }
5211  }
5212  if (vardata->statsTuple)
5213  break;
5214  }
5215 
5216  /*
5217  * Search extended statistics for one with a matching expression.
5218  * There might be multiple ones, so just grab the first one. In the
5219  * future, we might consider the statistics target (and pick the most
5220  * accurate statistics) and maybe some other parameters.
5221  */
5222  foreach(slist, onerel->statlist)
5223  {
5224  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5225  ListCell *expr_item;
5226  int pos;
5227 
5228  /*
5229  * Stop once we've found statistics for the expression (either
5230  * from extended stats, or for an index in the preceding loop).
5231  */
5232  if (vardata->statsTuple)
5233  break;
5234 
5235  /* skip stats without per-expression stats */
5236  if (info->kind != STATS_EXT_EXPRESSIONS)
5237  continue;
5238 
5239  pos = 0;
5240  foreach(expr_item, info->exprs)
5241  {
5242  Node *expr = (Node *) lfirst(expr_item);
5243 
5244  Assert(expr);
5245 
5246  /* strip RelabelType before comparing it */
5247  if (expr && IsA(expr, RelabelType))
5248  expr = (Node *) ((RelabelType *) expr)->arg;
5249 
5250  /* found a match, see if we can extract pg_statistic row */
5251  if (equal(node, expr))
5252  {
5253  HeapTuple t = statext_expressions_load(info->statOid, pos);
5254 
5255  /* Get index's table for permission check */
5256  RangeTblEntry *rte;
5257  Oid userid;
5258 
5259  vardata->statsTuple = t;
5260 
5261  /*
5262  * XXX Not sure if we should cache the tuple somewhere.
5263  * Now we just create a new copy every time.
5264  */
5265  vardata->freefunc = ReleaseDummy;
5266 
5267  rte = planner_rt_fetch(onerel->relid, root);
5268  Assert(rte->rtekind == RTE_RELATION);
5269 
5270  /*
5271  * Use checkAsUser if it's set, in case we're accessing
5272  * the table via a view.
5273  */
5274  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5275 
5276  /*
5277  * For simplicity, we insist on the whole table being
5278  * selectable, rather than trying to identify which
5279  * column(s) the statistics depends on. Also require all
5280  * rows to be selectable --- there must be no
5281  * securityQuals from security barrier views or RLS
5282  * policies.
5283  */
5284  vardata->acl_ok =
5285  rte->securityQuals == NIL &&
5286  (pg_class_aclcheck(rte->relid, userid,
5287  ACL_SELECT) == ACLCHECK_OK);
5288 
5289  /*
5290  * If the user doesn't have permissions to access an
5291  * inheritance child relation, check the permissions of
5292  * the table actually mentioned in the query, since most
5293  * likely the user does have that permission. Note that
5294  * whole-table select privilege on the parent doesn't
5295  * quite guarantee that the user could read all columns of
5296  * the child. But in practice it's unlikely that any
5297  * interesting security violation could result from
5298  * allowing access to the expression stats, so we allow it
5299  * anyway. See similar code in examine_simple_variable()
5300  * for additional comments.
5301  */
5302  if (!vardata->acl_ok &&
5303  root->append_rel_array != NULL)
5304  {
5305  AppendRelInfo *appinfo;
5306  Index varno = onerel->relid;
5307 
5308  appinfo = root->append_rel_array[varno];
5309  while (appinfo &&
5310  planner_rt_fetch(appinfo->parent_relid,
5311  root)->rtekind == RTE_RELATION)
5312  {
5313  varno = appinfo->parent_relid;
5314  appinfo = root->append_rel_array[varno];
5315  }
5316  if (varno != onerel->relid)
5317  {
5318  /* Repeat access check on this rel */
5319  rte = planner_rt_fetch(varno, root);
5320  Assert(rte->rtekind == RTE_RELATION);
5321 
5322  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
5323 
5324  vardata->acl_ok =
5325  rte->securityQuals == NIL &&
5326  (pg_class_aclcheck(rte->relid,
5327  userid,
5328  ACL_SELECT) == ACLCHECK_OK);
5329  }
5330  }
5331 
5332  break;
5333  }
5334 
5335  pos++;
5336  }
5337  }
5338  }
5339 }
#define NIL
Definition: pg_list.h:65
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * statlist
Definition: pathnodes.h:714
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:438
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3122
HeapTuple statsTuple
Definition: selfuncs.h:91
Oid GetUserId(void)
Definition: miscinit.c:478
HeapTuple statext_expressions_load(Oid stxoid, int idx)
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
List * securityQuals
Definition: parsenodes.h:1151
RelOptInfo * rel
Definition: selfuncs.h:90
#define Int16GetDatum(X)
Definition: postgres.h:495
Definition: nodes.h:539
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:93
#define MemSet(start, val, len)
Definition: c.h:1008
AttrNumber varattno
Definition: primnodes.h:191
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5351
int32 atttypmod
Definition: selfuncs.h:96
Definition: type.h:89
RelOptInfo * rel
Definition: pathnodes.h:832
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2086
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Oid vartype
Definition: primnodes.h:193
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
Index relid
Definition: pathnodes.h:704
Index varno
Definition: primnodes.h:189
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ACL_SELECT
Definition: parsenodes.h:83
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:201
unsigned int Index
Definition: c.h:549
List * indexlist
Definition: pathnodes.h:713
#define BoolGetDatum(X)
Definition: postgres.h:446
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int nkeycolumns
Definition: pathnodes.h:841
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:4680
RTEKind rtekind
Definition: parsenodes.h:995
#define elog(elevel,...)
Definition: elog.h:232
void * arg
int * indexkeys
Definition: pathnodes.h:842
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
Index parent_relid
Definition: pathnodes.h:2295
List * indpred
Definition: pathnodes.h:856
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
static void ReleaseDummy(HeapTuple tuple)
Definition: selfuncs.c:4913
List * indexprs
Definition: pathnodes.h:855
int32 vartypmod
Definition: primnodes.h:194

◆ find_join_input_rel()

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

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

6234 {
6235  RelOptInfo *rel = NULL;
6236 
6237  switch (bms_membership(relids))
6238  {
6239  case BMS_EMPTY_SET:
6240  /* should not happen */
6241  break;
6242  case BMS_SINGLETON:
6243  rel = find_base_rel(root, bms_singleton_member(relids));
6244  break;
6245  case BMS_MULTIPLE:
6246  rel = find_join_rel(root, relids);
6247  break;
6248  }
6249 
6250  if (rel == NULL)
6251  elog(ERROR, "could not find RelOptInfo for given relids");
6252 
6253  return rel;
6254 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:438
#define ERROR
Definition: elog.h:46
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:232
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:590
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
HeapTuple statsTuple
Definition: selfuncs.h:91
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4825
Definition: nodes.h:539
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:135
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
uintptr_t Datum
Definition: postgres.h:411
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:1256
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:101

◆ genericcostestimate()

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

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

6356 {
6357  IndexOptInfo *index = path->indexinfo;
6358  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6359  List *indexOrderBys = path->indexorderbys;
6360  Cost indexStartupCost;
6361  Cost indexTotalCost;
6362  Selectivity indexSelectivity;
6363  double indexCorrelation;
6364  double numIndexPages;
6365  double numIndexTuples;
6366  double spc_random_page_cost;
6367  double num_sa_scans;
6368  double num_outer_scans;
6369  double num_scans;
6370  double qual_op_cost;
6371  double qual_arg_cost;
6372  List *selectivityQuals;
6373  ListCell *l;
6374 
6375  /*
6376  * If the index is partial, AND the index predicate with the explicitly
6377  * given indexquals to produce a more accurate idea of the index
6378  * selectivity.
6379  */
6380  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6381 
6382  /*
6383  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6384  * index scans that will be performed.
6385  */
6386  num_sa_scans = 1;
6387  foreach(l, indexQuals)
6388  {
6389  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6390 
6391  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6392  {
6393  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6394  int alength = estimate_array_length(lsecond(saop->args));
6395 
6396  if (alength > 1)
6397  num_sa_scans *= alength;
6398  }
6399  }
6400 
6401  /* Estimate the fraction of main-table tuples that will be visited */
6402  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6403  index->rel->relid,
6404  JOIN_INNER,
6405  NULL);
6406 
6407  /*
6408  * If caller didn't give us an estimate, estimate the number of index
6409  * tuples that will be visited. We do it in this rather peculiar-looking
6410  * way in order to get the right answer for partial indexes.
6411  */
6412  numIndexTuples = costs->numIndexTuples;
6413  if (numIndexTuples <= 0.0)
6414  {
6415  numIndexTuples = indexSelectivity * index->rel->tuples;
6416 
6417  /*
6418  * The above calculation counts all the tuples visited across all
6419  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6420  * average per-indexscan number, so adjust. This is a handy place to
6421  * round to integer, too. (If caller supplied tuple estimate, it's
6422  * responsible for handling these considerations.)
6423  */
6424  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6425  }
6426 
6427  /*
6428  * We can bound the number of tuples by the index size in any case. Also,
6429  * always estimate at least one tuple is touched, even when
6430  * indexSelectivity estimate is tiny.
6431  */
6432  if (numIndexTuples > index->tuples)
6433  numIndexTuples = index->tuples;
6434  if (numIndexTuples < 1.0)
6435  numIndexTuples = 1.0;
6436 
6437  /*
6438  * Estimate the number of index pages that will be retrieved.
6439  *
6440  * We use the simplistic method of taking a pro-rata fraction of the total
6441  * number of index pages. In effect, this counts only leaf pages and not
6442  * any overhead such as index metapage or upper tree levels.
6443  *
6444  * In practice access to upper index levels is often nearly free because
6445  * those tend to stay in cache under load; moreover, the cost involved is
6446  * highly dependent on index type. We therefore ignore such costs here
6447  * and leave it to the caller to add a suitable charge if needed.
6448  */
6449  if (index->pages > 1 && index->tuples > 1)
6450  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6451  else
6452  numIndexPages = 1.0;
6453 
6454  /* fetch estimated page cost for tablespace containing index */
6456  &spc_random_page_cost,
6457  NULL);
6458 
6459  /*
6460  * Now compute the disk access costs.
6461  *
6462  * The above calculations are all per-index-scan. However, if we are in a
6463  * nestloop inner scan, we can expect the scan to be repeated (with
6464  * different search keys) for each row of the outer relation. Likewise,
6465  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6466  * the potential for cache effects to reduce the number of disk page
6467  * fetches needed. We want to estimate the average per-scan I/O cost in
6468  * the presence of caching.
6469  *
6470  * We use the Mackert-Lohman formula (see costsize.c for details) to
6471  * estimate the total number of page fetches that occur. While this
6472  * wasn't what it was designed for, it seems a reasonable model anyway.
6473  * Note that we are counting pages not tuples anymore, so we take N = T =
6474  * index size, as if there were one "tuple" per page.
6475  */
6476  num_outer_scans = loop_count;
6477  num_scans = num_sa_scans * num_outer_scans;
6478 
6479  if (num_scans > 1)
6480  {
6481  double pages_fetched;
6482 
6483  /* total page fetches ignoring cache effects */
6484  pages_fetched = numIndexPages * num_scans;
6485 
6486  /* use Mackert and Lohman formula to adjust for cache effects */
6487  pages_fetched = index_pages_fetched(pages_fetched,
6488  index->pages,
6489  (double) index->pages,
6490  root);
6491 
6492  /*
6493  * Now compute the total disk access cost, and then report a pro-rated
6494  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6495  * since that's internal to the indexscan.)
6496  */
6497  indexTotalCost = (pages_fetched * spc_random_page_cost)
6498  / num_outer_scans;
6499  }
6500  else
6501  {
6502  /*
6503  * For a single index scan, we just charge spc_random_page_cost per
6504  * page touched.
6505  */
6506  indexTotalCost = numIndexPages * spc_random_page_cost;
6507  }
6508 
6509  /*
6510  * CPU cost: any complex expressions in the indexquals will need to be
6511  * evaluated once at the start of the scan to reduce them to runtime keys
6512  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6513  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6514  * indexqual operator. Because we have numIndexTuples as a per-scan
6515  * number, we have to multiply by num_sa_scans to get the correct result
6516  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6517  * ORDER BY expressions.
6518  *
6519  * Note: this neglects the possible costs of rechecking lossy operators.
6520  * Detecting that that might be needed seems more expensive than it's
6521  * worth, though, considering all the other inaccuracies here ...
6522  */
6523  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
6524  index_other_operands_eval_cost(root, indexOrderBys);
6525  qual_op_cost = cpu_operator_cost *
6526  (list_length(indexQuals) + list_length(indexOrderBys));
6527 
6528  indexStartupCost = qual_arg_cost;
6529  indexTotalCost += qual_arg_cost;
6530  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6531 
6532  /*
6533  * Generic assumption about index correlation: there isn't any.
6534  */
6535  indexCorrelation = 0.0;
6536 
6537  /*
6538  * Return everything to caller.
6539  */
6540  costs->indexStartupCost = indexStartupCost;
6541  costs->indexTotalCost = indexTotalCost;
6542  costs->indexSelectivity = indexSelectivity;
6543  costs->indexCorrelation = indexCorrelation;
6544  costs->numIndexPages = numIndexPages;
6545  costs->numIndexTuples = numIndexTuples;
6546  costs->spc_random_page_cost = spc_random_page_cost;
6547  costs->num_sa_scans = num_sa_scans;
6548 }
Selectivity indexSelectivity
Definition: selfuncs.h:126
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
double tuples
Definition: pathnodes.h:716
Oid reltablespace
Definition: pathnodes.h:831
List * indexclauses
Definition: pathnodes.h:1238
double Selectivity
Definition: nodes.h:672
double tuples
Definition: pathnodes.h:836
#define lsecond(l)
Definition: pg_list.h:179
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:835
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2132
RelOptInfo * rel
Definition: pathnodes.h:832
double num_sa_scans
Definition: selfuncs.h:133
double cpu_operator_cost
Definition: costsize.c:123
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:6268
Cost indexTotalCost
Definition: selfuncs.h:125
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:704
Expr * clause
Definition: pathnodes.h:2045
double indexCorrelation
Definition: selfuncs.h:127
List * indexorderbys
Definition: pathnodes.h:1239
double spc_random_page_cost
Definition: selfuncs.h:132
double numIndexTuples
Definition: selfuncs.h:131
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6298
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
Cost indexStartupCost
Definition: selfuncs.h:124
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
Definition: pg_list.h:50
double cpu_index_tuple_cost
Definition: costsize.c:122
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:840
double Cost
Definition: nodes.h:673
double numIndexPages
Definition: selfuncs.h:130
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6570

◆ 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 6104 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().

6113 {
6114  bool have_data = false;
6115  SnapshotData SnapshotNonVacuumable;
6116  IndexScanDesc index_scan;
6117  Buffer vmbuffer = InvalidBuffer;
6118  ItemPointer tid;
6120  bool isnull[INDEX_MAX_KEYS];
6121  MemoryContext oldcontext;
6122 
6123  /*
6124  * We use the index-only-scan machinery for this. With mostly-static
6125  * tables that's a win because it avoids a heap visit. It's also a win
6126  * for dynamic data, but the reason is less obvious; read on for details.
6127  *
6128  * In principle, we should scan the index with our current active
6129  * snapshot, which is the best approximation we've got to what the query
6130  * will see when executed. But that won't be exact if a new snap is taken
6131  * before running the query, and it can be very expensive if a lot of
6132  * recently-dead or uncommitted rows exist at the beginning or end of the
6133  * index (because we'll laboriously fetch each one and reject it).
6134  * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
6135  * and uncommitted rows as well as normal visible rows. On the other
6136  * hand, it will reject known-dead rows, and thus not give a bogus answer
6137  * when the extreme value has been deleted (unless the deletion was quite
6138  * recent); that case motivates not using SnapshotAny here.
6139  *
6140  * A crucial point here is that SnapshotNonVacuumable, with
6141  * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
6142  * condition that the indexscan will use to decide that index entries are
6143  * killable (see heap_hot_search_buffer()). Therefore, if the snapshot
6144  * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
6145  * have to continue scanning past it, we know that the indexscan will mark
6146  * that index entry killed. That means that the next
6147  * get_actual_variable_endpoint() call will not have to re-consider that
6148  * index entry. In this way we avoid repetitive work when this function
6149  * is used a lot during planning.
6150  *
6151  * But using SnapshotNonVacuumable creates a hazard of its own. In a
6152  * recently-created index, some index entries may point at "broken" HOT
6153  * chains in which not all the tuple versions contain data matching the
6154  * index entry. The live tuple version(s) certainly do match the index,
6155  * but SnapshotNonVacuumable can accept recently-dead tuple versions that
6156  * don't match. Hence, if we took data from the selected heap tuple, we
6157  * might get a bogus answer that's not close to the index extremal value,
6158  * or could even be NULL. We avoid this hazard because we take the data
6159  * from the index entry not the heap.
6160  */
6161  InitNonVacuumableSnapshot(SnapshotNonVacuumable,
6162  GlobalVisTestFor(heapRel));
6163 
6164  index_scan = index_beginscan(heapRel, indexRel,
6165  &SnapshotNonVacuumable,
6166  1, 0);
6167  /* Set it up for index-only scan */
6168  index_scan->xs_want_itup = true;
6169  index_rescan(index_scan, scankeys, 1, NULL, 0);
6170 
6171  /* Fetch first/next tuple in specified direction */
6172  while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
6173  {
6174  if (!VM_ALL_VISIBLE(heapRel,
6176  &vmbuffer))
6177  {
6178  /* Rats, we have to visit the heap to check visibility */
6179  if (!index_fetch_heap(index_scan, tableslot))
6180  continue; /* no visible tuple, try next index entry */
6181 
6182  /* We don't actually need the heap tuple for anything */
6183  ExecClearTuple(tableslot);
6184 
6185  /*
6186  * We don't care whether there's more than one visible tuple in
6187  * the HOT chain; if any are visible, that's good enough.
6188  */
6189  }
6190 
6191  /*
6192  * We expect that btree will return data in IndexTuple not HeapTuple
6193  * format. It's not lossy either.
6194  */
6195  if (!index_scan->xs_itup)
6196  elog(ERROR, "no data returned for index-only scan");
6197  if (index_scan->xs_recheck)
6198  elog(ERROR, "unexpected recheck indication from btree");
6199 
6200  /* OK to deconstruct the index tuple */
6201  index_deform_tuple(index_scan->xs_itup,
6202  index_scan->xs_itupdesc,
6203  values, isnull);
6204 
6205  /* Shouldn't have got a null, but be careful */
6206  if (isnull[0])
6207  elog(ERROR, "found unexpected null value in index \"%s\"",
6208  RelationGetRelationName(indexRel));
6209 
6210  /* Copy the index column value out to caller's context */
6211  oldcontext = MemoryContextSwitchTo(outercontext);
6212  *endpointDatum = datumCopy(values[0], typByVal, typLen);
6213  MemoryContextSwitchTo(oldcontext);
6214  have_data = true;
6215  break;
6216  }
6217 
6218  if (vmbuffer != InvalidBuffer)
6219  ReleaseBuffer(vmbuffer);
6220  index_endscan(index_scan);
6221 
6222  return have_data;
6223 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
IndexTuple xs_itup
Definition: relscan.h:142
struct TupleDescData * xs_itupdesc
Definition: relscan.h:143
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:297
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:82
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3772
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition: procarray.c:4029
ItemPointer index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:517
#define ERROR
Definition: elog.h:46
#define RelationGetRelationName(relation)
Definition: rel.h:511
void index_deform_tuple(IndexTuple tup, TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:437
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:323
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
uintptr_t Datum
Definition: postgres.h:411
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:32
#define INDEX_MAX_KEYS
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define elog(elevel,...)
Definition: elog.h:232
bool index_fetch_heap(IndexScanDesc scan, TupleTableSlot *slot)
Definition: indexam.c:575
#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:205

◆ get_actual_variable_range()

static bool get_actual_variable_range ( PlannerInfo root,
VariableStatData vardata,
Oid  sortop,