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

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

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

5756 {
5757  List *predExtraQuals = NIL;
5758  ListCell *lc;
5759 
5760  if (index->indpred == NIL)
5761  return indexQuals;
5762 
5763  foreach(lc, index->indpred)
5764  {
5765  Node *predQual = (Node *) lfirst(lc);
5766  List *oneQual = list_make1(predQual);
5767 
5768  if (!predicate_implied_by(oneQual, indexQuals, false))
5769  predExtraQuals = list_concat(predExtraQuals, oneQual);
5770  }
5771  return list_concat(predExtraQuals, indexQuals);
5772 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:524
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
#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:2998
RelOptInfo * rel
Definition: selfuncs.h:69
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:4854
Node * var
Definition: selfuncs.c:2924
List * lappend(List *list, void *datum)
Definition: list.c:321
#define lfirst(lc)
Definition: pg_list.h:190
void * palloc(Size size)
Definition: mcxt.c:924
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:70
int nnumbers
Definition: lsyscache.h:54
double Selectivity
Definition: nodes.h:657
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:134
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:56
#define DEFAULT_NOT_UNK_SEL
Definition: selfuncs.h:49
#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:48
#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:4421
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:80
#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:70
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:4421
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80

◆ brincostestimate()

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

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

6845 {
6846  IndexOptInfo *index = path->indexinfo;
6847  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6848  double numPages = index->pages;
6849  RelOptInfo *baserel = index->rel;
6850  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
6851  Cost spc_seq_page_cost;
6852  Cost spc_random_page_cost;
6853  double qual_arg_cost;
6854  double qualSelectivity;
6855  BrinStatsData statsData;
6856  double indexRanges;
6857  double minimalRanges;
6858  double estimatedRanges;
6859  double selec;
6860  Relation indexRel;
6861  ListCell *l;
6862  VariableStatData vardata;
6863 
6864  Assert(rte->rtekind == RTE_RELATION);
6865 
6866  /* fetch estimated page cost for the tablespace containing the index */
6868  &spc_random_page_cost,
6869  &spc_seq_page_cost);
6870 
6871  /*
6872  * Obtain some data from the index itself. A lock should have already
6873  * been obtained on the index in plancat.c.
6874  */
6875  indexRel = index_open(index->indexoid, NoLock);
6876  brinGetStats(indexRel, &statsData);
6877  index_close(indexRel, NoLock);
6878 
6879  /*
6880  * Compute index correlation
6881  *
6882  * Because we can use all index quals equally when scanning, we can use
6883  * the largest correlation (in absolute value) among columns used by the
6884  * query. Start at zero, the worst possible case. If we cannot find any
6885  * correlation statistics, we will keep it as 0.
6886  */
6887  *indexCorrelation = 0;
6888 
6889  foreach(l, path->indexclauses)
6890  {
6891  IndexClause *iclause = lfirst_node(IndexClause, l);
6892  AttrNumber attnum = index->indexkeys[iclause->indexcol];
6893 
6894  /* attempt to lookup stats in relation for this index column */
6895  if (attnum != 0)
6896  {
6897  /* Simple variable -- look to stats for the underlying table */
6899  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
6900  {
6901  /*
6902  * The hook took control of acquiring a stats tuple. If it
6903  * did supply a tuple, it'd better have supplied a freefunc.
6904  */
6905  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
6906  elog(ERROR,
6907  "no function provided to release variable stats with");
6908  }
6909  else
6910  {
6911  vardata.statsTuple =
6913  ObjectIdGetDatum(rte->relid),
6914  Int16GetDatum(attnum),
6915  BoolGetDatum(false));
6916  vardata.freefunc = ReleaseSysCache;
6917  }
6918  }
6919  else
6920  {
6921  /*
6922  * Looks like we've found an expression column in the index. Let's
6923  * see if there's any stats for it.
6924  */
6925 
6926  /* get the attnum from the 0-based index. */
6927  attnum = iclause->indexcol + 1;
6928 
6929  if (get_index_stats_hook &&
6930  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
6931  {
6932  /*
6933  * The hook took control of acquiring a stats tuple. If it
6934  * did supply a tuple, it'd better have supplied a freefunc.
6935  */
6936  if (HeapTupleIsValid(vardata.statsTuple) &&
6937  !vardata.freefunc)
6938  elog(ERROR, "no function provided to release variable stats with");
6939  }
6940  else
6941  {
6943  ObjectIdGetDatum(index->indexoid),
6944  Int16GetDatum(attnum),
6945  BoolGetDatum(false));
6946  vardata.freefunc = ReleaseSysCache;
6947  }
6948  }
6949 
6950  if (HeapTupleIsValid(vardata.statsTuple))
6951  {
6952  AttStatsSlot sslot;
6953 
6954  if (get_attstatsslot(&sslot, vardata.statsTuple,
6955  STATISTIC_KIND_CORRELATION, InvalidOid,
6957  {
6958  double varCorrelation = 0.0;
6959 
6960  if (sslot.nnumbers > 0)
6961  varCorrelation = Abs(sslot.numbers[0]);
6962 
6963  if (varCorrelation > *indexCorrelation)
6964  *indexCorrelation = varCorrelation;
6965 
6966  free_attstatsslot(&sslot);
6967  }
6968  }
6969 
6970  ReleaseVariableStats(vardata);
6971  }
6972 
6973  qualSelectivity = clauselist_selectivity(root, indexQuals,
6974  baserel->relid,
6975  JOIN_INNER, NULL);
6976 
6977  /* work out the actual number of ranges in the index */
6978  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
6979  1.0);
6980 
6981  /*
6982  * Now calculate the minimum possible ranges we could match with if all of
6983  * the rows were in the perfect order in the table's heap.
6984  */
6985  minimalRanges = ceil(indexRanges * qualSelectivity);
6986 
6987  /*
6988  * Now estimate the number of ranges that we'll touch by using the
6989  * indexCorrelation from the stats. Careful not to divide by zero (note
6990  * we're using the absolute value of the correlation).
6991  */
6992  if (*indexCorrelation < 1.0e-10)
6993  estimatedRanges = indexRanges;
6994  else
6995  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
6996 
6997  /* we expect to visit this portion of the table */
6998  selec = estimatedRanges / indexRanges;
6999 
7000  CLAMP_PROBABILITY(selec);
7001 
7002  *indexSelectivity = selec;
7003 
7004  /*
7005  * Compute the index qual costs, much as in genericcostestimate, to add to
7006  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7007  * support those.
7008  */
7009  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7010 
7011  /*
7012  * Compute the startup cost as the cost to read the whole revmap
7013  * sequentially, including the cost to execute the index quals.
7014  */
7015  *indexStartupCost =
7016  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7017  *indexStartupCost += qual_arg_cost;
7018 
7019  /*
7020  * To read a BRIN index there might be a bit of back and forth over
7021  * regular pages, as revmap might point to them out of sequential order;
7022  * calculate the total cost as reading the whole index in random order.
7023  */
7024  *indexTotalCost = *indexStartupCost +
7025  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7026 
7027  /*
7028  * Charge a small amount per range tuple which we expect to match to. This
7029  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7030  * will set a bit for each page in the range when we find a matching
7031  * range, so we must multiply the charge by the number of pages in the
7032  * range.
7033  */
7034  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7035  statsData.pagesPerRange;
7036 
7037  *indexPages = index->pages;
7038 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1177
HeapTuple statsTuple
Definition: selfuncs.h:70
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:72
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:56
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:5453
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:5483
#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:80
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:658
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 5776 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().

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

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

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

Referenced by convert_to_scalar().

4152 {
4153  bytea *valuep = DatumGetByteaPP(value);
4154  bytea *loboundp = DatumGetByteaPP(lobound);
4155  bytea *hiboundp = DatumGetByteaPP(hibound);
4156  int rangelo,
4157  rangehi,
4158  valuelen = VARSIZE_ANY_EXHDR(valuep),
4159  loboundlen = VARSIZE_ANY_EXHDR(loboundp),
4160  hiboundlen = VARSIZE_ANY_EXHDR(hiboundp),
4161  i,
4162  minlen;
4163  unsigned char *valstr = (unsigned char *) VARDATA_ANY(valuep);
4164  unsigned char *lostr = (unsigned char *) VARDATA_ANY(loboundp);
4165  unsigned char *histr = (unsigned char *) VARDATA_ANY(hiboundp);
4166 
4167  /*
4168  * Assume bytea data is uniformly distributed across all byte values.
4169  */
4170  rangelo = 0;
4171  rangehi = 255;
4172 
4173  /*
4174  * Now strip any common prefix of the three strings.
4175  */
4176  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4177  for (i = 0; i < minlen; i++)
4178  {
4179  if (*lostr != *histr || *lostr != *valstr)
4180  break;
4181  lostr++, histr++, valstr++;
4182  loboundlen--, hiboundlen--, valuelen--;
4183  }
4184 
4185  /*
4186  * Now we can do the conversions.
4187  */
4188  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4189  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4190  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4191 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:348
#define Min(x, y)
Definition: c.h:904
static struct @144 value
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4194
#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 @144 value
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:616
#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 4194 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

4196 {
4197  double num,
4198  denom,
4199  base;
4200 
4201  if (valuelen <= 0)
4202  return 0.0; /* empty string has scalar value 0 */
4203 
4204  /*
4205  * Since base is 256, need not consider more than about 10 chars (even
4206  * this many seems like overkill)
4207  */
4208  if (valuelen > 10)
4209  valuelen = 10;
4210 
4211  /* Convert initial characters to fraction */
4212  base = rangehi - rangelo + 1;
4213  num = 0.0;
4214  denom = base;
4215  while (valuelen-- > 0)
4216  {
4217  int ch = *value++;
4218 
4219  if (ch < rangelo)
4220  ch = rangelo - 1;
4221  else if (ch > rangehi)
4222  ch = rangehi + 1;
4223  num += ((double) (ch - rangelo)) / denom;
4224  denom *= base;
4225  }
4226 
4227  return num;
4228 }
static struct @144 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 @144 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 #if _MSC_VER == 1400 /* VS.Net 2005 */
4096 
4097  /*
4098  *
4099  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4100  */
4101  {
4102  char x[1];
4103 
4104  xfrmlen = strxfrm(x, val, 0);
4105  }
4106 #else
4107  xfrmlen = strxfrm(NULL, val, 0);
4108 #endif
4109 #ifdef WIN32
4110 
4111  /*
4112  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4113  * of trying to allocate this much memory (and fail), just return the
4114  * original string unmodified as if we were in the C locale.
4115  */
4116  if (xfrmlen == INT_MAX)
4117  return val;
4118 #endif
4119  xfrmstr = (char *) palloc(xfrmlen + 1);
4120  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4121 
4122  /*
4123  * Some systems (e.g., glibc) can return a smaller value from the
4124  * second call than the first; thus the Assert must be <= not ==.
4125  */
4126  Assert(xfrmlen2 <= xfrmlen);
4127  pfree(val);
4128  val = xfrmstr;
4129  }
4130 
4131  return val;
4132 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
static struct @144 value
void pfree(void *pointer)
Definition: mcxt.c:1031
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1191
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:924
#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 @144 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 4237 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().

4238 {
4239  switch (typid)
4240  {
4241  case TIMESTAMPOID:
4242  return DatumGetTimestamp(value);
4243  case TIMESTAMPTZOID:
4244  return DatumGetTimestampTz(value);
4245  case DATEOID:
4247  case INTERVALOID:
4248  {
4250 
4251  /*
4252  * Convert the month part of Interval to days using assumed
4253  * average month length of 365.25/12.0 days. Not too
4254  * accurate, but plenty good enough for our purposes.
4255  */
4256  return interval->time + interval->day * (double) USECS_PER_DAY +
4257  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4258  }
4259  case TIMEOID:
4260  return DatumGetTimeADT(value);
4261  case TIMETZOID:
4262  {
4263  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4264 
4265  /* use GMT-equivalent time */
4266  return (double) (timetz->time + (timetz->zone * 1000000.0));
4267  }
4268  }
4269 
4270  *failure = true;
4271  return 0;
4272 }
#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 @144 value
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:648
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 @144 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:1031
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:4146
static double convert_timevalue_to_scalar(Datum value, Oid typid, bool *failure)
Definition: selfuncs.c:4237
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:70
bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid)
Definition: selfuncs.c:4825
#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:691
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:56
#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:4359
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4854
#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:5418
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:80
#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:56
void pfree(void *pointer)
Definition: mcxt.c:1031
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:955
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:69
#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:56
void pfree(void *pointer)
Definition: mcxt.c:1031
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:955
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:575
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
Definition: selfuncs.c:4299
double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:288
Definition: nodes.h:524
#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:33
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
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:575
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:70
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:681
RelOptInfo * rel
Definition: selfuncs.h:69
double Selectivity
Definition: nodes.h:657
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:4854
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:4421
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80
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:575
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:321
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:259
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:352
#define Assert(condition)
Definition: c.h: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:70
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
double tuples
Definition: pathnodes.h:681
Definition: nodes.h:524
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:654
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
static bool estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
Definition: selfuncs.c:3567
List * lappend(List *list, void *datum)
Definition: list.c:321
static List * add_unique_group_var(PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
Definition: selfuncs.c: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:4421
#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:80
#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 4648 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().

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

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

5419 {
5420  RelOptInfo *rel = NULL;
5421 
5422  switch (bms_membership(relids))
5423  {
5424  case BMS_EMPTY_SET:
5425  /* should not happen */
5426  break;
5427  case BMS_SINGLETON:
5428  rel = find_base_rel(root, bms_singleton_member(relids));
5429  break;
5430  case BMS_MULTIPLE:
5431  rel = find_join_rel(root, relids);
5432  break;
5433  }
5434 
5435  if (rel == NULL)
5436  elog(ERROR, "could not find RelOptInfo for given relids");
5437 
5438  return rel;
5439 }
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 5537 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().

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

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

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

5123 {
5124  bool have_data = false;
5125  RelOptInfo *rel = vardata->rel;
5126  RangeTblEntry *rte;
5127  ListCell *lc;
5128 
5129  /* No hope if no relation or it doesn't have indexes */
5130  if (rel == NULL || rel->indexlist == NIL)
5131  return false;
5132  /* If it has indexes it must be a plain relation */
5133  rte = root->simple_rte_array[rel->relid];
5134  Assert(rte->rtekind == RTE_RELATION);
5135 
5136  /* Search through the indexes to see if any match our problem */
5137  foreach(lc, rel->indexlist)
5138  {
5140  ScanDirection indexscandir;
5141 
5142  /* Ignore non-btree indexes */
5143  if (index->relam != BTREE_AM_OID)
5144  continue;
5145 
5146  /*
5147  * Ignore partial indexes --- we only want stats that cover the entire
5148  * relation.
5149  */
5150  if (index->indpred != NIL)
5151  continue;
5152 
5153  /*
5154  * The index list might include hypothetical indexes inserted by a
5155  * get_relation_info hook --- don't try to access them.
5156  */
5157  if (index->hypothetical)
5158  continue;
5159 
5160  /*
5161  * The first index column must match the desired variable and sort
5162  * operator --- but we can use a descending-order index.
5163  */
5164  if (!match_index_to_operand(vardata->var, 0, index))
5165  continue;
5166  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5167  {
5168  case BTLessStrategyNumber:
5169  if (index->reverse_sort[0])
5170  indexscandir = BackwardScanDirection;
5171  else
5172  indexscandir = ForwardScanDirection;
5173  break;
5175  if (index->reverse_sort[0])
5176  indexscandir = ForwardScanDirection;
5177  else
5178  indexscandir = BackwardScanDirection;
5179  break;
5180  default:
5181  /* index doesn't match the sortop */
5182  continue;
5183  }
5184 
5185  /*
5186  * Found a suitable index to extract data from. Set up some data that
5187  * can be used by both invocations of get_actual_variable_endpoint.
5188  */
5189  {
5190  MemoryContext tmpcontext;
5191  MemoryContext oldcontext;
5192  Relation heapRel;
5193  Relation indexRel;
5194  TupleTableSlot *slot;
5195  int16 typLen;
5196  bool typByVal;
5197  ScanKeyData scankeys[1];
5198 
5199  /* Make sure any cruft gets recycled when we're done */
5201  "get_actual_variable_range workspace",
5203  oldcontext = MemoryContextSwitchTo(tmpcontext);
5204 
5205  /*
5206  * Open the table and index so we can read from them. We should
5207  * already have some type of lock on each.
5208  */
5209  heapRel = table_open(rte->relid, NoLock);
5210  indexRel = index_open(index->indexoid, NoLock);
5211 
5212  /* build some stuff needed for indexscan execution */
5213  slot = table_slot_create(heapRel, NULL);
5214  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5215 
5216  /* set up an IS NOT NULL scan key so that we ignore nulls */
5217  ScanKeyEntryInitialize(&scankeys[0],
5219  1, /* index col to scan */
5220  InvalidStrategy, /* no strategy */
5221  InvalidOid, /* no strategy subtype */
5222  InvalidOid, /* no collation */
5223  InvalidOid, /* no reg proc for this */
5224  (Datum) 0); /* constant */
5225 
5226  /* If min is requested ... */
5227  if (min)
5228  {
5229  have_data = get_actual_variable_endpoint(heapRel,
5230  indexRel,
5231  indexscandir,
5232  scankeys,
5233  typLen,
5234  typByVal,
5235  slot,
5236  oldcontext,
5237  min);
5238  }
5239  else
5240  {
5241  /* If min not requested, assume index is nonempty */
5242  have_data = true;
5243  }
5244 
5245  /* If max is requested, and we didn't find the index is empty */
5246  if (max && have_data)
5247  {
5248  /* scan in the opposite direction; all else is the same */
5249  have_data = get_actual_variable_endpoint(heapRel,
5250  indexRel,
5251  -indexscandir,
5252  scankeys,
5253  typLen,
5254  typByVal,
5255  slot,
5256  oldcontext,
5257  max);
5258  }
5259 
5260  /* Clean everything up */
5262 
5263  index_close(indexRel, NoLock);
5264  table_close(heapRel, NoLock);
5265 
5266  MemoryContextSwitchTo(oldcontext);
5267  MemoryContextDelete(tmpcontext);
5268 
5269  /* And we're done */
5270  break;
5271  }
5272  }
5273 
5274  return have_data;
5275 }
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:169
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:69
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:191
#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:5291
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 4359 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().

4362 {
4363  Node *left,
4364  *right;
4365 
4366  if (list_length(args) != 2)
4367  elog(ERROR, "join operator should take two arguments");
4368 
4369  left = (Node *) linitial(args);
4370  right = (Node *) lsecond(args);
4371 
4372  examine_variable(root, left, 0, vardata1);
4373  examine_variable(root, right, 0, vardata2);
4374 
4375  if (vardata1->rel &&
4376  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4377  *join_is_reversed = true; /* var1 is on RHS */
4378  else if (vardata2->rel &&
4379  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4380  *join_is_reversed = true; /* var2 is on LHS */
4381  else
4382  *join_is_reversed = false;
4383 }
RelOptInfo * rel
Definition: selfuncs.h:69
Definition: nodes.h:524
#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:4421
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 5453 of file selfuncs.c.

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

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

5454 {
5455  List *result = NIL;
5456  ListCell *lc;
5457 
5458  foreach(lc, indexclauses)
5459  {
5460  IndexClause *iclause = lfirst_node(IndexClause, lc);
5461  ListCell *lc2;
5462 
5463  foreach(lc2, iclause->indexquals)
5464  {
5465  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5466 
5467  result = lappend(result, rinfo);
5468  }
5469  }
5470  return result;
5471 }
#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:321
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 4299 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().

4302 {
4303  Node *left,
4304  *right;
4305  VariableStatData rdata;
4306 
4307  /* Fail if not a binary opclause (probably shouldn't happen) */
4308  if (list_length(args) != 2)
4309  return false;
4310 
4311  left = (Node *) linitial(args);
4312  right = (Node *) lsecond(args);
4313 
4314  /*
4315  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4316  * relations will be treated as pseudoconstants.
4317  */
4318  examine_variable(root, left, varRelid, vardata);
4319  examine_variable(root, right, varRelid, &rdata);
4320 
4321  /*
4322  * If one side is a variable and the other not, we win.
4323  */
4324  if (vardata->rel && rdata.rel == NULL)
4325  {
4326  *varonleft = true;
4327  *other = estimate_expression_value(root, rdata.var);
4328  /* Assume we need no ReleaseVariableStats(rdata) here */
4329  return true;
4330  }
4331 
4332  if (vardata->rel == NULL && rdata.rel)
4333  {
4334  *varonleft = false;
4335  *other = estimate_expression_value(root, vardata->var);
4336  /* Assume we need no ReleaseVariableStats(*vardata) here */
4337  *vardata = rdata;
4338  return true;
4339  }
4340 
4341  /* Oops, clause has wrong structure (probably var op var) */
4342  ReleaseVariableStats(*vardata);
4343  ReleaseVariableStats(rdata);
4344 
4345  return false;
4346 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2286
RelOptInfo * rel
Definition: selfuncs.h:69
Definition: nodes.h:524
#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:4421
static int list_length(const List *l)
Definition: pg_list.h:169
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:80

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

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

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

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