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

Go to the source code of this file.

Data Structures

struct  GroupVarInfo
 
struct  GinQualCounts
 

Functions

static double eqsel_internal (PG_FUNCTION_ARGS, bool negate)
 
static double eqjoinsel_inner (Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2)
 
static double eqjoinsel_semi (Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2, RelOptInfo *inner_rel)
 
static bool estimate_multivariate_ndistinct (PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
 
static bool convert_to_scalar (Datum value, Oid valuetypid, Oid collid, double *scaledvalue, Datum lobound, Datum hibound, Oid boundstypid, double *scaledlobound, double *scaledhibound)
 
static double convert_numeric_to_scalar (Datum value, Oid typid, bool *failure)
 
static void convert_string_to_scalar (char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
 
static void convert_bytea_to_scalar (Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
 
static double convert_one_string_to_scalar (char *value, int rangelo, int rangehi)
 
static double convert_one_bytea_to_scalar (unsigned char *value, int valuelen, int rangelo, int rangehi)
 
static char * convert_string_datum (Datum value, Oid typid, Oid collid, bool *failure)
 
static double convert_timevalue_to_scalar (Datum value, Oid typid, bool *failure)
 
static void examine_simple_variable (PlannerInfo *root, Var *var, VariableStatData *vardata)
 
static bool get_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
 
static void get_stats_slot_range (AttStatsSlot *sslot, Oid opfuncoid, FmgrInfo *opproc, Oid collation, int16 typLen, bool typByVal, Datum *min, Datum *max, bool *p_have_data)
 
static bool get_actual_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Oid collation, Datum *min, Datum *max)
 
static bool get_actual_variable_endpoint (Relation heapRel, Relation indexRel, ScanDirection indexscandir, ScanKey scankeys, int16 typLen, bool typByVal, TupleTableSlot *tableslot, MemoryContext outercontext, Datum *endpointDatum)
 
static RelOptInfofind_join_input_rel (PlannerInfo *root, Relids relids)
 
Datum eqsel (PG_FUNCTION_ARGS)
 
double var_eq_const (VariableStatData *vardata, Oid operator, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
 
double var_eq_non_const (VariableStatData *vardata, Oid operator, Oid collation, Node *other, bool varonleft, bool negate)
 
Datum neqsel (PG_FUNCTION_ARGS)
 
static double scalarineqsel (PlannerInfo *root, Oid operator, bool isgt, bool iseq, Oid collation, VariableStatData *vardata, Datum constval, Oid consttype)
 
double mcv_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
 
double histogram_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
 
double generic_restriction_selectivity (PlannerInfo *root, Oid oproid, Oid collation, List *args, int varRelid, double default_selectivity)
 
double ineq_histogram_selectivity (PlannerInfo *root, VariableStatData *vardata, Oid opoid, FmgrInfo *opproc, bool isgt, bool iseq, Oid collation, Datum constval, Oid consttype)
 
static Datum scalarineqsel_wrapper (PG_FUNCTION_ARGS, bool isgt, bool iseq)
 
Datum scalarltsel (PG_FUNCTION_ARGS)
 
Datum scalarlesel (PG_FUNCTION_ARGS)
 
Datum scalargtsel (PG_FUNCTION_ARGS)
 
Datum scalargesel (PG_FUNCTION_ARGS)
 
Selectivity boolvarsel (PlannerInfo *root, Node *arg, int varRelid)
 
Selectivity booltestsel (PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity nulltestsel (PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
static Nodestrip_array_coercion (Node *node)
 
Selectivity scalararraysel (PlannerInfo *root, ScalarArrayOpExpr *clause, bool is_join_clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
int estimate_array_length (Node *arrayexpr)
 
Selectivity rowcomparesel (PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Datum eqjoinsel (PG_FUNCTION_ARGS)
 
Datum neqjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarltjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarlejoinsel (PG_FUNCTION_ARGS)
 
Datum scalargtjoinsel (PG_FUNCTION_ARGS)
 
Datum scalargejoinsel (PG_FUNCTION_ARGS)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
Datum matchingsel (PG_FUNCTION_ARGS)
 
Datum matchingjoinsel (PG_FUNCTION_ARGS)
 
static Listadd_unique_group_var (PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
double estimate_hashagg_tablesize (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)
 
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 6220 of file selfuncs.c.

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

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

6221 {
6222  List *predExtraQuals = NIL;
6223  ListCell *lc;
6224 
6225  if (index->indpred == NIL)
6226  return indexQuals;
6227 
6228  foreach(lc, index->indpred)
6229  {
6230  Node *predQual = (Node *) lfirst(lc);
6231  List *oneQual = list_make1(predQual);
6232 
6233  if (!predicate_implied_by(oneQual, indexQuals, false))
6234  predExtraQuals = list_concat(predExtraQuals, oneQual);
6235  }
6236  return list_concat(predExtraQuals, indexQuals);
6237 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:527
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
#define list_make1(x1)
Definition: pg_list.h:206
#define lfirst(lc)
Definition: pg_list.h:169
List * indpred
Definition: pathnodes.h:844
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50

◆ add_unique_group_var()

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

Definition at line 3247 of file selfuncs.c.

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

Referenced by estimate_num_groups().

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

◆ booltestsel()

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

Definition at line 1537 of file selfuncs.c.

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

Referenced by clause_selectivity().

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

◆ boolvarsel()

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

Definition at line 1509 of file selfuncs.c.

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

Referenced by clause_selectivity().

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

◆ brincostestimate()

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

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

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

◆ btcostestimate()

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

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

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

◆ convert_bytea_to_scalar()

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

Definition at line 4454 of file selfuncs.c.

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

Referenced by convert_to_scalar().

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

◆ convert_numeric_to_scalar()

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

Definition at line 4181 of file selfuncs.c.

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

Referenced by convert_to_scalar().

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

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

Referenced by convert_bytea_to_scalar().

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

Referenced by convert_string_to_scalar().

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

◆ convert_string_datum()

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

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

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

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

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

◆ convert_timevalue_to_scalar()

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

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

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

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

◆ 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:1426
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Relids min_righthand
Definition: pathnodes.h:2182
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:74
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5249
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define Min(x, y)
Definition: c.h:982
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define OidIsValid(objectId)
Definition: c.h:706
#define PG_GET_COLLATION()
Definition: fmgr.h:198
JoinType
Definition: nodes.h:694
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
static double eqjoinsel_inner(Oid opfuncoid, Oid collation, VariableStatData *vardata1, VariableStatData *vardata2, double nd1, double nd2, bool isdefault1, bool isdefault2, AttStatsSlot *sslot1, AttStatsSlot *sslot2, Form_pg_statistic stats1, Form_pg_statistic stats2, bool have_mcvs1, bool have_mcvs2)
Definition: selfuncs.c:2386
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:553
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4667
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5278
#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:5883
double rows
Definition: pathnodes.h:669
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:3057
JoinType jointype
Definition: pathnodes.h:2185
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
#define elog(elevel,...)
Definition: elog.h:228
Definition: pg_list.h:50
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3174

◆ eqjoinsel_inner()

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

Definition at line 2386 of file selfuncs.c.

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

Referenced by eqjoinsel().

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

◆ eqjoinsel_semi()

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

Definition at line 2583 of file selfuncs.c.

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

Referenced by eqjoinsel().

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

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 224 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

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

◆ 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:578
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4607
Definition: nodes.h:527
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:706
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define DEFAULT_EQ_SEL
Definition: selfuncs.h:34
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84
double var_eq_const(VariableStatData *vardata, Oid operator, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:292
double var_eq_non_const(VariableStatData *vardata, Oid operator, Oid collation, Node *other, bool varonleft, bool negate)
Definition: selfuncs.c:463
Oid get_negator(Oid opno)
Definition: lsyscache.c:1450
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:578
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:282
uintptr_t Datum
Definition: postgres.h:367
static int list_length(const List *l)
Definition: pg_list.h:149
#define ARR_NDIM(a)
Definition: array.h:278
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1780
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ estimate_hash_bucket_stats()

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

Definition at line 3723 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

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

◆ estimate_hashagg_tablesize()

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

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

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

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

Referenced by estimate_num_groups().

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

◆ estimate_num_groups()

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

Definition at line 3360 of file selfuncs.c.

References add_unique_group_var(), Assert, clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), expression_returns_set_rows(), exprType(), for_each_from, HeapTupleIsValid, i, IS_SIMPLE_REL, 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, VariableStatData::statsTuple, and RelOptInfo::tuples.

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

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

◆ examine_simple_variable()

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

Definition at line 5002 of file selfuncs.c.

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

Referenced by examine_variable().

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

◆ examine_variable()

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

Definition at line 4729 of file selfuncs.c.

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

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

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

◆ find_join_input_rel()

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

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

5884 {
5885  RelOptInfo *rel = NULL;
5886 
5887  switch (bms_membership(relids))
5888  {
5889  case BMS_EMPTY_SET:
5890  /* should not happen */
5891  break;
5892  case BMS_SINGLETON:
5893  rel = find_base_rel(root, bms_singleton_member(relids));
5894  break;
5895  case BMS_MULTIPLE:
5896  rel = find_join_rel(root, relids);
5897  break;
5898  }
5899 
5900  if (rel == NULL)
5901  elog(ERROR, "could not find RelOptInfo for given relids");
5902 
5903  return rel;
5904 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:438
#define ERROR
Definition: elog.h:43
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
#define elog(elevel,...)
Definition: elog.h:228
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:373

◆ 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:578
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
HeapTuple statsTuple
Definition: selfuncs.h:74
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4607
Definition: nodes.h:527
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:60
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
uintptr_t Datum
Definition: postgres.h:367
double mcv_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, double *sumcommonp)
Definition: selfuncs.c:729
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1202
double histogram_selectivity(VariableStatData *vardata, FmgrInfo *opproc, Oid collation, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
Definition: selfuncs.c:820
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:84

◆ genericcostestimate()

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

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

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

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

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

◆ get_actual_variable_range()

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

Definition at line 5581 of file selfuncs.c.

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

Referenced by get_variable_range(), and ineq_histogram_selectivity().

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

◆ get_join_variables()

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

Definition at line 4667 of file selfuncs.c.

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

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

4670 {
4671  Node *left,
4672  *right;
4673 
4674  if (list_length(args) != 2)
4675  elog(ERROR, "join operator should take two arguments");
4676 
4677  left = (Node *) linitial(args);
4678  right = (Node *) lsecond(args);
4679 
4680  examine_variable(root, left, 0, vardata1);
4681  examine_variable(root, right, 0, vardata2);
4682 
4683  if (vardata1->rel &&
4684  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4685  *join_is_reversed = true; /* var1 is on RHS */
4686  else if (vardata2->rel &&
4687  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4688  *join_is_reversed = true; /* var2 is on LHS */
4689  else
4690  *join_is_reversed = false;
4691 }
RelOptInfo * rel
Definition: selfuncs.h:73
Definition: nodes.h:527
#define lsecond(l)
Definition: pg_list.h:179
Relids syn_lefthand
Definition: pathnodes.h:2183
Relids syn_righthand
Definition: pathnodes.h:2184
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Relids relids
Definition: pathnodes.h:666
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4729
static int list_length(const List *l)
Definition: pg_list.h:149
#define elog(elevel,...)
Definition: elog.h:228

◆ get_quals_from_indexclauses()

List* get_quals_from_indexclauses ( List indexclauses)

Definition at line 5918 of file selfuncs.c.

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

Referenced by brincost