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/parse_relation.h"
#include "parser/parsetree.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "utils/acl.h"
#include "utils/array.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
 

Macros

#define DEFAULT_PAGE_CPU_MULTIPLIER   50.0
 
#define VISITED_PAGES_LIMIT   100
 

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 oproid, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
 
double var_eq_non_const (VariableStatData *vardata, Oid oproid, 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)
 
double estimate_array_length (PlannerInfo *root, Node *arrayexpr)
 
Selectivity rowcomparesel (PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Datum eqjoinsel (PG_FUNCTION_ARGS)
 
Datum neqjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarltjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarlejoinsel (PG_FUNCTION_ARGS)
 
Datum scalargtjoinsel (PG_FUNCTION_ARGS)
 
Datum scalargejoinsel (PG_FUNCTION_ARGS)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
Datum matchingsel (PG_FUNCTION_ARGS)
 
Datum matchingjoinsel (PG_FUNCTION_ARGS)
 
static Listadd_unique_group_var (PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
double estimate_hashagg_tablesize (PlannerInfo *root, Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
 
bool get_restriction_variable (PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
 
void get_join_variables (PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
 
static void ReleaseDummy (HeapTuple tuple)
 
void examine_variable (PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
 
bool statistic_proc_security_check (VariableStatData *vardata, Oid func_oid)
 
double get_variable_numdistinct (VariableStatData *vardata, bool *isdefault)
 
Listget_quals_from_indexclauses (List *indexclauses)
 
Cost index_other_operands_eval_cost (PlannerInfo *root, List *indexquals)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
 
Listadd_predicate_to_index_quals (IndexOptInfo *index, List *indexQuals)
 
void btcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void hashcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void gistcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void spgcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
static bool gincost_pattern (IndexOptInfo *index, int indexcol, Oid clause_op, Datum query, GinQualCounts *counts)
 
static bool gincost_opexpr (PlannerInfo *root, IndexOptInfo *index, int indexcol, OpExpr *clause, GinQualCounts *counts)
 
static bool gincost_scalararrayopexpr (PlannerInfo *root, IndexOptInfo *index, int indexcol, ScalarArrayOpExpr *clause, double numIndexEntries, GinQualCounts *counts)
 
void gincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void brincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 

Variables

get_relation_stats_hook_type get_relation_stats_hook = NULL
 
get_index_stats_hook_type get_index_stats_hook = NULL
 

Macro Definition Documentation

◆ DEFAULT_PAGE_CPU_MULTIPLIER

#define DEFAULT_PAGE_CPU_MULTIPLIER   50.0

Definition at line 144 of file selfuncs.c.

◆ VISITED_PAGES_LIMIT

#define VISITED_PAGES_LIMIT   100

Function Documentation

◆ add_predicate_to_index_quals()

List* add_predicate_to_index_quals ( IndexOptInfo index,
List indexQuals 
)

Definition at line 6775 of file selfuncs.c.

6776 {
6777  List *predExtraQuals = NIL;
6778  ListCell *lc;
6779 
6780  if (index->indpred == NIL)
6781  return indexQuals;
6782 
6783  foreach(lc, index->indpred)
6784  {
6785  Node *predQual = (Node *) lfirst(lc);
6786  List *oneQual = list_make1(predQual);
6787 
6788  if (!predicate_implied_by(oneQual, indexQuals, false))
6789  predExtraQuals = list_concat(predExtraQuals, oneQual);
6790  }
6791  return list_concat(predExtraQuals, indexQuals);
6792 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:152
Definition: pg_list.h:54
Definition: nodes.h:129
Definition: type.h:95

References lfirst, list_concat(), list_make1, NIL, and predicate_implied_by().

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

◆ add_unique_group_var()

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

Definition at line 3296 of file selfuncs.c.

3298 {
3299  GroupVarInfo *varinfo;
3300  double ndistinct;
3301  bool isdefault;
3302  ListCell *lc;
3303 
3304  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3305 
3306  foreach(lc, varinfos)
3307  {
3308  varinfo = (GroupVarInfo *) lfirst(lc);
3309 
3310  /* Drop exact duplicates */
3311  if (equal(var, varinfo->var))
3312  return varinfos;
3313 
3314  /*
3315  * Drop known-equal vars, but only if they belong to different
3316  * relations (see comments for estimate_num_groups). We aren't too
3317  * fussy about the semantics of "equal" here.
3318  */
3319  if (vardata->rel != varinfo->rel &&
3320  exprs_known_equal(root, var, varinfo->var, InvalidOid))
3321  {
3322  if (varinfo->ndistinct <= ndistinct)
3323  {
3324  /* Keep older item, forget new one */
3325  return varinfos;
3326  }
3327  else
3328  {
3329  /* Delete the older item */
3330  varinfos = foreach_delete_current(varinfos, lc);
3331  }
3332  }
3333  }
3334 
3335  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3336 
3337  varinfo->var = var;
3338  varinfo->rel = vardata->rel;
3339  varinfo->ndistinct = ndistinct;
3340  varinfo->isdefault = isdefault;
3341  varinfos = lappend(varinfos, varinfo);
3342  return varinfos;
3343 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
Definition: equivclass.c:2464
List * lappend(List *list, void *datum)
Definition: list.c:339
void * palloc(Size size)
Definition: mcxt.c:1317
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
#define InvalidOid
Definition: postgres_ext.h:36
tree ctl root
Definition: radixtree.h:1886
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5772
RelOptInfo * rel
Definition: selfuncs.c:3290
double ndistinct
Definition: selfuncs.c:3291
bool isdefault
Definition: selfuncs.c:3292
Node * var
Definition: selfuncs.c:3289
RelOptInfo * rel
Definition: selfuncs.h:88

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

Referenced by estimate_num_groups().

◆ booltestsel()

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

Definition at line 1540 of file selfuncs.c.

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

References arg, 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, root, VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by clause_selectivity_ext().

◆ boolvarsel()

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

Definition at line 1512 of file selfuncs.c.

1513 {
1514  VariableStatData vardata;
1515  double selec;
1516 
1517  examine_variable(root, arg, varRelid, &vardata);
1518  if (HeapTupleIsValid(vardata.statsTuple))
1519  {
1520  /*
1521  * A boolean variable V is equivalent to the clause V = 't', so we
1522  * compute the selectivity as if that is what we have.
1523  */
1524  selec = var_eq_const(&vardata, BooleanEqualOperator, InvalidOid,
1525  BoolGetDatum(true), false, true, false);
1526  }
1527  else
1528  {
1529  /* Otherwise, the default estimate is 0.5 */
1530  selec = 0.5;
1531  }
1532  ReleaseVariableStats(vardata);
1533  return selec;
1534 }
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
double var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:295

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

Referenced by clause_selectivity_ext().

◆ brincostestimate()

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

Definition at line 7981 of file selfuncs.c.

7985 {
7986  IndexOptInfo *index = path->indexinfo;
7987  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
7988  double numPages = index->pages;
7989  RelOptInfo *baserel = index->rel;
7990  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7991  Cost spc_seq_page_cost;
7992  Cost spc_random_page_cost;
7993  double qual_arg_cost;
7994  double qualSelectivity;
7995  BrinStatsData statsData;
7996  double indexRanges;
7997  double minimalRanges;
7998  double estimatedRanges;
7999  double selec;
8000  Relation indexRel;
8001  ListCell *l;
8002  VariableStatData vardata;
8003 
8004  Assert(rte->rtekind == RTE_RELATION);
8005 
8006  /* fetch estimated page cost for the tablespace containing the index */
8007  get_tablespace_page_costs(index->reltablespace,
8008  &spc_random_page_cost,
8009  &spc_seq_page_cost);
8010 
8011  /*
8012  * Obtain some data from the index itself, if possible. Otherwise invent
8013  * some plausible internal statistics based on the relation page count.
8014  */
8015  if (!index->hypothetical)
8016  {
8017  /*
8018  * A lock should have already been obtained on the index in plancat.c.
8019  */
8020  indexRel = index_open(index->indexoid, NoLock);
8021  brinGetStats(indexRel, &statsData);
8022  index_close(indexRel, NoLock);
8023 
8024  /* work out the actual number of ranges in the index */
8025  indexRanges = Max(ceil((double) baserel->pages /
8026  statsData.pagesPerRange), 1.0);
8027  }
8028  else
8029  {
8030  /*
8031  * Assume default number of pages per range, and estimate the number
8032  * of ranges based on that.
8033  */
8034  indexRanges = Max(ceil((double) baserel->pages /
8036 
8038  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
8039  }
8040 
8041  /*
8042  * Compute index correlation
8043  *
8044  * Because we can use all index quals equally when scanning, we can use
8045  * the largest correlation (in absolute value) among columns used by the
8046  * query. Start at zero, the worst possible case. If we cannot find any
8047  * correlation statistics, we will keep it as 0.
8048  */
8049  *indexCorrelation = 0;
8050 
8051  foreach(l, path->indexclauses)
8052  {
8053  IndexClause *iclause = lfirst_node(IndexClause, l);
8054  AttrNumber attnum = index->indexkeys[iclause->indexcol];
8055 
8056  /* attempt to lookup stats in relation for this index column */
8057  if (attnum != 0)
8058  {
8059  /* Simple variable -- look to stats for the underlying table */
8061  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
8062  {
8063  /*
8064  * The hook took control of acquiring a stats tuple. If it
8065  * did supply a tuple, it'd better have supplied a freefunc.
8066  */
8067  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
8068  elog(ERROR,
8069  "no function provided to release variable stats with");
8070  }
8071  else
8072  {
8073  vardata.statsTuple =
8074  SearchSysCache3(STATRELATTINH,
8075  ObjectIdGetDatum(rte->relid),
8077  BoolGetDatum(false));
8078  vardata.freefunc = ReleaseSysCache;
8079  }
8080  }
8081  else
8082  {
8083  /*
8084  * Looks like we've found an expression column in the index. Let's
8085  * see if there's any stats for it.
8086  */
8087 
8088  /* get the attnum from the 0-based index. */
8089  attnum = iclause->indexcol + 1;
8090 
8091  if (get_index_stats_hook &&
8092  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
8093  {
8094  /*
8095  * The hook took control of acquiring a stats tuple. If it
8096  * did supply a tuple, it'd better have supplied a freefunc.
8097  */
8098  if (HeapTupleIsValid(vardata.statsTuple) &&
8099  !vardata.freefunc)
8100  elog(ERROR, "no function provided to release variable stats with");
8101  }
8102  else
8103  {
8104  vardata.statsTuple = SearchSysCache3(STATRELATTINH,
8105  ObjectIdGetDatum(index->indexoid),
8107  BoolGetDatum(false));
8108  vardata.freefunc = ReleaseSysCache;
8109  }
8110  }
8111 
8112  if (HeapTupleIsValid(vardata.statsTuple))
8113  {
8114  AttStatsSlot sslot;
8115 
8116  if (get_attstatsslot(&sslot, vardata.statsTuple,
8117  STATISTIC_KIND_CORRELATION, InvalidOid,
8119  {
8120  double varCorrelation = 0.0;
8121 
8122  if (sslot.nnumbers > 0)
8123  varCorrelation = fabs(sslot.numbers[0]);
8124 
8125  if (varCorrelation > *indexCorrelation)
8126  *indexCorrelation = varCorrelation;
8127 
8128  free_attstatsslot(&sslot);
8129  }
8130  }
8131 
8132  ReleaseVariableStats(vardata);
8133  }
8134 
8135  qualSelectivity = clauselist_selectivity(root, indexQuals,
8136  baserel->relid,
8137  JOIN_INNER, NULL);
8138 
8139  /*
8140  * Now calculate the minimum possible ranges we could match with if all of
8141  * the rows were in the perfect order in the table's heap.
8142  */
8143  minimalRanges = ceil(indexRanges * qualSelectivity);
8144 
8145  /*
8146  * Now estimate the number of ranges that we'll touch by using the
8147  * indexCorrelation from the stats. Careful not to divide by zero (note
8148  * we're using the absolute value of the correlation).
8149  */
8150  if (*indexCorrelation < 1.0e-10)
8151  estimatedRanges = indexRanges;
8152  else
8153  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8154 
8155  /* we expect to visit this portion of the table */
8156  selec = estimatedRanges / indexRanges;
8157 
8158  CLAMP_PROBABILITY(selec);
8159 
8160  *indexSelectivity = selec;
8161 
8162  /*
8163  * Compute the index qual costs, much as in genericcostestimate, to add to
8164  * the index costs. We can disregard indexorderbys, since BRIN doesn't
8165  * support those.
8166  */
8167  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
8168 
8169  /*
8170  * Compute the startup cost as the cost to read the whole revmap
8171  * sequentially, including the cost to execute the index quals.
8172  */
8173  *indexStartupCost =
8174  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8175  *indexStartupCost += qual_arg_cost;
8176 
8177  /*
8178  * To read a BRIN index there might be a bit of back and forth over
8179  * regular pages, as revmap might point to them out of sequential order;
8180  * calculate the total cost as reading the whole index in random order.
8181  */
8182  *indexTotalCost = *indexStartupCost +
8183  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8184 
8185  /*
8186  * Charge a small amount per range tuple which we expect to match to. This
8187  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8188  * will set a bit for each page in the range when we find a matching
8189  * range, so we must multiply the charge by the number of pages in the
8190  * range.
8191  */
8192  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8193  statsData.pagesPerRange;
8194 
8195  *indexPages = index->pages;
8196 }
int16 AttrNumber
Definition: attnum.h:21
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1637
#define BRIN_DEFAULT_PAGES_PER_RANGE
Definition: brin.h:39
#define REVMAP_PAGE_MAXITEMS
Definition: brin_page.h:93
#define Min(x, y)
Definition: c.h:1004
#define Max(x, y)
Definition: c.h:998
#define Assert(condition)
Definition: c.h:858
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
double cpu_operator_cost
Definition: costsize.c:134
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
#define NoLock
Definition: lockdefs.h:34
double Cost
Definition: nodes.h:251
@ JOIN_INNER
Definition: nodes.h:293
@ RTE_RELATION
Definition: parsenodes.h:1017
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:570
int16 attnum
Definition: pg_attribute.h:74
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:6468
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:148
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:6498
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:147
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
BlockNumber revmapNumPages
Definition: brin.h:35
BlockNumber pagesPerRange
Definition: brin.h:34
AttrNumber indexcol
Definition: pathnodes.h:1768
List * indexclauses
Definition: pathnodes.h:1718
IndexOptInfo * indexinfo
Definition: pathnodes.h:1717
RTEKind rtekind
Definition: parsenodes.h:1047
Index relid
Definition: pathnodes.h:918
BlockNumber pages
Definition: pathnodes.h:948
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:91
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:240

References 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, index_close(), index_open(), index_other_operands_eval_cost(), IndexPath::indexclauses, IndexClause::indexcol, IndexPath::indexinfo, Int16GetDatum(), InvalidOid, JOIN_INNER, lfirst_node, Max, Min, AttStatsSlot::nnumbers, NoLock, AttStatsSlot::numbers, ObjectIdGetDatum(), RelOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, ReleaseSysCache(), ReleaseVariableStats, RangeTblEntry::relid, RelOptInfo::relid, REVMAP_PAGE_MAXITEMS, BrinStatsData::revmapNumPages, root, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), and VariableStatData::statsTuple.

Referenced by brinhandler().

◆ btcostestimate()

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

Definition at line 6796 of file selfuncs.c.

6800 {
6801  IndexOptInfo *index = path->indexinfo;
6802  GenericCosts costs = {0};
6803  Oid relid;
6804  AttrNumber colnum;
6805  VariableStatData vardata = {0};
6806  double numIndexTuples;
6807  Cost descentCost;
6808  List *indexBoundQuals;
6809  int indexcol;
6810  bool eqQualHere;
6811  bool found_saop;
6812  bool found_is_null_op;
6813  double num_sa_scans;
6814  ListCell *lc;
6815 
6816  /*
6817  * For a btree scan, only leading '=' quals plus inequality quals for the
6818  * immediately next attribute contribute to index selectivity (these are
6819  * the "boundary quals" that determine the starting and stopping points of
6820  * the index scan). Additional quals can suppress visits to the heap, so
6821  * it's OK to count them in indexSelectivity, but they should not count
6822  * for estimating numIndexTuples. So we must examine the given indexquals
6823  * to find out which ones count as boundary quals. We rely on the
6824  * knowledge that they are given in index column order.
6825  *
6826  * For a RowCompareExpr, we consider only the first column, just as
6827  * rowcomparesel() does.
6828  *
6829  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform up
6830  * to N index descents (not just one), but the ScalarArrayOpExpr's
6831  * operator can be considered to act the same as it normally does.
6832  */
6833  indexBoundQuals = NIL;
6834  indexcol = 0;
6835  eqQualHere = false;
6836  found_saop = false;
6837  found_is_null_op = false;
6838  num_sa_scans = 1;
6839  foreach(lc, path->indexclauses)
6840  {
6841  IndexClause *iclause = lfirst_node(IndexClause, lc);
6842  ListCell *lc2;
6843 
6844  if (indexcol != iclause->indexcol)
6845  {
6846  /* Beginning of a new column's quals */
6847  if (!eqQualHere)
6848  break; /* done if no '=' qual for indexcol */
6849  eqQualHere = false;
6850  indexcol++;
6851  if (indexcol != iclause->indexcol)
6852  break; /* no quals at all for indexcol */
6853  }
6854 
6855  /* Examine each indexqual associated with this index clause */
6856  foreach(lc2, iclause->indexquals)
6857  {
6858  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6859  Expr *clause = rinfo->clause;
6860  Oid clause_op = InvalidOid;
6861  int op_strategy;
6862 
6863  if (IsA(clause, OpExpr))
6864  {
6865  OpExpr *op = (OpExpr *) clause;
6866 
6867  clause_op = op->opno;
6868  }
6869  else if (IsA(clause, RowCompareExpr))
6870  {
6871  RowCompareExpr *rc = (RowCompareExpr *) clause;
6872 
6873  clause_op = linitial_oid(rc->opnos);
6874  }
6875  else if (IsA(clause, ScalarArrayOpExpr))
6876  {
6877  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6878  Node *other_operand = (Node *) lsecond(saop->args);
6879  double alength = estimate_array_length(root, other_operand);
6880 
6881  clause_op = saop->opno;
6882  found_saop = true;
6883  /* estimate SA descents by indexBoundQuals only */
6884  if (alength > 1)
6885  num_sa_scans *= alength;
6886  }
6887  else if (IsA(clause, NullTest))
6888  {
6889  NullTest *nt = (NullTest *) clause;
6890 
6891  if (nt->nulltesttype == IS_NULL)
6892  {
6893  found_is_null_op = true;
6894  /* IS NULL is like = for selectivity purposes */
6895  eqQualHere = true;
6896  }
6897  }
6898  else
6899  elog(ERROR, "unsupported indexqual type: %d",
6900  (int) nodeTag(clause));
6901 
6902  /* check for equality operator */
6903  if (OidIsValid(clause_op))
6904  {
6905  op_strategy = get_op_opfamily_strategy(clause_op,
6906  index->opfamily[indexcol]);
6907  Assert(op_strategy != 0); /* not a member of opfamily?? */
6908  if (op_strategy == BTEqualStrategyNumber)
6909  eqQualHere = true;
6910  }
6911 
6912  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6913  }
6914  }
6915 
6916  /*
6917  * If index is unique and we found an '=' clause for each column, we can
6918  * just assume numIndexTuples = 1 and skip the expensive
6919  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6920  * NullTest invalidates that theory, even though it sets eqQualHere.
6921  */
6922  if (index->unique &&
6923  indexcol == index->nkeycolumns - 1 &&
6924  eqQualHere &&
6925  !found_saop &&
6926  !found_is_null_op)
6927  numIndexTuples = 1.0;
6928  else
6929  {
6930  List *selectivityQuals;
6931  Selectivity btreeSelectivity;
6932 
6933  /*
6934  * If the index is partial, AND the index predicate with the
6935  * index-bound quals to produce a more accurate idea of the number of
6936  * rows covered by the bound conditions.
6937  */
6938  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6939 
6940  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6941  index->rel->relid,
6942  JOIN_INNER,
6943  NULL);
6944  numIndexTuples = btreeSelectivity * index->rel->tuples;
6945 
6946  /*
6947  * btree automatically combines individual ScalarArrayOpExpr primitive
6948  * index scans whenever the tuples covered by the next set of array
6949  * keys are close to tuples covered by the current set. That puts a
6950  * natural ceiling on the worst case number of descents -- there
6951  * cannot possibly be more than one descent per leaf page scanned.
6952  *
6953  * Clamp the number of descents to at most 1/3 the number of index
6954  * pages. This avoids implausibly high estimates with low selectivity
6955  * paths, where scans usually require only one or two descents. This
6956  * is most likely to help when there are several SAOP clauses, where
6957  * naively accepting the total number of distinct combinations of
6958  * array elements as the number of descents would frequently lead to
6959  * wild overestimates.
6960  *
6961  * We somewhat arbitrarily don't just make the cutoff the total number
6962  * of leaf pages (we make it 1/3 the total number of pages instead) to
6963  * give the btree code credit for its ability to continue on the leaf
6964  * level with low selectivity scans.
6965  */
6966  num_sa_scans = Min(num_sa_scans, ceil(index->pages * 0.3333333));
6967  num_sa_scans = Max(num_sa_scans, 1);
6968 
6969  /*
6970  * As in genericcostestimate(), we have to adjust for any
6971  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6972  * to integer.
6973  *
6974  * It is tempting to make genericcostestimate behave as if SAOP
6975  * clauses work in almost the same way as scalar operators during
6976  * btree scans, making the top-level scan look like a continuous scan
6977  * (as opposed to num_sa_scans-many primitive index scans). After
6978  * all, btree scans mostly work like that at runtime. However, such a
6979  * scheme would badly bias genericcostestimate's simplistic approach
6980  * to calculating numIndexPages through prorating.
6981  *
6982  * Stick with the approach taken by non-native SAOP scans for now.
6983  * genericcostestimate will use the Mackert-Lohman formula to
6984  * compensate for repeat page fetches, even though that definitely
6985  * won't happen during btree scans (not for leaf pages, at least).
6986  * We're usually very pessimistic about the number of primitive index
6987  * scans that will be required, but it's not clear how to do better.
6988  */
6989  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6990  }
6991 
6992  /*
6993  * Now do generic index cost estimation.
6994  */
6995  costs.numIndexTuples = numIndexTuples;
6996  costs.num_sa_scans = num_sa_scans;
6997 
6998  genericcostestimate(root, path, loop_count, &costs);
6999 
7000  /*
7001  * Add a CPU-cost component to represent the costs of initial btree
7002  * descent. We don't charge any I/O cost for touching upper btree levels,
7003  * since they tend to stay in cache, but we still have to do about log2(N)
7004  * comparisons to descend a btree of N leaf tuples. We charge one
7005  * cpu_operator_cost per comparison.
7006  *
7007  * If there are ScalarArrayOpExprs, charge this once per estimated SA
7008  * index descent. The ones after the first one are not startup cost so
7009  * far as the overall plan goes, so just add them to "total" cost.
7010  */
7011  if (index->tuples > 1) /* avoid computing log(0) */
7012  {
7013  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
7014  costs.indexStartupCost += descentCost;
7015  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7016  }
7017 
7018  /*
7019  * Even though we're not charging I/O cost for touching upper btree pages,
7020  * it's still reasonable to charge some CPU cost per page descended
7021  * through. Moreover, if we had no such charge at all, bloated indexes
7022  * would appear to have the same search cost as unbloated ones, at least
7023  * in cases where only a single leaf page is expected to be visited. This
7024  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
7025  * touched. The number of such pages is btree tree height plus one (ie,
7026  * we charge for the leaf page too). As above, charge once per estimated
7027  * SA index descent.
7028  */
7029  descentCost = (index->tree_height + 1) * DEFAULT_PAGE_CPU_MULTIPLIER * cpu_operator_cost;
7030  costs.indexStartupCost += descentCost;
7031  costs.indexTotalCost += costs.num_sa_scans * descentCost;
7032 
7033  /*
7034  * If we can get an estimate of the first column's ordering correlation C
7035  * from pg_statistic, estimate the index correlation as C for a
7036  * single-column index, or C * 0.75 for multiple columns. (The idea here
7037  * is that multiple columns dilute the importance of the first column's
7038  * ordering, but don't negate it entirely. Before 8.0 we divided the
7039  * correlation by the number of columns, but that seems too strong.)
7040  */
7041  if (index->indexkeys[0] != 0)
7042  {
7043  /* Simple variable --- look to stats for the underlying table */
7044  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7045 
7046  Assert(rte->rtekind == RTE_RELATION);
7047  relid = rte->relid;
7048  Assert(relid != InvalidOid);
7049  colnum = index->indexkeys[0];
7050 
7052  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7053  {
7054  /*
7055  * The hook took control of acquiring a stats tuple. If it did
7056  * supply a tuple, it'd better have supplied a freefunc.
7057  */
7058  if (HeapTupleIsValid(vardata.statsTuple) &&
7059  !vardata.freefunc)
7060  elog(ERROR, "no function provided to release variable stats with");
7061  }
7062  else
7063  {
7064  vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7065  ObjectIdGetDatum(relid),
7066  Int16GetDatum(colnum),
7067  BoolGetDatum(rte->inh));
7068  vardata.freefunc = ReleaseSysCache;
7069  }
7070  }
7071  else
7072  {
7073  /* Expression --- maybe there are stats for the index itself */
7074  relid = index->indexoid;
7075  colnum = 1;
7076 
7077  if (get_index_stats_hook &&
7078  (*get_index_stats_hook) (root, relid, colnum, &vardata))
7079  {
7080  /*
7081  * The hook took control of acquiring a stats tuple. If it did
7082  * supply a tuple, it'd better have supplied a freefunc.
7083  */
7084  if (HeapTupleIsValid(vardata.statsTuple) &&
7085  !vardata.freefunc)
7086  elog(ERROR, "no function provided to release variable stats with");
7087  }
7088  else
7089  {
7090  vardata.statsTuple = SearchSysCache3(STATRELATTINH,
7091  ObjectIdGetDatum(relid),
7092  Int16GetDatum(colnum),
7093  BoolGetDatum(false));
7094  vardata.freefunc = ReleaseSysCache;
7095  }
7096  }
7097 
7098  if (HeapTupleIsValid(vardata.statsTuple))
7099  {
7100  Oid sortop;
7101  AttStatsSlot sslot;
7102 
7103  sortop = get_opfamily_member(index->opfamily[0],
7104  index->opcintype[0],
7105  index->opcintype[0],
7107  if (OidIsValid(sortop) &&
7108  get_attstatsslot(&sslot, vardata.statsTuple,
7109  STATISTIC_KIND_CORRELATION, sortop,
7111  {
7112  double varCorrelation;
7113 
7114  Assert(sslot.nnumbers == 1);
7115  varCorrelation = sslot.numbers[0];
7116 
7117  if (index->reverse_sort[0])
7118  varCorrelation = -varCorrelation;
7119 
7120  if (index->nkeycolumns > 1)
7121  costs.indexCorrelation = varCorrelation * 0.75;
7122  else
7123  costs.indexCorrelation = varCorrelation;
7124 
7125  free_attstatsslot(&sslot);
7126  }
7127  }
7128 
7129  ReleaseVariableStats(vardata);
7130 
7131  *indexStartupCost = costs.indexStartupCost;
7132  *indexTotalCost = costs.indexTotalCost;
7133  *indexSelectivity = costs.indexSelectivity;
7134  *indexCorrelation = costs.indexCorrelation;
7135  *indexPages = costs.numIndexPages;
7136 }
#define OidIsValid(objectId)
Definition: c.h:775
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:83
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:166
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define lsecond(l)
Definition: pg_list.h:183
#define linitial_oid(l)
Definition: pg_list.h:180
unsigned int Oid
Definition: postgres_ext.h:31
@ IS_NULL
Definition: primnodes.h:1948
#define DEFAULT_PAGE_CPU_MULTIPLIER
Definition: selfuncs.c:144
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2136
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:6552
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6775
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Selectivity indexSelectivity
Definition: selfuncs.h:127
Cost indexStartupCost
Definition: selfuncs.h:125
double indexCorrelation
Definition: selfuncs.h:128
double num_sa_scans
Definition: selfuncs.h:134
Cost indexTotalCost
Definition: selfuncs.h:126
double numIndexPages
Definition: selfuncs.h:131
double numIndexTuples
Definition: selfuncs.h:132
List * indexquals
Definition: pathnodes.h:1766
NullTestType nulltesttype
Definition: primnodes.h:1955
Oid opno
Definition: primnodes.h:818
Expr * clause
Definition: pathnodes.h:2571

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum(), BTEqualStrategyNumber, BTLessStrategyNumber, RestrictInfo::clause, clauselist_selectivity(), cpu_operator_cost, DEFAULT_PAGE_CPU_MULTIPLIER, 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, IndexClause::indexquals, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, RangeTblEntry::inh, Int16GetDatum(), InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst_node, linitial_oid, lsecond, Max, Min, NIL, AttStatsSlot::nnumbers, nodeTag, NullTest::nulltesttype, GenericCosts::num_sa_scans, AttStatsSlot::numbers, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, ObjectIdGetDatum(), OidIsValid, OpExpr::opno, ScalarArrayOpExpr::opno, planner_rt_fetch, ReleaseSysCache(), ReleaseVariableStats, RangeTblEntry::relid, root, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), and VariableStatData::statsTuple.

Referenced by bthandler().

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

4740 {
4741  bytea *valuep = DatumGetByteaPP(value);
4742  bytea *loboundp = DatumGetByteaPP(lobound);
4743  bytea *hiboundp = DatumGetByteaPP(hibound);
4744  int rangelo,
4745  rangehi,
4746  valuelen = VARSIZE_ANY_EXHDR(valuep),
4747  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4748  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4749  i,
4750  minlen;
4751  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4752  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4753  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4754 
4755  /*
4756  * Assume bytea data is uniformly distributed across all byte values.
4757  */
4758  rangelo = 0;
4759  rangehi = 255;
4760 
4761  /*
4762  * Now strip any common prefix of the three strings.
4763  */
4764  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4765  for (i = 0; i < minlen; i++)
4766  {
4767  if (*lostr != *histr || *lostr != *valstr)
4768  break;
4769  lostr++, histr++, valstr++;
4770  loboundlen--, hiboundlen--, valuelen--;
4771  }
4772 
4773  /*
4774  * Now we can do the conversions.
4775  */
4776  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4777  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4778  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4779 }
#define DatumGetByteaPP(X)
Definition: fmgr.h:291
static struct @157 value
int i
Definition: isn.c:73
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4782
Definition: c.h:687
#define VARDATA_ANY(PTR)
Definition: varatt.h:324
#define VARSIZE_ANY_EXHDR(PTR)
Definition: varatt.h:317

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

Referenced by convert_to_scalar().

◆ convert_numeric_to_scalar()

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

Definition at line 4453 of file selfuncs.c.

4454 {
4455  switch (typid)
4456  {
4457  case BOOLOID:
4458  return (double) DatumGetBool(value);
4459  case INT2OID:
4460  return (double) DatumGetInt16(value);
4461  case INT4OID:
4462  return (double) DatumGetInt32(value);
4463  case INT8OID:
4464  return (double) DatumGetInt64(value);
4465  case FLOAT4OID:
4466  return (double) DatumGetFloat4(value);
4467  case FLOAT8OID:
4468  return (double) DatumGetFloat8(value);
4469  case NUMERICOID:
4470  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4471  return (double)
4473  value));
4474  case OIDOID:
4475  case REGPROCOID:
4476  case REGPROCEDUREOID:
4477  case REGOPEROID:
4478  case REGOPERATOROID:
4479  case REGCLASSOID:
4480  case REGTYPEOID:
4481  case REGCOLLATIONOID:
4482  case REGCONFIGOID:
4483  case REGDICTIONARYOID:
4484  case REGROLEOID:
4485  case REGNAMESPACEOID:
4486  /* we can treat OIDs as integers... */
4487  return (double) DatumGetObjectId(value);
4488  }
4489 
4490  *failure = true;
4491  return 0;
4492 }
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:4661
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:641
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:385
static float4 DatumGetFloat4(Datum X)
Definition: postgres.h:458
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:494
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:162
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:202

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

Referenced by convert_to_scalar().

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

4784 {
4785  double num,
4786  denom,
4787  base;
4788 
4789  if (valuelen <= 0)
4790  return 0.0; /* empty string has scalar value 0 */
4791 
4792  /*
4793  * Since base is 256, need not consider more than about 10 chars (even
4794  * this many seems like overkill)
4795  */
4796  if (valuelen > 10)
4797  valuelen = 10;
4798 
4799  /* Convert initial characters to fraction */
4800  base = rangehi - rangelo + 1;
4801  num = 0.0;
4802  denom = base;
4803  while (valuelen-- > 0)
4804  {
4805  int ch = *value++;
4806 
4807  if (ch < rangelo)
4808  ch = rangelo - 1;
4809  else if (ch > rangehi)
4810  ch = rangehi + 1;
4811  num += ((double) (ch - rangelo)) / denom;
4812  denom *= base;
4813  }
4814 
4815  return num;
4816 }

References value.

Referenced by convert_bytea_to_scalar().

◆ convert_one_string_to_scalar()

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

Definition at line 4595 of file selfuncs.c.

4596 {
4597  int slen = strlen(value);
4598  double num,
4599  denom,
4600  base;
4601 
4602  if (slen <= 0)
4603  return 0.0; /* empty string has scalar value 0 */
4604 
4605  /*
4606  * There seems little point in considering more than a dozen bytes from
4607  * the string. Since base is at least 10, that will give us nominal
4608  * resolution of at least 12 decimal digits, which is surely far more
4609  * precision than this estimation technique has got anyway (especially in
4610  * non-C locales). Also, even with the maximum possible base of 256, this
4611  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4612  * overflow on any known machine.
4613  */
4614  if (slen > 12)
4615  slen = 12;
4616 
4617  /* Convert initial characters to fraction */
4618  base = rangehi - rangelo + 1;
4619  num = 0.0;
4620  denom = base;
4621  while (slen-- > 0)
4622  {
4623  int ch = (unsigned char) *value++;
4624 
4625  if (ch < rangelo)
4626  ch = rangelo - 1;
4627  else if (ch > rangehi)
4628  ch = rangehi + 1;
4629  num += ((double) (ch - rangelo)) / denom;
4630  denom *= base;
4631  }
4632 
4633  return num;
4634 }

References value.

Referenced by convert_string_to_scalar().

◆ convert_string_datum()

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

Definition at line 4646 of file selfuncs.c.

4647 {
4648  char *val;
4649  pg_locale_t mylocale;
4650 
4651  switch (typid)
4652  {
4653  case CHAROID:
4654  val = (char *) palloc(2);
4655  val[0] = DatumGetChar(value);
4656  val[1] = '\0';
4657  break;
4658  case BPCHAROID:
4659  case VARCHAROID:
4660  case TEXTOID:
4662  break;
4663  case NAMEOID:
4664  {
4666 
4667  val = pstrdup(NameStr(*nm));
4668  break;
4669  }
4670  default:
4671  *failure = true;
4672  return NULL;
4673  }
4674 
4675  mylocale = pg_newlocale_from_collation(collid);
4676 
4677  if (!mylocale->collate_is_c)
4678  {
4679  char *xfrmstr;
4680  size_t xfrmlen;
4681  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4682 
4683  /*
4684  * XXX: We could guess at a suitable output buffer size and only call
4685  * pg_strxfrm() twice if our guess is too small.
4686  *
4687  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4688  * bogus data or set an error. This is not really a problem unless it
4689  * crashes since it will only give an estimation error and nothing
4690  * fatal.
4691  *
4692  * XXX: we do not check pg_strxfrm_enabled(). On some platforms and in
4693  * some cases, libc strxfrm() may return the wrong results, but that
4694  * will only lead to an estimation error.
4695  */
4696  xfrmlen = pg_strxfrm(NULL, val, 0, mylocale);
4697 #ifdef WIN32
4698 
4699  /*
4700  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4701  * of trying to allocate this much memory (and fail), just return the
4702  * original string unmodified as if we were in the C locale.
4703  */
4704  if (xfrmlen == INT_MAX)
4705  return val;
4706 #endif
4707  xfrmstr = (char *) palloc(xfrmlen + 1);
4708  xfrmlen2 = pg_strxfrm(xfrmstr, val, xfrmlen + 1, mylocale);
4709 
4710  /*
4711  * Some systems (e.g., glibc) can return a smaller value from the
4712  * second call than the first; thus the Assert must be <= not ==.
4713  */
4714  Assert(xfrmlen2 <= xfrmlen);
4715  pfree(val);
4716  val = xfrmstr;
4717  }
4718 
4719  return val;
4720 }
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:746
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:182
Oid collid
long val
Definition: informix.c:689
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition: pg_locale.c:1510
size_t pg_strxfrm(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition: pg_locale.c:2299
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
static char DatumGetChar(Datum X)
Definition: postgres.h:112
Definition: c.h:741

References Assert, pg_locale_struct::collate_is_c, collid, DatumGetChar(), DatumGetPointer(), NameStr, palloc(), pfree(), pg_newlocale_from_collation(), pg_strxfrm(), PG_USED_FOR_ASSERTS_ONLY, pstrdup(), TextDatumGetCString, val, and value.

Referenced by convert_to_scalar().

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

4521 {
4522  int rangelo,
4523  rangehi;
4524  char *sptr;
4525 
4526  rangelo = rangehi = (unsigned char) hibound[0];
4527  for (sptr = lobound; *sptr; sptr++)
4528  {
4529  if (rangelo > (unsigned char) *sptr)
4530  rangelo = (unsigned char) *sptr;
4531  if (rangehi < (unsigned char) *sptr)
4532  rangehi = (unsigned char) *sptr;
4533  }
4534  for (sptr = hibound; *sptr; sptr++)
4535  {
4536  if (rangelo > (unsigned char) *sptr)
4537  rangelo = (unsigned char) *sptr;
4538  if (rangehi < (unsigned char) *sptr)
4539  rangehi = (unsigned char) *sptr;
4540  }
4541  /* If range includes any upper-case ASCII chars, make it include all */
4542  if (rangelo <= 'Z' && rangehi >= 'A')
4543  {
4544  if (rangelo > 'A')
4545  rangelo = 'A';
4546  if (rangehi < 'Z')
4547  rangehi = 'Z';
4548  }
4549  /* Ditto lower-case */
4550  if (rangelo <= 'z' && rangehi >= 'a')
4551  {
4552  if (rangelo > 'a')
4553  rangelo = 'a';
4554  if (rangehi < 'z')
4555  rangehi = 'z';
4556  }
4557  /* Ditto digits */
4558  if (rangelo <= '9' && rangehi >= '0')
4559  {
4560  if (rangelo > '0')
4561  rangelo = '0';
4562  if (rangehi < '9')
4563  rangehi = '9';
4564  }
4565 
4566  /*
4567  * If range includes less than 10 chars, assume we have not got enough
4568  * data, and make it include regular ASCII set.
4569  */
4570  if (rangehi - rangelo < 9)
4571  {
4572  rangelo = ' ';
4573  rangehi = 127;
4574  }
4575 
4576  /*
4577  * Now strip any common prefix of the three strings.
4578  */
4579  while (*lobound)
4580  {
4581  if (*lobound != *hibound || *lobound != *value)
4582  break;
4583  lobound++, hibound++, value++;
4584  }
4585 
4586  /*
4587  * Now we can do the conversions.
4588  */
4589  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4590  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4591  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4592 }
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4595

References convert_one_string_to_scalar(), and value.

Referenced by convert_to_scalar().

◆ convert_timevalue_to_scalar()

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

Definition at line 4825 of file selfuncs.c.

4826 {
4827  switch (typid)
4828  {
4829  case TIMESTAMPOID:
4830  return DatumGetTimestamp(value);
4831  case TIMESTAMPTZOID:
4832  return DatumGetTimestampTz(value);
4833  case DATEOID:
4835  case INTERVALOID:
4836  {
4838 
4839  /*
4840  * Convert the month part of Interval to days using assumed
4841  * average month length of 365.25/12.0 days. Not too
4842  * accurate, but plenty good enough for our purposes.
4843  *
4844  * This also works for infinite intervals, which just have all
4845  * fields set to INT_MIN/INT_MAX, and so will produce a result
4846  * smaller/larger than any finite interval.
4847  */
4848  return interval->time + interval->day * (double) USECS_PER_DAY +
4850  }
4851  case TIMEOID:
4852  return DatumGetTimeADT(value);
4853  case TIMETZOID:
4854  {
4855  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4856 
4857  /* use GMT-equivalent time */
4858  return (double) (timetz->time + (timetz->zone * 1000000.0));
4859  }
4860  }
4861 
4862  *failure = true;
4863  return 0;
4864 }
#define MONTHS_PER_YEAR
Definition: timestamp.h:108
#define USECS_PER_DAY
Definition: timestamp.h:131
#define DAYS_PER_YEAR
Definition: timestamp.h:107
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:732
static DateADT DatumGetDateADT(Datum X)
Definition: date.h:54
static TimeADT DatumGetTimeADT(Datum X)
Definition: date.h:60
static TimeTzADT * DatumGetTimeTzADTP(Datum X)
Definition: date.h:66
Definition: date.h:28
TimeADT time
Definition: date.h:29
int32 zone
Definition: date.h:30
static Interval * DatumGetIntervalP(Datum X)
Definition: timestamp.h:40
static Timestamp DatumGetTimestamp(Datum X)
Definition: timestamp.h:28
static TimestampTz DatumGetTimestampTz(Datum X)
Definition: timestamp.h:34

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

Referenced by convert_to_scalar().

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

4309 {
4310  bool failure = false;
4311 
4312  /*
4313  * Both the valuetypid and the boundstypid should exactly match the
4314  * declared input type(s) of the operator we are invoked for. However,
4315  * extensions might try to use scalarineqsel as estimator for operators
4316  * with input type(s) we don't handle here; in such cases, we want to
4317  * return false, not fail. In any case, we mustn't assume that valuetypid
4318  * and boundstypid are identical.
4319  *
4320  * XXX The histogram we are interpolating between points of could belong
4321  * to a column that's only binary-compatible with the declared type. In
4322  * essence we are assuming that the semantics of binary-compatible types
4323  * are enough alike that we can use a histogram generated with one type's
4324  * operators to estimate selectivity for the other's. This is outright
4325  * wrong in some cases --- in particular signed versus unsigned
4326  * interpretation could trip us up. But it's useful enough in the
4327  * majority of cases that we do it anyway. Should think about more
4328  * rigorous ways to do it.
4329  */
4330  switch (valuetypid)
4331  {
4332  /*
4333  * Built-in numeric types
4334  */
4335  case BOOLOID:
4336  case INT2OID:
4337  case INT4OID:
4338  case INT8OID:
4339  case FLOAT4OID:
4340  case FLOAT8OID:
4341  case NUMERICOID:
4342  case OIDOID:
4343  case REGPROCOID:
4344  case REGPROCEDUREOID:
4345  case REGOPEROID:
4346  case REGOPERATOROID:
4347  case REGCLASSOID:
4348  case REGTYPEOID:
4349  case REGCOLLATIONOID:
4350  case REGCONFIGOID:
4351  case REGDICTIONARYOID:
4352  case REGROLEOID:
4353  case REGNAMESPACEOID:
4354  *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
4355  &failure);
4356  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
4357  &failure);
4358  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
4359  &failure);
4360  return !failure;
4361 
4362  /*
4363  * Built-in string types
4364  */
4365  case CHAROID:
4366  case BPCHAROID:
4367  case VARCHAROID:
4368  case TEXTOID:
4369  case NAMEOID:
4370  {
4371  char *valstr = convert_string_datum(value, valuetypid,
4372  collid, &failure);
4373  char *lostr = convert_string_datum(lobound, boundstypid,
4374  collid, &failure);
4375  char *histr = convert_string_datum(hibound, boundstypid,
4376  collid, &failure);
4377 
4378  /*
4379  * Bail out if any of the values is not of string type. We
4380  * might leak converted strings for the other value(s), but
4381  * that's not worth troubling over.
4382  */
4383  if (failure)
4384  return false;
4385 
4386  convert_string_to_scalar(valstr, scaledvalue,
4387  lostr, scaledlobound,
4388  histr, scaledhibound);
4389  pfree(valstr);
4390  pfree(lostr);
4391  pfree(histr);
4392  return true;
4393  }
4394 
4395  /*
4396  * Built-in bytea type
4397  */
4398  case BYTEAOID:
4399  {
4400  /* We only support bytea vs bytea comparison */
4401  if (boundstypid != BYTEAOID)
4402  return false;
4403  convert_bytea_to_scalar(value, scaledvalue,
4404  lobound, scaledlobound,
4405  hibound, scaledhibound);
4406  return true;
4407  }
4408 
4409  /*
4410  * Built-in time types
4411  */
4412  case TIMESTAMPOID:
4413  case TIMESTAMPTZOID:
4414  case DATEOID:
4415  case INTERVALOID:
4416  case TIMEOID:
4417  case TIMETZOID:
4418  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
4419  &failure);
4420  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
4421  &failure);
4422  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
4423  &failure);
4424  return !failure;
4425 
4426  /*
4427  * Built-in network types
4428  */
4429  case INETOID:
4430  case CIDROID:
4431  case MACADDROID:
4432  case MACADDR8OID:
4433  *scaledvalue = convert_network_to_scalar(value, valuetypid,
4434  &failure);
4435  *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
4436  &failure);
4437  *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
4438  &failure);
4439  return !failure;
4440  }
4441  /* Don't know how to convert */
4442  *scaledvalue = *scaledlobound = *scaledhibound = 0;
4443  return false;
4444 }
double convert_network_to_scalar(Datum value, Oid typid, bool *failure)
Definition: network.c:1496
static void convert_string_to_scalar(char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
Definition: selfuncs.c:4515
static double convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4825
static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4453
static void convert_bytea_to_scalar(Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
Definition: selfuncs.c:4734
static char * convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
Definition: selfuncs.c:4646

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

Referenced by ineq_histogram_selectivity().

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

Definition at line 2269 of file selfuncs.c.

2270 {
2272  Oid operator = PG_GETARG_OID(1);
2273  List *args = (List *) PG_GETARG_POINTER(2);
2274 
2275 #ifdef NOT_USED
2276  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2277 #endif
2279  Oid collation = PG_GET_COLLATION();
2280  double selec;
2281  double selec_inner;
2282  VariableStatData vardata1;
2283  VariableStatData vardata2;
2284  double nd1;
2285  double nd2;
2286  bool isdefault1;
2287  bool isdefault2;
2288  Oid opfuncoid;
2289  AttStatsSlot sslot1;
2290  AttStatsSlot sslot2;
2291  Form_pg_statistic stats1 = NULL;
2292  Form_pg_statistic stats2 = NULL;
2293  bool have_mcvs1 = false;
2294  bool have_mcvs2 = false;
2295  bool get_mcv_stats;
2296  bool join_is_reversed;
2297  RelOptInfo *inner_rel;
2298 
2299  get_join_variables(root, args, sjinfo,
2300  &vardata1, &vardata2, &join_is_reversed);
2301 
2302  nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2303  nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2304 
2305  opfuncoid = get_opcode(operator);
2306 
2307  memset(&sslot1, 0, sizeof(sslot1));
2308  memset(&sslot2, 0, sizeof(sslot2));
2309 
2310  /*
2311  * There is no use in fetching one side's MCVs if we lack MCVs for the
2312  * other side, so do a quick check to verify that both stats exist.
2313  */
2314  get_mcv_stats = (HeapTupleIsValid(vardata1.statsTuple) &&
2315  HeapTupleIsValid(vardata2.statsTuple) &&
2316  get_attstatsslot(&sslot1, vardata1.statsTuple,
2317  STATISTIC_KIND_MCV, InvalidOid,
2318  0) &&
2319  get_attstatsslot(&sslot2, vardata2.statsTuple,
2320  STATISTIC_KIND_MCV, InvalidOid,
2321  0));
2322 
2323  if (HeapTupleIsValid(vardata1.statsTuple))
2324  {
2325  /* note we allow use of nullfrac regardless of security check */
2326  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2327  if (get_mcv_stats &&
2328  statistic_proc_security_check(&vardata1, opfuncoid))
2329  have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2330  STATISTIC_KIND_MCV, InvalidOid,
2332  }
2333 
2334  if (HeapTupleIsValid(vardata2.statsTuple))
2335  {
2336  /* note we allow use of nullfrac regardless of security check */
2337  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2338  if (get_mcv_stats &&
2339  statistic_proc_security_check(&vardata2, opfuncoid))
2340  have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2341  STATISTIC_KIND_MCV, InvalidOid,
2343  }
2344 
2345  /* We need to compute the inner-join selectivity in all cases */
2346  selec_inner = eqjoinsel_inner(opfuncoid, collation,
2347  &vardata1, &vardata2,
2348  nd1, nd2,
2349  isdefault1, isdefault2,
2350  &sslot1, &sslot2,
2351  stats1, stats2,
2352  have_mcvs1, have_mcvs2);
2353 
2354  switch (sjinfo->jointype)
2355  {
2356  case JOIN_INNER:
2357  case JOIN_LEFT:
2358  case JOIN_FULL:
2359  selec = selec_inner;
2360  break;
2361  case JOIN_SEMI:
2362  case JOIN_ANTI:
2363 
2364  /*
2365  * Look up the join's inner relation. min_righthand is sufficient
2366  * information because neither SEMI nor ANTI joins permit any
2367  * reassociation into or out of their RHS, so the righthand will
2368  * always be exactly that set of rels.
2369  */
2370  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2371 
2372  if (!join_is_reversed)
2373  selec = eqjoinsel_semi(opfuncoid, collation,
2374  &vardata1, &vardata2,
2375  nd1, nd2,
2376  isdefault1, isdefault2,
2377  &sslot1, &sslot2,
2378  stats1, stats2,
2379  have_mcvs1, have_mcvs2,
2380  inner_rel);
2381  else
2382  {
2383  Oid commop = get_commutator(operator);
2384  Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2385 
2386  selec = eqjoinsel_semi(commopfuncoid, collation,
2387  &vardata2, &vardata1,
2388  nd2, nd1,
2389  isdefault2, isdefault1,
2390  &sslot2, &sslot1,
2391  stats2, stats1,
2392  have_mcvs2, have_mcvs1,
2393  inner_rel);
2394  }
2395 
2396  /*
2397  * We should never estimate the output of a semijoin to be more
2398  * rows than we estimate for an inner join with the same input
2399  * rels and join condition; it's obviously impossible for that to
2400  * happen. The former estimate is N1 * Ssemi while the latter is
2401  * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2402  * this is worthwhile because of the shakier estimation rules we
2403  * use in eqjoinsel_semi, particularly in cases where it has to
2404  * punt entirely.
2405  */
2406  selec = Min(selec, inner_rel->rows * selec_inner);
2407  break;
2408  default:
2409  /* other values not expected here */
2410  elog(ERROR, "unrecognized join type: %d",
2411  (int) sjinfo->jointype);
2412  selec = 0; /* keep compiler quiet */
2413  break;
2414  }
2415 
2416  free_attstatsslot(&sslot1);
2417  free_attstatsslot(&sslot2);
2418 
2419  ReleaseVariableStats(vardata1);
2420  ReleaseVariableStats(vardata2);
2421 
2422  CLAMP_PROBABILITY(selec);
2423 
2424  PG_RETURN_FLOAT8((float8) selec);
2425 }
double float8
Definition: c.h:630
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:367
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define PG_GET_COLLATION()
Definition: fmgr.h:198
#define PG_GETARG_INT16(n)
Definition: fmgr.h:271
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1509
JoinType
Definition: nodes.h:288
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_LEFT
Definition: nodes.h:294
@ JOIN_ANTI
Definition: nodes.h:308
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:6436
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:2434
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:2631
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:5743
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4951
Cardinality rows
Definition: pathnodes.h:877
Relids min_righthand
Definition: pathnodes.h:2902
JoinType jointype
Definition: pathnodes.h:2905

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, root, RelOptInfo::rows, statistic_proc_security_check(), and VariableStatData::statsTuple.

Referenced by neqjoinsel().

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

2441 {
2442  double selec;
2443 
2444  if (have_mcvs1 && have_mcvs2)
2445  {
2446  /*
2447  * We have most-common-value lists for both relations. Run through
2448  * the lists to see which MCVs actually join to each other with the
2449  * given operator. This allows us to determine the exact join
2450  * selectivity for the portion of the relations represented by the MCV
2451  * lists. We still have to estimate for the remaining population, but
2452  * in a skewed distribution this gives us a big leg up in accuracy.
2453  * For motivation see the analysis in Y. Ioannidis and S.
2454  * Christodoulakis, "On the propagation of errors in the size of join
2455  * results", Technical Report 1018, Computer Science Dept., University
2456  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2457  */
2458  LOCAL_FCINFO(fcinfo, 2);
2459  FmgrInfo eqproc;
2460  bool *hasmatch1;
2461  bool *hasmatch2;
2462  double nullfrac1 = stats1->stanullfrac;
2463  double nullfrac2 = stats2->stanullfrac;
2464  double matchprodfreq,
2465  matchfreq1,
2466  matchfreq2,
2467  unmatchfreq1,
2468  unmatchfreq2,
2469  otherfreq1,
2470  otherfreq2,
2471  totalsel1,
2472  totalsel2;
2473  int i,
2474  nmatches;
2475 
2476  fmgr_info(opfuncoid, &eqproc);
2477 
2478  /*
2479  * Save a few cycles by setting up the fcinfo struct just once. Using
2480  * FunctionCallInvoke directly also avoids failure if the eqproc
2481  * returns NULL, though really equality functions should never do
2482  * that.
2483  */
2484  InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2485  NULL, NULL);
2486  fcinfo->args[0].isnull = false;
2487  fcinfo->args[1].isnull = false;
2488 
2489  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2490  hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2491 
2492  /*
2493  * Note we assume that each MCV will match at most one member of the
2494  * other MCV list. If the operator isn't really equality, there could
2495  * be multiple matches --- but we don't look for them, both for speed
2496  * and because the math wouldn't add up...
2497  */
2498  matchprodfreq = 0.0;
2499  nmatches = 0;
2500  for (i = 0; i < sslot1->nvalues; i++)
2501  {
2502  int j;
2503 
2504  fcinfo->args[0].value = sslot1->values[i];
2505 
2506  for (j = 0; j < sslot2->nvalues; j++)
2507  {
2508  Datum fresult;
2509 
2510  if (hasmatch2[j])
2511  continue;
2512  fcinfo->args[1].value = sslot2->values[j];
2513  fcinfo->isnull = false;
2514  fresult = FunctionCallInvoke(fcinfo);
2515  if (!fcinfo->isnull && DatumGetBool(fresult))
2516  {
2517  hasmatch1[i] = hasmatch2[j] = true;
2518  matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2519  nmatches++;
2520  break;
2521  }
2522  }
2523  }
2524  CLAMP_PROBABILITY(matchprodfreq);
2525  /* Sum up frequencies of matched and unmatched MCVs */
2526  matchfreq1 = unmatchfreq1 = 0.0;
2527  for (i = 0; i < sslot1->nvalues; i++)
2528  {
2529  if (hasmatch1[i])
2530  matchfreq1 += sslot1->numbers[i];
2531  else
2532  unmatchfreq1 += sslot1->numbers[i];
2533  }
2534  CLAMP_PROBABILITY(matchfreq1);
2535  CLAMP_PROBABILITY(unmatchfreq1);
2536  matchfreq2 = unmatchfreq2 = 0.0;
2537  for (i = 0; i < sslot2->nvalues; i++)
2538  {
2539  if (hasmatch2[i])
2540  matchfreq2 += sslot2->numbers[i];
2541  else
2542  unmatchfreq2 += sslot2->numbers[i];
2543  }
2544  CLAMP_PROBABILITY(matchfreq2);
2545  CLAMP_PROBABILITY(unmatchfreq2);
2546  pfree(hasmatch1);
2547  pfree(hasmatch2);
2548 
2549  /*
2550  * Compute total frequency of non-null values that are not in the MCV
2551  * lists.
2552  */
2553  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2554  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2555  CLAMP_PROBABILITY(otherfreq1);
2556  CLAMP_PROBABILITY(otherfreq2);
2557 
2558  /*
2559  * We can estimate the total selectivity from the point of view of
2560  * relation 1 as: the known selectivity for matched MCVs, plus
2561  * unmatched MCVs that are assumed to match against random members of
2562  * relation 2's non-MCV population, plus non-MCV values that are
2563  * assumed to match against random members of relation 2's unmatched
2564  * MCVs plus non-MCV values.
2565  */
2566  totalsel1 = matchprodfreq;
2567  if (nd2 > sslot2->nvalues)
2568  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2569  if (nd2 > nmatches)
2570  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2571  (nd2 - nmatches);
2572  /* Same estimate from the point of view of relation 2. */
2573  totalsel2 = matchprodfreq;
2574  if (nd1 > sslot1->nvalues)
2575  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2576  if (nd1 > nmatches)
2577  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2578  (nd1 - nmatches);
2579 
2580  /*
2581  * Use the smaller of the two estimates. This can be justified in
2582  * essentially the same terms as given below for the no-stats case: to
2583  * a first approximation, we are estimating from the point of view of
2584  * the relation with smaller nd.
2585  */
2586  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2587  }
2588  else
2589  {
2590  /*
2591  * We do not have MCV lists for both sides. Estimate the join
2592  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2593  * is plausible if we assume that the join operator is strict and the
2594  * non-null values are about equally distributed: a given non-null
2595  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2596  * of rel2, so total join rows are at most
2597  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2598  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2599  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2600  * with MIN() is an upper bound. Using the MIN() means we estimate
2601  * from the point of view of the relation with smaller nd (since the
2602  * larger nd is determining the MIN). It is reasonable to assume that
2603  * most tuples in this rel will have join partners, so the bound is
2604  * probably reasonably tight and should be taken as-is.
2605  *
2606  * XXX Can we be smarter if we have an MCV list for just one side? It
2607  * seems that if we assume equal distribution for the other side, we
2608  * end up with the same answer anyway.
2609  */
2610  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2611  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2612 
2613  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2614  if (nd1 > nd2)
2615  selec /= nd1;
2616  else
2617  selec /= nd2;
2618  }
2619 
2620  return selec;
2621 }
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
int j
Definition: isn.c:74
void * palloc0(Size size)
Definition: mcxt.c:1347
uintptr_t Datum
Definition: postgres.h:64
Definition: fmgr.h:57

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

Referenced by eqjoinsel().

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

2639 {
2640  double selec;
2641 
2642  /*
2643  * We clamp nd2 to be not more than what we estimate the inner relation's
2644  * size to be. This is intuitively somewhat reasonable since obviously
2645  * there can't be more than that many distinct values coming from the
2646  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2647  * likewise) is that this is the only pathway by which restriction clauses
2648  * applied to the inner rel will affect the join result size estimate,
2649  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2650  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2651  * the selectivity of outer-rel restrictions.
2652  *
2653  * We can apply this clamping both with respect to the base relation from
2654  * which the join variable comes (if there is just one), and to the
2655  * immediate inner input relation of the current join.
2656  *
2657  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2658  * great, maybe, but it didn't come out of nowhere either. This is most
2659  * helpful when the inner relation is empty and consequently has no stats.
2660  */
2661  if (vardata2->rel)
2662  {
2663  if (nd2 >= vardata2->rel->rows)
2664  {
2665  nd2 = vardata2->rel->rows;
2666  isdefault2 = false;
2667  }
2668  }
2669  if (nd2 >= inner_rel->rows)
2670  {
2671  nd2 = inner_rel->rows;
2672  isdefault2 = false;
2673  }
2674 
2675  if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2676  {
2677  /*
2678  * We have most-common-value lists for both relations. Run through
2679  * the lists to see which MCVs actually join to each other with the
2680  * given operator. This allows us to determine the exact join
2681  * selectivity for the portion of the relations represented by the MCV
2682  * lists. We still have to estimate for the remaining population, but
2683  * in a skewed distribution this gives us a big leg up in accuracy.
2684  */
2685  LOCAL_FCINFO(fcinfo, 2);
2686  FmgrInfo eqproc;
2687  bool *hasmatch1;
2688  bool *hasmatch2;
2689  double nullfrac1 = stats1->stanullfrac;
2690  double matchfreq1,
2691  uncertainfrac,
2692  uncertain;
2693  int i,
2694  nmatches,
2695  clamped_nvalues2;
2696 
2697  /*
2698  * The clamping above could have resulted in nd2 being less than
2699  * sslot2->nvalues; in which case, we assume that precisely the nd2
2700  * most common values in the relation will appear in the join input,
2701  * and so compare to only the first nd2 members of the MCV list. Of
2702  * course this is frequently wrong, but it's the best bet we can make.
2703  */
2704  clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2705 
2706  fmgr_info(opfuncoid, &eqproc);
2707 
2708  /*
2709  * Save a few cycles by setting up the fcinfo struct just once. Using
2710  * FunctionCallInvoke directly also avoids failure if the eqproc
2711  * returns NULL, though really equality functions should never do
2712  * that.
2713  */
2714  InitFunctionCallInfoData(*fcinfo, &eqproc, 2, collation,
2715  NULL, NULL);
2716  fcinfo->args[0].isnull = false;
2717  fcinfo->args[1].isnull = false;
2718 
2719  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2720  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2721 
2722  /*
2723  * Note we assume that each MCV will match at most one member of the
2724  * other MCV list. If the operator isn't really equality, there could
2725  * be multiple matches --- but we don't look for them, both for speed
2726  * and because the math wouldn't add up...
2727  */
2728  nmatches = 0;
2729  for (i = 0; i < sslot1->nvalues; i++)
2730  {
2731  int j;
2732 
2733  fcinfo->args[0].value = sslot1->values[i];
2734 
2735  for (j = 0; j < clamped_nvalues2; j++)
2736  {
2737  Datum fresult;
2738 
2739  if (hasmatch2[j])
2740  continue;
2741  fcinfo->args[1].value = sslot2->values[j];
2742  fcinfo->isnull = false;
2743  fresult = FunctionCallInvoke(fcinfo);
2744  if (!fcinfo->isnull && DatumGetBool(fresult))
2745  {
2746  hasmatch1[i] = hasmatch2[j] = true;
2747  nmatches++;
2748  break;
2749  }
2750  }
2751  }
2752  /* Sum up frequencies of matched MCVs */
2753  matchfreq1 = 0.0;
2754  for (i = 0; i < sslot1->nvalues; i++)
2755  {
2756  if (hasmatch1[i])
2757  matchfreq1 += sslot1->numbers[i];
2758  }
2759  CLAMP_PROBABILITY(matchfreq1);
2760  pfree(hasmatch1);
2761  pfree(hasmatch2);
2762 
2763  /*
2764  * Now we need to estimate the fraction of relation 1 that has at
2765  * least one join partner. We know for certain that the matched MCVs
2766  * do, so that gives us a lower bound, but we're really in the dark
2767  * about everything else. Our crude approach is: if nd1 <= nd2 then
2768  * assume all non-null rel1 rows have join partners, else assume for
2769  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2770  * can discount the known-matched MCVs from the distinct-values counts
2771  * before doing the division.
2772  *
2773  * Crude as the above is, it's completely useless if we don't have
2774  * reliable ndistinct values for both sides. Hence, if either nd1 or
2775  * nd2 is default, punt and assume half of the uncertain rows have
2776  * join partners.
2777  */
2778  if (!isdefault1 && !isdefault2)
2779  {
2780  nd1 -= nmatches;
2781  nd2 -= nmatches;
2782  if (nd1 <= nd2 || nd2 < 0)
2783  uncertainfrac = 1.0;
2784  else
2785  uncertainfrac = nd2 / nd1;
2786  }
2787  else
2788  uncertainfrac = 0.5;
2789  uncertain = 1.0 - matchfreq1 - nullfrac1;
2790  CLAMP_PROBABILITY(uncertain);
2791  selec = matchfreq1 + uncertainfrac * uncertain;
2792  }
2793  else
2794  {
2795  /*
2796  * Without MCV lists for both sides, we can only use the heuristic
2797  * about nd1 vs nd2.
2798  */
2799  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2800 
2801  if (!isdefault1 && !isdefault2)
2802  {
2803  if (nd1 <= nd2 || nd2 < 0)
2804  selec = 1.0 - nullfrac1;
2805  else
2806  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2807  }
2808  else
2809  selec = 0.5 * (1.0 - nullfrac1);
2810  }
2811 
2812  return selec;
2813 }

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

Referenced by eqjoinsel().

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 227 of file selfuncs.c.

228 {
229  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
230 }
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:236

References eqsel_internal(), and PG_RETURN_FLOAT8.

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

Definition at line 236 of file selfuncs.c.

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

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, root, var_eq_const(), and var_eq_non_const().

Referenced by eqsel(), and neqsel().

◆ estimate_array_length()

double estimate_array_length ( PlannerInfo root,
Node arrayexpr 
)

Definition at line 2136 of file selfuncs.c.

2137 {
2138  /* look through any binary-compatible relabeling of arrayexpr */
2139  arrayexpr = strip_array_coercion(arrayexpr);
2140 
2141  if (arrayexpr && IsA(arrayexpr, Const))
2142  {
2143  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2144  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2145  ArrayType *arrayval;
2146 
2147  if (arrayisnull)
2148  return 0;
2149  arrayval = DatumGetArrayTypeP(arraydatum);
2150  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2151  }
2152  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2153  !((ArrayExpr *) arrayexpr)->multidims)
2154  {
2155  return list_length(((ArrayExpr *) arrayexpr)->elements);
2156  }
2157  else if (arrayexpr)
2158  {
2159  /* See if we can find any statistics about it */
2160  VariableStatData vardata;
2161  AttStatsSlot sslot;
2162  double nelem = 0;
2163 
2164  examine_variable(root, arrayexpr, 0, &vardata);
2165  if (HeapTupleIsValid(vardata.statsTuple))
2166  {
2167  /*
2168  * Found stats, so use the average element count, which is stored
2169  * in the last stanumbers element of the DECHIST statistics.
2170  * Actually that is the average count of *distinct* elements;
2171  * perhaps we should scale it up somewhat?
2172  */
2173  if (get_attstatsslot(&sslot, vardata.statsTuple,
2174  STATISTIC_KIND_DECHIST, InvalidOid,
2176  {
2177  if (sslot.nnumbers > 0)
2178  nelem = clamp_row_est(sslot.numbers[sslot.nnumbers - 1]);
2179  free_attstatsslot(&sslot);
2180  }
2181  }
2182  ReleaseVariableStats(vardata);
2183 
2184  if (nelem > 0)
2185  return nelem;
2186  }
2187 
2188  /* Else use a default guess --- this should match scalararraysel */
2189  return 10;
2190 }
#define ARR_NDIM(a)
Definition: array.h:290
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_DIMS(a)
Definition: array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
double clamp_row_est(double nrows)
Definition: costsize.c:213
static int list_length(const List *l)
Definition: pg_list.h:152
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1783

References ARR_DIMS, ARR_NDIM, ArrayGetNItems(), ATTSTATSSLOT_NUMBERS, clamp_row_est(), DatumGetArrayTypeP, examine_variable(), free_attstatsslot(), get_attstatsslot(), HeapTupleIsValid, InvalidOid, IsA, list_length(), AttStatsSlot::nnumbers, AttStatsSlot::numbers, ReleaseVariableStats, root, VariableStatData::statsTuple, and strip_array_coercion().

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

◆ estimate_hash_bucket_stats()

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

Definition at line 3799 of file selfuncs.c.

3802 {
3803  VariableStatData vardata;
3804  double estfract,
3805  ndistinct,
3806  stanullfrac,
3807  avgfreq;
3808  bool isdefault;
3809  AttStatsSlot sslot;
3810 
3811  examine_variable(root, hashkey, 0, &vardata);
3812 
3813  /* Look up the frequency of the most common value, if available */
3814  *mcv_freq = 0.0;
3815 
3816  if (HeapTupleIsValid(vardata.statsTuple))
3817  {
3818  if (get_attstatsslot(&sslot, vardata.statsTuple,
3819  STATISTIC_KIND_MCV, InvalidOid,
3821  {
3822  /*
3823  * The first MCV stat is for the most common value.
3824  */
3825  if (sslot.nnumbers > 0)
3826  *mcv_freq = sslot.numbers[0];
3827  free_attstatsslot(&sslot);
3828  }
3829  }
3830 
3831  /* Get number of distinct values */
3832  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3833 
3834  /*
3835  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3836  * mcv_freq is known to be even higher than that, use it instead.
3837  */
3838  if (isdefault)
3839  {
3840  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3841  ReleaseVariableStats(vardata);
3842  return;
3843  }
3844 
3845  /* Get fraction that are null */
3846  if (HeapTupleIsValid(vardata.statsTuple))
3847  {
3848  Form_pg_statistic stats;
3849 
3850  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3851  stanullfrac = stats->stanullfrac;
3852  }
3853  else
3854  stanullfrac = 0.0;
3855 
3856  /* Compute avg freq of all distinct data values in raw relation */
3857  avgfreq = (1.0 - stanullfrac) / ndistinct;
3858 
3859  /*
3860  * Adjust ndistinct to account for restriction clauses. Observe we are
3861  * assuming that the data distribution is affected uniformly by the
3862  * restriction clauses!
3863  *
3864  * XXX Possibly better way, but much more expensive: multiply by
3865  * selectivity of rel's restriction clauses that mention the target Var.
3866  */
3867  if (vardata.rel && vardata.rel->tuples > 0)
3868  {
3869  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3870  ndistinct = clamp_row_est(ndistinct);
3871  }
3872 
3873  /*
3874  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3875  * number of buckets is less than the expected number of distinct values;
3876  * otherwise it is 1/ndistinct.
3877  */
3878  if (ndistinct > nbuckets)
3879  estfract = 1.0 / nbuckets;
3880  else
3881  estfract = 1.0 / ndistinct;
3882 
3883  /*
3884  * Adjust estimated bucketsize upward to account for skewed distribution.
3885  */
3886  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3887  estfract *= *mcv_freq / avgfreq;
3888 
3889  /*
3890  * Clamp bucketsize to sane range (the above adjustment could easily
3891  * produce an out-of-range result). We set the lower bound a little above
3892  * zero, since zero isn't a very sane result.
3893  */
3894  if (estfract < 1.0e-6)
3895  estfract = 1.0e-6;
3896  else if (estfract > 1.0)
3897  estfract = 1.0;
3898 
3899  *bucketsize_frac = (Selectivity) estfract;
3900 
3901  ReleaseVariableStats(vardata);
3902 }
Cardinality tuples
Definition: pathnodes.h:949

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, root, RelOptInfo::rows, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by final_cost_hashjoin().

◆ estimate_hashagg_tablesize()

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

Definition at line 3918 of file selfuncs.c.

3920 {
3921  Size hashentrysize;
3922 
3923  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
3924  path->pathtarget->width,
3925  agg_costs->transitionSpace);
3926 
3927  /*
3928  * Note that this disregards the effect of fill-factor and growth policy
3929  * of the hash table. That's probably ok, given that the default
3930  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3931  * "double-in-size" growth policies here.
3932  */
3933  return hashentrysize * dNumGroups;
3934 }
size_t Size
Definition: c.h:605
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1694
Size transitionSpace
Definition: pathnodes.h:62

References hash_agg_entry_size(), list_length(), root, and AggClauseCosts::transitionSpace.

Referenced by consider_groupingsets_paths().

◆ estimate_multivariate_ndistinct()

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

Definition at line 3955 of file selfuncs.c.

3957 {
3958  ListCell *lc;
3959  int nmatches_vars;
3960  int nmatches_exprs;
3961  Oid statOid = InvalidOid;
3962  MVNDistinct *stats;
3963  StatisticExtInfo *matched_info = NULL;
3964  RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
3965 
3966  /* bail out immediately if the table has no extended statistics */
3967  if (!rel->statlist)
3968  return false;
3969 
3970  /* look for the ndistinct statistics object matching the most vars */
3971  nmatches_vars = 0; /* we require at least two matches */
3972  nmatches_exprs = 0;
3973  foreach(lc, rel->statlist)
3974  {
3975  ListCell *lc2;
3976  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3977  int nshared_vars = 0;
3978  int nshared_exprs = 0;
3979 
3980  /* skip statistics of other kinds */
3981  if (info->kind != STATS_EXT_NDISTINCT)
3982  continue;
3983 
3984  /* skip statistics with mismatching stxdinherit value */
3985  if (info->inherit != rte->inh)
3986  continue;
3987 
3988  /*
3989  * Determine how many expressions (and variables in non-matched
3990  * expressions) match. We'll then use these numbers to pick the
3991  * statistics object that best matches the clauses.
3992  */
3993  foreach(lc2, *varinfos)
3994  {
3995  ListCell *lc3;
3996  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
3998 
3999  Assert(varinfo->rel == rel);
4000 
4001  /* simple Var, search in statistics keys directly */
4002  if (IsA(varinfo->var, Var))
4003  {
4004  attnum = ((Var *) varinfo->var)->varattno;
4005 
4006  /*
4007  * Ignore system attributes - we don't support statistics on
4008  * them, so can't match them (and it'd fail as the values are
4009  * negative).
4010  */
4012  continue;
4013 
4014  if (bms_is_member(attnum, info->keys))
4015  nshared_vars++;
4016 
4017  continue;
4018  }
4019 
4020  /* expression - see if it's in the statistics object */
4021  foreach(lc3, info->exprs)
4022  {
4023  Node *expr = (Node *) lfirst(lc3);
4024 
4025  if (equal(varinfo->var, expr))
4026  {
4027  nshared_exprs++;
4028  break;
4029  }
4030  }
4031  }
4032 
4033  if (nshared_vars + nshared_exprs < 2)
4034  continue;
4035 
4036  /*
4037  * Does this statistics object match more columns than the currently
4038  * best object? If so, use this one instead.
4039  *
4040  * XXX This should break ties using name of the object, or something
4041  * like that, to make the outcome stable.
4042  */
4043  if ((nshared_exprs > nmatches_exprs) ||
4044  (((nshared_exprs == nmatches_exprs)) && (nshared_vars > nmatches_vars)))
4045  {
4046  statOid = info->statOid;
4047  nmatches_vars = nshared_vars;
4048  nmatches_exprs = nshared_exprs;
4049  matched_info = info;
4050  }
4051  }
4052 
4053  /* No match? */
4054  if (statOid == InvalidOid)
4055  return false;
4056 
4057  Assert(nmatches_vars + nmatches_exprs > 1);
4058 
4059  stats = statext_ndistinct_load(statOid, rte->inh);
4060 
4061  /*
4062  * If we have a match, search it for the specific item that matches (there
4063  * must be one), and construct the output values.
4064  */
4065  if (stats)
4066  {
4067  int i;
4068  List *newlist = NIL;
4069  MVNDistinctItem *item = NULL;
4070  ListCell *lc2;
4071  Bitmapset *matched = NULL;
4072  AttrNumber attnum_offset;
4073 
4074  /*
4075  * How much we need to offset the attnums? If there are no
4076  * expressions, no offset is needed. Otherwise offset enough to move
4077  * the lowest one (which is equal to number of expressions) to 1.
4078  */
4079  if (matched_info->exprs)
4080  attnum_offset = (list_length(matched_info->exprs) + 1);
4081  else
4082  attnum_offset = 0;
4083 
4084  /* see what actually matched */
4085  foreach(lc2, *varinfos)
4086  {
4087  ListCell *lc3;
4088  int idx;
4089  bool found = false;
4090 
4091  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc2);
4092 
4093  /*
4094  * Process a simple Var expression, by matching it to keys
4095  * directly. If there's a matching expression, we'll try matching
4096  * it later.
4097  */
4098  if (IsA(varinfo->var, Var))
4099  {
4100  AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4101 
4102  /*
4103  * Ignore expressions on system attributes. Can't rely on the
4104  * bms check for negative values.
4105  */
4107  continue;
4108 
4109  /* Is the variable covered by the statistics object? */
4110  if (!bms_is_member(attnum, matched_info->keys))
4111  continue;
4112 
4113  attnum = attnum + attnum_offset;
4114 
4115  /* ensure sufficient offset */
4117 
4118  matched = bms_add_member(matched, attnum);
4119 
4120  found = true;
4121  }
4122 
4123  /*
4124  * XXX Maybe we should allow searching the expressions even if we
4125  * found an attribute matching the expression? That would handle
4126  * trivial expressions like "(a)" but it seems fairly useless.
4127  */
4128  if (found)
4129  continue;
4130 
4131  /* expression - see if it's in the statistics object */
4132  idx = 0;
4133  foreach(lc3, matched_info->exprs)
4134  {
4135  Node *expr = (Node *) lfirst(lc3);
4136 
4137  if (equal(varinfo->var, expr))
4138  {
4139  AttrNumber attnum = -(idx + 1);
4140 
4141  attnum = attnum + attnum_offset;
4142 
4143  /* ensure sufficient offset */
4145 
4146  matched = bms_add_member(matched, attnum);
4147 
4148  /* there should be just one matching expression */
4149  break;
4150  }
4151 
4152  idx++;
4153  }
4154  }
4155 
4156  /* Find the specific item that exactly matches the combination */
4157  for (i = 0; i < stats->nitems; i++)
4158  {
4159  int j;
4160  MVNDistinctItem *tmpitem = &stats->items[i];
4161 
4162  if (tmpitem->nattributes != bms_num_members(matched))
4163  continue;
4164 
4165  /* assume it's the right item */
4166  item = tmpitem;
4167 
4168  /* check that all item attributes/expressions fit the match */
4169  for (j = 0; j < tmpitem->nattributes; j++)
4170  {
4171  AttrNumber attnum = tmpitem->attributes[j];
4172 
4173  /*
4174  * Thanks to how we constructed the matched bitmap above, we
4175  * can just offset all attnums the same way.
4176  */
4177  attnum = attnum + attnum_offset;
4178 
4179  if (!bms_is_member(attnum, matched))
4180  {
4181  /* nah, it's not this item */
4182  item = NULL;
4183  break;
4184  }
4185  }
4186 
4187  /*
4188  * If the item has all the matched attributes, we know it's the
4189  * right one - there can't be a better one. matching more.
4190  */
4191  if (item)
4192  break;
4193  }
4194 
4195  /*
4196  * Make sure we found an item. There has to be one, because ndistinct
4197  * statistics includes all combinations of attributes.
4198  */
4199  if (!item)
4200  elog(ERROR, "corrupt MVNDistinct entry");
4201 
4202  /* Form the output varinfo list, keeping only unmatched ones */
4203  foreach(lc, *varinfos)
4204  {
4205  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
4206  ListCell *lc3;
4207  bool found = false;
4208 
4209  /*
4210  * Let's look at plain variables first, because it's the most
4211  * common case and the check is quite cheap. We can simply get the
4212  * attnum and check (with an offset) matched bitmap.
4213  */
4214  if (IsA(varinfo->var, Var))
4215  {
4216  AttrNumber attnum = ((Var *) varinfo->var)->varattno;
4217 
4218  /*
4219  * If it's a system attribute, we're done. We don't support
4220  * extended statistics on system attributes, so it's clearly
4221  * not matched. Just keep the expression and continue.
4222  */
4224  {
4225  newlist = lappend(newlist, varinfo);
4226  continue;
4227  }
4228 
4229  /* apply the same offset as above */
4230  attnum += attnum_offset;
4231 
4232  /* if it's not matched, keep the varinfo */
4233  if (!bms_is_member(attnum, matched))
4234  newlist = lappend(newlist, varinfo);
4235 
4236  /* The rest of the loop deals with complex expressions. */
4237  continue;
4238  }
4239 
4240  /*
4241  * Process complex expressions, not just simple Vars.
4242  *
4243  * First, we search for an exact match of an expression. If we
4244  * find one, we can just discard the whole GroupVarInfo, with all
4245  * the variables we extracted from it.
4246  *
4247  * Otherwise we inspect the individual vars, and try matching it
4248  * to variables in the item.
4249  */
4250  foreach(lc3, matched_info->exprs)
4251  {
4252  Node *expr = (Node *) lfirst(lc3);
4253 
4254  if (equal(varinfo->var, expr))
4255  {
4256  found = true;
4257  break;
4258  }
4259  }
4260 
4261  /* found exact match, skip */
4262  if (found)
4263  continue;
4264 
4265  newlist = lappend(newlist, varinfo);
4266  }
4267 
4268  *varinfos = newlist;
4269  *ndistinct = item->ndistinct;
4270  return true;
4271  }
4272 
4273  return false;
4274 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
MVNDistinct * statext_ndistinct_load(Oid mvoid, bool inh)
Definition: mvdistinct.c:148
double ndistinct
Definition: statistics.h:28
AttrNumber * attributes
Definition: statistics.h:30
uint32 nitems
Definition: statistics.h:38
MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:39
List * statlist
Definition: pathnodes.h:946
Bitmapset * keys
Definition: pathnodes.h:1289
Definition: primnodes.h:248

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

Referenced by estimate_num_groups().

◆ estimate_num_groups()

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

Definition at line 3417 of file selfuncs.c.

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

References add_unique_group_var(), Assert, clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), expression_returns_set_rows(), exprType(), EstimationInfo::flags, for_each_from, HeapTupleIsValid, i, IS_SIMPLE_REL, GroupVarInfo::isdefault, VariableStatData::isunique, lappend(), lfirst, linitial, list_member_int(), GroupVarInfo::ndistinct, NIL, pull_var_clause(), PVC_RECURSE_AGGREGATES, PVC_RECURSE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, GroupVarInfo::rel, ReleaseVariableStats, root, RelOptInfo::rows, SELFLAG_USED_DEFAULT, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by adjust_rowcount_for_semijoins(), build_setop_child_paths(), cost_incremental_sort(), cost_memoize_rescan(), create_final_distinct_paths(), create_partial_distinct_paths(), create_unique_path(), estimate_path_cost_size(), get_number_of_groups(), and get_windowclause_startup_tuples().

◆ examine_simple_variable()

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

Definition at line 5414 of file selfuncs.c.

5416 {
5417  RangeTblEntry *rte = root->simple_rte_array[var->varno];
5418 
5419  Assert(IsA(rte, RangeTblEntry));
5420 
5422  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
5423  {
5424  /*
5425  * The hook took control of acquiring a stats tuple. If it did supply
5426  * a tuple, it'd better have supplied a freefunc.
5427  */
5428  if (HeapTupleIsValid(vardata->statsTuple) &&
5429  !vardata->freefunc)
5430  elog(ERROR, "no function provided to release variable stats with");
5431  }
5432  else if (rte->rtekind == RTE_RELATION)
5433  {
5434  /*
5435  * Plain table or parent of an inheritance appendrel, so look up the
5436  * column in pg_statistic
5437  */
5438  vardata->statsTuple = SearchSysCache3(STATRELATTINH,
5439  ObjectIdGetDatum(rte->relid),
5440  Int16GetDatum(var->varattno),
5441  BoolGetDatum(rte->inh));
5442  vardata->freefunc = ReleaseSysCache;
5443 
5444  if (HeapTupleIsValid(vardata->statsTuple))
5445  {
5446  RelOptInfo *onerel = find_base_rel_noerr(root, var->varno);
5447  Oid userid;
5448 
5449  /*
5450  * Check if user has permission to read this column. We require
5451  * all rows to be accessible, so there must be no securityQuals
5452  * from security barrier views or RLS policies.
5453  *
5454  * Normally the Var will have an associated RelOptInfo from which
5455  * we can find out which userid to do the check as; but it might
5456  * not if it's a RETURNING Var for an INSERT target relation. In
5457  * that case use the RTEPermissionInfo associated with the RTE.
5458  */
5459  if (onerel)
5460  userid = onerel->userid;
5461  else
5462  {
5463  RTEPermissionInfo *perminfo;
5464 
5465  perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
5466  userid = perminfo->checkAsUser;
5467  }
5468  if (!OidIsValid(userid))
5469  userid = GetUserId();
5470 
5471  vardata->acl_ok =
5472  rte->securityQuals == NIL &&
5473  ((pg_class_aclcheck(rte->relid, userid,
5474  ACL_SELECT) == ACLCHECK_OK) ||
5475  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
5476  ACL_SELECT) == ACLCHECK_OK));
5477 
5478  /*
5479  * If the user doesn't have permissions to access an inheritance
5480  * child relation or specifically this attribute, check the
5481  * permissions of the table/column actually mentioned in the
5482  * query, since most likely the user does have that permission
5483  * (else the query will fail at runtime), and if the user can read
5484  * the column there then he can get the values of the child table
5485  * too. To do that, we must find out which of the root parent's
5486  * attributes the child relation's attribute corresponds to.
5487  */
5488  if (!vardata->acl_ok && var->varattno > 0 &&
5489  root->append_rel_array != NULL)
5490  {
5491  AppendRelInfo *appinfo;
5492  Index varno = var->varno;
5493  int varattno = var->varattno;
5494  bool found = false;
5495 
5496  appinfo = root->append_rel_array[varno];
5497 
5498  /*
5499  * Partitions are mapped to their immediate parent, not the
5500  * root parent, so must be ready to walk up multiple
5501  * AppendRelInfos. But stop if we hit a parent that is not
5502  * RTE_RELATION --- that's a flattened UNION ALL subquery, not
5503  * an inheritance parent.
5504  */
5505  while (appinfo &&
5506  planner_rt_fetch(appinfo->parent_relid,
5507  root)->rtekind == RTE_RELATION)
5508  {
5509  int parent_varattno;
5510 
5511  found = false;
5512  if (varattno <= 0 || varattno > appinfo->num_child_cols)
5513  break; /* safety check */
5514  parent_varattno = appinfo->parent_colnos[varattno - 1];
5515  if (parent_varattno == 0)
5516  break; /* Var is local to child */
5517 
5518  varno = appinfo->parent_relid;
5519  varattno = parent_varattno;
5520  found = true;
5521 
5522  /* If the parent is itself a child, continue up. */
5523  appinfo = root->append_rel_array[varno];
5524  }
5525 
5526  /*
5527  * In rare cases, the Var may be local to the child table, in
5528  * which case, we've got to live with having no access to this
5529  * column's stats.
5530  */
5531  if (!found)
5532  return;
5533 
5534  /* Repeat the access check on this parent rel & column */
5535  rte = planner_rt_fetch(varno, root);
5536  Assert(rte->rtekind == RTE_RELATION);
5537 
5538  /*
5539  * Fine to use the same userid as it's the same in all
5540  * relations of a given inheritance tree.
5541  */
5542  vardata->acl_ok =
5543  rte->securityQuals == NIL &&
5544  ((pg_class_aclcheck(rte->relid, userid,
5545  ACL_SELECT) == ACLCHECK_OK) ||
5546  (pg_attribute_aclcheck(rte->relid, varattno, userid,
5547  ACL_SELECT) == ACLCHECK_OK));
5548  }
5549  }
5550  else
5551  {
5552  /* suppress any possible leakproofness checks later */
5553  vardata->acl_ok = true;
5554  }
5555  }
5556  else if ((rte->rtekind == RTE_SUBQUERY && !rte->inh) ||
5557  (rte->rtekind == RTE_CTE && !rte->self_reference))
5558  {
5559  /*
5560  * Plain subquery (not one that was converted to an appendrel) or
5561  * non-recursive CTE. In either case, we can try to find out what the
5562  * Var refers to within the subquery. We skip this for appendrel and
5563  * recursive-CTE cases because any column stats we did find would
5564  * likely not be very relevant.
5565  */
5566  PlannerInfo *subroot;
5567  Query *subquery;
5568  List *subtlist;
5569  TargetEntry *ste;
5570 
5571  /*
5572  * Punt if it's a whole-row var rather than a plain column reference.
5573  */
5574  if (var->varattno == InvalidAttrNumber)
5575  return;
5576 
5577  /*
5578  * Otherwise, find the subquery's planner subroot.
5579  */
5580  if (rte->rtekind == RTE_SUBQUERY)
5581  {
5582  RelOptInfo *rel;
5583 
5584  /*
5585  * Fetch RelOptInfo for subquery. Note that we don't change the
5586  * rel returned in vardata, since caller expects it to be a rel of
5587  * the caller's query level. Because we might already be
5588  * recursing, we can't use that rel pointer either, but have to
5589  * look up the Var's rel afresh.
5590  */
5591  rel = find_base_rel(root, var->varno);
5592 
5593  subroot = rel->subroot;
5594  }
5595  else
5596  {
5597  /* CTE case is more difficult */
5598  PlannerInfo *cteroot;
5599  Index levelsup;
5600  int ndx;
5601  int plan_id;
5602  ListCell *lc;
5603 
5604  /*
5605  * Find the referenced CTE, and locate the subroot previously made
5606  * for it.
5607  */
5608  levelsup = rte->ctelevelsup;
5609  cteroot = root;
5610  while (levelsup-- > 0)
5611  {
5612  cteroot = cteroot->parent_root;
5613  if (!cteroot) /* shouldn't happen */
5614  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
5615  }
5616 
5617  /*
5618  * Note: cte_plan_ids can be shorter than cteList, if we are still
5619  * working on planning the CTEs (ie, this is a side-reference from
5620  * another CTE). So we mustn't use forboth here.
5621  */
5622  ndx = 0;
5623  foreach(lc, cteroot->parse->cteList)
5624  {
5625  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
5626 
5627  if (strcmp(cte->ctename, rte->ctename) == 0)
5628  break;
5629  ndx++;
5630  }
5631  if (lc == NULL) /* shouldn't happen */
5632  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
5633  if (ndx >= list_length(cteroot->cte_plan_ids))
5634  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
5635  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
5636  if (plan_id <= 0)
5637  elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
5638  subroot = list_nth(root->glob->subroots, plan_id - 1);
5639  }
5640 
5641  /* If the subquery hasn't been planned yet, we have to punt */
5642  if (subroot == NULL)
5643  return;
5644  Assert(IsA(subroot, PlannerInfo));
5645 
5646  /*
5647  * We must use the subquery parsetree as mangled by the planner, not
5648  * the raw version from the RTE, because we need a Var that will refer
5649  * to the subroot's live RelOptInfos. For instance, if any subquery
5650  * pullup happened during planning, Vars in the targetlist might have
5651  * gotten replaced, and we need to see the replacement expressions.
5652  */
5653  subquery = subroot->parse;
5654  Assert(IsA(subquery, Query));
5655 
5656  /*
5657  * Punt if subquery uses set operations or GROUP BY, as these will
5658  * mash underlying columns' stats beyond recognition. (Set ops are
5659  * particularly nasty; if we forged ahead, we would return stats
5660  * relevant to only the leftmost subselect...) DISTINCT is also
5661  * problematic, but we check that later because there is a possibility
5662  * of learning something even with it.
5663  */
5664  if (subquery->setOperations ||
5665  subquery->groupClause ||
5666  subquery->groupingSets)
5667  return;
5668 
5669  /* Get the subquery output expression referenced by the upper Var */
5670  if (subquery->returningList)
5671  subtlist = subquery->returningList;
5672  else
5673  subtlist = subquery->targetList;
5674  ste = get_tle_by_resno(subtlist, var->varattno);
5675  if (ste == NULL || ste->resjunk)
5676  elog(ERROR, "subquery %s does not have attribute %d",
5677  rte->eref->aliasname, var->varattno);
5678  var = (Var *) ste->expr;
5679 
5680  /*
5681  * If subquery uses DISTINCT, we can't make use of any stats for the
5682  * variable ... but, if it's the only DISTINCT column, we are entitled
5683  * to consider it unique. We do the test this way so that it works
5684  * for cases involving DISTINCT ON.
5685  */
5686  if (subquery->distinctClause)
5687  {
5688  if (list_length(subquery->distinctClause) == 1 &&
5689  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
5690  vardata->isunique = true;
5691  /* cannot go further */
5692  return;
5693  }
5694 
5695  /*
5696  * If the sub-query originated from a view with the security_barrier
5697  * attribute, we must not look at the variable's statistics, though it
5698  * seems all right to notice the existence of a DISTINCT clause. So
5699  * stop here.
5700  *
5701  * This is probably a harsher restriction than necessary; it's
5702  * certainly OK for the selectivity estimator (which is a C function,
5703  * and therefore omnipotent anyway) to look at the statistics. But
5704  * many selectivity estimators will happily *invoke the operator
5705  * function* to try to work out a good estimate - and that's not OK.
5706  * So for now, don't dig down for stats.
5707  */
5708  if (rte->security_barrier)
5709  return;
5710 
5711  /* Can only handle a simple Var of subquery's query level */
5712  if (var && IsA(var, Var) &&
5713  var->varlevelsup == 0)
5714  {
5715  /*
5716  * OK, recurse into the subquery. Note that the original setting
5717  * of vardata->isunique (which will surely be false) is left
5718  * unchanged in this situation. That's what we want, since even
5719  * if the underlying column is unique, the subquery may have
5720  * joined to other tables in a way that creates duplicates.
5721  */
5722  examine_simple_variable(subroot, var, vardata);
5723  }
5724  }
5725  else
5726  {
5727  /*
5728  * Otherwise, the Var comes from a FUNCTION or VALUES RTE. (We won't
5729  * see RTE_JOIN here because join alias Vars have already been
5730  * flattened.) There's not much we can do with function outputs, but
5731  * maybe someday try to be smarter about VALUES.
5732  */
5733  }
5734 }
@ ACLCHECK_OK
Definition: acl.h:183
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:3918
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4089
#define InvalidAttrNumber
Definition: attnum.h:23
unsigned int Index
Definition: c.h:614
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Oid GetUserId(void)
Definition: miscinit.c:514
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
@ RTE_CTE
Definition: parsenodes.h:1023
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
#define ACL_SELECT
Definition: parsenodes.h:77
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:310
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:414
RelOptInfo * find_base_rel_noerr(PlannerInfo *root, int relid)
Definition: relnode.c:436
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:5414
Index parent_relid
Definition: pathnodes.h:2976
int num_child_cols
Definition: pathnodes.h:3012
List * cte_plan_ids
Definition: pathnodes.h:305
Query * parse
Definition: pathnodes.h:202
List * returningList
Definition: parsenodes.h:200
Node * setOperations
Definition: parsenodes.h:221
List * cteList
Definition: parsenodes.h:168
List * groupClause
Definition: parsenodes.h:202
List * targetList
Definition: parsenodes.h:193
List * groupingSets
Definition: parsenodes.h:205
List * distinctClause
Definition: parsenodes.h:211
char * ctename
Definition: parsenodes.h:1196
Index ctelevelsup
Definition: parsenodes.h:1198
Oid userid
Definition: pathnodes.h:966
PlannerInfo * subroot
Definition: pathnodes.h:953
Expr * expr
Definition: primnodes.h:2186
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, Assert, BoolGetDatum(), RTEPermissionInfo::checkAsUser, PlannerInfo::cte_plan_ids, RangeTblEntry::ctelevelsup, Query::cteList, RangeTblEntry::ctename, CommonTableExpr::ctename, Query::distinctClause, elog, ERROR, TargetEntry::expr, find_base_rel(), find_base_rel_noerr(), VariableStatData::freefunc, get_relation_stats_hook, get_tle_by_resno(), getRTEPermissionInfo(), GetUserId(), Query::groupClause, Query::groupingSets, HeapTupleIsValid, if(), RangeTblEntry::inh, Int16GetDatum(), InvalidAttrNumber, InvalidOid, IsA, VariableStatData::isunique, lfirst, list_length(), list_nth(), list_nth_int(), NIL, AppendRelInfo::num_child_cols, ObjectIdGetDatum(), OidIsValid, AppendRelInfo::parent_relid, PlannerInfo::parse, pg_attribute_aclcheck(), pg_class_aclcheck(), planner_rt_fetch, ReleaseSysCache(), RangeTblEntry::relid, Query::returningList, root, RTE_CTE, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, SearchSysCache3(), Query::setOperations, VariableStatData::statsTuple, RelOptInfo::subroot, targetIsInSortList(), Query::targetList, RelOptInfo::userid, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by examine_variable().

◆ examine_variable()

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

Definition at line 5020 of file selfuncs.c.

5022 {
5023  Node *basenode;
5024  Relids varnos;
5025  RelOptInfo *onerel;
5026 
5027  /* Make sure we don't return dangling pointers in vardata */
5028  MemSet(vardata, 0, sizeof(VariableStatData));
5029 
5030  /* Save the exposed type of the expression */
5031  vardata->vartype = exprType(node);
5032 
5033  /* Look inside any binary-compatible relabeling */
5034 
5035  if (IsA(node, RelabelType))
5036  basenode = (Node *) ((RelabelType *) node)->arg;
5037  else
5038  basenode = node;
5039 
5040  /* Fast path for a simple Var */
5041 
5042  if (IsA(basenode, Var) &&
5043  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
5044  {
5045  Var *var = (Var *) basenode;
5046 
5047  /* Set up result fields other than the stats tuple */
5048  vardata->var = basenode; /* return Var without relabeling */
5049  vardata->rel = find_base_rel(root, var->varno);
5050  vardata->atttype = var->vartype;
5051  vardata->atttypmod = var->vartypmod;
5052  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
5053 
5054  /* Try to locate some stats */
5055  examine_simple_variable(root, var, vardata);
5056 
5057  return;
5058  }
5059 
5060  /*
5061  * Okay, it's a more complicated expression. Determine variable
5062  * membership. Note that when varRelid isn't zero, only vars of that
5063  * relation are considered "real" vars.
5064  */
5065  varnos = pull_varnos(root, basenode);
5066 
5067  onerel = NULL;
5068 
5069  if (bms_is_empty(varnos))
5070  {
5071  /* No Vars at all ... must be pseudo-constant clause */
5072  }
5073  else
5074  {
5075  int relid;
5076 
5077  if (bms_get_singleton_member(varnos, &relid))
5078  {
5079  if (varRelid == 0 || varRelid == relid)
5080  {
5081  onerel = find_base_rel(root, relid);
5082  vardata->rel = onerel;
5083  node = basenode; /* strip any relabeling */
5084  }
5085  /* else treat it as a constant */
5086  }
5087  else
5088  {
5089  /* varnos has multiple relids */
5090  if (varRelid == 0)
5091  {
5092  /* treat it as a variable of a join relation */
5093  vardata->rel = find_join_rel(root, varnos);
5094  node = basenode; /* strip any relabeling */
5095  }
5096  else if (bms_is_member(varRelid, varnos))
5097  {
5098  /* ignore the vars belonging to other relations */
5099  vardata->rel = find_base_rel(root, varRelid);
5100  node = basenode; /* strip any relabeling */
5101  /* note: no point in expressional-index search here */
5102  }
5103  /* else treat it as a constant */
5104  }
5105  }
5106 
5107  bms_free(varnos);
5108 
5109  vardata->var = node;
5110  vardata->atttype = exprType(node);
5111  vardata->atttypmod = exprTypmod(node);
5112 
5113  if (onerel)
5114  {
5115  /*
5116  * We have an expression in vars of a single relation. Try to match
5117  * it to expressional index columns, in hopes of finding some
5118  * statistics.
5119  *
5120  * Note that we consider all index columns including INCLUDE columns,
5121  * since there could be stats for such columns. But the test for
5122  * uniqueness needs to be warier.
5123  *
5124  * XXX it's conceivable that there are multiple matches with different
5125  * index opfamilies; if so, we need to pick one that matches the
5126  * operator we are estimating for. FIXME later.
5127  */
5128  ListCell *ilist;
5129  ListCell *slist;
5130  Oid userid;
5131 
5132  /*
5133  * Determine the user ID to use for privilege checks: either
5134  * onerel->userid if it's set (e.g., in case we're accessing the table
5135  * via a view), or the current user otherwise.
5136  *
5137  * If we drill down to child relations, we keep using the same userid:
5138  * it's going to be the same anyway, due to how we set up the relation
5139  * tree (q.v. build_simple_rel).
5140  */
5141  userid = OidIsValid(onerel->userid) ? onerel->userid : GetUserId();
5142 
5143  foreach(ilist, onerel->indexlist)
5144  {
5145  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
5146  ListCell *indexpr_item;
5147  int pos;
5148 
5149  indexpr_item = list_head(index->indexprs);
5150  if (indexpr_item == NULL)
5151  continue; /* no expressions here... */
5152 
5153  for (pos = 0; pos < index->ncolumns; pos++)
5154  {
5155  if (index->indexkeys[pos] == 0)
5156  {
5157  Node *indexkey;
5158 
5159  if (indexpr_item == NULL)
5160  elog(ERROR, "too few entries in indexprs list");
5161  indexkey = (Node *) lfirst(indexpr_item);
5162  if (indexkey && IsA(indexkey, RelabelType))
5163  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5164  if (equal(node, indexkey))
5165  {
5166  /*
5167  * Found a match ... is it a unique index? Tests here
5168  * should match has_unique_index().
5169  */
5170  if (index->unique &&
5171  index->nkeycolumns == 1 &&
5172  pos == 0 &&
5173  (index->indpred == NIL || index->predOK))
5174  vardata->isunique = true;
5175 
5176  /*
5177  * Has it got stats? We only consider stats for
5178  * non-partial indexes, since partial indexes probably
5179  * don't reflect whole-relation statistics; the above
5180  * check for uniqueness is the only info we take from
5181  * a partial index.
5182  *
5183  * An index stats hook, however, must make its own
5184  * decisions about what to do with partial indexes.
5185  */
5187  (*get_index_stats_hook) (root, index->indexoid,
5188  pos + 1, vardata))
5189  {
5190  /*
5191  * The hook took control of acquiring a stats
5192  * tuple. If it did supply a tuple, it'd better
5193  * have supplied a freefunc.
5194  */
5195  if (HeapTupleIsValid(vardata->statsTuple) &&
5196  !vardata->freefunc)
5197  elog(ERROR, "no function provided to release variable stats with");
5198  }
5199  else if (index->indpred == NIL)
5200  {
5201  vardata->statsTuple =
5202  SearchSysCache3(STATRELATTINH,
5203  ObjectIdGetDatum(index->indexoid),
5204  Int16GetDatum(pos + 1),
5205  BoolGetDatum(false));
5206  vardata->freefunc = ReleaseSysCache;
5207 
5208  if (HeapTupleIsValid(vardata->statsTuple))
5209  {
5210  /* Get index's table for permission check */
5211  RangeTblEntry *rte;
5212 
5213  rte = planner_rt_fetch(index->rel->relid, root);
5214  Assert(rte->rtekind == RTE_RELATION);
5215 
5216  /*
5217  * For simplicity, we insist on the whole
5218  * table being selectable, rather than trying
5219  * to identify which column(s) the index
5220  * depends on. Also require all rows to be
5221  * selectable --- there must be no
5222  * securityQuals from security barrier views
5223  * or RLS policies.
5224  */
5225  vardata->acl_ok =
5226  rte->securityQuals == NIL &&
5227  (pg_class_aclcheck(rte->relid, userid,
5228  ACL_SELECT) == ACLCHECK_OK);
5229 
5230  /*
5231  * If the user doesn't have permissions to
5232  * access an inheritance child relation, check
5233  * the permissions of the table actually
5234  * mentioned in the query, since most likely
5235  * the user does have that permission. Note
5236  * that whole-table select privilege on the
5237  * parent doesn't quite guarantee that the
5238  * user could read all columns of the child.
5239  * But in practice it's unlikely that any
5240  * interesting security violation could result
5241  * from allowing access to the expression
5242  * index's stats, so we allow it anyway. See
5243  * similar code in examine_simple_variable()
5244  * for additional comments.
5245  */
5246  if (!vardata->acl_ok &&
5247  root->append_rel_array != NULL)
5248  {
5249  AppendRelInfo *appinfo;
5250  Index varno = index->rel->relid;
5251 
5252  appinfo = root->append_rel_array[varno];
5253  while (appinfo &&
5254  planner_rt_fetch(appinfo->parent_relid,
5255  root)->rtekind == RTE_RELATION)
5256  {
5257  varno = appinfo->parent_relid;
5258  appinfo = root->append_rel_array[varno];
5259  }
5260  if (varno != index->rel->relid)
5261  {
5262  /* Repeat access check on this rel */
5263  rte = planner_rt_fetch(varno, root);
5264  Assert(rte->rtekind == RTE_RELATION);
5265 
5266  vardata->acl_ok =
5267  rte->securityQuals == NIL &&
5268  (pg_class_aclcheck(rte->relid,
5269  userid,
5270  ACL_SELECT) == ACLCHECK_OK);
5271  }
5272  }
5273  }
5274  else
5275  {
5276  /* suppress leakproofness checks later */
5277  vardata->acl_ok = true;
5278  }
5279  }
5280  if (vardata->statsTuple)
5281  break;
5282  }
5283  indexpr_item = lnext(index->indexprs, indexpr_item);
5284  }
5285  }
5286  if (vardata->statsTuple)
5287  break;
5288  }
5289 
5290  /*
5291  * Search extended statistics for one with a matching expression.
5292  * There might be multiple ones, so just grab the first one. In the
5293  * future, we might consider the statistics target (and pick the most
5294  * accurate statistics) and maybe some other parameters.
5295  */
5296  foreach(slist, onerel->statlist)
5297  {
5298  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(slist);
5299  RangeTblEntry *rte = planner_rt_fetch(onerel->relid, root);
5300  ListCell *expr_item;
5301  int pos;
5302 
5303  /*
5304  * Stop once we've found statistics for the expression (either
5305  * from extended stats, or for an index in the preceding loop).
5306  */
5307  if (vardata->statsTuple)
5308  break;
5309 
5310  /* skip stats without per-expression stats */
5311  if (info->kind != STATS_EXT_EXPRESSIONS)
5312  continue;
5313 
5314  /* skip stats with mismatching stxdinherit value */
5315  if (info->inherit != rte->inh)
5316  continue;
5317 
5318  pos = 0;
5319  foreach(expr_item, info->exprs)
5320  {
5321  Node *expr = (Node *) lfirst(expr_item);
5322 
5323  Assert(expr);
5324 
5325  /* strip RelabelType before comparing it */
5326  if (expr && IsA(expr, RelabelType))
5327  expr = (Node *) ((RelabelType *) expr)->arg;
5328 
5329  /* found a match, see if we can extract pg_statistic row */
5330  if (equal(node, expr))
5331  {
5332  /*
5333  * XXX Not sure if we should cache the tuple somewhere.
5334  * Now we just create a new copy every time.
5335  */
5336  vardata->statsTuple =
5337  statext_expressions_load(info->statOid, rte->inh, pos);
5338 
5339  vardata->freefunc = ReleaseDummy;
5340 
5341  /*
5342  * For simplicity, we insist on the whole table being
5343  * selectable, rather than trying to identify which
5344  * column(s) the statistics object depends on. Also
5345  * require all rows to be selectable --- there must be no
5346  * securityQuals from security barrier views or RLS
5347  * policies.
5348  */
5349  vardata->acl_ok =
5350  rte->securityQuals == NIL &&
5351  (pg_class_aclcheck(rte->relid, userid,
5352  ACL_SELECT) == ACLCHECK_OK);
5353 
5354  /*
5355  * If the user doesn't have permissions to access an
5356  * inheritance child relation, check the permissions of
5357  * the table actually mentioned in the query, since most
5358  * likely the user does have that permission. Note that
5359  * whole-table select privilege on the parent doesn't
5360  * quite guarantee that the user could read all columns of
5361  * the child. But in practice it's unlikely that any
5362  * interesting security violation could result from
5363  * allowing access to the expression stats, so we allow it
5364  * anyway. See similar code in examine_simple_variable()
5365  * for additional comments.
5366  */
5367  if (!vardata->acl_ok &&
5368  root->append_rel_array != NULL)
5369  {
5370  AppendRelInfo *appinfo;
5371  Index varno = onerel->relid;
5372 
5373  appinfo = root->append_rel_array[varno];
5374  while (appinfo &&
5375  planner_rt_fetch(appinfo->parent_relid,
5376  root)->rtekind == RTE_RELATION)
5377  {
5378  varno = appinfo->parent_relid;
5379  appinfo = root->append_rel_array[varno];
5380  }
5381  if (varno != onerel->relid)
5382  {
5383  /* Repeat access check on this rel */
5384  rte = planner_rt_fetch(varno, root);
5385  Assert(rte->rtekind == RTE_RELATION);
5386 
5387  vardata->acl_ok =
5388  rte->securityQuals == NIL &&
5389  (pg_class_aclcheck(rte->relid,
5390  userid,
5391  ACL_SELECT) == ACLCHECK_OK);
5392  }
5393  }
5394 
5395  break;
5396  }
5397 
5398  pos++;
5399  }
5400  }
5401  }
5402 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:715
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define MemSet(start, val, len)
Definition: c.h:1020
HeapTuple statext_expressions_load(Oid stxoid, bool inh, int idx)
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2207
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:527
static void ReleaseDummy(HeapTuple tuple)
Definition: selfuncs.c:4979
List * indexlist
Definition: pathnodes.h:944
int32 atttypmod
Definition: selfuncs.h:94
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:113

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, arg, Assert, VariableStatData::atttype, VariableStatData::atttypmod, bms_free(), bms_get_singleton_member(), bms_is_empty, bms_is_member(), BoolGetDatum(), elog, equal(), ERROR, examine_simple_variable(), StatisticExtInfo::exprs, exprType(), exprTypmod(), find_base_rel(), find_join_rel(), VariableStatData::freefunc, get_index_stats_hook, GetUserId(), has_unique_index(), HeapTupleIsValid, if(), RelOptInfo::indexlist, RangeTblEntry::inh, StatisticExtInfo::inherit, Int16GetDatum(), IsA, VariableStatData::isunique, StatisticExtInfo::kind, lfirst, list_head(), lnext(), MemSet, NIL, ObjectIdGetDatum(), OidIsValid, AppendRelInfo::parent_relid, pg_class_aclcheck(), planner_rt_fetch, pull_varnos(), VariableStatData::rel, ReleaseDummy(), ReleaseSysCache(), RangeTblEntry::relid, RelOptInfo::relid, root, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), statext_expressions_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, VariableStatData::statsTuple, RelOptInfo::userid, VariableStatData::var, Var::varattno, Var::varno, and VariableStatData::vartype.

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

◆ find_join_input_rel()

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

Definition at line 6436 of file selfuncs.c.

6437 {
6438  RelOptInfo *rel = NULL;
6439 
6440  if (!bms_is_empty(relids))
6441  {
6442  int relid;
6443 
6444  if (bms_get_singleton_member(relids, &relid))
6445  rel = find_base_rel(root, relid);
6446  else
6447  rel = find_join_rel(root, relids);
6448  }
6449 
6450  if (rel == NULL)
6451  elog(ERROR, "could not find RelOptInfo for given relids");
6452 
6453  return rel;
6454 }

References bms_get_singleton_member(), bms_is_empty, elog, ERROR, find_base_rel(), find_join_rel(), and root.

Referenced by eqjoinsel().

◆ generic_restriction_selectivity()

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

Definition at line 914 of file selfuncs.c.

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

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

Referenced by ltreeparentsel(), and matchingsel().

◆ genericcostestimate()

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

Definition at line 6552 of file selfuncs.c.

6556 {
6557  IndexOptInfo *index = path->indexinfo;
6558  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6559  List *indexOrderBys = path->indexorderbys;
6560  Cost indexStartupCost;
6561  Cost indexTotalCost;
6562  Selectivity indexSelectivity;
6563  double indexCorrelation;
6564  double numIndexPages;
6565  double numIndexTuples;
6566  double spc_random_page_cost;
6567  double num_sa_scans;
6568  double num_outer_scans;
6569  double num_scans;
6570  double qual_op_cost;
6571  double qual_arg_cost;
6572  List *selectivityQuals;
6573  ListCell *l;
6574 
6575  /*
6576  * If the index is partial, AND the index predicate with the explicitly
6577  * given indexquals to produce a more accurate idea of the index
6578  * selectivity.
6579  */
6580  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
6581 
6582  /*
6583  * If caller didn't give us an estimate for ScalarArrayOpExpr index scans,
6584  * just assume that the number of index descents is the number of distinct
6585  * combinations of array elements from all of the scan's SAOP clauses.
6586  */
6587  num_sa_scans = costs->num_sa_scans;
6588  if (num_sa_scans < 1)
6589  {
6590  num_sa_scans = 1;
6591  foreach(l, indexQuals)
6592  {
6593  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6594 
6595  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6596  {
6597  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6598  double alength = estimate_array_length(root, lsecond(saop->args));
6599 
6600  if (alength > 1)
6601  num_sa_scans *= alength;
6602  }
6603  }
6604  }
6605 
6606  /* Estimate the fraction of main-table tuples that will be visited */
6607  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6608  index->rel->relid,
6609  JOIN_INNER,
6610  NULL);
6611 
6612  /*
6613  * If caller didn't give us an estimate, estimate the number of index
6614  * tuples that will be visited. We do it in this rather peculiar-looking
6615  * way in order to get the right answer for partial indexes.
6616  */
6617  numIndexTuples = costs->numIndexTuples;
6618  if (numIndexTuples <= 0.0)
6619  {
6620  numIndexTuples = indexSelectivity * index->rel->tuples;
6621 
6622  /*
6623  * The above calculation counts all the tuples visited across all
6624  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6625  * average per-indexscan number, so adjust. This is a handy place to
6626  * round to integer, too. (If caller supplied tuple estimate, it's
6627  * responsible for handling these considerations.)
6628  */
6629  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6630  }
6631 
6632  /*
6633  * We can bound the number of tuples by the index size in any case. Also,
6634  * always estimate at least one tuple is touched, even when
6635  * indexSelectivity estimate is tiny.
6636  */
6637  if (numIndexTuples > index->tuples)
6638  numIndexTuples = index->tuples;
6639  if (numIndexTuples < 1.0)
6640  numIndexTuples = 1.0;
6641 
6642  /*
6643  * Estimate the number of index pages that will be retrieved.
6644  *
6645  * We use the simplistic method of taking a pro-rata fraction of the total
6646  * number of index pages. In effect, this counts only leaf pages and not
6647  * any overhead such as index metapage or upper tree levels.
6648  *
6649  * In practice access to upper index levels is often nearly free because
6650  * those tend to stay in cache under load; moreover, the cost involved is
6651  * highly dependent on index type. We therefore ignore such costs here
6652  * and leave it to the caller to add a suitable charge if needed.
6653  */
6654  if (index->pages > 1 && index->tuples > 1)
6655  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6656  else
6657  numIndexPages = 1.0;
6658 
6659  /* fetch estimated page cost for tablespace containing index */
6660  get_tablespace_page_costs(index->reltablespace,
6661  &spc_random_page_cost,
6662  NULL);
6663 
6664  /*
6665  * Now compute the disk access costs.
6666  *
6667  * The above calculations are all per-index-scan. However, if we are in a
6668  * nestloop inner scan, we can expect the scan to be repeated (with
6669  * different search keys) for each row of the outer relation. Likewise,
6670  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6671  * the potential for cache effects to reduce the number of disk page
6672  * fetches needed. We want to estimate the average per-scan I/O cost in
6673  * the presence of caching.
6674  *
6675  * We use the Mackert-Lohman formula (see costsize.c for details) to
6676  * estimate the total number of page fetches that occur. While this
6677  * wasn't what it was designed for, it seems a reasonable model anyway.
6678  * Note that we are counting pages not tuples anymore, so we take N = T =
6679  * index size, as if there were one "tuple" per page.
6680  */
6681  num_outer_scans = loop_count;
6682  num_scans = num_sa_scans * num_outer_scans;
6683 
6684  if (num_scans > 1)
6685  {
6686  double pages_fetched;
6687 
6688  /* total page fetches ignoring cache effects */
6689  pages_fetched = numIndexPages * num_scans;
6690 
6691  /* use Mackert and Lohman formula to adjust for cache effects */
6692  pages_fetched = index_pages_fetched(pages_fetched,
6693  index->pages,
6694  (double) index->pages,
6695  root);
6696 
6697  /*
6698  * Now compute the total disk access cost, and then report a pro-rated
6699  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6700  * since that's internal to the indexscan.)
6701  */
6702  indexTotalCost = (pages_fetched * spc_random_page_cost)
6703  / num_outer_scans;
6704  }
6705  else
6706  {
6707  /*
6708  * For a single index scan, we just charge spc_random_page_cost per
6709  * page touched.
6710  */
6711  indexTotalCost = numIndexPages * spc_random_page_cost;
6712  }
6713 
6714  /*
6715  * CPU cost: any complex expressions in the indexquals will need to be
6716  * evaluated once at the start of the scan to reduce them to runtime keys
6717  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6718  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6719  * indexqual operator. Because we have numIndexTuples as a per-scan
6720  * number, we have to multiply by num_sa_scans to get the correct result
6721  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6722  * ORDER BY expressions.
6723  *
6724  * Note: this neglects the possible costs of rechecking lossy operators.
6725  * Detecting that that might be needed seems more expensive than it's
6726  * worth, though, considering all the other inaccuracies here ...
6727  */
6728  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
6729  index_other_operands_eval_cost(root, indexOrderBys);
6730  qual_op_cost = cpu_operator_cost *
6731  (list_length(indexQuals) + list_length(indexOrderBys));
6732 
6733  indexStartupCost = qual_arg_cost;
6734  indexTotalCost += qual_arg_cost;
6735  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6736 
6737  /*
6738  * Generic assumption about index correlation: there isn't any.
6739  */
6740  indexCorrelation = 0.0;
6741 
6742  /*
6743  * Return everything to caller.
6744  */
6745  costs->indexStartupCost = indexStartupCost;
6746  costs->indexTotalCost = indexTotalCost;
6747  costs->indexSelectivity = indexSelectivity;
6748  costs->indexCorrelation = indexCorrelation;
6749  costs->numIndexPages = numIndexPages;
6750  costs->numIndexTuples = numIndexTuples;
6751  costs->spc_random_page_cost = spc_random_page_cost;
6752  costs->num_sa_scans = num_sa_scans;
6753 }
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:908
double cpu_index_tuple_cost
Definition: costsize.c:133
double spc_random_page_cost
Definition: selfuncs.h:133
List * indexorderbys
Definition: pathnodes.h:1719

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, root, and GenericCosts::spc_random_page_cost.

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

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

6284 {
6285  bool have_data = false;
6286  SnapshotData SnapshotNonVacuumable;
6287  IndexScanDesc index_scan;
6288  Buffer vmbuffer = InvalidBuffer;
6289  BlockNumber last_heap_block = InvalidBlockNumber;
6290  int n_visited_heap_pages = 0;
6291  ItemPointer tid;
6293  bool isnull[INDEX_MAX_KEYS];
6294  MemoryContext oldcontext;
6295 
6296  /*
6297  * We use the index-only-scan machinery for this. With mostly-static
6298  * tables that's a win because it avoids a heap visit. It's also a win
6299  * for dynamic data, but the reason is less obvious; read on for details.
6300  *
6301  * In principle, we should scan the index with our current active
6302  * snapshot, which is the best approximation we've got to what the query
6303  * will see when executed. But that won't be exact if a new snap is taken
6304  * before running the query, and it can be very expensive if a lot of
6305  * recently-dead or uncommitted rows exist at the beginning or end of the
6306  * index (because we'll laboriously fetch each one and reject it).
6307  * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
6308  * and uncommitted rows as well as normal visible rows. On the other
6309  * hand, it will reject known-dead rows, and thus not give a bogus answer
6310  * when the extreme value has been deleted (unless the deletion was quite
6311  * recent); that case motivates not using SnapshotAny here.
6312  *
6313  * A crucial point here is that SnapshotNonVacuumable, with
6314  * GlobalVisTestFor(heapRel) as horizon, yields the inverse of the
6315  * condition that the indexscan will use to decide that index entries are
6316  * killable (see heap_hot_search_buffer()). Therefore, if the snapshot
6317  * rejects a tuple (or more precisely, all tuples of a HOT chain) and we
6318  * have to continue scanning past it, we know that the indexscan will mark
6319  * that index entry killed. That means that the next
6320  * get_actual_variable_endpoint() call will not have to re-consider that
6321  * index entry. In this way we avoid repetitive work when this function
6322  * is used a lot during planning.
6323  *
6324  * But using SnapshotNonVacuumable creates a hazard of its own. In a
6325  * recently-created index, some index entries may point at "broken" HOT
6326  * chains in which not all the tuple versions contain data matching the
6327  * index entry. The live tuple version(s) certainly do match the index,
6328  * but SnapshotNonVacuumable can accept recently-dead tuple versions that
6329  * don't match. Hence, if we took data from the selected heap tuple, we
6330  * might get a bogus answer that's not close to the index extremal value,
6331  * or could even be NULL. We avoid this hazard because we take the data
6332  * from the index entry not the heap.
6333  *
6334  * Despite all this care, there are situations where we might find many
6335  * non-visible tuples near the end of the index. We don't want to expend
6336  * a huge amount of time here, so we give up once we've read too many heap
6337  * pages. When we fail for that reason, the caller will end up using
6338  * whatever extremal value is recorded in pg_statistic.
6339  */
6340  InitNonVacuumableSnapshot(SnapshotNonVacuumable,
6341  GlobalVisTestFor(heapRel));
6342 
6343  index_scan = index_beginscan(heapRel, indexRel,
6344  &SnapshotNonVacuumable,
6345  1, 0);
6346  /* Set it up for index-only scan */
6347  index_scan->xs_want_itup = true;
6348  index_rescan(index_scan, scankeys, 1, NULL, 0);
6349 
6350  /* Fetch first/next tuple in specified direction */
6351  while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
6352  {
6354 
6355  if (!VM_ALL_VISIBLE(heapRel,
6356  block,
6357  &vmbuffer))
6358  {
6359  /* Rats, we have to visit the heap to check visibility */
6360  if (!index_fetch_heap(index_scan, tableslot))
6361  {
6362  /*
6363  * No visible tuple for this index entry, so we need to
6364  * advance to the next entry. Before doing so, count heap
6365  * page fetches and give up if we've done too many.
6366  *
6367  * We don't charge a page fetch if this is the same heap page
6368  * as the previous tuple. This is on the conservative side,
6369  * since other recently-accessed pages are probably still in
6370  * buffers too; but it's good enough for this heuristic.
6371  */
6372 #define VISITED_PAGES_LIMIT 100
6373 
6374  if (block != last_heap_block)
6375  {
6376  last_heap_block = block;
6377  n_visited_heap_pages++;
6378  if (n_visited_heap_pages > VISITED_PAGES_LIMIT)
6379  break;
6380  }
6381 
6382  continue; /* no visible tuple, try next index entry */
6383  }
6384 
6385  /* We don't actually need the heap tuple for anything */
6386  ExecClearTuple(tableslot);
6387 
6388  /*
6389  * We don't care whether there's more than one visible tuple in
6390  * the HOT chain; if any are visible, that's good enough.
6391  */
6392  }
6393 
6394  /*
6395  * We expect that btree will return data in IndexTuple not HeapTuple
6396  * format. It's not lossy either.
6397  */
6398  if (!index_scan->xs_itup)
6399  elog(ERROR, "no data returned for index-only scan");
6400  if (index_scan->xs_recheck)
6401  elog(ERROR, "unexpected recheck indication from btree");
6402 
6403  /* OK to deconstruct the index tuple */
6404  index_deform_tuple(index_scan->xs_itup,
6405  index_scan->xs_itupdesc,
6406  values, isnull);
6407 
6408  /* Shouldn't have got a null, but be careful */
6409  if (isnull[0])
6410  elog(ERROR, "found unexpected null value in index \"%s\"",
6411  RelationGetRelationName(indexRel));
6412 
6413  /* Copy the index column value out to caller's context */
6414  oldcontext = MemoryContextSwitchTo(outercontext);
6415  *endpointDatum = datumCopy(values[0], typByVal, typLen);
6416  MemoryContextSwitchTo(oldcontext);
6417  have_data = true;
6418  break;
6419  }
6420 
6421  if (vmbuffer != InvalidBuffer)
6422  ReleaseBuffer(vmbuffer);
6423  index_endscan(index_scan);
6424 
6425  return have_data;
6426 }
uint32 BlockNumber
Definition: block.h:31
#define InvalidBlockNumber
Definition: block.h:33
static Datum values[MAXATTR]
Definition: bootstrap.c:150
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4906
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
ItemPointer index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:574
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:256
bool index_fetch_heap(IndexScanDesc scan, TupleTableSlot *slot)
Definition: indexam.c:632
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:378
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:352
void index_deform_tuple(IndexTuple tup, TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:456
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
#define INDEX_MAX_KEYS
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition: procarray.c:4111
MemoryContextSwitchTo(old_ctx)
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define VISITED_PAGES_LIMIT
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:48
IndexTuple xs_itup
Definition: relscan.h:142
struct TupleDescData * xs_itupdesc
Definition: relscan.h:143
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:24

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, InvalidBlockNumber, InvalidBuffer, ItemPointerGetBlockNumber(), MemoryContextSwitchTo(), RelationGetRelationName, ReleaseBuffer(), values, VISITED_PAGES_LIMIT, VM_ALL_VISIBLE, IndexScanDescData::xs_itup, IndexScanDescData::xs_itupdesc, IndexScanDescData::xs_recheck, and IndexScanDescData::xs_want_itup.

Referenced by get_actual_variable_range().

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

6098 {
6099  bool have_data = false;
6100  RelOptInfo *rel = vardata->rel;
6101  RangeTblEntry *rte;
6102  ListCell *lc;
6103 
6104  /* No hope if no relation or it doesn't have indexes */
6105  if (rel == NULL || rel->indexlist == NIL)
6106  return false;
6107  /* If it has indexes it must be a plain relation */
6108  rte = root->simple_rte_array[rel->relid];
6109  Assert(rte->rtekind == RTE_RELATION);
6110 
6111  /* ignore partitioned tables. Any indexes here are not real indexes */
6112  if (rte->relkind == RELKIND_PARTITIONED_TABLE)
6113  return false;
6114 
6115  /* Search through the indexes to see if any match our problem */
6116  foreach(lc, rel->indexlist)
6117  {
6119  ScanDirection indexscandir;
6120 
6121  /* Ignore non-btree indexes */
6122  if (index->relam != BTREE_AM_OID)
6123  continue;
6124 
6125  /*
6126  * Ignore partial indexes --- we only want stats that cover the entire
6127  * relation.
6128  */
6129  if (index->indpred != NIL)
6130  continue;
6131 
6132  /*
6133  * The index list might include hypothetical indexes inserted by a
6134  * get_relation_info hook --- don't try to access them.
6135  */
6136  if (index->hypothetical)
6137  continue;
6138 
6139  /*
6140  * The first index column must match the desired variable, sortop, and
6141  * collation --- but we can use a descending-order index.
6142  */
6143  if (collation != index->indexcollations[0])
6144  continue; /* test first 'cause it's cheapest */
6145  if (!match_index_to_operand(vardata->var, 0, index))
6146  continue;
6147  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
6148  {
6149  case BTLessStrategyNumber:
6150  if (index->reverse_sort[0])
6151  indexscandir = BackwardScanDirection;
6152  else
6153  indexscandir = ForwardScanDirection;
6154  break;
6156  if (index->reverse_sort[0])
6157  indexscandir = ForwardScanDirection;
6158  else
6159  indexscandir = BackwardScanDirection;
6160  break;
6161  default:
6162  /* index doesn't match the sortop */
6163  continue;
6164  }
6165 
6166  /*
6167  * Found a suitable index to extract data from. Set up some data that
6168  * can be used by both invocations of get_actual_variable_endpoint.
6169  */
6170  {
6171  MemoryContext tmpcontext;
6172  MemoryContext oldcontext;
6173  Relation heapRel;
6174  Relation indexRel;
6175  TupleTableSlot *slot;
6176  int16 typLen;
6177  bool typByVal;
6178  ScanKeyData scankeys[1];
6179 
6180  /* Make sure any cruft gets recycled when we're done */
6182  "get_actual_variable_range workspace",
6184  oldcontext = MemoryContextSwitchTo(tmpcontext);
6185 
6186  /*
6187  * Open the table and index so we can read from them. We should
6188  * already have some type of lock on each.
6189  */
6190  heapRel = table_open(rte->relid, NoLock);
6191  indexRel = index_open(index->indexoid, NoLock);
6192 
6193  /* build some stuff needed for indexscan execution */
6194  slot = table_slot_create(heapRel, NULL);
6195  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
6196 
6197  /* set up an IS NOT NULL scan key so that we ignore nulls */
6198  ScanKeyEntryInitialize(&scankeys[0],
6200  1, /* index col to scan */
6201  InvalidStrategy, /* no strategy */
6202  InvalidOid, /* no strategy subtype */
6203  InvalidOid, /* no collation */
6204  InvalidOid, /* no reg proc for this */
6205  (Datum) 0); /* constant */
6206 
6207  /* If min is requested ... */
6208  if (min)
6209  {
6210  have_data = get_actual_variable_endpoint(heapRel,
6211  indexRel,
6212  indexscandir,
6213  scankeys,
6214  typLen,
6215  typByVal,
6216  slot,
6217  oldcontext,
6218  min);
6219  }
6220  else
6221  {
6222  /* If min not requested, still want to fetch max */
6223  have_data = true;
6224  }
6225 
6226  /* If max is requested, and we didn't already fail ... */
6227  if (max && have_data)
6228  {
6229  /* scan in the opposite direction; all else is the same */
6230  have_data = get_actual_variable_endpoint(heapRel,
6231  indexRel,
6232  -indexscandir,
6233  scankeys,
6234  typLen,
6235  typByVal,
6236  slot,
6237  oldcontext,
6238  max);
6239  }
6240 
6241  /* Clean everything up */
6243 
6244  index_close(indexRel, NoLock);
6245  table_close(heapRel, NoLock);
6246 
6247  MemoryContextSwitchTo(oldcontext);
6248  MemoryContextDelete(tmpcontext);
6249 
6250  /* And we're done */
6251  break;
6252  }
6253  }
6254 
6255  return have_data;
6256 }
signed short int16
Definition: c.h:493
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1341
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3665
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2251
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
ScanDirection
Definition: sdir.h:25
@ BackwardScanDirection
Definition: sdir.h:26
@ ForwardScanDirection
Definition: sdir.h:28
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:6275
#define SK_SEARCHNOTNULL
Definition: skey.h:122
#define SK_ISNULL
Definition: skey.h:115
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define InvalidStrategy
Definition: stratnum.h:24
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91

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

Referenced by get_variable_range(), and ineq_histogram_selectivity().

◆ get_join_variables()

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

Definition at line 4951 of file selfuncs.c.

4954 {
4955  Node *left,
4956  *right;
4957 
4958  if (list_length(args) != 2)
4959  elog(ERROR, "join operator should take two arguments");
4960 
4961  left = (Node *) linitial(args);
4962  right = (Node *) lsecond(args);
4963 
4964  examine_variable(root, left, 0, vardata1);
4965  examine_variable(root, right, 0, vardata2);
4966 
4967  if (vardata1->rel &&
4968  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4969  *join_is_reversed = true; /* var1 is on RHS */
4970  else if (vardata2->rel &&
4971  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4972  *join_is_reversed = true; /* var2 is on LHS */
4973  else
4974  *join_is_reversed = false;
4975 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Relids relids
Definition: pathnodes.h:871
Relids syn_lefthand
Definition: pathnodes.h:2903
Relids syn_righthand
Definition: pathnodes.h:2904

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

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

◆ get_quals_from_indexclauses()

List* get_quals_from_indexclauses ( List indexclauses)

Definition at line 6468 of file selfuncs.c.

6469 {
6470  List *result = NIL;
6471  ListCell *lc;
6472 
6473  foreach(lc, indexclauses)
6474  {
6475  IndexClause *iclause = lfirst_node(IndexClause, lc);
6476  ListCell *lc2;
6477 
6478  foreach(lc2, iclause->indexquals)
6479  {
6480  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
6481 
6482  result = lappend(result, rinfo);
6483  }
6484  }
6485  return result;
6486 }

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

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

◆ get_restriction_variable()

bool get_restriction_variable ( PlannerInfo root,
List args,
int  varRelid,
VariableStatData vardata,
Node **  other,
bool varonleft 
)

Definition at line 4891 of file selfuncs.c.

4894 {
4895  Node *left,
4896  *right;
4897  VariableStatData rdata;
4898 
4899  /* Fail if not a binary opclause (probably shouldn't happen) */
4900  if (list_length(args) != 2)
4901  return false;
4902 
4903  left = (Node *) linitial(args);
4904  right = (Node *) lsecond(args);
4905 
4906  /*
4907  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4908  * relations will be treated as pseudoconstants.
4909  */
4910  examine_variable(root, left, varRelid, vardata);
4911  examine_variable(root, right, varRelid, &rdata);
4912 
4913  /*
4914  * If one side is a variable and the other not, we win.
4915  */
4916  if (vardata->rel && rdata.rel == NULL)
4917  {
4918  *varonleft = true;
4919  *other = estimate_expression_value(root, rdata.var);
4920  /* Assume we need no ReleaseVariableStats(rdata) here */
4921  return true;
4922  }
4923 
4924  if (vardata->rel == NULL && rdata.rel)
4925  {
4926  *varonleft = false;
4927  *other = estimate_expression_value(root, vardata->var);
4928  /* Assume we need no ReleaseVariableStats(*vardata) here */
4929  *vardata = rdata;
4930  return true;
4931  }
4932 
4933  /* Oops, clause has wrong structure (probably var op var) */
4934  ReleaseVariableStats(*vardata);
4935  ReleaseVariableStats(rdata);
4936 
4937  return false;
4938 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2395

References generate_unaccent_rules::args, estimate_expression_value(), examine_variable(), linitial, list_length(), lsecond, VariableStatData::rel, ReleaseVariableStats, root, and VariableStatData::var.

Referenced by _int_matchsel(), arraycontsel(), eqsel_internal(), generic_restriction_selectivity(), multirangesel(), networksel(), patternsel_common(), rangesel(), scalarineqsel_wrapper(), and tsmatchsel().

◆ get_stats_slot_range()

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

Definition at line 6032 of file selfuncs.c.

6035 {
6036  Datum tmin = *min;
6037  Datum tmax = *max;
6038  bool have_data = *p_have_data;
6039  bool found_tmin = false;
6040  bool found_tmax = false;
6041 
6042  /* Look up the comparison function, if we didn't already do so */
6043  if (opproc->fn_oid != opfuncoid)
6044  fmgr_info(opfuncoid, opproc);
6045 
6046  /* Scan all the slot's values */
6047  for (int i = 0; i < sslot->nvalues; i++)
6048  {
6049  if (!have_data)
6050  {
6051  tmin = tmax = sslot->values[i];
6052  found_tmin = found_tmax = true;
6053