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

Go to the source code of this file.

Data Structures

struct  GroupVarInfo
 
struct  GinQualCounts
 

Functions

static double eqsel_internal (PG_FUNCTION_ARGS, bool negate)
 
static double eqjoinsel_inner (Oid opfuncoid, 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, 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, Datum *min, Datum *max)
 
static bool get_actual_variable_range (PlannerInfo *root, VariableStatData *vardata, Oid sortop, Datum *min, Datum *max)
 
static bool get_actual_variable_endpoint (Relation heapRel, Relation indexRel, ScanDirection indexscandir, ScanKey scankeys, int16 typLen, bool typByVal, TupleTableSlot *tableslot, MemoryContext outercontext, Datum *endpointDatum)
 
static RelOptInfofind_join_input_rel (PlannerInfo *root, Relids relids)
 
Datum eqsel (PG_FUNCTION_ARGS)
 
double var_eq_const (VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
 
double var_eq_non_const (VariableStatData *vardata, Oid operator, Node *other, bool varonleft, bool negate)
 
Datum neqsel (PG_FUNCTION_ARGS)
 
static double scalarineqsel (PlannerInfo *root, Oid operator, bool isgt, bool iseq, VariableStatData *vardata, Datum constval, Oid consttype)
 
double mcv_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Datum constval, bool varonleft, double *sumcommonp)
 
double histogram_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
 
double ineq_histogram_selectivity (PlannerInfo *root, VariableStatData *vardata, FmgrInfo *opproc, bool isgt, bool iseq, Datum constval, Oid consttype)
 
static Datum scalarineqsel_wrapper (PG_FUNCTION_ARGS, bool isgt, bool iseq)
 
Datum scalarltsel (PG_FUNCTION_ARGS)
 
Datum scalarlesel (PG_FUNCTION_ARGS)
 
Datum scalargtsel (PG_FUNCTION_ARGS)
 
Datum scalargesel (PG_FUNCTION_ARGS)
 
Selectivity boolvarsel (PlannerInfo *root, Node *arg, int varRelid)
 
Selectivity booltestsel (PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity nulltestsel (PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
static Nodestrip_array_coercion (Node *node)
 
Selectivity scalararraysel (PlannerInfo *root, ScalarArrayOpExpr *clause, bool is_join_clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
int estimate_array_length (Node *arrayexpr)
 
Selectivity rowcomparesel (PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Datum eqjoinsel (PG_FUNCTION_ARGS)
 
Datum neqjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarltjoinsel (PG_FUNCTION_ARGS)
 
Datum scalarlejoinsel (PG_FUNCTION_ARGS)
 
Datum scalargtjoinsel (PG_FUNCTION_ARGS)
 
Datum scalargejoinsel (PG_FUNCTION_ARGS)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
static Listadd_unique_group_var (PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
double estimate_hashagg_tablesize (Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
 
bool get_restriction_variable (PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
 
void get_join_variables (PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
 
void examine_variable (PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
 
bool statistic_proc_security_check (VariableStatData *vardata, Oid func_oid)
 
double get_variable_numdistinct (VariableStatData *vardata, bool *isdefault)
 
Listget_quals_from_indexclauses (List *indexclauses)
 
Cost index_other_operands_eval_cost (PlannerInfo *root, List *indexquals)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
 
Listadd_predicate_to_index_quals (IndexOptInfo *index, List *indexQuals)
 
void btcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void hashcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void gistcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void spgcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
static bool gincost_pattern (IndexOptInfo *index, int indexcol, Oid clause_op, Datum query, GinQualCounts *counts)
 
static bool gincost_opexpr (PlannerInfo *root, IndexOptInfo *index, int indexcol, OpExpr *clause, GinQualCounts *counts)
 
static bool gincost_scalararrayopexpr (PlannerInfo *root, IndexOptInfo *index, int indexcol, ScalarArrayOpExpr *clause, double numIndexEntries, GinQualCounts *counts)
 
void gincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void brincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 

Variables

get_relation_stats_hook_type get_relation_stats_hook = NULL
 
get_index_stats_hook_type get_index_stats_hook = NULL
 

Function Documentation

◆ add_predicate_to_index_quals()

List* add_predicate_to_index_quals ( IndexOptInfo index,
List indexQuals 
)

Definition at line 5742 of file selfuncs.c.

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

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

5743 {
5744  List *predExtraQuals = NIL;
5745  ListCell *lc;
5746 
5747  if (index->indpred == NIL)
5748  return indexQuals;
5749 
5750  foreach(lc, index->indpred)
5751  {
5752  Node *predQual = (Node *) lfirst(lc);
5753  List *oneQual = list_make1(predQual);
5754 
5755  if (!predicate_implied_by(oneQual, indexQuals, false))
5756  predExtraQuals = list_concat(predExtraQuals, oneQual);
5757  }
5758  return list_concat(predExtraQuals, indexQuals);
5759 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
#define list_make1(x1)
Definition: pg_list.h:227
#define lfirst(lc)
Definition: pg_list.h:190
List * indpred
Definition: pathnodes.h:814
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50

◆ add_unique_group_var()

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

Definition at line 2930 of file selfuncs.c.

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

Referenced by estimate_num_groups().

2932 {
2933  GroupVarInfo *varinfo;
2934  double ndistinct;
2935  bool isdefault;
2936  ListCell *lc;
2937 
2938  ndistinct = get_variable_numdistinct(vardata, &isdefault);
2939 
2940  foreach(lc, varinfos)
2941  {
2942  varinfo = (GroupVarInfo *) lfirst(lc);
2943 
2944  /* Drop exact duplicates */
2945  if (equal(var, varinfo->var))
2946  return varinfos;
2947 
2948  /*
2949  * Drop known-equal vars, but only if they belong to different
2950  * relations (see comments for estimate_num_groups)
2951  */
2952  if (vardata->rel != varinfo->rel &&
2953  exprs_known_equal(root, var, varinfo->var))
2954  {
2955  if (varinfo->ndistinct <= ndistinct)
2956  {
2957  /* Keep older item, forget new one */
2958  return varinfos;
2959  }
2960  else
2961  {
2962  /* Delete the older item */
2963  varinfos = foreach_delete_current(varinfos, lc);
2964  }
2965  }
2966  }
2967 
2968  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
2969 
2970  varinfo->var = var;
2971  varinfo->rel = vardata->rel;
2972  varinfo->ndistinct = ndistinct;
2973  varinfos = lappend(varinfos, varinfo);
2974  return varinfos;
2975 }
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:2085
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3008
RelOptInfo * rel
Definition: selfuncs.h:70
double ndistinct
Definition: selfuncs.c:2926
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4841
Node * var
Definition: selfuncs.c:2924
List * lappend(List *list, void *datum)
Definition: list.c:322
#define lfirst(lc)
Definition: pg_list.h:190
void * palloc(Size size)
Definition: mcxt.c:949
RelOptInfo * rel
Definition: selfuncs.c:2925

◆ booltestsel()

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

Definition at line 1295 of file selfuncs.c.

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

Referenced by clause_selectivity().

1297 {
1298  VariableStatData vardata;
1299  double selec;
1300 
1301  examine_variable(root, arg, varRelid, &vardata);
1302 
1303  if (HeapTupleIsValid(vardata.statsTuple))
1304  {
1305  Form_pg_statistic stats;
1306  double freq_null;
1307  AttStatsSlot sslot;
1308 
1309  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1310  freq_null = stats->stanullfrac;
1311 
1312  if (get_attstatsslot(&sslot, vardata.statsTuple,
1313  STATISTIC_KIND_MCV, InvalidOid,
1315  && sslot.nnumbers > 0)
1316  {
1317  double freq_true;
1318  double freq_false;
1319 
1320  /*
1321  * Get first MCV frequency and derive frequency for true.
1322  */
1323  if (DatumGetBool(sslot.values[0]))
1324  freq_true = sslot.numbers[0];
1325  else
1326  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1327 
1328  /*
1329  * Next derive frequency for false. Then use these as appropriate
1330  * to derive frequency for each case.
1331  */
1332  freq_false = 1.0 - freq_true - freq_null;
1333 
1334  switch (booltesttype)
1335  {
1336  case IS_UNKNOWN:
1337  /* select only NULL values */
1338  selec = freq_null;
1339  break;
1340  case IS_NOT_UNKNOWN:
1341  /* select non-NULL values */
1342  selec = 1.0 - freq_null;
1343  break;
1344  case IS_TRUE:
1345  /* select only TRUE values */
1346  selec = freq_true;
1347  break;
1348  case IS_NOT_TRUE:
1349  /* select non-TRUE values */
1350  selec = 1.0 - freq_true;
1351  break;
1352  case IS_FALSE:
1353  /* select only FALSE values */
1354  selec = freq_false;
1355  break;
1356  case IS_NOT_FALSE:
1357  /* select non-FALSE values */
1358  selec = 1.0 - freq_false;
1359  break;
1360  default:
1361  elog(ERROR, "unrecognized booltesttype: %d",
1362  (int) booltesttype);
1363  selec = 0.0; /* Keep compiler quiet */
1364  break;
1365  }
1366 
1367  free_attstatsslot(&sslot);
1368  }
1369  else
1370  {
1371  /*
1372  * No most-common-value info available. Still have null fraction
1373  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1374  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1375  */
1376  switch (booltesttype)
1377  {
1378  case IS_UNKNOWN:
1379  /* select only NULL values */
1380  selec = freq_null;
1381  break;
1382  case IS_NOT_UNKNOWN:
1383  /* select non-NULL values */
1384  selec = 1.0 - freq_null;
1385  break;
1386  case IS_TRUE:
1387  case IS_FALSE:
1388  /* Assume we select half of the non-NULL values */
1389  selec = (1.0 - freq_null) / 2.0;
1390  break;
1391  case IS_NOT_TRUE:
1392  case IS_NOT_FALSE:
1393  /* Assume we select NULLs plus half of the non-NULLs */
1394  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1395  selec = (freq_null + 1.0) / 2.0;
1396  break;
1397  default:
1398  elog(ERROR, "unrecognized booltesttype: %d",
1399  (int) booltesttype);
1400  selec = 0.0; /* Keep compiler quiet */
1401  break;
1402  }
1403  }
1404  }
1405  else
1406  {
1407  /*
1408  * If we can't get variable statistics for the argument, perhaps
1409  * clause_selectivity can do something with it. We ignore the
1410  * possibility of a NULL value when using clause_selectivity, and just
1411  * assume the value is either TRUE or FALSE.
1412  */
1413  switch (booltesttype)
1414  {
1415  case IS_UNKNOWN:
1416  selec = DEFAULT_UNK_SEL;
1417  break;
1418  case IS_NOT_UNKNOWN:
1419  selec = DEFAULT_NOT_UNK_SEL;
1420  break;
1421  case IS_TRUE:
1422  case IS_NOT_FALSE:
1423  selec = (double) clause_selectivity(root, arg,
1424  varRelid,
1425  jointype, sjinfo);
1426  break;
1427  case IS_FALSE:
1428  case IS_NOT_TRUE:
1429  selec = 1.0 - (double) clause_selectivity(root, arg,
1430  varRelid,
1431  jointype, sjinfo);
1432  break;
1433  default:
1434  elog(ERROR, "unrecognized booltesttype: %d",
1435  (int) booltesttype);
1436  selec = 0.0; /* Keep compiler quiet */
1437  break;
1438  }
1439  }
1440 
1441  ReleaseVariableStats(vardata);
1442 
1443  /* result should be in range, but make sure... */
1444  CLAMP_PROBABILITY(selec);
1445 
1446  return (Selectivity) selec;
1447 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
double Selectivity
Definition: nodes.h:658
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:50
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ERROR
Definition: elog.h:43
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:601
float4 * numbers
Definition: lsyscache.h:53
#define DatumGetBool(X)
Definition: postgres.h:393
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:49
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4408
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
Datum * values
Definition: lsyscache.h:50
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog(elevel,...)
Definition: elog.h:226
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3072

◆ boolvarsel()

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

Definition at line 1267 of file selfuncs.c.

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

Referenced by clause_selectivity().

1268 {
1269  VariableStatData vardata;
1270  double selec;
1271 
1272  examine_variable(root, arg, varRelid, &vardata);
1273  if (HeapTupleIsValid(vardata.statsTuple))
1274  {
1275  /*
1276  * A boolean variable V is equivalent to the clause V = 't', so we
1277  * compute the selectivity as if that is what we have.
1278  */
1279  selec = var_eq_const(&vardata, BooleanEqualOperator,
1280  BoolGetDatum(true), false, true, false);
1281  }
1282  else
1283  {
1284  /* Otherwise, the default estimate is 0.5 */
1285  selec = 0.5;
1286  }
1287  ReleaseVariableStats(vardata);
1288  return selec;
1289 }
HeapTuple statsTuple
Definition: selfuncs.h:71
double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:288
#define BoolGetDatum(X)
Definition: postgres.h:402
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4408
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81

◆ brincostestimate()

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

Definition at line 6828 of file selfuncs.c.

References Abs, Assert, attnum, ATTSTATSSLOT_NUMBERS, BoolGetDatum, 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, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, Int16GetDatum, InvalidOid, JOIN_INNER, lfirst_node, Max, Min, AttStatsSlot::nnumbers, NoLock, AttStatsSlot::numbers, ObjectIdGetDatum, RelOptInfo::pages, IndexOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reltablespace, BrinStatsData::revmapNumPages, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

6832 {
6833  IndexOptInfo *index = path->indexinfo;
6834  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6835  double numPages = index->pages;
6836  RelOptInfo *baserel = index->rel;
6837  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
6838  Cost spc_seq_page_cost;
6839  Cost spc_random_page_cost;
6840  double qual_arg_cost;
6841  double qualSelectivity;
6842  BrinStatsData statsData;
6843  double indexRanges;
6844  double minimalRanges;
6845  double estimatedRanges;
6846  double selec;
6847  Relation indexRel;
6848  ListCell *l;
6849  VariableStatData vardata;
6850 
6851  Assert(rte->rtekind == RTE_RELATION);
6852 
6853  /* fetch estimated page cost for the tablespace containing the index */
6855  &spc_random_page_cost,
6856  &spc_seq_page_cost);
6857 
6858  /*
6859  * Obtain some data from the index itself. A lock should have already
6860  * been obtained on the index in plancat.c.
6861  */
6862  indexRel = index_open(index->indexoid, NoLock);
6863  brinGetStats(indexRel, &statsData);
6864  index_close(indexRel, NoLock);
6865 
6866  /*
6867  * Compute index correlation
6868  *
6869  * Because we can use all index quals equally when scanning, we can use
6870  * the largest correlation (in absolute value) among columns used by the
6871  * query. Start at zero, the worst possible case. If we cannot find any
6872  * correlation statistics, we will keep it as 0.
6873  */
6874  *indexCorrelation = 0;
6875 
6876  foreach(l, path->indexclauses)
6877  {
6878  IndexClause *iclause = lfirst_node(IndexClause, l);
6879  AttrNumber attnum = index->indexkeys[iclause->indexcol];
6880 
6881  /* attempt to lookup stats in relation for this index column */
6882  if (attnum != 0)
6883  {
6884  /* Simple variable -- look to stats for the underlying table */
6886  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
6887  {
6888  /*
6889  * The hook took control of acquiring a stats tuple. If it
6890  * did supply a tuple, it'd better have supplied a freefunc.
6891  */
6892  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
6893  elog(ERROR,
6894  "no function provided to release variable stats with");
6895  }
6896  else
6897  {
6898  vardata.statsTuple =
6900  ObjectIdGetDatum(rte->relid),
6901  Int16GetDatum(attnum),
6902  BoolGetDatum(false));
6903  vardata.freefunc = ReleaseSysCache;
6904  }
6905  }
6906  else
6907  {
6908  /*
6909  * Looks like we've found an expression column in the index. Let's
6910  * see if there's any stats for it.
6911  */
6912 
6913  /* get the attnum from the 0-based index. */
6914  attnum = iclause->indexcol + 1;
6915 
6916  if (get_index_stats_hook &&
6917  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
6918  {
6919  /*
6920  * The hook took control of acquiring a stats tuple. If it
6921  * did supply a tuple, it'd better have supplied a freefunc.
6922  */
6923  if (HeapTupleIsValid(vardata.statsTuple) &&
6924  !vardata.freefunc)
6925  elog(ERROR, "no function provided to release variable stats with");
6926  }
6927  else
6928  {
6930  ObjectIdGetDatum(index->indexoid),
6931  Int16GetDatum(attnum),
6932  BoolGetDatum(false));
6933  vardata.freefunc = ReleaseSysCache;
6934  }
6935  }
6936 
6937  if (HeapTupleIsValid(vardata.statsTuple))
6938  {
6939  AttStatsSlot sslot;
6940 
6941  if (get_attstatsslot(&sslot, vardata.statsTuple,
6942  STATISTIC_KIND_CORRELATION, InvalidOid,
6944  {
6945  double varCorrelation = 0.0;
6946 
6947  if (sslot.nnumbers > 0)
6948  varCorrelation = Abs(sslot.numbers[0]);
6949 
6950  if (varCorrelation > *indexCorrelation)
6951  *indexCorrelation = varCorrelation;
6952 
6953  free_attstatsslot(&sslot);
6954  }
6955  }
6956 
6957  ReleaseVariableStats(vardata);
6958  }
6959 
6960  qualSelectivity = clauselist_selectivity(root, indexQuals,
6961  baserel->relid,
6962  JOIN_INNER, NULL);
6963 
6964  /* work out the actual number of ranges in the index */
6965  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
6966  1.0);
6967 
6968  /*
6969  * Now calculate the minimum possible ranges we could match with if all of
6970  * the rows were in the perfect order in the table's heap.
6971  */
6972  minimalRanges = ceil(indexRanges * qualSelectivity);
6973 
6974  /*
6975  * Now estimate the number of ranges that we'll touch by using the
6976  * indexCorrelation from the stats. Careful not to divide by zero (note
6977  * we're using the absolute value of the correlation).
6978  */
6979  if (*indexCorrelation < 1.0e-10)
6980  estimatedRanges = indexRanges;
6981  else
6982  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
6983 
6984  /* we expect to visit this portion of the table */
6985  selec = estimatedRanges / indexRanges;
6986 
6987  CLAMP_PROBABILITY(selec);
6988 
6989  *indexSelectivity = selec;
6990 
6991  /*
6992  * Compute the index qual costs, much as in genericcostestimate, to add to
6993  * the index costs. We can disregard indexorderbys, since BRIN doesn't
6994  * support those.
6995  */
6996  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
6997 
6998  /*
6999  * Compute the startup cost as the cost to read the whole revmap
7000  * sequentially, including the cost to execute the index quals.
7001  */
7002  *indexStartupCost =
7003  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7004  *indexStartupCost += qual_arg_cost;
7005 
7006  /*
7007  * To read a BRIN index there might be a bit of back and forth over
7008  * regular pages, as revmap might point to them out of sequential order;
7009  * calculate the total cost as reading the whole index in random order.
7010  */
7011  *indexTotalCost = *indexStartupCost +
7012  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7013 
7014  /*
7015  * Charge a small amount per range tuple which we expect to match to. This
7016  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7017  * will set a bit for each page in the range when we find a matching
7018  * range, so we must multiply the charge by the number of pages in the
7019  * range.
7020  */
7021  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7022  statsData.pagesPerRange;
7023 
7024  *indexPages = index->pages;
7025 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1177
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
#define Min(x, y)
Definition: c.h:904
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
Oid reltablespace
Definition: pathnodes.h:790
List * indexclauses
Definition: pathnodes.h:1178
#define Abs(x)
Definition: c.h:910
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:794
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
RelOptInfo * rel
Definition: pathnodes.h:791
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1146
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
AttrNumber indexcol
Definition: pathnodes.h:1226
#define lfirst_node(type, lc)
Definition: pg_list.h:193
#define NoLock
Definition: lockdefs.h:34
float4 * numbers
Definition: lsyscache.h:53
double cpu_operator_cost
Definition: costsize.c:114
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5440
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:146
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
int16 attnum
Definition: pg_attribute.h:79
#define Max(x, y)
Definition: c.h:898
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5470
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:680
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
#define Assert(condition)
Definition: c.h:732
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:147
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
RTEKind rtekind
Definition: parsenodes.h:974
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
#define elog(elevel,...)
Definition: elog.h:226
int * indexkeys
Definition: pathnodes.h:801
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
double Cost
Definition: nodes.h:659
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1093
BlockNumber revmapNumPages
Definition: brin.h:34
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3072

◆ btcostestimate()

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

Definition at line 5763 of file selfuncs.c.

References add_predicate_to_index_quals(), ScalarArrayOpExpr::args, Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BTEqualStrategyNumber, BTLessStrategyNumber, RestrictInfo::clause, clauselist_selectivity(), cpu_operator_cost, elog, ERROR, estimate_array_length(), free_attstatsslot(), VariableStatData::freefunc, genericcostestimate(), get_attstatsslot(), get_index_stats_hook, get_op_opfamily_strategy(), get_opfamily_member(), get_relation_stats_hook, HeapTupleIsValid, IndexPath::indexclauses, IndexClause::indexcol, GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, IndexClause::indexquals, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, RangeTblEntry::inh, Int16GetDatum, InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst_node, linitial_oid, lsecond, MemSet, NIL, IndexOptInfo::nkeycolumns, AttStatsSlot::nnumbers, nodeTag, NullTest::nulltesttype, GenericCosts::num_sa_scans, AttStatsSlot::numbers, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, ObjectIdGetDatum, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, OpExpr::opno, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, rint(), RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by bthandler().

5767 {
5768  IndexOptInfo *index = path->indexinfo;
5769  GenericCosts costs;
5770  Oid relid;
5771  AttrNumber colnum;
5772  VariableStatData vardata;
5773  double numIndexTuples;
5774  Cost descentCost;
5775  List *indexBoundQuals;
5776  int indexcol;
5777  bool eqQualHere;
5778  bool found_saop;
5779  bool found_is_null_op;
5780  double num_sa_scans;
5781  ListCell *lc;
5782 
5783  /*
5784  * For a btree scan, only leading '=' quals plus inequality quals for the
5785  * immediately next attribute contribute to index selectivity (these are
5786  * the "boundary quals" that determine the starting and stopping points of
5787  * the index scan). Additional quals can suppress visits to the heap, so
5788  * it's OK to count them in indexSelectivity, but they should not count
5789  * for estimating numIndexTuples. So we must examine the given indexquals
5790  * to find out which ones count as boundary quals. We rely on the
5791  * knowledge that they are given in index column order.
5792  *
5793  * For a RowCompareExpr, we consider only the first column, just as
5794  * rowcomparesel() does.
5795  *
5796  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
5797  * index scans not one, but the ScalarArrayOpExpr's operator can be
5798  * considered to act the same as it normally does.
5799  */
5800  indexBoundQuals = NIL;
5801  indexcol = 0;
5802  eqQualHere = false;
5803  found_saop = false;
5804  found_is_null_op = false;
5805  num_sa_scans = 1;
5806  foreach(lc, path->indexclauses)
5807  {
5808  IndexClause *iclause = lfirst_node(IndexClause, lc);
5809  ListCell *lc2;
5810 
5811  if (indexcol != iclause->indexcol)
5812  {
5813  /* Beginning of a new column's quals */
5814  if (!eqQualHere)
5815  break; /* done if no '=' qual for indexcol */
5816  eqQualHere = false;
5817  indexcol++;
5818  if (indexcol != iclause->indexcol)
5819  break; /* no quals at all for indexcol */
5820  }
5821 
5822  /* Examine each indexqual associated with this index clause */
5823  foreach(lc2, iclause->indexquals)
5824  {
5825  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5826  Expr *clause = rinfo->clause;
5827  Oid clause_op = InvalidOid;
5828  int op_strategy;
5829 
5830  if (IsA(clause, OpExpr))
5831  {
5832  OpExpr *op = (OpExpr *) clause;
5833 
5834  clause_op = op->opno;
5835  }
5836  else if (IsA(clause, RowCompareExpr))
5837  {
5838  RowCompareExpr *rc = (RowCompareExpr *) clause;
5839 
5840  clause_op = linitial_oid(rc->opnos);
5841  }
5842  else if (IsA(clause, ScalarArrayOpExpr))
5843  {
5844  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
5845  Node *other_operand = (Node *) lsecond(saop->args);
5846  int alength = estimate_array_length(other_operand);
5847 
5848  clause_op = saop->opno;
5849  found_saop = true;
5850  /* count number of SA scans induced by indexBoundQuals only */
5851  if (alength > 1)
5852  num_sa_scans *= alength;
5853  }
5854  else if (IsA(clause, NullTest))
5855  {
5856  NullTest *nt = (NullTest *) clause;
5857 
5858  if (nt->nulltesttype == IS_NULL)
5859  {
5860  found_is_null_op = true;
5861  /* IS NULL is like = for selectivity purposes */
5862  eqQualHere = true;
5863  }
5864  }
5865  else
5866  elog(ERROR, "unsupported indexqual type: %d",
5867  (int) nodeTag(clause));
5868 
5869  /* check for equality operator */
5870  if (OidIsValid(clause_op))
5871  {
5872  op_strategy = get_op_opfamily_strategy(clause_op,
5873  index->opfamily[indexcol]);
5874  Assert(op_strategy != 0); /* not a member of opfamily?? */
5875  if (op_strategy == BTEqualStrategyNumber)
5876  eqQualHere = true;
5877  }
5878 
5879  indexBoundQuals = lappend(indexBoundQuals, rinfo);
5880  }
5881  }
5882 
5883  /*
5884  * If index is unique and we found an '=' clause for each column, we can
5885  * just assume numIndexTuples = 1 and skip the expensive
5886  * clauselist_selectivity calculations. However, a ScalarArrayOp or
5887  * NullTest invalidates that theory, even though it sets eqQualHere.
5888  */
5889  if (index->unique &&
5890  indexcol == index->nkeycolumns - 1 &&
5891  eqQualHere &&
5892  !found_saop &&
5893  !found_is_null_op)
5894  numIndexTuples = 1.0;
5895  else
5896  {
5897  List *selectivityQuals;
5898  Selectivity btreeSelectivity;
5899 
5900  /*
5901  * If the index is partial, AND the index predicate with the
5902  * index-bound quals to produce a more accurate idea of the number of
5903  * rows covered by the bound conditions.
5904  */
5905  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
5906 
5907  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
5908  index->rel->relid,
5909  JOIN_INNER,
5910  NULL);
5911  numIndexTuples = btreeSelectivity * index->rel->tuples;
5912 
5913  /*
5914  * As in genericcostestimate(), we have to adjust for any
5915  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
5916  * to integer.
5917  */
5918  numIndexTuples = rint(numIndexTuples / num_sa_scans);
5919  }
5920 
5921  /*
5922  * Now do generic index cost estimation.
5923  */
5924  MemSet(&costs, 0, sizeof(costs));
5925  costs.numIndexTuples = numIndexTuples;
5926 
5927  genericcostestimate(root, path, loop_count, &costs);
5928 
5929  /*
5930  * Add a CPU-cost component to represent the costs of initial btree
5931  * descent. We don't charge any I/O cost for touching upper btree levels,
5932  * since they tend to stay in cache, but we still have to do about log2(N)
5933  * comparisons to descend a btree of N leaf tuples. We charge one
5934  * cpu_operator_cost per comparison.
5935  *
5936  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
5937  * ones after the first one are not startup cost so far as the overall
5938  * plan is concerned, so add them only to "total" cost.
5939  */
5940  if (index->tuples > 1) /* avoid computing log(0) */
5941  {
5942  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
5943  costs.indexStartupCost += descentCost;
5944  costs.indexTotalCost += costs.num_sa_scans * descentCost;
5945  }
5946 
5947  /*
5948  * Even though we're not charging I/O cost for touching upper btree pages,
5949  * it's still reasonable to charge some CPU cost per page descended
5950  * through. Moreover, if we had no such charge at all, bloated indexes
5951  * would appear to have the same search cost as unbloated ones, at least
5952  * in cases where only a single leaf page is expected to be visited. This
5953  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
5954  * touched. The number of such pages is btree tree height plus one (ie,
5955  * we charge for the leaf page too). As above, charge once per SA scan.
5956  */
5957  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
5958  costs.indexStartupCost += descentCost;
5959  costs.indexTotalCost += costs.num_sa_scans * descentCost;
5960 
5961  /*
5962  * If we can get an estimate of the first column's ordering correlation C
5963  * from pg_statistic, estimate the index correlation as C for a
5964  * single-column index, or C * 0.75 for multiple columns. (The idea here
5965  * is that multiple columns dilute the importance of the first column's
5966  * ordering, but don't negate it entirely. Before 8.0 we divided the
5967  * correlation by the number of columns, but that seems too strong.)
5968  */
5969  MemSet(&vardata, 0, sizeof(vardata));
5970 
5971  if (index->indexkeys[0] != 0)
5972  {
5973  /* Simple variable --- look to stats for the underlying table */
5974  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
5975 
5976  Assert(rte->rtekind == RTE_RELATION);
5977  relid = rte->relid;
5978  Assert(relid != InvalidOid);
5979  colnum = index->indexkeys[0];
5980 
5982  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
5983  {
5984  /*
5985  * The hook took control of acquiring a stats tuple. If it did
5986  * supply a tuple, it'd better have supplied a freefunc.
5987  */
5988  if (HeapTupleIsValid(vardata.statsTuple) &&
5989  !vardata.freefunc)
5990  elog(ERROR, "no function provided to release variable stats with");
5991  }
5992  else
5993  {
5995  ObjectIdGetDatum(relid),
5996  Int16GetDatum(colnum),
5997  BoolGetDatum(rte->inh));
5998  vardata.freefunc = ReleaseSysCache;
5999  }
6000  }
6001  else
6002  {
6003  /* Expression --- maybe there are stats for the index itself */
6004  relid = index->indexoid;
6005  colnum = 1;
6006 
6007  if (get_index_stats_hook &&
6008  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6009  {
6010  /*
6011  * The hook took control of acquiring a stats tuple. If it did
6012  * supply a tuple, it'd better have supplied a freefunc.
6013  */
6014  if (HeapTupleIsValid(vardata.statsTuple) &&
6015  !vardata.freefunc)
6016  elog(ERROR, "no function provided to release variable stats with");
6017  }
6018  else
6019  {
6021  ObjectIdGetDatum(relid),
6022  Int16GetDatum(colnum),
6023  BoolGetDatum(false));
6024  vardata.freefunc = ReleaseSysCache;
6025  }
6026  }
6027 
6028  if (HeapTupleIsValid(vardata.statsTuple))
6029  {
6030  Oid sortop;
6031  AttStatsSlot sslot;
6032 
6033  sortop = get_opfamily_member(index->opfamily[0],
6034  index->opcintype[0],
6035  index->opcintype[0],
6037  if (OidIsValid(sortop) &&
6038  get_attstatsslot(&sslot, vardata.statsTuple,
6039  STATISTIC_KIND_CORRELATION, sortop,
6041  {
6042  double varCorrelation;
6043 
6044  Assert(sslot.nnumbers == 1);
6045  varCorrelation = sslot.numbers[0];
6046 
6047  if (index->reverse_sort[0])
6048  varCorrelation = -varCorrelation;
6049 
6050  if (index->nkeycolumns > 1)
6051  costs.indexCorrelation = varCorrelation * 0.75;
6052  else
6053  costs.indexCorrelation = varCorrelation;
6054 
6055  free_attstatsslot(&sslot);
6056  }
6057  }
6058 
6059  ReleaseVariableStats(vardata);
6060 
6061  *indexStartupCost = costs.indexStartupCost;
6062  *indexTotalCost = costs.indexTotalCost;
6063  *indexSelectivity = costs.indexSelectivity;
6064  *indexCorrelation = costs.indexCorrelation;
6065  *indexPages = costs.numIndexPages;
6066 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
IndexOptInfo * indexinfo
Definition: pathnodes.h:1177
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:681
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:525
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:955
List * indexclauses
Definition: pathnodes.h:1178
double Selectivity
Definition: nodes.h:658
double tuples
Definition: pathnodes.h:795
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: pathnodes.h:796
#define OidIsValid(objectId)
Definition: c.h:638
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1890
RelOptInfo * rel
Definition: pathnodes.h:791
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1146
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
AttrNumber indexcol
Definition: pathnodes.h:1226
double num_sa_scans
Definition: selfuncs.h:113
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5524
float4 * numbers
Definition: lsyscache.h:53
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
double cpu_operator_cost
Definition: costsize.c:114
Cost indexTotalCost
Definition: selfuncs.h:105
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:146
double rint(double x)
Definition: rint.c:21
List * indexquals
Definition: pathnodes.h:1224
Index relid
Definition: pathnodes.h:669
List * lappend(List *list, void *datum)
Definition: list.c:322
Expr * clause
Definition: pathnodes.h:1943
double indexCorrelation
Definition: selfuncs.h:107
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
NullTestType nulltesttype
Definition: primnodes.h:1206
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:111
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
#define Assert(condition)
Definition: c.h:732
#define linitial_oid(l)
Definition: pg_list.h:197
int nkeycolumns
Definition: pathnodes.h:800
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:147
Oid * opcintype
Definition: pathnodes.h:805
#define nodeTag(nodeptr)
Definition: nodes.h:530
Cost indexStartupCost
Definition: selfuncs.h:104
Oid * opfamily
Definition: pathnodes.h:804
RTEKind rtekind
Definition: parsenodes.h:974
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog(elevel,...)
Definition: elog.h:226
int * indexkeys
Definition: pathnodes.h:801
Oid opno
Definition: primnodes.h:502
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
bool * reverse_sort
Definition: pathnodes.h:807
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define BTEqualStrategyNumber
Definition: stratnum.h:31
double Cost
Definition: nodes.h:659
double numIndexPages
Definition: selfuncs.h:110
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3072
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:5742

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

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

Referenced by convert_to_scalar().

4139 {
4140  bytea *valuep = DatumGetByteaPP(value);
4141  bytea *loboundp = DatumGetByteaPP(lobound);
4142  bytea *hiboundp = DatumGetByteaPP(hibound);
4143  int rangelo,
4144  rangehi,
4145  valuelen = VARSIZE_ANY_EXHDR(valuep),
4146  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4147  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4148  i,
4149  minlen;
4150  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4151  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4152  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4153 
4154  /*
4155  * Assume bytea data is uniformly distributed across all byte values.
4156  */
4157  rangelo = 0;
4158  rangehi = 255;
4159 
4160  /*
4161  * Now strip any common prefix of the three strings.
4162  */
4163  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4164  for (i = 0; i < minlen; i++)
4165  {
4166  if (*lostr != *histr || *lostr != *valstr)
4167  break;
4168  lostr++, histr++, valstr++;
4169  loboundlen--, hiboundlen--, valuelen--;
4170  }
4171 
4172  /*
4173  * Now we can do the conversions.
4174  */
4175  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4176  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4177  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4178 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:348
#define Min(x, y)
Definition: c.h:904
static struct @145 value
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4181
#define DatumGetByteaPP(X)
Definition: fmgr.h:285
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:341
int i
Definition: c.h:549

◆ convert_numeric_to_scalar()

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

Definition at line 3860 of file selfuncs.c.

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

Referenced by convert_to_scalar().

3861 {
3862  switch (typid)
3863  {
3864  case BOOLOID:
3865  return (double) DatumGetBool(value);
3866  case INT2OID:
3867  return (double) DatumGetInt16(value);
3868  case INT4OID:
3869  return (double) DatumGetInt32(value);
3870  case INT8OID:
3871  return (double) DatumGetInt64(value);
3872  case FLOAT4OID:
3873  return (double) DatumGetFloat4(value);
3874  case FLOAT8OID:
3875  return (double) DatumGetFloat8(value);
3876  case NUMERICOID:
3877  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3878  return (double)
3880  value));
3881  case OIDOID:
3882  case REGPROCOID:
3883  case REGPROCEDUREOID:
3884  case REGOPEROID:
3885  case REGOPERATOROID:
3886  case REGCLASSOID:
3887  case REGTYPEOID:
3888  case REGCONFIGOID:
3889  case REGDICTIONARYOID:
3890  case REGROLEOID:
3891  case REGNAMESPACEOID:
3892  /* we can treat OIDs as integers... */
3893  return (double) DatumGetObjectId(value);
3894  }
3895 
3896  *failure = true;
3897  return 0;
3898 }
#define DatumGetInt32(X)
Definition: postgres.h:472
#define DatumGetObjectId(X)
Definition: postgres.h:500
static struct @145 value
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:617
#define DatumGetInt64(X)
Definition: postgres.h:607
#define DatumGetInt16(X)
Definition: postgres.h:444
#define DatumGetBool(X)
Definition: postgres.h:393
#define DatumGetFloat8(X)
Definition: postgres.h:728
#define DatumGetFloat4(X)
Definition: postgres.h:680
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:3440

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

Referenced by convert_bytea_to_scalar().

4183 {
4184  double num,
4185  denom,
4186  base;
4187 
4188  if (valuelen <= 0)
4189  return 0.0; /* empty string has scalar value 0 */
4190 
4191  /*
4192  * Since base is 256, need not consider more than about 10 chars (even
4193  * this many seems like overkill)
4194  */
4195  if (valuelen > 10)
4196  valuelen = 10;
4197 
4198  /* Convert initial characters to fraction */
4199  base = rangehi - rangelo + 1;
4200  num = 0.0;
4201  denom = base;
4202  while (valuelen-- > 0)
4203  {
4204  int ch = *value++;
4205 
4206  if (ch < rangelo)
4207  ch = rangelo - 1;
4208  else if (ch > rangehi)
4209  ch = rangehi + 1;
4210  num += ((double) (ch - rangelo)) / denom;
4211  denom *= base;
4212  }
4213 
4214  return num;
4215 }
static struct @145 value

◆ convert_one_string_to_scalar()

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

Definition at line 4001 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4002 {
4003  int slen = strlen(value);
4004  double num,
4005  denom,
4006  base;
4007 
4008  if (slen <= 0)
4009  return 0.0; /* empty string has scalar value 0 */
4010 
4011  /*
4012  * There seems little point in considering more than a dozen bytes from
4013  * the string. Since base is at least 10, that will give us nominal
4014  * resolution of at least 12 decimal digits, which is surely far more
4015  * precision than this estimation technique has got anyway (especially in
4016  * non-C locales). Also, even with the maximum possible base of 256, this
4017  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4018  * overflow on any known machine.
4019  */
4020  if (slen > 12)
4021  slen = 12;
4022 
4023  /* Convert initial characters to fraction */
4024  base = rangehi - rangelo + 1;
4025  num = 0.0;
4026  denom = base;
4027  while (slen-- > 0)
4028  {
4029  int ch = (unsigned char) *value++;
4030 
4031  if (ch < rangelo)
4032  ch = rangelo - 1;
4033  else if (ch > rangehi)
4034  ch = rangehi + 1;
4035  num += ((double) (ch - rangelo)) / denom;
4036  denom *= base;
4037  }
4038 
4039  return num;
4040 }
static struct @145 value

◆ convert_string_datum()

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

Definition at line 4052 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4053 {
4054  char *val;
4055 
4056  switch (typid)
4057  {
4058  case CHAROID:
4059  val = (char *) palloc(2);
4060  val[0] = DatumGetChar(value);
4061  val[1] = '\0';
4062  break;
4063  case BPCHAROID:
4064  case VARCHAROID:
4065  case TEXTOID:
4066  val = TextDatumGetCString(value);
4067  break;
4068  case NAMEOID:
4069  {
4071 
4072  val = pstrdup(NameStr(*nm));
4073  break;
4074  }
4075  default:
4076  *failure = true;
4077  return NULL;
4078  }
4079 
4080  if (!lc_collate_is_c(collid))
4081  {
4082  char *xfrmstr;
4083  size_t xfrmlen;
4084  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4085 
4086  /*
4087  * XXX: We could guess at a suitable output buffer size and only call
4088  * strxfrm twice if our guess is too small.
4089  *
4090  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4091  * bogus data or set an error. This is not really a problem unless it
4092  * crashes since it will only give an estimation error and nothing
4093  * fatal.
4094  */
4095  xfrmlen = strxfrm(NULL, val, 0);
4096 #ifdef WIN32
4097 
4098  /*
4099  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4100  * of trying to allocate this much memory (and fail), just return the
4101  * original string unmodified as if we were in the C locale.
4102  */
4103  if (xfrmlen == INT_MAX)
4104  return val;
4105 #endif
4106  xfrmstr = (char *) palloc(xfrmlen + 1);
4107  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4108 
4109  /*
4110  * Some systems (e.g., glibc) can return a smaller value from the
4111  * second call than the first; thus the Assert must be <= not ==.
4112  */
4113  Assert(xfrmlen2 <= xfrmlen);
4114  pfree(val);
4115  val = xfrmstr;
4116  }
4117 
4118  return val;
4119 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static struct @145 value
void pfree(void *pointer)
Definition: mcxt.c:1056
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1176
Definition: c.h:603
#define TextDatumGetCString(d)
Definition: builtins.h:84
#define DatumGetChar(X)
Definition: postgres.h:409
#define Assert(condition)
Definition: c.h:732
#define DatumGetPointer(X)
Definition: postgres.h:549
void * palloc(Size size)
Definition: mcxt.c:949
#define NameStr(name)
Definition: c.h:609
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
long val
Definition: informix.c:684

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

3927 {
3928  int rangelo,
3929  rangehi;
3930  char *sptr;
3931 
3932  rangelo = rangehi = (unsigned char) hibound[0];
3933  for (sptr = lobound; *sptr; sptr++)
3934  {
3935  if (rangelo > (unsigned char) *sptr)
3936  rangelo = (unsigned char) *sptr;
3937  if (rangehi < (unsigned char) *sptr)
3938  rangehi = (unsigned char) *sptr;
3939  }
3940  for (sptr = hibound; *sptr; sptr++)
3941  {
3942  if (rangelo > (unsigned char) *sptr)
3943  rangelo = (unsigned char) *sptr;
3944  if (rangehi < (unsigned char) *sptr)
3945  rangehi = (unsigned char) *sptr;
3946  }
3947  /* If range includes any upper-case ASCII chars, make it include all */
3948  if (rangelo <= 'Z' && rangehi >= 'A')
3949  {
3950  if (rangelo > 'A')
3951  rangelo = 'A';
3952  if (rangehi < 'Z')
3953  rangehi = 'Z';
3954  }
3955  /* Ditto lower-case */
3956  if (rangelo <= 'z' && rangehi >= 'a')
3957  {
3958  if (rangelo > 'a')
3959  rangelo = 'a';
3960  if (rangehi < 'z')
3961  rangehi = 'z';
3962  }
3963  /* Ditto digits */
3964  if (rangelo <= '9' && rangehi >= '0')
3965  {
3966  if (rangelo > '0')
3967  rangelo = '0';
3968  if (rangehi < '9')
3969  rangehi = '9';
3970  }
3971 
3972  /*
3973  * If range includes less than 10 chars, assume we have not got enough
3974  * data, and make it include regular ASCII set.
3975  */
3976  if (rangehi - rangelo < 9)
3977  {
3978  rangelo = ' ';
3979  rangehi = 127;
3980  }
3981 
3982  /*
3983  * Now strip any common prefix of the three strings.
3984  */
3985  while (*lobound)
3986  {
3987  if (*lobound != *hibound || *lobound != *value)
3988  break;
3989  lobound++, hibound++, value++;
3990  }
3991 
3992  /*
3993  * Now we can do the conversions.
3994  */
3995  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
3996  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
3997  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
3998 }
static struct @145 value
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4001

◆ convert_timevalue_to_scalar()

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

Definition at line 4224 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4225 {
4226  switch (typid)
4227  {
4228  case TIMESTAMPOID:
4229  return DatumGetTimestamp(value);
4230  case TIMESTAMPTZOID:
4231  return DatumGetTimestampTz(value);
4232  case DATEOID:
4234  case INTERVALOID:
4235  {
4237 
4238  /*
4239  * Convert the month part of Interval to days using assumed
4240  * average month length of 365.25/12.0 days. Not too
4241  * accurate, but plenty good enough for our purposes.
4242  */
4243  return interval->time + interval->day * (double) USECS_PER_DAY +
4244  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4245  }
4246  case TIMEOID:
4247  return DatumGetTimeADT(value);
4248  case TIMETZOID:
4249  {
4250  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4251 
4252  /* use GMT-equivalent time */
4253  return (double) (timetz->time + (timetz->zone * 1000000.0));
4254  }
4255  }
4256 
4257  *failure = true;
4258  return 0;
4259 }
#define DatumGetDateADT(X)
Definition: date.h:53
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:29
#define DatumGetTimeTzADTP(X)
Definition: date.h:55
static struct @145 value
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:699
int32 day
Definition: timestamp.h:47
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define DAYS_PER_YEAR
Definition: timestamp.h:68
int32 zone
Definition: date.h:30
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
TimeOffset time
Definition: timestamp.h:45
#define USECS_PER_DAY
Definition: timestamp.h:91
int32 month
Definition: timestamp.h:48
#define DatumGetTimeADT(X)
Definition: date.h:54
Definition: date.h:27
#define DatumGetTimestamp(X)
Definition: timestamp.h:27

◆ convert_to_scalar()

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

Definition at line 3714 of file selfuncs.c.

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

Referenced by ineq_histogram_selectivity().

3717 {
3718  bool failure = false;
3719 
3720  /*
3721  * Both the valuetypid and the boundstypid should exactly match the
3722  * declared input type(s) of the operator we are invoked for. However,
3723  * extensions might try to use scalarineqsel as estimator for operators
3724  * with input type(s) we don't handle here; in such cases, we want to
3725  * return false, not fail. In any case, we mustn't assume that valuetypid
3726  * and boundstypid are identical.
3727  *
3728  * XXX The histogram we are interpolating between points of could belong
3729  * to a column that's only binary-compatible with the declared type. In
3730  * essence we are assuming that the semantics of binary-compatible types
3731  * are enough alike that we can use a histogram generated with one type's
3732  * operators to estimate selectivity for the other's. This is outright
3733  * wrong in some cases --- in particular signed versus unsigned
3734  * interpretation could trip us up. But it's useful enough in the
3735  * majority of cases that we do it anyway. Should think about more
3736  * rigorous ways to do it.
3737  */
3738  switch (valuetypid)
3739  {
3740  /*
3741  * Built-in numeric types
3742  */
3743  case BOOLOID:
3744  case INT2OID:
3745  case INT4OID:
3746  case INT8OID:
3747  case FLOAT4OID:
3748  case FLOAT8OID:
3749  case NUMERICOID:
3750  case OIDOID:
3751  case REGPROCOID:
3752  case REGPROCEDUREOID:
3753  case REGOPEROID:
3754  case REGOPERATOROID:
3755  case REGCLASSOID:
3756  case REGTYPEOID:
3757  case REGCONFIGOID:
3758  case REGDICTIONARYOID:
3759  case REGROLEOID:
3760  case REGNAMESPACEOID:
3761  *scaledvalue = convert_numeric_to_scalar(value, valuetypid,
3762  &failure);
3763  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid,
3764  &failure);
3765  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid,
3766  &failure);
3767  return !failure;
3768 
3769  /*
3770  * Built-in string types
3771  */
3772  case CHAROID:
3773  case BPCHAROID:
3774  case VARCHAROID:
3775  case TEXTOID:
3776  case NAMEOID:
3777  {
3778  char *valstr = convert_string_datum(value, valuetypid,
3779  collid, &failure);
3780  char *lostr = convert_string_datum(lobound, boundstypid,
3781  collid, &failure);
3782  char *histr = convert_string_datum(hibound, boundstypid,
3783  collid, &failure);
3784 
3785  /*
3786  * Bail out if any of the values is not of string type. We
3787  * might leak converted strings for the other value(s), but
3788  * that's not worth troubling over.
3789  */
3790  if (failure)
3791  return false;
3792 
3793  convert_string_to_scalar(valstr, scaledvalue,
3794  lostr, scaledlobound,
3795  histr, scaledhibound);
3796  pfree(valstr);
3797  pfree(lostr);
3798  pfree(histr);
3799  return true;
3800  }
3801 
3802  /*
3803  * Built-in bytea type
3804  */
3805  case BYTEAOID:
3806  {
3807  /* We only support bytea vs bytea comparison */
3808  if (boundstypid != BYTEAOID)
3809  return false;
3810  convert_bytea_to_scalar(value, scaledvalue,
3811  lobound, scaledlobound,
3812  hibound, scaledhibound);
3813  return true;
3814  }
3815 
3816  /*
3817  * Built-in time types
3818  */
3819  case TIMESTAMPOID:
3820  case TIMESTAMPTZOID:
3821  case DATEOID:
3822  case INTERVALOID:
3823  case TIMEOID:
3824  case TIMETZOID:
3825  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid,
3826  &failure);
3827  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid,
3828  &failure);
3829  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid,
3830  &failure);
3831  return !failure;
3832 
3833  /*
3834  * Built-in network types
3835  */
3836  case INETOID:
3837  case CIDROID:
3838  case MACADDROID:
3839  case MACADDR8OID:
3840  *scaledvalue = convert_network_to_scalar(value, valuetypid,
3841  &failure);
3842  *scaledlobound = convert_network_to_scalar(lobound, boundstypid,
3843  &failure);
3844  *scaledhibound = convert_network_to_scalar(hibound, boundstypid,
3845  &failure);
3846  return !failure;
3847  }
3848  /* Don't know how to convert */
3849  *scaledvalue = *scaledlobound = *scaledhibound = 0;
3850  return false;
3851 }
static struct @145 value
static char * convert_string_datum(Datum value, Oid typid, Oid collid, bool *failure)
Definition: selfuncs.c:4052
void pfree(void *pointer)
Definition: mcxt.c:1056
double convert_network_to_scalar(Datum value, Oid typid, bool *failure)
Definition: network.c:1517
static double convert_numeric_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:3860
static void convert_bytea_to_scalar(Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
Definition: selfuncs.c:4133
static double convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4224
static void convert_string_to_scalar(char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
Definition: selfuncs.c:3921

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

Definition at line 1995 of file selfuncs.c.

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

Referenced by neqjoinsel().

1996 {
1997  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1998  Oid operator = PG_GETARG_OID(1);
1999  List *args = (List *) PG_GETARG_POINTER(2);
2000 
2001 #ifdef NOT_USED
2002  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2003 #endif
2005  double selec;
2006  double selec_inner;
2007  VariableStatData vardata1;
2008  VariableStatData vardata2;
2009  double nd1;
2010  double nd2;
2011  bool isdefault1;
2012  bool isdefault2;
2013  Oid opfuncoid;
2014  AttStatsSlot sslot1;
2015  AttStatsSlot sslot2;
2016  Form_pg_statistic stats1 = NULL;
2017  Form_pg_statistic stats2 = NULL;
2018  bool have_mcvs1 = false;
2019  bool have_mcvs2 = false;
2020  bool join_is_reversed;
2021  RelOptInfo *inner_rel;
2022 
2023  get_join_variables(root, args, sjinfo,
2024  &vardata1, &vardata2, &join_is_reversed);
2025 
2026  nd1 = get_variable_numdistinct(&vardata1, &isdefault1);
2027  nd2 = get_variable_numdistinct(&vardata2, &isdefault2);
2028 
2029  opfuncoid = get_opcode(operator);
2030 
2031  memset(&sslot1, 0, sizeof(sslot1));
2032  memset(&sslot2, 0, sizeof(sslot2));
2033 
2034  if (HeapTupleIsValid(vardata1.statsTuple))
2035  {
2036  /* note we allow use of nullfrac regardless of security check */
2037  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1.statsTuple);
2038  if (statistic_proc_security_check(&vardata1, opfuncoid))
2039  have_mcvs1 = get_attstatsslot(&sslot1, vardata1.statsTuple,
2040  STATISTIC_KIND_MCV, InvalidOid,
2042  }
2043 
2044  if (HeapTupleIsValid(vardata2.statsTuple))
2045  {
2046  /* note we allow use of nullfrac regardless of security check */
2047  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2.statsTuple);
2048  if (statistic_proc_security_check(&vardata2, opfuncoid))
2049  have_mcvs2 = get_attstatsslot(&sslot2, vardata2.statsTuple,
2050  STATISTIC_KIND_MCV, InvalidOid,
2052  }
2053 
2054  /* We need to compute the inner-join selectivity in all cases */
2055  selec_inner = eqjoinsel_inner(opfuncoid,
2056  &vardata1, &vardata2,
2057  nd1, nd2,
2058  isdefault1, isdefault2,
2059  &sslot1, &sslot2,
2060  stats1, stats2,
2061  have_mcvs1, have_mcvs2);
2062 
2063  switch (sjinfo->jointype)
2064  {
2065  case JOIN_INNER:
2066  case JOIN_LEFT:
2067  case JOIN_FULL:
2068  selec = selec_inner;
2069  break;
2070  case JOIN_SEMI:
2071  case JOIN_ANTI:
2072 
2073  /*
2074  * Look up the join's inner relation. min_righthand is sufficient
2075  * information because neither SEMI nor ANTI joins permit any
2076  * reassociation into or out of their RHS, so the righthand will
2077  * always be exactly that set of rels.
2078  */
2079  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2080 
2081  if (!join_is_reversed)
2082  selec = eqjoinsel_semi(opfuncoid,
2083  &vardata1, &vardata2,
2084  nd1, nd2,
2085  isdefault1, isdefault2,
2086  &sslot1, &sslot2,
2087  stats1, stats2,
2088  have_mcvs1, have_mcvs2,
2089  inner_rel);
2090  else
2091  {
2092  Oid commop = get_commutator(operator);
2093  Oid commopfuncoid = OidIsValid(commop) ? get_opcode(commop) : InvalidOid;
2094 
2095  selec = eqjoinsel_semi(commopfuncoid,
2096  &vardata2, &vardata1,
2097  nd2, nd1,
2098  isdefault2, isdefault1,
2099  &sslot2, &sslot1,
2100  stats2, stats1,
2101  have_mcvs2, have_mcvs1,
2102  inner_rel);
2103  }
2104 
2105  /*
2106  * We should never estimate the output of a semijoin to be more
2107  * rows than we estimate for an inner join with the same input
2108  * rels and join condition; it's obviously impossible for that to
2109  * happen. The former estimate is N1 * Ssemi while the latter is
2110  * N1 * N2 * Sinner, so we may clamp Ssemi <= N2 * Sinner. Doing
2111  * this is worthwhile because of the shakier estimation rules we
2112  * use in eqjoinsel_semi, particularly in cases where it has to
2113  * punt entirely.
2114  */
2115  selec = Min(selec, inner_rel->rows * selec_inner);
2116  break;
2117  default:
2118  /* other values not expected here */
2119  elog(ERROR, "unrecognized join type: %d",
2120  (int) sjinfo->jointype);
2121  selec = 0; /* keep compiler quiet */
2122  break;
2123  }
2124 
2125  free_attstatsslot(&sslot1);
2126  free_attstatsslot(&sslot2);
2127 
2128  ReleaseVariableStats(vardata1);
2129  ReleaseVariableStats(vardata2);
2130 
2131  CLAMP_PROBABILITY(selec);
2132 
2133  PG_RETURN_FLOAT8((float8) selec);
2134 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1311
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Relids min_righthand
Definition: pathnodes.h:2134
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:4812
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:356
#define Min(x, y)
Definition: c.h:904
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:271
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define OidIsValid(objectId)
Definition: c.h:638
static double eqjoinsel_inner(Oid opfuncoid, 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:2143
JoinType
Definition: nodes.h:692
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:491
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4346
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4841
#define PG_GETARG_OID(n)
Definition: fmgr.h:270
static double eqjoinsel_semi(Oid opfuncoid, 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:2323
#define PG_GETARG_INT16(n)
Definition: fmgr.h:266
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:5405
double rows
Definition: pathnodes.h:644
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1092
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
JoinType jointype
Definition: pathnodes.h:2137
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog(elevel,...)
Definition: elog.h:226
Definition: pg_list.h:50
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3072

◆ eqjoinsel_inner()

static double eqjoinsel_inner ( Oid  opfuncoid,
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 2143 of file selfuncs.c.

References CLAMP_PROBABILITY, DatumGetBool, fmgr_info(), FunctionCall2Coll(), i, AttStatsSlot::numbers, AttStatsSlot::nvalues, palloc0(), pfree(), AttStatsSlot::stacoll, and AttStatsSlot::values.

Referenced by eqjoinsel().

2150 {
2151  double selec;
2152 
2153  if (have_mcvs1 && have_mcvs2)
2154  {
2155  /*
2156  * We have most-common-value lists for both relations. Run through
2157  * the lists to see which MCVs actually join to each other with the
2158  * given operator. This allows us to determine the exact join
2159  * selectivity for the portion of the relations represented by the MCV
2160  * lists. We still have to estimate for the remaining population, but
2161  * in a skewed distribution this gives us a big leg up in accuracy.
2162  * For motivation see the analysis in Y. Ioannidis and S.
2163  * Christodoulakis, "On the propagation of errors in the size of join
2164  * results", Technical Report 1018, Computer Science Dept., University
2165  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2166  */
2167  FmgrInfo eqproc;
2168  bool *hasmatch1;
2169  bool *hasmatch2;
2170  double nullfrac1 = stats1->stanullfrac;
2171  double nullfrac2 = stats2->stanullfrac;
2172  double matchprodfreq,
2173  matchfreq1,
2174  matchfreq2,
2175  unmatchfreq1,
2176  unmatchfreq2,
2177  otherfreq1,
2178  otherfreq2,
2179  totalsel1,
2180  totalsel2;
2181  int i,
2182  nmatches;
2183 
2184  fmgr_info(opfuncoid, &eqproc);
2185  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2186  hasmatch2 = (bool *) palloc0(sslot2->nvalues * sizeof(bool));
2187 
2188  /*
2189  * Note we assume that each MCV will match at most one member of the
2190  * other MCV list. If the operator isn't really equality, there could
2191  * be multiple matches --- but we don't look for them, both for speed
2192  * and because the math wouldn't add up...
2193  */
2194  matchprodfreq = 0.0;
2195  nmatches = 0;
2196  for (i = 0; i < sslot1->nvalues; i++)
2197  {
2198  int j;
2199 
2200  for (j = 0; j < sslot2->nvalues; j++)
2201  {
2202  if (hasmatch2[j])
2203  continue;
2204  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2205  sslot1->stacoll,
2206  sslot1->values[i],
2207  sslot2->values[j])))
2208  {
2209  hasmatch1[i] = hasmatch2[j] = true;
2210  matchprodfreq += sslot1->numbers[i] * sslot2->numbers[j];
2211  nmatches++;
2212  break;
2213  }
2214  }
2215  }
2216  CLAMP_PROBABILITY(matchprodfreq);
2217  /* Sum up frequencies of matched and unmatched MCVs */
2218  matchfreq1 = unmatchfreq1 = 0.0;
2219  for (i = 0; i < sslot1->nvalues; i++)
2220  {
2221  if (hasmatch1[i])
2222  matchfreq1 += sslot1->numbers[i];
2223  else
2224  unmatchfreq1 += sslot1->numbers[i];
2225  }
2226  CLAMP_PROBABILITY(matchfreq1);
2227  CLAMP_PROBABILITY(unmatchfreq1);
2228  matchfreq2 = unmatchfreq2 = 0.0;
2229  for (i = 0; i < sslot2->nvalues; i++)
2230  {
2231  if (hasmatch2[i])
2232  matchfreq2 += sslot2->numbers[i];
2233  else
2234  unmatchfreq2 += sslot2->numbers[i];
2235  }
2236  CLAMP_PROBABILITY(matchfreq2);
2237  CLAMP_PROBABILITY(unmatchfreq2);
2238  pfree(hasmatch1);
2239  pfree(hasmatch2);
2240 
2241  /*
2242  * Compute total frequency of non-null values that are not in the MCV
2243  * lists.
2244  */
2245  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2246  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2247  CLAMP_PROBABILITY(otherfreq1);
2248  CLAMP_PROBABILITY(otherfreq2);
2249 
2250  /*
2251  * We can estimate the total selectivity from the point of view of
2252  * relation 1 as: the known selectivity for matched MCVs, plus
2253  * unmatched MCVs that are assumed to match against random members of
2254  * relation 2's non-MCV population, plus non-MCV values that are
2255  * assumed to match against random members of relation 2's unmatched
2256  * MCVs plus non-MCV values.
2257  */
2258  totalsel1 = matchprodfreq;
2259  if (nd2 > sslot2->nvalues)
2260  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2->nvalues);
2261  if (nd2 > nmatches)
2262  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2263  (nd2 - nmatches);
2264  /* Same estimate from the point of view of relation 2. */
2265  totalsel2 = matchprodfreq;
2266  if (nd1 > sslot1->nvalues)
2267  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1->nvalues);
2268  if (nd1 > nmatches)
2269  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2270  (nd1 - nmatches);
2271 
2272  /*
2273  * Use the smaller of the two estimates. This can be justified in
2274  * essentially the same terms as given below for the no-stats case: to
2275  * a first approximation, we are estimating from the point of view of
2276  * the relation with smaller nd.
2277  */
2278  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2279  }
2280  else
2281  {
2282  /*
2283  * We do not have MCV lists for both sides. Estimate the join
2284  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2285  * is plausible if we assume that the join operator is strict and the
2286  * non-null values are about equally distributed: a given non-null
2287  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2288  * of rel2, so total join rows are at most
2289  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2290  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2291  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2292  * with MIN() is an upper bound. Using the MIN() means we estimate
2293  * from the point of view of the relation with smaller nd (since the
2294  * larger nd is determining the MIN). It is reasonable to assume that
2295  * most tuples in this rel will have join partners, so the bound is
2296  * probably reasonably tight and should be taken as-is.
2297  *
2298  * XXX Can we be smarter if we have an MCV list for just one side? It
2299  * seems that if we assume equal distribution for the other side, we
2300  * end up with the same answer anyway.
2301  */
2302  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2303  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2304 
2305  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2306  if (nd1 > nd2)
2307  selec /= nd1;
2308  else
2309  selec /= nd2;
2310  }
2311 
2312  return selec;
2313 }
Definition: fmgr.h:56
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:1056
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
float4 * numbers
Definition: lsyscache.h:53
#define DatumGetBool(X)
Definition: postgres.h:393
void * palloc0(Size size)
Definition: mcxt.c:980
Datum * values
Definition: lsyscache.h:50
int i

◆ eqjoinsel_semi()

static double eqjoinsel_semi ( Oid  opfuncoid,
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 2323 of file selfuncs.c.

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

Referenced by eqjoinsel().

2331 {
2332  double selec;
2333 
2334  /*
2335  * We clamp nd2 to be not more than what we estimate the inner relation's
2336  * size to be. This is intuitively somewhat reasonable since obviously
2337  * there can't be more than that many distinct values coming from the
2338  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2339  * likewise) is that this is the only pathway by which restriction clauses
2340  * applied to the inner rel will affect the join result size estimate,
2341  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2342  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2343  * the selectivity of outer-rel restrictions.
2344  *
2345  * We can apply this clamping both with respect to the base relation from
2346  * which the join variable comes (if there is just one), and to the
2347  * immediate inner input relation of the current join.
2348  *
2349  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2350  * great, maybe, but it didn't come out of nowhere either. This is most
2351  * helpful when the inner relation is empty and consequently has no stats.
2352  */
2353  if (vardata2->rel)
2354  {
2355  if (nd2 >= vardata2->rel->rows)
2356  {
2357  nd2 = vardata2->rel->rows;
2358  isdefault2 = false;
2359  }
2360  }
2361  if (nd2 >= inner_rel->rows)
2362  {
2363  nd2 = inner_rel->rows;
2364  isdefault2 = false;
2365  }
2366 
2367  if (have_mcvs1 && have_mcvs2 && OidIsValid(opfuncoid))
2368  {
2369  /*
2370  * We have most-common-value lists for both relations. Run through
2371  * the lists to see which MCVs actually join to each other with the
2372  * given operator. This allows us to determine the exact join
2373  * selectivity for the portion of the relations represented by the MCV
2374  * lists. We still have to estimate for the remaining population, but
2375  * in a skewed distribution this gives us a big leg up in accuracy.
2376  */
2377  FmgrInfo eqproc;
2378  bool *hasmatch1;
2379  bool *hasmatch2;
2380  double nullfrac1 = stats1->stanullfrac;
2381  double matchfreq1,
2382  uncertainfrac,
2383  uncertain;
2384  int i,
2385  nmatches,
2386  clamped_nvalues2;
2387 
2388  /*
2389  * The clamping above could have resulted in nd2 being less than
2390  * sslot2->nvalues; in which case, we assume that precisely the nd2
2391  * most common values in the relation will appear in the join input,
2392  * and so compare to only the first nd2 members of the MCV list. Of
2393  * course this is frequently wrong, but it's the best bet we can make.
2394  */
2395  clamped_nvalues2 = Min(sslot2->nvalues, nd2);
2396 
2397  fmgr_info(opfuncoid, &eqproc);
2398  hasmatch1 = (bool *) palloc0(sslot1->nvalues * sizeof(bool));
2399  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2400 
2401  /*
2402  * Note we assume that each MCV will match at most one member of the
2403  * other MCV list. If the operator isn't really equality, there could
2404  * be multiple matches --- but we don't look for them, both for speed
2405  * and because the math wouldn't add up...
2406  */
2407  nmatches = 0;
2408  for (i = 0; i < sslot1->nvalues; i++)
2409  {
2410  int j;
2411 
2412  for (j = 0; j < clamped_nvalues2; j++)
2413  {
2414  if (hasmatch2[j])
2415  continue;
2416  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2417  sslot1->stacoll,
2418  sslot1->values[i],
2419  sslot2->values[j])))
2420  {
2421  hasmatch1[i] = hasmatch2[j] = true;
2422  nmatches++;
2423  break;
2424  }
2425  }
2426  }
2427  /* Sum up frequencies of matched MCVs */
2428  matchfreq1 = 0.0;
2429  for (i = 0; i < sslot1->nvalues; i++)
2430  {
2431  if (hasmatch1[i])
2432  matchfreq1 += sslot1->numbers[i];
2433  }
2434  CLAMP_PROBABILITY(matchfreq1);
2435  pfree(hasmatch1);
2436  pfree(hasmatch2);
2437 
2438  /*
2439  * Now we need to estimate the fraction of relation 1 that has at
2440  * least one join partner. We know for certain that the matched MCVs
2441  * do, so that gives us a lower bound, but we're really in the dark
2442  * about everything else. Our crude approach is: if nd1 <= nd2 then
2443  * assume all non-null rel1 rows have join partners, else assume for
2444  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2445  * can discount the known-matched MCVs from the distinct-values counts
2446  * before doing the division.
2447  *
2448  * Crude as the above is, it's completely useless if we don't have
2449  * reliable ndistinct values for both sides. Hence, if either nd1 or
2450  * nd2 is default, punt and assume half of the uncertain rows have
2451  * join partners.
2452  */
2453  if (!isdefault1 && !isdefault2)
2454  {
2455  nd1 -= nmatches;
2456  nd2 -= nmatches;
2457  if (nd1 <= nd2 || nd2 < 0)
2458  uncertainfrac = 1.0;
2459  else
2460  uncertainfrac = nd2 / nd1;
2461  }
2462  else
2463  uncertainfrac = 0.5;
2464  uncertain = 1.0 - matchfreq1 - nullfrac1;
2465  CLAMP_PROBABILITY(uncertain);
2466  selec = matchfreq1 + uncertainfrac * uncertain;
2467  }
2468  else
2469  {
2470  /*
2471  * Without MCV lists for both sides, we can only use the heuristic
2472  * about nd1 vs nd2.
2473  */
2474  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2475 
2476  if (!isdefault1 && !isdefault2)
2477  {
2478  if (nd1 <= nd2 || nd2 < 0)
2479  selec = 1.0 - nullfrac1;
2480  else
2481  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2482  }
2483  else
2484  selec = 0.5 * (1.0 - nullfrac1);
2485  }
2486 
2487  return selec;
2488 }
Definition: fmgr.h:56
RelOptInfo * rel
Definition: selfuncs.h:70
#define Min(x, y)
Definition: c.h:904
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
#define OidIsValid(objectId)
Definition: c.h:638
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:1056
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
float4 * numbers
Definition: lsyscache.h:53
#define DatumGetBool(X)
Definition: postgres.h:393
void * palloc0(Size size)
Definition: mcxt.c:980
double rows
Definition: pathnodes.h:644
Datum * values
Definition: lsyscache.h:50
int i

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 221 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

222 {
223  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
224 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:356
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:230
double float8
Definition: c.h:491

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

Definition at line 230 of file selfuncs.c.

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

Referenced by eqsel(), and neqsel().

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

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

Definition at line 1890 of file selfuncs.c.

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

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

1891 {
1892  /* look through any binary-compatible relabeling of arrayexpr */
1893  arrayexpr = strip_array_coercion(arrayexpr);
1894 
1895  if (arrayexpr && IsA(arrayexpr, Const))
1896  {
1897  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
1898  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
1899  ArrayType *arrayval;
1900 
1901  if (arrayisnull)
1902  return 0;
1903  arrayval = DatumGetArrayTypeP(arraydatum);
1904  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1905  }
1906  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
1907  !((ArrayExpr *) arrayexpr)->multidims)
1908  {
1909  return list_length(((ArrayExpr *) arrayexpr)->elements);
1910  }
1911  else
1912  {
1913  /* default guess --- see also scalararraysel */
1914  return 10;
1915  }
1916 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:282
uintptr_t Datum
Definition: postgres.h:367
static int list_length(const List *l)
Definition: pg_list.h:169
#define ARR_NDIM(a)
Definition: array.h:278
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1538
#define DatumGetArrayTypeP(X)
Definition: array.h:249

◆ estimate_hash_bucket_stats()

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

Definition at line 3406 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

3409 {
3410  VariableStatData vardata;
3411  double estfract,
3412  ndistinct,
3413  stanullfrac,
3414  avgfreq;
3415  bool isdefault;
3416  AttStatsSlot sslot;
3417 
3418  examine_variable(root, hashkey, 0, &vardata);
3419 
3420  /* Look up the frequency of the most common value, if available */
3421  *mcv_freq = 0.0;
3422 
3423  if (HeapTupleIsValid(vardata.statsTuple))
3424  {
3425  if (get_attstatsslot(&sslot, vardata.statsTuple,
3426  STATISTIC_KIND_MCV, InvalidOid,
3428  {
3429  /*
3430  * The first MCV stat is for the most common value.
3431  */
3432  if (sslot.nnumbers > 0)
3433  *mcv_freq = sslot.numbers[0];
3434  free_attstatsslot(&sslot);
3435  }
3436  }
3437 
3438  /* Get number of distinct values */
3439  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3440 
3441  /*
3442  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3443  * mcv_freq is known to be even higher than that, use it instead.
3444  */
3445  if (isdefault)
3446  {
3447  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3448  ReleaseVariableStats(vardata);
3449  return;
3450  }
3451 
3452  /* Get fraction that are null */
3453  if (HeapTupleIsValid(vardata.statsTuple))
3454  {
3455  Form_pg_statistic stats;
3456 
3457  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3458  stanullfrac = stats->stanullfrac;
3459  }
3460  else
3461  stanullfrac = 0.0;
3462 
3463  /* Compute avg freq of all distinct data values in raw relation */
3464  avgfreq = (1.0 - stanullfrac) / ndistinct;
3465 
3466  /*
3467  * Adjust ndistinct to account for restriction clauses. Observe we are
3468  * assuming that the data distribution is affected uniformly by the
3469  * restriction clauses!
3470  *
3471  * XXX Possibly better way, but much more expensive: multiply by
3472  * selectivity of rel's restriction clauses that mention the target Var.
3473  */
3474  if (vardata.rel && vardata.rel->tuples > 0)
3475  {
3476  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3477  ndistinct = clamp_row_est(ndistinct);
3478  }
3479 
3480  /*
3481  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3482  * number of buckets is less than the expected number of distinct values;
3483  * otherwise it is 1/ndistinct.
3484  */
3485  if (ndistinct > nbuckets)
3486  estfract = 1.0 / nbuckets;
3487  else
3488  estfract = 1.0 / ndistinct;
3489 
3490  /*
3491  * Adjust estimated bucketsize upward to account for skewed distribution.
3492  */
3493  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3494  estfract *= *mcv_freq / avgfreq;
3495 
3496  /*
3497  * Clamp bucketsize to sane range (the above adjustment could easily
3498  * produce an out-of-range result). We set the lower bound a little above
3499  * zero, since zero isn't a very sane result.
3500  */
3501  if (estfract < 1.0e-6)
3502  estfract = 1.0e-6;
3503  else if (estfract > 1.0)
3504  estfract = 1.0;
3505 
3506  *bucketsize_frac = (Selectivity) estfract;
3507 
3508  ReleaseVariableStats(vardata);
3509 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:681
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:658
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4841
float4 * numbers
Definition: lsyscache.h:53
double rows
Definition: pathnodes.h:644
#define InvalidOid
Definition: postgres_ext.h:36
#define Max(x, y)
Definition: c.h:898
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4408
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
double clamp_row_est(double nrows)
Definition: costsize.c:187
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3072

◆ estimate_hashagg_tablesize()

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

Definition at line 3525 of file selfuncs.c.

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

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

3527 {
3528  Size hashentrysize;
3529 
3530  /* Estimate per-hash-entry space at tuple width... */
3531  hashentrysize = MAXALIGN(path->pathtarget->width) +
3533 
3534  /* plus space for pass-by-ref transition values... */
3535  hashentrysize += agg_costs->transitionSpace;
3536  /* plus the per-hash-entry overhead */
3537  hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
3538 
3539  /*
3540  * Note that this disregards the effect of fill-factor and growth policy
3541  * of the hash table. That's probably ok, given that the default
3542  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3543  * "double-in-size" growth policies here.
3544  */
3545  return hashentrysize * dNumGroups;
3546 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
#define SizeofMinimalTupleHeader
Definition: htup_details.h:649
size_t Size
Definition: c.h:466
Size hash_agg_entry_size(int numAggs)
Definition: nodeAgg.c:1446
#define MAXALIGN(LEN)
Definition: c.h:685
Size transitionSpace
Definition: pathnodes.h:64

◆ estimate_multivariate_ndistinct()

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

Definition at line 3567 of file selfuncs.c.

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

Referenced by estimate_num_groups().

3569 {
3570  ListCell *lc;
3571  Bitmapset *attnums = NULL;
3572  int nmatches;
3573  Oid statOid = InvalidOid;
3574  MVNDistinct *stats;
3575  Bitmapset *matched = NULL;
3576 
3577  /* bail out immediately if the table has no extended statistics */
3578  if (!rel->statlist)
3579  return false;
3580 
3581  /* Determine the attnums we're looking for */
3582  foreach(lc, *varinfos)
3583  {
3584  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3585 
3586  Assert(varinfo->rel == rel);
3587 
3588  if (IsA(varinfo->var, Var))
3589  {
3590  attnums = bms_add_member(attnums,
3591  ((Var *) varinfo->var)->varattno);
3592  }
3593  }
3594 
3595  /* look for the ndistinct statistics matching the most vars */
3596  nmatches = 1; /* we require at least two matches */
3597  foreach(lc, rel->statlist)
3598  {
3599  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3600  Bitmapset *shared;
3601  int nshared;
3602 
3603  /* skip statistics of other kinds */
3604  if (info->kind != STATS_EXT_NDISTINCT)
3605  continue;
3606 
3607  /* compute attnums shared by the vars and the statistics object */
3608  shared = bms_intersect(info->keys, attnums);
3609  nshared = bms_num_members(shared);
3610 
3611  /*
3612  * Does this statistics object match more columns than the currently
3613  * best object? If so, use this one instead.
3614  *
3615  * XXX This should break ties using name of the object, or something
3616  * like that, to make the outcome stable.
3617  */
3618  if (nshared > nmatches)
3619  {
3620  statOid = info->statOid;
3621  nmatches = nshared;
3622  matched = shared;
3623  }
3624  }
3625 
3626  /* No match? */
3627  if (statOid == InvalidOid)
3628  return false;
3629  Assert(nmatches > 1 && matched != NULL);
3630 
3631  stats = statext_ndistinct_load(statOid);
3632 
3633  /*
3634  * If we have a match, search it for the specific item that matches (there
3635  * must be one), and construct the output values.
3636  */
3637  if (stats)
3638  {
3639  int i;
3640  List *newlist = NIL;
3641  MVNDistinctItem *item = NULL;
3642 
3643  /* Find the specific item that exactly matches the combination */
3644  for (i = 0; i < stats->nitems; i++)
3645  {
3646  MVNDistinctItem *tmpitem = &stats->items[i];
3647 
3648  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3649  {
3650  item = tmpitem;
3651  break;
3652  }
3653  }
3654 
3655  /* make sure we found an item */
3656  if (!item)
3657  elog(ERROR, "corrupt MVNDistinct entry");
3658 
3659  /* Form the output varinfo list, keeping only unmatched ones */
3660  foreach(lc, *varinfos)
3661  {
3662  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3664 
3665  if (!IsA(varinfo->var, Var))
3666  {
3667  newlist = lappend(newlist, varinfo);
3668  continue;
3669  }
3670 
3671  attnum = ((Var *) varinfo->var)->varattno;
3672  if (!bms_is_member(attnum, matched))
3673  newlist = lappend(newlist, varinfo);
3674  }
3675 
3676  *varinfos = newlist;
3677  *ndistinct = item->ndistinct;
3678  return true;
3679  }
3680 
3681  return false;
3682 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * statlist
Definition: pathnodes.h:679
MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:38
double ndistinct
Definition: statistics.h:28
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
#define ERROR
Definition: elog.h:43
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:646
Node * var
Definition: selfuncs.c:2924
uint32 nitems
Definition: statistics.h:37
List * lappend(List *list, void *datum)
Definition: list.c:322
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:259
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:352
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
Bitmapset * attrs
Definition: statistics.h:29
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
Bitmapset * keys
Definition: pathnodes.h:885
#define elog(elevel,...)
Definition: elog.h:226
int i
MVNDistinct * statext_ndistinct_load(Oid mvoid)
Definition: mvdistinct.c:142
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
int16 AttrNumber
Definition: attnum.h:21
RelOptInfo * rel
Definition: selfuncs.c:2925

◆ estimate_num_groups()

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

Definition at line 3043 of file selfuncs.c.

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

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

3045 {
3046  List *varinfos = NIL;
3047  double srf_multiplier = 1.0;
3048  double numdistinct;
3049  ListCell *l;
3050  int i;
3051 
3052  /*
3053  * We don't ever want to return an estimate of zero groups, as that tends
3054  * to lead to division-by-zero and other unpleasantness. The input_rows
3055  * estimate is usually already at least 1, but clamp it just in case it
3056  * isn't.
3057  */
3058  input_rows = clamp_row_est(input_rows);
3059 
3060  /*
3061  * If no grouping columns, there's exactly one group. (This can't happen
3062  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3063  * corner cases with set operations.)
3064  */
3065  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3066  return 1.0;
3067 
3068  /*
3069  * Count groups derived from boolean grouping expressions. For other
3070  * expressions, find the unique Vars used, treating an expression as a Var
3071  * if we can find stats for it. For each one, record the statistical
3072  * estimate of number of distinct values (total in its table, without
3073  * regard for filtering).
3074  */
3075  numdistinct = 1.0;
3076 
3077  i = 0;
3078  foreach(l, groupExprs)
3079  {
3080  Node *groupexpr = (Node *) lfirst(l);
3081  double this_srf_multiplier;
3082  VariableStatData vardata;
3083  List *varshere;
3084  ListCell *l2;
3085 
3086  /* is expression in this grouping set? */
3087  if (pgset && !list_member_int(*pgset, i++))
3088  continue;
3089 
3090  /*
3091  * Set-returning functions in grouping columns are a bit problematic.
3092  * The code below will effectively ignore their SRF nature and come up
3093  * with a numdistinct estimate as though they were scalar functions.
3094  * We compensate by scaling up the end result by the largest SRF
3095  * rowcount estimate. (This will be an overestimate if the SRF
3096  * produces multiple copies of any output value, but it seems best to
3097  * assume the SRF's outputs are distinct. In any case, it's probably
3098  * pointless to worry too much about this without much better
3099  * estimates for SRF output rowcounts than we have today.)
3100  */
3101  this_srf_multiplier = expression_returns_set_rows(root, groupexpr);
3102  if (srf_multiplier < this_srf_multiplier)
3103  srf_multiplier = this_srf_multiplier;
3104 
3105  /* Short-circuit for expressions returning boolean */
3106  if (exprType(groupexpr) == BOOLOID)
3107  {
3108  numdistinct *= 2.0;
3109  continue;
3110  }
3111 
3112  /*
3113  * If examine_variable is able to deduce anything about the GROUP BY
3114  * expression, treat it as a single variable even if it's really more
3115  * complicated.
3116  */
3117  examine_variable(root, groupexpr, 0, &vardata);
3118  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3119  {
3120  varinfos = add_unique_group_var(root, varinfos,
3121  groupexpr, &vardata);
3122  ReleaseVariableStats(vardata);
3123  continue;
3124  }
3125  ReleaseVariableStats(vardata);
3126 
3127  /*
3128  * Else pull out the component Vars. Handle PlaceHolderVars by
3129  * recursing into their arguments (effectively assuming that the
3130  * PlaceHolderVar doesn't change the number of groups, which boils
3131  * down to ignoring the possible addition of nulls to the result set).
3132  */
3133  varshere = pull_var_clause(groupexpr,
3137 
3138  /*
3139  * If we find any variable-free GROUP BY item, then either it is a
3140  * constant (and we can ignore it) or it contains a volatile function;
3141  * in the latter case we punt and assume that each input row will
3142  * yield a distinct group.
3143  */
3144  if (varshere == NIL)
3145  {
3146  if (contain_volatile_functions(groupexpr))
3147  return input_rows;
3148  continue;
3149  }
3150 
3151  /*
3152  * Else add variables to varinfos list
3153  */
3154  foreach(l2, varshere)
3155  {
3156  Node *var = (Node *) lfirst(l2);
3157 
3158  examine_variable(root, var, 0, &vardata);
3159  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3160  ReleaseVariableStats(vardata);
3161  }
3162  }
3163 
3164  /*
3165  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3166  * list.
3167  */
3168  if (varinfos == NIL)
3169  {
3170  /* Apply SRF multiplier as we would do in the long path */
3171  numdistinct *= srf_multiplier;
3172  /* Round off */
3173  numdistinct = ceil(numdistinct);
3174  /* Guard against out-of-range answers */
3175  if (numdistinct > input_rows)
3176  numdistinct = input_rows;
3177  if (numdistinct < 1.0)
3178  numdistinct = 1.0;
3179  return numdistinct;
3180  }
3181 
3182  /*
3183  * Group Vars by relation and estimate total numdistinct.
3184  *
3185  * For each iteration of the outer loop, we process the frontmost Var in
3186  * varinfos, plus all other Vars in the same relation. We remove these
3187  * Vars from the newvarinfos list for the next iteration. This is the
3188  * easiest way to group Vars of same rel together.
3189  */
3190  do
3191  {
3192  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3193  RelOptInfo *rel = varinfo1->rel;
3194  double reldistinct = 1;
3195  double relmaxndistinct = reldistinct;
3196  int relvarcount = 0;
3197  List *newvarinfos = NIL;
3198  List *relvarinfos = NIL;
3199 
3200  /*
3201  * Split the list of varinfos in two - one for the current rel, one
3202  * for remaining Vars on other rels.
3203  */
3204  relvarinfos = lappend(relvarinfos, varinfo1);
3205  for_each_cell(l, varinfos, list_second_cell(varinfos))
3206  {
3207  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3208 
3209  if (varinfo2->rel == varinfo1->rel)
3210  {
3211  /* varinfos on current rel */
3212  relvarinfos = lappend(relvarinfos, varinfo2);
3213  }
3214  else
3215  {
3216  /* not time to process varinfo2 yet */
3217  newvarinfos = lappend(newvarinfos, varinfo2);
3218  }
3219  }
3220 
3221  /*
3222  * Get the numdistinct estimate for the Vars of this rel. We
3223  * iteratively search for multivariate n-distinct with maximum number
3224  * of vars; assuming that each var group is independent of the others,
3225  * we multiply them together. Any remaining relvarinfos after no more
3226  * multivariate matches are found are assumed independent too, so
3227  * their individual ndistinct estimates are multiplied also.
3228  *
3229  * While iterating, count how many separate numdistinct values we
3230  * apply. We apply a fudge factor below, but only if we multiplied
3231  * more than one such values.
3232  */
3233  while (relvarinfos)
3234  {
3235  double mvndistinct;
3236 
3237  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3238  &mvndistinct))
3239  {
3240  reldistinct *= mvndistinct;
3241  if (relmaxndistinct < mvndistinct)
3242  relmaxndistinct = mvndistinct;
3243  relvarcount++;
3244  }
3245  else
3246  {
3247  foreach(l, relvarinfos)
3248  {
3249  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3250 
3251  reldistinct *= varinfo2->ndistinct;
3252  if (relmaxndistinct < varinfo2->ndistinct)
3253  relmaxndistinct = varinfo2->ndistinct;
3254  relvarcount++;
3255  }
3256 
3257  /* we're done with this relation */
3258  relvarinfos = NIL;
3259  }
3260  }
3261 
3262  /*
3263  * Sanity check --- don't divide by zero if empty relation.
3264  */
3265  Assert(IS_SIMPLE_REL(rel));
3266  if (rel->tuples > 0)
3267  {
3268  /*
3269  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3270  * fudge factor is because the Vars are probably correlated but we
3271  * don't know by how much. We should never clamp to less than the
3272  * largest ndistinct value for any of the Vars, though, since
3273  * there will surely be at least that many groups.
3274  */
3275  double clamp = rel->tuples;
3276 
3277  if (relvarcount > 1)
3278  {
3279  clamp *= 0.1;
3280  if (clamp < relmaxndistinct)
3281  {
3282  clamp = relmaxndistinct;
3283  /* for sanity in case some ndistinct is too large: */
3284  if (clamp > rel->tuples)
3285  clamp = rel->tuples;
3286  }
3287  }
3288  if (reldistinct > clamp)
3289  reldistinct = clamp;
3290 
3291  /*
3292  * Update the estimate based on the restriction selectivity,
3293  * guarding against division by zero when reldistinct is zero.
3294  * Also skip this if we know that we are returning all rows.
3295  */
3296  if (reldistinct > 0 && rel->rows < rel->tuples)
3297  {
3298  /*
3299  * Given a table containing N rows with n distinct values in a
3300  * uniform distribution, if we select p rows at random then
3301  * the expected number of distinct values selected is
3302  *
3303  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3304  *
3305  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3306  *
3307  * See "Approximating block accesses in database
3308  * organizations", S. B. Yao, Communications of the ACM,
3309  * Volume 20 Issue 4, April 1977 Pages 260-261.
3310  *
3311  * Alternatively, re-arranging the terms from the factorials,
3312  * this may be written as
3313  *
3314  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3315  *
3316  * This form of the formula is more efficient to compute in
3317  * the common case where p is larger than N/n. Additionally,
3318  * as pointed out by Dell'Era, if i << N for all terms in the
3319  * product, it can be approximated by
3320  *
3321  * n * (1 - ((N-p)/N)^(N/n))
3322  *
3323  * See "Expected distinct values when selecting from a bag
3324  * without replacement", Alberto Dell'Era,
3325  * http://www.adellera.it/investigations/distinct_balls/.
3326  *
3327  * The condition i << N is equivalent to n >> 1, so this is a
3328  * good approximation when the number of distinct values in
3329  * the table is large. It turns out that this formula also
3330  * works well even when n is small.
3331  */
3332  reldistinct *=
3333  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3334  rel->tuples / reldistinct));
3335  }
3336  reldistinct = clamp_row_est(reldistinct);
3337 
3338  /*
3339  * Update estimate of total distinct groups.
3340  */
3341  numdistinct *= reldistinct;
3342  }
3343 
3344  varinfos = newvarinfos;
3345  } while (varinfos != NIL);
3346 
3347  /* Now we can account for the effects of any SRFs */
3348  numdistinct *= srf_multiplier;
3349 
3350  /* Round off */
3351  numdistinct = ceil(numdistinct);
3352 
3353  /* Guard against out-of-range answers */
3354  if (numdistinct > input_rows)
3355  numdistinct = input_rows;
3356  if (numdistinct < 1.0)
3357  numdistinct = 1.0;
3358 
3359  return numdistinct;
3360 }
#define NIL
Definition: pg_list.h:65
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:569
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:176
HeapTuple statsTuple
Definition: selfuncs.h:71
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
double tuples
Definition: pathnodes.h:681
Definition: nodes.h:525
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:724
double ndistinct
Definition: selfuncs.c:2926
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:614
#define linitial(l)
Definition: pg_list.h:195
bool list_member_int(const List *list, int datum)
Definition: list.c:655
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
static bool estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
Definition: selfuncs.c:3567
List * lappend(List *list, void *datum)
Definition: list.c:322
static List * add_unique_group_var(PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
Definition: selfuncs.c:2930
double rows
Definition: pathnodes.h:644
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4408
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:169
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:173
int i
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:171
RelOptInfo * rel
Definition: selfuncs.c:2925

◆ examine_simple_variable()

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

Definition at line 4635 of file selfuncs.c.

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

Referenced by examine_variable().

4637 {
4638  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4639 
4640  Assert(IsA(rte, RangeTblEntry));
4641 
4643  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4644  {
4645  /*
4646  * The hook took control of acquiring a stats tuple. If it did supply
4647  * a tuple, it'd better have supplied a freefunc.
4648  */
4649  if (HeapTupleIsValid(vardata->statsTuple) &&
4650  !vardata->freefunc)
4651  elog(ERROR, "no function provided to release variable stats with");
4652  }
4653  else if (rte->rtekind == RTE_RELATION)
4654  {
4655  /*
4656  * Plain table or parent of an inheritance appendrel, so look up the
4657  * column in pg_statistic
4658  */
4660  ObjectIdGetDatum(rte->relid),
4661  Int16GetDatum(var->varattno),
4662  BoolGetDatum(rte->inh));
4663  vardata->freefunc = ReleaseSysCache;
4664 
4665  if (HeapTupleIsValid(vardata->statsTuple))
4666  {
4667  Oid userid;
4668 
4669  /*
4670  * Check if user has permission to read this column. We require
4671  * all rows to be accessible, so there must be no securityQuals
4672  * from security barrier views or RLS policies. Use checkAsUser
4673  * if it's set, in case we're accessing the table via a view.
4674  */
4675  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4676 
4677  vardata->acl_ok =
4678  rte->securityQuals == NIL &&
4679  ((pg_class_aclcheck(rte->relid, userid,
4680  ACL_SELECT) == ACLCHECK_OK) ||
4681  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
4682  ACL_SELECT) == ACLCHECK_OK));
4683  }
4684  else
4685  {
4686  /* suppress any possible leakproofness checks later */
4687  vardata->acl_ok = true;
4688  }
4689  }
4690  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4691  {
4692  /*
4693  * Plain subquery (not one that was converted to an appendrel).
4694  */
4695  Query *subquery = rte->subquery;
4696  RelOptInfo *rel;
4697  TargetEntry *ste;
4698 
4699  /*
4700  * Punt if it's a whole-row var rather than a plain column reference.
4701  */
4702  if (var->varattno == InvalidAttrNumber)
4703  return;
4704 
4705  /*
4706  * Punt if subquery uses set operations or GROUP BY, as these will
4707  * mash underlying columns' stats beyond recognition. (Set ops are
4708  * particularly nasty; if we forged ahead, we would return stats
4709  * relevant to only the leftmost subselect...) DISTINCT is also
4710  * problematic, but we check that later because there is a possibility
4711  * of learning something even with it.
4712  */
4713  if (subquery->setOperations ||
4714  subquery->groupClause)
4715  return;
4716 
4717  /*
4718  * OK, fetch RelOptInfo for subquery. Note that we don't change the
4719  * rel returned in vardata, since caller expects it to be a rel of the
4720  * caller's query level. Because we might already be recursing, we
4721  * can't use that rel pointer either, but have to look up the Var's
4722  * rel afresh.
4723  */
4724  rel = find_base_rel(root, var->varno);
4725 
4726  /* If the subquery hasn't been planned yet, we have to punt */
4727  if (rel->subroot == NULL)
4728  return;
4729  Assert(IsA(rel->subroot, PlannerInfo));
4730 
4731  /*
4732  * Switch our attention to the subquery as mangled by the planner. It
4733  * was okay to look at the pre-planning version for the tests above,
4734  * but now we need a Var that will refer to the subroot's live
4735  * RelOptInfos. For instance, if any subquery pullup happened during
4736  * planning, Vars in the targetlist might have gotten replaced, and we
4737  * need to see the replacement expressions.
4738  */
4739  subquery = rel->subroot->parse;
4740  Assert(IsA(subquery, Query));
4741 
4742  /* Get the subquery output expression referenced by the upper Var */
4743  ste = get_tle_by_resno(subquery->targetList, var->varattno);
4744  if (ste == NULL || ste->resjunk)
4745  elog(ERROR, "subquery %s does not have attribute %d",
4746  rte->eref->aliasname, var->varattno);
4747  var = (Var *) ste->expr;
4748 
4749  /*
4750  * If subquery uses DISTINCT, we can't make use of any stats for the
4751  * variable ... but, if it's the only DISTINCT column, we are entitled
4752  * to consider it unique. We do the test this way so that it works
4753  * for cases involving DISTINCT ON.
4754  */
4755  if (subquery->distinctClause)
4756  {
4757  if (list_length(subquery->distinctClause) == 1 &&
4758  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4759  vardata->isunique = true;
4760  /* cannot go further */
4761  return;
4762  }
4763 
4764  /*
4765  * If the sub-query originated from a view with the security_barrier
4766  * attribute, we must not look at the variable's statistics, though it
4767  * seems all right to notice the existence of a DISTINCT clause. So
4768  * stop here.
4769  *
4770  * This is probably a harsher restriction than necessary; it's
4771  * certainly OK for the selectivity estimator (which is a C function,
4772  * and therefore omnipotent anyway) to look at the statistics. But
4773  * many selectivity estimators will happily *invoke the operator
4774  * function* to try to work out a good estimate - and that's not OK.
4775  * So for now, don't dig down for stats.
4776  */
4777  if (rte->security_barrier)
4778  return;
4779 
4780  /* Can only handle a simple Var of subquery's query level */
4781  if (var && IsA(var, Var) &&
4782  var->varlevelsup == 0)
4783  {
4784  /*
4785  * OK, recurse into the subquery. Note that the original setting
4786  * of vardata->isunique (which will surely be false) is left
4787  * unchanged in this situation. That's what we want, since even
4788  * if the underlying column is unique, the subquery may have
4789  * joined to other tables in a way that creates duplicates.
4790  */
4791  examine_simple_variable(rel->subroot, var, vardata);
4792  }
4793  }
4794  else
4795  {
4796  /*
4797  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4798  * won't see RTE_JOIN here because join alias Vars have already been
4799  * flattened.) There's not much we can do with function outputs, but
4800  * maybe someday try to be smarter about VALUES and/or CTEs.
4801  */
4802  }
4803 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Query * parse
Definition: pathnodes.h:177
Index varlevelsup
Definition: primnodes.h:177
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4517
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:380
List * securityQuals
Definition: parsenodes.h:1102
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
AttrNumber varattno
Definition: primnodes.h:172
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4635
List * targetList
Definition: parsenodes.h:140
PlannerInfo * subroot
Definition: pathnodes.h:685
bool resjunk
Definition: primnodes.h:1400
List * distinctClause
Definition: parsenodes.h:156
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1146
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:146
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:209
Index varno
Definition: primnodes.h:170
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define ACL_SELECT
Definition: parsenodes.h:75
bool security_barrier
Definition: parsenodes.h:1010
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1393
static int list_length(const List *l)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4631
RTEKind rtekind
Definition: parsenodes.h:974
Node * setOperations
Definition: parsenodes.h:165
Query * subquery
Definition: parsenodes.h:1009
List * groupClause
Definition: parsenodes.h:148
#define elog(elevel,...)
Definition: elog.h:226
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
Alias * eref
Definition: parsenodes.h:1092
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363

◆ examine_variable()

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

Definition at line 4408 of file selfuncs.c.

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

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

4410 {
4411  Node *basenode;
4412  Relids varnos;
4413  RelOptInfo *onerel;
4414 
4415  /* Make sure we don't return dangling pointers in vardata */
4416  MemSet(vardata, 0, sizeof(VariableStatData));
4417 
4418  /* Save the exposed type of the expression */
4419  vardata->vartype = exprType(node);
4420 
4421  /* Look inside any binary-compatible relabeling */
4422 
4423  if (IsA(node, RelabelType))
4424  basenode = (Node *) ((RelabelType *) node)->arg;
4425  else
4426  basenode = node;
4427 
4428  /* Fast path for a simple Var */
4429 
4430  if (IsA(basenode, Var) &&
4431  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4432  {
4433  Var *var = (Var *) basenode;
4434 
4435  /* Set up result fields other than the stats tuple */
4436  vardata->var = basenode; /* return Var without relabeling */
4437  vardata->rel = find_base_rel(root, var->varno);
4438  vardata->atttype = var->vartype;
4439  vardata->atttypmod = var->vartypmod;
4440  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4441 
4442  /* Try to locate some stats */
4443  examine_simple_variable(root, var, vardata);
4444 
4445  return;
4446  }
4447 
4448  /*
4449  * Okay, it's a more complicated expression. Determine variable
4450  * membership. Note that when varRelid isn't zero, only vars of that
4451  * relation are considered "real" vars.
4452  */
4453  varnos = pull_varnos(basenode);
4454 
4455  onerel = NULL;
4456 
4457  switch (bms_membership(varnos))
4458  {
4459  case BMS_EMPTY_SET:
4460  /* No Vars at all ... must be pseudo-constant clause */
4461  break;
4462  case BMS_SINGLETON:
4463  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4464  {
4465  onerel = find_base_rel(root,
4466  (varRelid ? varRelid : bms_singleton_member(varnos)));
4467  vardata->rel = onerel;
4468  node = basenode; /* strip any relabeling */
4469  }
4470  /* else treat it as a constant */
4471  break;
4472  case BMS_MULTIPLE:
4473  if (varRelid == 0)
4474  {
4475  /* treat it as a variable of a join relation */
4476  vardata->rel = find_join_rel(root, varnos);
4477  node = basenode; /* strip any relabeling */
4478  }
4479  else if (bms_is_member(varRelid, varnos))
4480  {
4481  /* ignore the vars belonging to other relations */
4482  vardata->rel = find_base_rel(root, varRelid);
4483  node = basenode; /* strip any relabeling */
4484  /* note: no point in expressional-index search here */
4485  }
4486  /* else treat it as a constant */
4487  break;
4488  }
4489 
4490  bms_free(varnos);
4491 
4492  vardata->var = node;
4493  vardata->atttype = exprType(node);
4494  vardata->atttypmod = exprTypmod(node);
4495 
4496  if (onerel)
4497  {
4498  /*
4499  * We have an expression in vars of a single relation. Try to match
4500  * it to expressional index columns, in hopes of finding some
4501  * statistics.
4502  *
4503  * Note that we consider all index columns including INCLUDE columns,
4504  * since there could be stats for such columns. But the test for
4505  * uniqueness needs to be warier.
4506  *
4507  * XXX it's conceivable that there are multiple matches with different
4508  * index opfamilies; if so, we need to pick one that matches the
4509  * operator we are estimating for. FIXME later.
4510  */
4511  ListCell *ilist;
4512 
4513  foreach(ilist, onerel->indexlist)
4514  {
4515  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4516  ListCell *indexpr_item;
4517  int pos;
4518 
4519  indexpr_item = list_head(index->indexprs);
4520  if (indexpr_item == NULL)
4521  continue; /* no expressions here... */
4522 
4523  for (pos = 0; pos < index->ncolumns; pos++)
4524  {
4525  if (index->indexkeys[pos] == 0)
4526  {
4527  Node *indexkey;
4528 
4529  if (indexpr_item == NULL)
4530  elog(ERROR, "too few entries in indexprs list");
4531  indexkey = (Node *) lfirst(indexpr_item);
4532  if (indexkey && IsA(indexkey, RelabelType))
4533  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4534  if (equal(node, indexkey))
4535  {
4536  /*
4537  * Found a match ... is it a unique index? Tests here
4538  * should match has_unique_index().
4539  */
4540  if (index->unique &&
4541  index->nkeycolumns == 1 &&
4542  pos == 0 &&
4543  (index->indpred == NIL || index->predOK))
4544  vardata->isunique = true;
4545 
4546  /*
4547  * Has it got stats? We only consider stats for
4548  * non-partial indexes, since partial indexes probably
4549  * don't reflect whole-relation statistics; the above
4550  * check for uniqueness is the only info we take from
4551  * a partial index.
4552  *
4553  * An index stats hook, however, must make its own
4554  * decisions about what to do with partial indexes.
4555  */
4556  if (get_index_stats_hook &&
4557  (*get_index_stats_hook) (root, index->indexoid,
4558  pos + 1, vardata))
4559  {
4560  /*
4561  * The hook took control of acquiring a stats
4562  * tuple. If it did supply a tuple, it'd better
4563  * have supplied a freefunc.
4564  */
4565  if (HeapTupleIsValid(vardata->statsTuple) &&
4566  !vardata->freefunc)
4567  elog(ERROR, "no function provided to release variable stats with");
4568  }
4569  else if (index->indpred == NIL)
4570  {
4571  vardata->statsTuple =
4573  ObjectIdGetDatum(index->indexoid),
4574  Int16GetDatum(pos + 1),
4575  BoolGetDatum(false));
4576  vardata->freefunc = ReleaseSysCache;
4577 
4578  if (HeapTupleIsValid(vardata->statsTuple))
4579  {
4580  /* Get index's table for permission check */
4581  RangeTblEntry *rte;
4582  Oid userid;
4583 
4584  rte = planner_rt_fetch(index->rel->relid, root);
4585  Assert(rte->rtekind == RTE_RELATION);
4586 
4587  /*
4588  * Use checkAsUser if it's set, in case we're
4589  * accessing the table via a view.
4590  */
4591  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4592 
4593  /*
4594  * For simplicity, we insist on the whole
4595  * table being selectable, rather than trying
4596  * to identify which column(s) the index
4597  * depends on. Also require all rows to be
4598  * selectable --- there must be no
4599  * securityQuals from security barrier views
4600  * or RLS policies.
4601  */
4602  vardata->acl_ok =
4603  rte->securityQuals == NIL &&
4604  (pg_class_aclcheck(rte->relid, userid,
4605  ACL_SELECT) == ACLCHECK_OK);
4606  }
4607  else
4608  {
4609  /* suppress leakproofness checks later */
4610  vardata->acl_ok = true;
4611  }
4612  }
4613  if (vardata->statsTuple)
4614  break;
4615  }
4616  indexpr_item = lnext(index->indexprs, indexpr_item);
4617  }
4618  }
4619  if (vardata->statsTuple)
4620  break;
4621  }
4622  }
4623 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:428
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3008
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:380
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
List * securityQuals
Definition: parsenodes.h:1102
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:525
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:955
AttrNumber varattno
Definition: primnodes.h:172
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4635
int32 atttypmod
Definition: selfuncs.h:76
Definition: type.h:89
RelOptInfo * rel
Definition: pathnodes.h:791
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2025
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:174
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1146
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: pathnodes.h:669
Index varno
Definition: primnodes.h:170
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define ACL_SELECT
Definition: parsenodes.h:75
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
List * indexlist
Definition: pathnodes.h:678
#define BoolGetDatum(X)
Definition: postgres.h:402
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int nkeycolumns
Definition: pathnodes.h:800
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:147
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4631
RTEKind rtekind
Definition: parsenodes.h:974
#define elog(elevel,...)
Definition: elog.h:226
void * arg
int * indexkeys
Definition: pathnodes.h:801
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363
List * indpred
Definition: pathnodes.h:814
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
List * indexprs
Definition: pathnodes.h:813
int32 vartypmod
Definition: primnodes.h:175

◆ find_join_input_rel()

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

Definition at line 5405 of file selfuncs.c.

References BMS_EMPTY_SET, bms_membership(), BMS_MULTIPLE, BMS_SINGLETON, bms_singleton_member(), elog, ERROR, find_base_rel(), and find_join_rel().

Referenced by eqjoinsel().

5406 {
5407  RelOptInfo *rel = NULL;
5408 
5409  switch (bms_membership(relids))
5410  {
5411  case BMS_EMPTY_SET:
5412  /* should not happen */
5413  break;
5414  case BMS_SINGLETON:
5415  rel = find_base_rel(root, bms_singleton_member(relids));
5416  break;
5417  case BMS_MULTIPLE:
5418  rel = find_join_rel(root, relids);
5419  break;
5420  }
5421 
5422  if (rel == NULL)
5423  elog(ERROR, "could not find RelOptInfo for given relids");
5424 
5425  return rel;
5426 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:428
#define ERROR
Definition: elog.h:43
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
#define elog(elevel,...)
Definition: elog.h:226
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363

◆ genericcostestimate()

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

Definition at line 5524 of file selfuncs.c.

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

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

5528 {
5529  IndexOptInfo *index = path->indexinfo;
5530  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
5531  List *indexOrderBys = path->indexorderbys;
5532  Cost indexStartupCost;
5533  Cost indexTotalCost;
5534  Selectivity indexSelectivity;
5535  double indexCorrelation;
5536  double numIndexPages;
5537  double numIndexTuples;
5538  double spc_random_page_cost;
5539  double num_sa_scans;
5540  double num_outer_scans;
5541  double num_scans;
5542  double qual_op_cost;
5543  double qual_arg_cost;
5544  List *selectivityQuals;
5545  ListCell *l;
5546 
5547  /*
5548  * If the index is partial, AND the index predicate with the explicitly
5549  * given indexquals to produce a more accurate idea of the index
5550  * selectivity.
5551  */
5552  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
5553 
5554  /*
5555  * Check for ScalarArrayOpExpr index quals, and estimate the number of
5556  * index scans that will be performed.
5557  */
5558  num_sa_scans = 1;
5559  foreach(l, indexQuals)
5560  {
5561  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
5562 
5563  if (IsA(rinfo->clause, ScalarArrayOpExpr))
5564  {
5565  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
5566  int alength = estimate_array_length(lsecond(saop->args));
5567 
5568  if (alength > 1)
5569  num_sa_scans *= alength;
5570  }
5571  }
5572 
5573  /* Estimate the fraction of main-table tuples that will be visited */
5574  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
5575  index->rel->relid,
5576  JOIN_INNER,
5577  NULL);
5578 
5579  /*
5580  * If caller didn't give us an estimate, estimate the number of index
5581  * tuples that will be visited. We do it in this rather peculiar-looking
5582  * way in order to get the right answer for partial indexes.
5583  */
5584  numIndexTuples = costs->numIndexTuples;
5585  if (numIndexTuples <= 0.0)
5586  {
5587  numIndexTuples = indexSelectivity * index->rel->tuples;
5588 
5589  /*
5590  * The above calculation counts all the tuples visited across all
5591  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
5592  * average per-indexscan number, so adjust. This is a handy place to
5593  * round to integer, too. (If caller supplied tuple estimate, it's
5594  * responsible for handling these considerations.)
5595  */
5596  numIndexTuples = rint(numIndexTuples / num_sa_scans);
5597  }
5598 
5599  /*
5600  * We can bound the number of tuples by the index size in any case. Also,
5601  * always estimate at least one tuple is touched, even when
5602  * indexSelectivity estimate is tiny.
5603  */
5604  if (numIndexTuples > index->tuples)
5605  numIndexTuples = index->tuples;
5606  if (numIndexTuples < 1.0)
5607  numIndexTuples = 1.0;
5608 
5609  /*
5610  * Estimate the number of index pages that will be retrieved.
5611  *
5612  * We use the simplistic method of taking a pro-rata fraction of the total
5613  * number of index pages. In effect, this counts only leaf pages and not
5614  * any overhead such as index metapage or upper tree levels.
5615  *
5616  * In practice access to upper index levels is often nearly free because
5617  * those tend to stay in cache under load; moreover, the cost involved is
5618  * highly dependent on index type. We therefore ignore such costs here
5619  * and leave it to the caller to add a suitable charge if needed.
5620  */
5621  if (index->pages > 1 && index->tuples > 1)
5622  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
5623  else
5624  numIndexPages = 1.0;
5625 
5626  /* fetch estimated page cost for tablespace containing index */
5628  &spc_random_page_cost,
5629  NULL);
5630 
5631  /*
5632  * Now compute the disk access costs.
5633  *
5634  * The above calculations are all per-index-scan. However, if we are in a
5635  * nestloop inner scan, we can expect the scan to be repeated (with
5636  * different search keys) for each row of the outer relation. Likewise,
5637  * ScalarArrayOpExpr quals result in multiple index scans. This creates
5638  * the potential for cache effects to reduce the number of disk page
5639  * fetches needed. We want to estimate the average per-scan I/O cost in
5640  * the presence of caching.
5641  *
5642  * We use the Mackert-Lohman formula (see costsize.c for details) to
5643  * estimate the total number of page fetches that occur. While this
5644  * wasn't what it was designed for, it seems a reasonable model anyway.
5645  * Note that we are counting pages not tuples anymore, so we take N = T =
5646  * index size, as if there were one "tuple" per page.
5647  */
5648  num_outer_scans = loop_count;
5649  num_scans = num_sa_scans * num_outer_scans;
5650 
5651  if (num_scans > 1)
5652  {
5653  double pages_fetched;
5654 
5655  /* total page fetches ignoring cache effects */
5656  pages_fetched = numIndexPages * num_scans;
5657 
5658  /* use Mackert and Lohman formula to adjust for cache effects */
5659  pages_fetched = index_pages_fetched(pages_fetched,
5660  index->pages,
5661  (double) index->pages,
5662  root);
5663 
5664  /*
5665  * Now compute the total disk access cost, and then report a pro-rated
5666  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
5667  * since that's internal to the indexscan.)
5668  */
5669  indexTotalCost = (pages_fetched * spc_random_page_cost)
5670  / num_outer_scans;
5671  }
5672  else
5673  {
5674  /*
5675  * For a single index scan, we just charge spc_random_page_cost per
5676  * page touched.
5677  */
5678  indexTotalCost = numIndexPages * spc_random_page_cost;
5679  }
5680 
5681  /*
5682  * CPU cost: any complex expressions in the indexquals will need to be
5683  * evaluated once at the start of the scan to reduce them to runtime keys
5684  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
5685  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
5686  * indexqual operator. Because we have numIndexTuples as a per-scan
5687  * number, we have to multiply by num_sa_scans to get the correct result
5688  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
5689  * ORDER BY expressions.
5690  *
5691  * Note: this neglects the possible costs of rechecking lossy operators.
5692  * Detecting that that might be needed seems more expensive than it's
5693  * worth, though, considering all the other inaccuracies here ...
5694  */
5695  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
5696  index_other_operands_eval_cost(root, indexOrderBys);
5697  qual_op_cost = cpu_operator_cost *
5698  (list_length(indexQuals) + list_length(indexOrderBys));
5699 
5700  indexStartupCost = qual_arg_cost;
5701  indexTotalCost += qual_arg_cost;
5702  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
5703 
5704  /*
5705  * Generic assumption about index correlation: there isn't any.
5706  */
5707  indexCorrelation = 0.0;
5708 
5709  /*
5710  * Return everything to caller.
5711  */
5712  costs->indexStartupCost = indexStartupCost;
5713  costs->indexTotalCost = indexTotalCost;
5714  costs->indexSelectivity = indexSelectivity;
5715  costs->indexCorrelation = indexCorrelation;
5716  costs->numIndexPages = numIndexPages;
5717  costs->numIndexTuples = numIndexTuples;
5718  costs->spc_random_page_cost = spc_random_page_cost;
5719  costs->num_sa_scans = num_sa_scans;
5720 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
IndexOptInfo * indexinfo
Definition: pathnodes.h:1177
double tuples
Definition: pathnodes.h:681
Oid reltablespace
Definition: pathnodes.h:790
List * indexclauses
Definition: pathnodes.h:1178
double Selectivity
Definition: nodes.h:658
double tuples
Definition: pathnodes.h:795
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:794
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1890
RelOptInfo * rel
Definition: pathnodes.h:791
double num_sa_scans
Definition: selfuncs.h:113
double cpu_operator_cost
Definition: costsize.c:114
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5440
Cost indexTotalCost
Definition: selfuncs.h:105
double rint(double x)
Definition: rint.c:21
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
Expr * clause
Definition: pathnodes.h:1943
double indexCorrelation
Definition: selfuncs.h:107
List * indexorderbys
Definition: pathnodes.h:1179
double spc_random_page_cost
Definition: selfuncs.h:112
double numIndexTuples
Definition: selfuncs.h:111
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5470
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
Cost indexStartupCost
Definition: selfuncs.h:104
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
Definition: pg_list.h:50
double cpu_index_tuple_cost
Definition: costsize.c:113
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:825
double Cost
Definition: nodes.h:659
double numIndexPages
Definition: selfuncs.h:110
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:5742

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

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

Referenced by get_actual_variable_range().

5287 {
5288  bool have_data = false;
5289  SnapshotData SnapshotNonVacuumable;
5290  IndexScanDesc index_scan;
5291  Buffer vmbuffer = InvalidBuffer;
5292  ItemPointer tid;
5294  bool isnull[INDEX_MAX_KEYS];
5295  MemoryContext oldcontext;
5296 
5297  /*
5298  * We use the index-only-scan machinery for this. With mostly-static
5299  * tables that's a win because it avoids a heap visit. It's also a win
5300  * for dynamic data, but the reason is less obvious; read on for details.
5301  *
5302  * In principle, we should scan the index with our current active
5303  * snapshot, which is the best approximation we've got to what the query
5304  * will see when executed. But that won't be exact if a new snap is taken
5305  * before running the query, and it can be very expensive if a lot of
5306  * recently-dead or uncommitted rows exist at the beginning or end of the
5307  * index (because we'll laboriously fetch each one and reject it).
5308  * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
5309  * and uncommitted rows as well as normal visible rows. On the other
5310  * hand, it will reject known-dead rows, and thus not give a bogus answer
5311  * when the extreme value has been deleted (unless the deletion was quite
5312  * recent); that case motivates not using SnapshotAny here.
5313  *
5314  * A crucial point here is that SnapshotNonVacuumable, with
5315  * RecentGlobalXmin as horizon, yields the inverse of the condition that
5316  * the indexscan will use to decide that index entries are killable (see
5317  * heap_hot_search_buffer()). Therefore, if the snapshot rejects a tuple
5318  * (or more precisely, all tuples of a HOT chain) and we have to continue
5319  * scanning past it, we know that the indexscan will mark that index entry
5320  * killed. That means that the next get_actual_variable_endpoint() call
5321  * will not have to re-consider that index entry. In this way we avoid
5322  * repetitive work when this function is used a lot during planning.
5323  *
5324  * But using SnapshotNonVacuumable creates a hazard of its own. In a
5325  * recently-created index, some index entries may point at "broken" HOT
5326  * chains in which not all the tuple versions contain data matching the
5327  * index entry. The live tuple version(s) certainly do match the index,
5328  * but SnapshotNonVacuumable can accept recently-dead tuple versions that
5329  * don't match. Hence, if we took data from the selected heap tuple, we
5330  * might get a bogus answer that's not close to the index extremal value,
5331  * or could even be NULL. We avoid this hazard because we take the data
5332  * from the index entry not the heap.
5333  */
5334  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5335 
5336  index_scan = index_beginscan(heapRel, indexRel,
5337  &SnapshotNonVacuumable,
5338  1, 0);
5339  /* Set it up for index-only scan */
5340  index_scan->xs_want_itup = true;
5341  index_rescan(index_scan, scankeys, 1, NULL, 0);
5342 
5343  /* Fetch first/next tuple in specified direction */
5344  while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
5345  {
5346  if (!VM_ALL_VISIBLE(heapRel,
5348  &vmbuffer))
5349  {
5350  /* Rats, we have to visit the heap to check visibility */
5351  if (!index_fetch_heap(index_scan, tableslot))
5352  continue; /* no visible tuple, try next index entry */
5353 
5354  /* We don't actually need the heap tuple for anything */
5355  ExecClearTuple(tableslot);
5356 
5357  /*
5358  * We don't care whether there's more than one visible tuple in
5359  * the HOT chain; if any are visible, that's good enough.
5360  */
5361  }
5362 
5363  /*
5364  * We expect that btree will return data in IndexTuple not HeapTuple
5365  * format. It's not lossy either.
5366  */
5367  if (!index_scan->xs_itup)
5368  elog(ERROR, "no data returned for index-only scan");
5369  if (index_scan->xs_recheck)
5370  elog(ERROR, "unexpected recheck indication from btree");
5371 
5372  /* OK to deconstruct the index tuple */
5373  index_deform_tuple(index_scan->xs_itup,
5374  index_scan->xs_itupdesc,
5375  values, isnull);
5376 
5377  /* Shouldn't have got a null, but be careful */
5378  if (isnull[0])
5379  elog(ERROR, "found unexpected null value in index \"%s\"",
5380  RelationGetRelationName(indexRel));
5381 
5382  /* Copy the index column value out to caller's context */
5383  oldcontext = MemoryContextSwitchTo(outercontext);
5384  *endpointDatum = datumCopy(values[0], typByVal, typLen);
5385  MemoryContextSwitchTo(oldcontext);
5386  have_data = true;
5387  break;
5388  }
5389 
5390  if (vmbuffer != InvalidBuffer)
5391  ReleaseBuffer(vmbuffer);
5392  index_endscan(index_scan);
5393 
5394  return have_data;
5395 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:426
IndexTuple xs_itup
Definition: relscan.h:127
struct TupleDescData * xs_itupdesc
Definition: relscan.h:128
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:289
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3365
#define InitNonVacuumableSnapshot(snapshotdata, xmin_horizon)
Definition: snapmgr.h:83
ItemPointer index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:509
#define ERROR
Definition: elog.h:43
TransactionId RecentGlobalXmin
Definition: snapmgr.c:168
#define RelationGetRelationName(relation)
Definition: rel.h:453
void index_deform_tuple(IndexTuple tup, TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:433
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:315
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
uintptr_t Datum
Definition: postgres.h:367
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:32
#define INDEX_MAX_KEYS
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define elog(elevel,...)
Definition: elog.h:226
bool index_fetch_heap(IndexScanDesc scan, TupleTableSlot *slot)
Definition: indexam.c:566
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
int Buffer
Definition: buf.h:23
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:197

◆ get_actual_variable_range()

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

Definition at line 5107 of file selfuncs.c.

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

Referenced by get_variable_range(), and ineq_histogram_selectivity().

5110 {
5111  bool have_data = false;
5112  RelOptInfo *rel = vardata->rel;
5113  RangeTblEntry *rte;
5114  ListCell *lc;
5115 
5116  /* No hope if no relation or it doesn't have indexes */
5117  if (rel == NULL || rel->indexlist == NIL)
5118  return false;
5119  /* If it has indexes it must be a plain relation */
5120  rte = root->simple_rte_array[rel->relid];
5121  Assert(rte->rtekind == RTE_RELATION);
5122 
5123  /* Search through the indexes to see if any match our problem */
5124  foreach(lc, rel->indexlist)
5125  {
5127  ScanDirection indexscandir;
5128 
5129  /* Ignore non-btree indexes */
5130  if (index->relam != BTREE_AM_OID)
5131  continue;
5132 
5133  /*
5134  * Ignore partial indexes --- we only want stats that cover the entire
5135  * relation.
5136  */
5137  if (index->indpred != NIL)
5138  continue;
5139 
5140  /*
5141  * The index list might include hypothetical indexes inserted by a
5142  * get_relation_info hook --- don't try to access them.
5143  */
5144  if (index->hypothetical)
5145  continue;
5146 
5147  /*
5148  * The first index column must match the desired variable and sort
5149  * operator --- but we can use a descending-order index.
5150  */
5151  if (!match_index_to_operand(vardata->var, 0, index))
5152  continue;
5153  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5154  {
5155  case BTLessStrategyNumber:
5156  if (index->reverse_sort[0])
5157  indexscandir = BackwardScanDirection;
5158  else
5159  indexscandir = ForwardScanDirection;
5160  break;
5162  if (index->reverse_sort[0])
5163  indexscandir = ForwardScanDirection;
5164  else
5165  indexscandir = BackwardScanDirection;
5166  break;
5167  default:
5168  /* index doesn't match the sortop */
5169  continue;
5170  }
5171 
5172  /*
5173  * Found a suitable index to extract data from. Set up some data that
5174  * can be used by both invocations of get_actual_variable_endpoint.
5175  */
5176  {
5177  MemoryContext tmpcontext;
5178  MemoryContext oldcontext;
5179  Relation heapRel;
5180  Relation indexRel;
5181  TupleTableSlot *slot;
5182  int16 typLen;
5183  bool typByVal;
5184  ScanKeyData scankeys[1];
5185 
5186  /* Make sure any cruft gets recycled when we're done */
5188  "get_actual_variable_range workspace",
5190  oldcontext = MemoryContextSwitchTo(tmpcontext);
5191 
5192  /*
5193  * Open the table and index so we can read from them. We should
5194  * already have some type of lock on each.
5195  */
5196  heapRel = table_open(rte->relid, NoLock);
5197  indexRel = index_open(index->indexoid, NoLock);
5198 
5199  /* build some stuff needed for indexscan execution */
5200  slot = table_slot_create(heapRel, NULL);
5201  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5202 
5203  /* set up an IS NOT NULL scan key so that we ignore nulls */
5204  ScanKeyEntryInitialize(&scankeys[0],
5206  1, /* index col to scan */
5207  InvalidStrategy, /* no strategy */
5208  InvalidOid, /* no strategy subtype */
5209  InvalidOid, /* no collation */
5210  InvalidOid, /* no reg proc for this */
5211  (Datum) 0); /* constant */
5212 
5213  /* If min is requested ... */
5214  if (min)
5215  {
5216  have_data = get_actual_variable_endpoint(heapRel,
5217  indexRel,
5218  indexscandir,
5219  scankeys,
5220  typLen,
5221  typByVal,
5222  slot,
5223  oldcontext,
5224  min);
5225  }
5226  else
5227  {
5228  /* If min not requested, assume index is nonempty */
5229  have_data = true;
5230  }
5231 
5232  /* If max is requested, and we didn't find the index is empty */
5233  if (max && have_data)
5234  {
5235  /* scan in the opposite direction; all else is the same */
5236  have_data = get_actual_variable_endpoint(heapRel,
5237  indexRel,
5238  -indexscandir,
5239  scankeys,
5240  typLen,
5241  typByVal,
5242  slot,
5243  oldcontext,
5244  max);
5245  }
5246 
5247  /* Clean everything up */
5249 
5250  index_close(indexRel, NoLock);
5251  table_close(heapRel, NoLock);
5252 
5253  MemoryContextSwitchTo(oldcontext);
5254  MemoryContextDelete(tmpcontext);
5255 
5256  /* And we're done */
5257  break;
5258  }
5259  }
5260 
5261  return have_data;
5262 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:77
signed short int16
Definition: c.h:345
#define InvalidStrategy
Definition: stratnum.h:24
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3806
RelOptInfo * rel
Definition: selfuncs.h:70
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Oid * sortopfamily
Definition: pathnodes.h:806
bool hypothetical
Definition: pathnodes.h:827
Definition: type.h:89
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define NoLock
Definition: lockdefs.h:34
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1219
ScanDirection
Definition: sdir.h:22
#define SK_SEARCHNOTNULL
Definition: skey.h:122
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define SK_ISNULL
Definition: skey.h:115
Index relid
Definition: pathnodes.h:669
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:209
uintptr_t Datum
Definition: postgres.h:367
List * indexlist
Definition: pathnodes.h:678
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2029
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
RTEKind rtekind
Definition: parsenodes.h:974
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
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:5278
bool * reverse_sort
Definition: pathnodes.h:807
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: pathnodes.h:814
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126

◆ get_join_variables()

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

Definition at line 4346 of file selfuncs.c.

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

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

4349 {
4350  Node *left,
4351  *right;
4352 
4353  if (list_length(args) != 2)
4354  elog(ERROR, "join operator should take two arguments");
4355 
4356  left = (Node *) linitial(args);
4357  right = (Node *) lsecond(args);
4358 
4359  examine_variable(root, left, 0, vardata1);
4360  examine_variable(root, right, 0, vardata2);
4361 
4362  if (vardata1->rel &&
4363  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4364  *join_is_reversed = true; /* var1 is on RHS */
4365  else if (vardata2->rel &&
4366  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4367  *join_is_reversed = true; /* var2 is on LHS */
4368  else
4369  *join_is_reversed = false;
4370 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:525
#define lsecond(l)
Definition: pg_list.h:200
Relids syn_lefthand
Definition: pathnodes.h:2135
Relids syn_righthand
Definition: pathnodes.h:2136
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Relids relids
Definition: pathnodes.h:641
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4408
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:226

◆ get_quals_from_indexclauses()

List* get_quals_from_indexclauses ( List indexclauses)

Definition at line 5440 of file selfuncs.c.

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

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

5441 {
5442  List *result = NIL;
5443  ListCell *lc;
5444 
5445  foreach(lc, indexclauses)
5446  {
5447  IndexClause *iclause = lfirst_node(IndexClause, lc);
5448  ListCell *lc2;
5449 
5450  foreach(lc2, iclause->indexquals)
5451  {
5452  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5453 
5454  result = lappend(result, rinfo);
5455  }
5456  }
5457  return result;
5458 }
#define NIL
Definition: pg_list.h:65
#define lfirst_node(type, lc)
Definition: pg_list.h:193
List * indexquals
Definition: pathnodes.h:1224
List * lappend(List *list, void *datum)
Definition: list.c:322
Definition: pg_list.h:50

◆ get_restriction_variable()

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

Definition at line 4286 of file selfuncs.c.

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

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

4289 {
4290  Node *left,
4291  *right;
4292  VariableStatData rdata;
4293 
4294  /* Fail if not a binary opclause (probably shouldn't happen) */
4295  if (list_length(args) != 2)
4296  return false;
4297 
4298  left = (Node *) linitial(args);
4299  right = (Node *) lsecond(args);
4300 
4301  /*
4302  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4303  * relations will be treated as pseudoconstants.
4304  */
4305  examine_variable(root, left, varRelid, vardata);
4306  examine_variable(root, right, varRelid, &rdata);
4307 
4308  /*
4309  * If one side is a variable and the other not, we win.
4310  */
4311  if (vardata->rel && rdata.rel == NULL)
4312  {
4313  *varonleft = true;
4314  *other = estimate_expression_value(root, rdata.var);
4315  /* Assume we need no ReleaseVariableStats(rdata) here */
4316  return true;
4317  }
4318 
4319  if (vardata->rel == NULL && rdata.rel)
4320  {
4321  *varonleft = false;
4322  *other = estimate_expression_value(root, vardata->var);
4323  /* Assume we need no ReleaseVariableStats(*vardata) here */
4324  *vardata = rdata;
4325  return true;
4326  }
4327 
4328  /* Oops, clause has wrong structure (probably var op var) */
4329  ReleaseVariableStats(*vardata);
4330  ReleaseVariableStats(rdata);
4331 
4332  return false;
4333 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2286
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:525
#define lsecond(l)
Definition: pg_list.h:200
#define linitial(l)
Definition: pg_list.h:195
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4408
static int list_length(const List *l)
Definition: pg_list.h:169
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

Definition at line 4841 of file selfuncs.c.

References clamp_row_est(), DEFAULT_NUM_DISTINCT, GETSTRUCT, HeapTupleIsValid, IsA, VariableStatData::isunique, VariableStatData::rel, RTE_VALUES, RelOptInfo::rtekind, SelfItemPointerAttributeNumber, VariableStatData::statsTuple, TableOidAttributeNumber, RelOptInfo::tuples, VariableStatData::var, and VariableStatData::vartype.

Referenced by add_unique_group_var(), eqjoinsel(), estimate_hash_bucket_stats(), ineq_histogram_selectivity(), var_eq_const(), and var_eq_non_const().

4842 {
4843  double stadistinct;
4844  double stanullfrac = 0.0;
4845  double ntuples;
4846 
4847  *isdefault = false;
4848 
4849  /*
4850  * Determine the stadistinct value to use. There are cases where we can
4851  * get an estimate even without a pg_statistic entry, or can get a better
4852  * value than is in pg_statistic. Grab stanullfrac too if we can find it
4853  * (otherwise, assume no nulls, for lack of any better idea).
4854  */
4855  if (HeapTupleIsValid(vardata->statsTuple))
4856  {
4857  /* Use the pg_statistic entry */
4858  Form_pg_statistic stats;
4859 
4860  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4861  stadistinct = stats->stadistinct;
4862  stanullfrac = stats->stanullfrac;
4863  }
4864  else if (vardata->vartype == BOOLOID)
4865  {
4866  /*
4867  * Special-case boolean columns: presumably, two distinct values.
4868  *
4869  * Are there any other datatypes we should wire in special estimates
4870  * for?
4871  */
4872  stadistinct = 2.0;
4873  }
4874  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
4875  {
4876  /*
4877  * If the Var represents a column of a VALUES RTE, assume it's unique.
4878  * This could of course be very wrong, but it should tend to be true
4879  * in well-written queries. We could consider examining the VALUES'
4880  * contents to get some real statistics; but that only works if the
4881  * entries are all constants, and it would be pretty expensive anyway.
4882  */
4883  stadistinct = -1.0; /* unique (and all non null) */
4884  }
4885  else
4886  {
4887  /*
4888  * We don't keep statistics for system columns, but in some cases we
4889  * can infer distinctness anyway.
4890  */
4891  if (vardata->var && IsA(vardata->var, Var))
4892  {
4893  switch (((Var *) vardata->var)->varattno)
4894  {
4896  stadistinct = -1.0; /* unique (and all non null) */
4897  break;
4899  stadistinct = 1.0; /* only 1 value */
4900  break;
4901  default:
4902  stadistinct = 0.0; /* means "unknown" */
4903  break;
4904  }
4905  }
4906  else
4907  stadistinct = 0.0; /* means "unknown" */
4908 
4909  /*
4910  * XXX consider using estimate_num_groups on expressions?
4911  */
4912  }
4913 
4914  /*
4915  * If there is a unique index or DISTINCT clause for the variable, assume
4916  * it is unique no matter what pg_statistic says; the statistics could be
4917  * out of date, or we might have found a partial unique index that proves
4918  * the var is unique for this query. However, we'd better still believe
4919  * the null-fraction statistic.
4920  */
4921  if (vardata->isunique)
4922  stadistinct = -1.0 * (1.0 - stanullfrac);
4923 
4924  /*
4925  * If we had an absolute estimate, use that.
4926  */
4927  if (stadistinct > 0.0)
4928  return clamp_row_est(stadistinct);
4929 
4930  /*
4931  * Otherwise we need to get the relation size; punt if not available.
4932  */
4933  if (vardata->rel == NULL)
4934  {
4935  *isdefault = true;
4936  return DEFAULT_NUM_DISTINCT;
4937  }
4938  ntuples = vardata->rel->tuples;
4939  if (ntuples <= 0.0)
4940  {
4941  *isdefault = true;
4942  return DEFAULT_NUM_DISTINCT;
4943  }
4944 
4945  /*
4946  * If we had a relative estimate, use that.
4947  */
4948  if (stadistinct < 0.0)
4949  return clamp_row_est(-stadistinct * ntuples);
4950 
4951  /*
4952  * With no data, estimate ndistinct = ntuples if the table is small, else
4953  * use default. We use DEFAULT_NUM_DISTINCT as the cutoff for "small" so
4954  * that the behavior isn't discontinuous.
4955  */
4956  if (ntuples < DEFAULT_NUM_DISTINCT)
4957  return clamp_row_est(ntuples);
4958 
4959  *isdefault = true;
4960  return DEFAULT_NUM_DISTINCT;
4961 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
HeapTuple statsTuple
Definition: selfuncs.h:71
double tuples
Definition: pathnodes.h:681
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: primnodes.h:167
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define TableOidAttributeNumber
Definition: sysattr.h:26
RTEKind rtekind
Definition: pathnodes.h:671
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:46
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
double clamp_row_est(double nrows)
Definition: costsize.c:187

◆ get_variable_range()

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

Definition at line 4973 of file selfuncs.c.

References ATTSTATSSLOT_VALUES, VariableStatData::atttype, datumCopy(), DatumGetBool, fmgr_info(), free_attstatsslot(), FunctionCall2Coll(), get_actual_variable_range(), get_attstatsslot(), get_opcode(), get_typlenbyval(), HeapTupleIsValid, i, InvalidOid, AttStatsSlot::nvalues, AttStatsSlot::stacoll, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by mergejoinscansel().

4975 {
4976  Datum tmin = 0;
4977  Datum tmax = 0;
4978  bool have_data = false;
4979  int16 typLen;
4980  bool typByVal;
4981  Oid opfuncoid;
4982  AttStatsSlot sslot;
4983  int i;
4984 
4985  /*
4986  * XXX It's very tempting to try to use the actual column min and max, if
4987  * we can get them relatively-cheaply with an index probe. However, since
4988  * this function is called many times during join planning, that could
4989  * have unpleasant effects on planning speed. Need more investigation
4990  * before enabling this.
4991  */
4992 #ifdef NOT_USED
4993  if (get_actual_variable_range(root, vardata, sortop, min, max))
4994  return true;
4995 #endif
4996 
4997  if (!HeapTupleIsValid(vardata->statsTuple))
4998  {
4999  /* no stats available, so default result */
5000  return false;
5001  }
5002 
5003  /*
5004  * If we can't apply the sortop to the stats data, just fail. In
5005  * principle, if there's a histogram and no MCVs, we could return the
5006  * histogram endpoints without ever applying the sortop ... but it's
5007  * probably not worth trying, because whatever the caller wants to do with
5008  * the endpoints would likely fail the security check too.
5009  */
5010  if (!statistic_proc_security_check(vardata,
5011  (opfuncoid = get_opcode(sortop))))
5012  return false;
5013 
5014  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5015 
5016  /*
5017  * If there is a histogram, grab the first and last values.
5018  *
5019  * If there is a histogram that is sorted with some other operator than
5020  * the one we want, fail --- this suggests that there is data we can't
5021  * use.
5022  */
5023  if (get_attstatsslot(&sslot, vardata->statsTuple,
5024  STATISTIC_KIND_HISTOGRAM, sortop,
5026  {
5027  if (sslot.nvalues > 0)
5028  {
5029  tmin = datumCopy(sslot.values[0], typByVal, typLen);
5030  tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
5031  have_data = true;
5032  }
5033  free_attstatsslot(&sslot);
5034  }
5035  else if (get_attstatsslot(&sslot, vardata->statsTuple,
5036  STATISTIC_KIND_HISTOGRAM, InvalidOid,
5037  0))
5038  {
5039  free_attstatsslot(&sslot);
5040  return false;
5041  }
5042 
5043  /*
5044  * If we have most-common-values info, look for extreme MCVs. This is
5045  * needed even if we also have a histogram, since the histogram excludes
5046  * the MCVs. However, usually the MCVs will not be the extreme values, so
5047  * avoid unnecessary data copying.
5048  */
5049  if (get_attstatsslot(&sslot, vardata->statsTuple,
5050  STATISTIC_KIND_MCV, InvalidOid,
5052  {
5053  bool tmin_is_mcv = false;
5054  bool tmax_is_mcv = false;
5055  FmgrInfo opproc;
5056 
5057  fmgr_info(opfuncoid, &opproc);
5058 
5059  for (i = 0; i < sslot.nvalues; i++)
5060  {
5061  if (!have_data)
5062  {
5063  tmin = tmax = sslot.values[i];
5064  tmin_is_mcv = tmax_is_mcv = have_data = true;
5065  continue;
5066  }
5067  if (DatumGetBool(FunctionCall2Coll(&opproc,
5068  sslot.stacoll,
5069  sslot.values[i], tmin)))
5070  {
5071  tmin = sslot.values[i];
5072  tmin_is_mcv = true;
5073  }
5074  if (DatumGetBool(FunctionCall2Coll(&opproc,
5075  sslot.stacoll,
5076  tmax, sslot.values[i])))
5077  {
5078  tmax = sslot.values[i];
5079  tmax_is_mcv = true;
5080  }
5081  }
5082  if (tmin_is_mcv)
5083  tmin = datumCopy(tmin, typByVal, typLen);
5084  if (tmax_is_mcv)
5085  tmax = datumCopy(tmax, typByVal, typLen);
5086  free_attstatsslot(&sslot);
5087  }
5088 
5089  *min = tmin;
5090  *max = tmax;
5091  return have_data;
5092 }