PostgreSQL Source Code  git master
selfuncs.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <math.h>
#include "access/brin.h"
#include "access/brin_page.h"
#include "access/gin.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/visibilitymap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_statistic_ext.h"
#include "executor/nodeAgg.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "utils/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 5868 of file selfuncs.c.

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

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

5869 {
5870  List *predExtraQuals = NIL;
5871  ListCell *lc;
5872 
5873  if (index->indpred == NIL)
5874  return indexQuals;
5875 
5876  foreach(lc, index->indpred)
5877  {
5878  Node *predQual = (Node *) lfirst(lc);
5879  List *oneQual = list_make1(predQual);
5880 
5881  if (!predicate_implied_by(oneQual, indexQuals, false))
5882  predExtraQuals = list_concat(predExtraQuals, oneQual);
5883  }
5884  return list_concat(predExtraQuals, indexQuals);
5885 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:525
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
#define list_make1(x1)
Definition: pg_list.h:227
#define lfirst(lc)
Definition: pg_list.h:190
List * indpred
Definition: pathnodes.h:816
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 2931 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().

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

◆ booltestsel()

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

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

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

◆ boolvarsel()

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

Definition at line 1268 of file selfuncs.c.

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

Referenced by clause_selectivity().

1269 {
1270  VariableStatData vardata;
1271  double selec;
1272 
1273  examine_variable(root, arg, varRelid, &vardata);
1274  if (HeapTupleIsValid(vardata.statsTuple))
1275  {
1276  /*
1277  * A boolean variable V is equivalent to the clause V = 't', so we
1278  * compute the selectivity as if that is what we have.
1279  */
1280  selec = var_eq_const(&vardata, BooleanEqualOperator,
1281  BoolGetDatum(true), false, true, false);
1282  }
1283  else
1284  {
1285  /* Otherwise, the default estimate is 0.5 */
1286  selec = 0.5;
1287  }
1288  ReleaseVariableStats(vardata);
1289  return selec;
1290 }
HeapTuple statsTuple
Definition: selfuncs.h:71
double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:289
#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:4418
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81

◆ brincostestimate()

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

Definition at line 6954 of file selfuncs.c.

References Abs, Assert, attnum, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BRIN_DEFAULT_PAGES_PER_RANGE, brinGetStats(), CLAMP_PROBABILITY, clauselist_selectivity(), cpu_operator_cost, elog, ERROR, free_attstatsslot(), VariableStatData::freefunc, get_attstatsslot(), get_index_stats_hook, get_quals_from_indexclauses(), get_relation_stats_hook, get_tablespace_page_costs(), HeapTupleIsValid, IndexOptInfo::hypothetical, index_close(), index_open(), index_other_operands_eval_cost(), IndexPath::indexclauses, IndexClause::indexcol, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, Int16GetDatum, InvalidOid, JOIN_INNER, lfirst_node, Max, Min, AttStatsSlot::nnumbers, NoLock, AttStatsSlot::numbers, ObjectIdGetDatum, RelOptInfo::pages, IndexOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reltablespace, REVMAP_PAGE_MAXITEMS, BrinStatsData::revmapNumPages, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

6958 {
6959  IndexOptInfo *index = path->indexinfo;
6960  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6961  double numPages = index->pages;
6962  RelOptInfo *baserel = index->rel;
6963  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
6964  Cost spc_seq_page_cost;
6965  Cost spc_random_page_cost;
6966  double qual_arg_cost;
6967  double qualSelectivity;
6968  BrinStatsData statsData;
6969  double indexRanges;
6970  double minimalRanges;
6971  double estimatedRanges;
6972  double selec;
6973  Relation indexRel;
6974  ListCell *l;
6975  VariableStatData vardata;
6976 
6977  Assert(rte->rtekind == RTE_RELATION);
6978 
6979  /* fetch estimated page cost for the tablespace containing the index */
6981  &spc_random_page_cost,
6982  &spc_seq_page_cost);
6983 
6984  /*
6985  * Obtain some data from the index itself, if possible. Otherwise invent
6986  * some plausible internal statistics based on the relation page count.
6987  */
6988  if (!index->hypothetical)
6989  {
6990  /*
6991  * A lock should have already been obtained on the index in plancat.c.
6992  */
6993  indexRel = index_open(index->indexoid, NoLock);
6994  brinGetStats(indexRel, &statsData);
6995  index_close(indexRel, NoLock);
6996 
6997  /* work out the actual number of ranges in the index */
6998  indexRanges = Max(ceil((double) baserel->pages /
6999  statsData.pagesPerRange), 1.0);
7000  }
7001  else
7002  {
7003  /*
7004  * Assume default number of pages per range, and estimate the number
7005  * of ranges based on that.
7006  */
7007  indexRanges = Max(ceil((double) baserel->pages /
7009 
7011  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7012  }
7013 
7014  /*
7015  * Compute index correlation
7016  *
7017  * Because we can use all index quals equally when scanning, we can use
7018  * the largest correlation (in absolute value) among columns used by the
7019  * query. Start at zero, the worst possible case. If we cannot find any
7020  * correlation statistics, we will keep it as 0.
7021  */
7022  *indexCorrelation = 0;
7023 
7024  foreach(l, path->indexclauses)
7025  {
7026  IndexClause *iclause = lfirst_node(IndexClause, l);
7027  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7028 
7029  /* attempt to lookup stats in relation for this index column */
7030  if (attnum != 0)
7031  {
7032  /* Simple variable -- look to stats for the underlying table */
7034  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7035  {
7036  /*
7037  * The hook took control of acquiring a stats tuple. If it
7038  * did supply a tuple, it'd better have supplied a freefunc.
7039  */
7040  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7041  elog(ERROR,
7042  "no function provided to release variable stats with");
7043  }
7044  else
7045  {
7046  vardata.statsTuple =
7048  ObjectIdGetDatum(rte->relid),
7049  Int16GetDatum(attnum),
7050  BoolGetDatum(false));
7051  vardata.freefunc = ReleaseSysCache;
7052  }
7053  }
7054  else
7055  {
7056  /*
7057  * Looks like we've found an expression column in the index. Let's
7058  * see if there's any stats for it.
7059  */
7060 
7061  /* get the attnum from the 0-based index. */
7062  attnum = iclause->indexcol + 1;
7063 
7064  if (get_index_stats_hook &&
7065  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7066  {
7067  /*
7068  * The hook took control of acquiring a stats tuple. If it
7069  * did supply a tuple, it'd better have supplied a freefunc.
7070  */
7071  if (HeapTupleIsValid(vardata.statsTuple) &&
7072  !vardata.freefunc)
7073  elog(ERROR, "no function provided to release variable stats with");
7074  }
7075  else
7076  {
7078  ObjectIdGetDatum(index->indexoid),
7079  Int16GetDatum(attnum),
7080  BoolGetDatum(false));
7081  vardata.freefunc = ReleaseSysCache;
7082  }
7083  }
7084 
7085  if (HeapTupleIsValid(vardata.statsTuple))
7086  {
7087  AttStatsSlot sslot;
7088 
7089  if (get_attstatsslot(&sslot, vardata.statsTuple,
7090  STATISTIC_KIND_CORRELATION, InvalidOid,
7092  {
7093  double varCorrelation = 0.0;
7094 
7095  if (sslot.nnumbers > 0)
7096  varCorrelation = Abs(sslot.numbers[0]);
7097 
7098  if (varCorrelation > *indexCorrelation)
7099  *indexCorrelation = varCorrelation;
7100 
7101  free_attstatsslot(&sslot);
7102  }
7103  }
7104 
7105  ReleaseVariableStats(vardata);
7106  }
7107 
7108  qualSelectivity = clauselist_selectivity(root, indexQuals,
7109  baserel->relid,
7110  JOIN_INNER, NULL);
7111 
7112  /*
7113  * Now calculate the minimum possible ranges we could match with if all of
7114  * the rows were in the perfect order in the table's heap.
7115  */
7116  minimalRanges = ceil(indexRanges * qualSelectivity);
7117 
7118  /*
7119  * Now estimate the number of ranges that we'll touch by using the
7120  * indexCorrelation from the stats. Careful not to divide by zero (note
7121  * we're using the absolute value of the correlation).
7122  */
7123  if (*indexCorrelation < 1.0e-10)
7124  estimatedRanges = indexRanges;
7125  else
7126  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7127 
7128  /* we expect to visit this portion of the table */
7129  selec = estimatedRanges / indexRanges;
7130 
7131  CLAMP_PROBABILITY(selec);
7132 
7133  *indexSelectivity = selec;
7134 
7135  /*
7136  * Compute the index qual costs, much as in genericcostestimate, to add to
7137  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7138  * support those.
7139  */
7140  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7141 
7142  /*
7143  * Compute the startup cost as the cost to read the whole revmap
7144  * sequentially, including the cost to execute the index quals.
7145  */
7146  *indexStartupCost =
7147  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7148  *indexStartupCost += qual_arg_cost;
7149 
7150  /*
7151  * To read a BRIN index there might be a bit of back and forth over
7152  * regular pages, as revmap might point to them out of sequential order;
7153  * calculate the total cost as reading the whole index in random order.
7154  */
7155  *indexTotalCost = *indexStartupCost +
7156  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7157 
7158  /*
7159  * Charge a small amount per range tuple which we expect to match to. This
7160  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7161  * will set a bit for each page in the range when we find a matching
7162  * range, so we must multiply the charge by the number of pages in the
7163  * range.
7164  */
7165  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7166  statsData.pagesPerRange;
7167 
7168  *indexPages = index->pages;
7169 }
IndexOptInfo * indexinfo
Definition: pathnodes.h:1179
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
#define Min(x, y)
Definition: c.h:911
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
Oid reltablespace
Definition: pathnodes.h:792
bool hypothetical
Definition: pathnodes.h:829
List * indexclauses
Definition: pathnodes.h:1180
#define Abs(x)
Definition: c.h:917
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:796
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
RelOptInfo * rel
Definition: pathnodes.h:793
#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:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
AttrNumber indexcol
Definition: pathnodes.h:1228
#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:5566
#define BRIN_DEFAULT_PAGES_PER_RANGE
Definition: brin.h:38
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:147
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:671
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define REVMAP_PAGE_MAXITEMS
Definition: brin_page.h:93
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:33
int16 attnum
Definition: pg_attribute.h:79
#define Max(x, y)
Definition: c.h:905
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5596
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:682
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
#define Assert(condition)
Definition: c.h:739
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:148
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
RTEKind rtekind
Definition: parsenodes.h:974
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
#define elog(elevel,...)
Definition: elog.h:228
int * indexkeys
Definition: pathnodes.h:803
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
double Cost
Definition: nodes.h:659
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1079
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 5889 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().

5893 {
5894  IndexOptInfo *index = path->indexinfo;
5895  GenericCosts costs;
5896  Oid relid;
5897  AttrNumber colnum;
5898  VariableStatData vardata;
5899  double numIndexTuples;
5900  Cost descentCost;
5901  List *indexBoundQuals;
5902  int indexcol;
5903  bool eqQualHere;
5904  bool found_saop;
5905  bool found_is_null_op;
5906  double num_sa_scans;
5907  ListCell *lc;
5908 
5909  /*
5910  * For a btree scan, only leading '=' quals plus inequality quals for the
5911  * immediately next attribute contribute to index selectivity (these are
5912  * the "boundary quals" that determine the starting and stopping points of
5913  * the index scan). Additional quals can suppress visits to the heap, so
5914  * it's OK to count them in indexSelectivity, but they should not count
5915  * for estimating numIndexTuples. So we must examine the given indexquals
5916  * to find out which ones count as boundary quals. We rely on the
5917  * knowledge that they are given in index column order.
5918  *
5919  * For a RowCompareExpr, we consider only the first column, just as
5920  * rowcomparesel() does.
5921  *
5922  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
5923  * index scans not one, but the ScalarArrayOpExpr's operator can be
5924  * considered to act the same as it normally does.
5925  */
5926  indexBoundQuals = NIL;
5927  indexcol = 0;
5928  eqQualHere = false;
5929  found_saop = false;
5930  found_is_null_op = false;
5931  num_sa_scans = 1;
5932  foreach(lc, path->indexclauses)
5933  {
5934  IndexClause *iclause = lfirst_node(IndexClause, lc);
5935  ListCell *lc2;
5936 
5937  if (indexcol != iclause->indexcol)
5938  {
5939  /* Beginning of a new column's quals */
5940  if (!eqQualHere)
5941  break; /* done if no '=' qual for indexcol */
5942  eqQualHere = false;
5943  indexcol++;
5944  if (indexcol != iclause->indexcol)
5945  break; /* no quals at all for indexcol */
5946  }
5947 
5948  /* Examine each indexqual associated with this index clause */
5949  foreach(lc2, iclause->indexquals)
5950  {
5951  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5952  Expr *clause = rinfo->clause;
5953  Oid clause_op = InvalidOid;
5954  int op_strategy;
5955 
5956  if (IsA(clause, OpExpr))
5957  {
5958  OpExpr *op = (OpExpr *) clause;
5959 
5960  clause_op = op->opno;
5961  }
5962  else if (IsA(clause, RowCompareExpr))
5963  {
5964  RowCompareExpr *rc = (RowCompareExpr *) clause;
5965 
5966  clause_op = linitial_oid(rc->opnos);
5967  }
5968  else if (IsA(clause, ScalarArrayOpExpr))
5969  {
5970  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
5971  Node *other_operand = (Node *) lsecond(saop->args);
5972  int alength = estimate_array_length(other_operand);
5973 
5974  clause_op = saop->opno;
5975  found_saop = true;
5976  /* count number of SA scans induced by indexBoundQuals only */
5977  if (alength > 1)
5978  num_sa_scans *= alength;
5979  }
5980  else if (IsA(clause, NullTest))
5981  {
5982  NullTest *nt = (NullTest *) clause;
5983 
5984  if (nt->nulltesttype == IS_NULL)
5985  {
5986  found_is_null_op = true;
5987  /* IS NULL is like = for selectivity purposes */
5988  eqQualHere = true;
5989  }
5990  }
5991  else
5992  elog(ERROR, "unsupported indexqual type: %d",
5993  (int) nodeTag(clause));
5994 
5995  /* check for equality operator */
5996  if (OidIsValid(clause_op))
5997  {
5998  op_strategy = get_op_opfamily_strategy(clause_op,
5999  index->opfamily[indexcol]);
6000  Assert(op_strategy != 0); /* not a member of opfamily?? */
6001  if (op_strategy == BTEqualStrategyNumber)
6002  eqQualHere = true;
6003  }
6004 
6005  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6006  }
6007  }
6008 
6009  /*
6010  * If index is unique and we found an '=' clause for each column, we can
6011  * just assume numIndexTuples = 1 and skip the expensive
6012  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6013  * NullTest invalidates that theory, even though it sets eqQualHere.
6014  */
6015  if (index->unique &&
6016  indexcol == index->nkeycolumns - 1 &&
6017  eqQualHere &&
6018  !found_saop &&
6019  !found_is_null_op)
6020  numIndexTuples = 1.0;
6021  else
6022  {
6023  List *selectivityQuals;
6024  Selectivity btreeSelectivity;
6025 
6026  /*
6027  * If the index is partial, AND the index predicate with the
6028  * index-bound quals to produce a more accurate idea of the number of
6029  * rows covered by the bound conditions.
6030  */
6031  selectivityQuals = add_predicate_to_index_quals(index, indexBoundQuals);
6032 
6033  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6034  index->rel->relid,
6035  JOIN_INNER,
6036  NULL);
6037  numIndexTuples = btreeSelectivity * index->rel->tuples;
6038 
6039  /*
6040  * As in genericcostestimate(), we have to adjust for any
6041  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6042  * to integer.
6043  */
6044  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6045  }
6046 
6047  /*
6048  * Now do generic index cost estimation.
6049  */
6050  MemSet(&costs, 0, sizeof(costs));
6051  costs.numIndexTuples = numIndexTuples;
6052 
6053  genericcostestimate(root, path, loop_count, &costs);
6054 
6055  /*
6056  * Add a CPU-cost component to represent the costs of initial btree
6057  * descent. We don't charge any I/O cost for touching upper btree levels,
6058  * since they tend to stay in cache, but we still have to do about log2(N)
6059  * comparisons to descend a btree of N leaf tuples. We charge one
6060  * cpu_operator_cost per comparison.
6061  *
6062  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6063  * ones after the first one are not startup cost so far as the overall
6064  * plan is concerned, so add them only to "total" cost.
6065  */
6066  if (index->tuples > 1) /* avoid computing log(0) */
6067  {
6068  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6069  costs.indexStartupCost += descentCost;
6070  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6071  }
6072 
6073  /*
6074  * Even though we're not charging I/O cost for touching upper btree pages,
6075  * it's still reasonable to charge some CPU cost per page descended
6076  * through. Moreover, if we had no such charge at all, bloated indexes
6077  * would appear to have the same search cost as unbloated ones, at least
6078  * in cases where only a single leaf page is expected to be visited. This
6079  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6080  * touched. The number of such pages is btree tree height plus one (ie,
6081  * we charge for the leaf page too). As above, charge once per SA scan.
6082  */
6083  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6084  costs.indexStartupCost += descentCost;
6085  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6086 
6087  /*
6088  * If we can get an estimate of the first column's ordering correlation C
6089  * from pg_statistic, estimate the index correlation as C for a
6090  * single-column index, or C * 0.75 for multiple columns. (The idea here
6091  * is that multiple columns dilute the importance of the first column's
6092  * ordering, but don't negate it entirely. Before 8.0 we divided the
6093  * correlation by the number of columns, but that seems too strong.)
6094  */
6095  MemSet(&vardata, 0, sizeof(vardata));
6096 
6097  if (index->indexkeys[0] != 0)
6098  {
6099  /* Simple variable --- look to stats for the underlying table */
6100  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6101 
6102  Assert(rte->rtekind == RTE_RELATION);
6103  relid = rte->relid;
6104  Assert(relid != InvalidOid);
6105  colnum = index->indexkeys[0];
6106 
6108  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6109  {
6110  /*
6111  * The hook took control of acquiring a stats tuple. If it did
6112  * supply a tuple, it'd better have supplied a freefunc.
6113  */
6114  if (HeapTupleIsValid(vardata.statsTuple) &&
6115  !vardata.freefunc)
6116  elog(ERROR, "no function provided to release variable stats with");
6117  }
6118  else
6119  {
6121  ObjectIdGetDatum(relid),
6122  Int16GetDatum(colnum),
6123  BoolGetDatum(rte->inh));
6124  vardata.freefunc = ReleaseSysCache;
6125  }
6126  }
6127  else
6128  {
6129  /* Expression --- maybe there are stats for the index itself */
6130  relid = index->indexoid;
6131  colnum = 1;
6132 
6133  if (get_index_stats_hook &&
6134  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6135  {
6136  /*
6137  * The hook took control of acquiring a stats tuple. If it did
6138  * supply a tuple, it'd better have supplied a freefunc.
6139  */
6140  if (HeapTupleIsValid(vardata.statsTuple) &&
6141  !vardata.freefunc)
6142  elog(ERROR, "no function provided to release variable stats with");
6143  }
6144  else
6145  {
6147  ObjectIdGetDatum(relid),
6148  Int16GetDatum(colnum),
6149  BoolGetDatum(false));
6150  vardata.freefunc = ReleaseSysCache;
6151  }
6152  }
6153 
6154  if (HeapTupleIsValid(vardata.statsTuple))
6155  {
6156  Oid sortop;
6157  AttStatsSlot sslot;
6158 
6159  sortop = get_opfamily_member(index->opfamily[0],
6160  index->opcintype[0],
6161  index->opcintype[0],
6163  if (OidIsValid(sortop) &&
6164  get_attstatsslot(&sslot, vardata.statsTuple,
6165  STATISTIC_KIND_CORRELATION, sortop,
6167  {
6168  double varCorrelation;
6169 
6170  Assert(sslot.nnumbers == 1);
6171  varCorrelation = sslot.numbers[0];
6172 
6173  if (index->reverse_sort[0])
6174  varCorrelation = -varCorrelation;
6175 
6176  if (index->nkeycolumns > 1)
6177  costs.indexCorrelation = varCorrelation * 0.75;
6178  else
6179  costs.indexCorrelation = varCorrelation;
6180 
6181  free_attstatsslot(&sslot);
6182  }
6183  }
6184 
6185  ReleaseVariableStats(vardata);
6186 
6187  *indexStartupCost = costs.indexStartupCost;
6188  *indexTotalCost = costs.indexTotalCost;
6189  *indexSelectivity = costs.indexSelectivity;
6190  *indexCorrelation = costs.indexCorrelation;
6191  *indexPages = costs.numIndexPages;
6192 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
IndexOptInfo * indexinfo
Definition: pathnodes.h:1179
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:54
double tuples
Definition: pathnodes.h:683
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:525
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:962
List * indexclauses
Definition: pathnodes.h:1180
double Selectivity
Definition: nodes.h:658
double tuples
Definition: pathnodes.h:797
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: pathnodes.h:798
#define OidIsValid(objectId)
Definition: c.h:645
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1891
RelOptInfo * rel
Definition: pathnodes.h:793
#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:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
AttrNumber indexcol
Definition: pathnodes.h:1228
double num_sa_scans
Definition: selfuncs.h:113
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, GenericCosts *costs)
Definition: selfuncs.c:5650
float4 * numbers
Definition: lsyscache.h:53
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
double cpu_operator_cost
Definition: costsize.c:114
Cost indexTotalCost
Definition: selfuncs.h:105
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:147
double rint(double x)
Definition: rint.c:21
List * indexquals
Definition: pathnodes.h:1226
Index relid
Definition: pathnodes.h:671
List * lappend(List *list, void *datum)
Definition: list.c:322
Expr * clause
Definition: pathnodes.h:1945
double indexCorrelation
Definition: selfuncs.h:107
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
NullTestType nulltesttype
Definition: primnodes.h:1206
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:111
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2942
#define Assert(condition)
Definition: c.h:739
#define linitial_oid(l)
Definition: pg_list.h:197
int nkeycolumns
Definition: pathnodes.h:802
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:148
Oid * opcintype
Definition: pathnodes.h:807
#define nodeTag(nodeptr)
Definition: nodes.h:530
Cost indexStartupCost
Definition: selfuncs.h:104
Oid * opfamily
Definition: pathnodes.h:806
RTEKind rtekind
Definition: parsenodes.h:974
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog(elevel,...)
Definition: elog.h:228
int * indexkeys
Definition: pathnodes.h:803
Oid opno
Definition: primnodes.h:502
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
bool * reverse_sort
Definition: pathnodes.h:809
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define BTEqualStrategyNumber
Definition: stratnum.h:31
double Cost
Definition: nodes.h:659
double numIndexPages
Definition: selfuncs.h:110
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3072
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:5868

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

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

Referenced by convert_to_scalar().

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

◆ convert_numeric_to_scalar()

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

Definition at line 3870 of file selfuncs.c.

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

Referenced by convert_to_scalar().

3871 {
3872  switch (typid)
3873  {
3874  case BOOLOID:
3875  return (double) DatumGetBool(value);
3876  case INT2OID:
3877  return (double) DatumGetInt16(value);
3878  case INT4OID:
3879  return (double) DatumGetInt32(value);
3880  case INT8OID:
3881  return (double) DatumGetInt64(value);
3882  case FLOAT4OID:
3883  return (double) DatumGetFloat4(value);
3884  case FLOAT8OID:
3885  return (double) DatumGetFloat8(value);
3886  case NUMERICOID:
3887  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3888  return (double)
3890  value));
3891  case OIDOID:
3892  case REGPROCOID:
3893  case REGPROCEDUREOID:
3894  case REGOPEROID:
3895  case REGOPERATOROID:
3896  case REGCLASSOID:
3897  case REGTYPEOID:
3898  case REGCONFIGOID:
3899  case REGDICTIONARYOID:
3900  case REGROLEOID:
3901  case REGNAMESPACEOID:
3902  /* we can treat OIDs as integers... */
3903  return (double) DatumGetObjectId(value);
3904  }
3905 
3906  *failure = true;
3907  return 0;
3908 }
#define DatumGetInt32(X)
Definition: postgres.h:472
#define DatumGetObjectId(X)
Definition: postgres.h:500
static struct @145 value
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:615
static float4 DatumGetFloat4(Datum X)
Definition: postgres.h:664
#define DatumGetInt64(X)
Definition: postgres.h:607
#define DatumGetInt16(X)
Definition: postgres.h:444
#define DatumGetBool(X)
Definition: postgres.h:393
#define DatumGetFloat8(X)
Definition: postgres.h:714
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 4191 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

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

◆ convert_one_string_to_scalar()

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

Definition at line 4011 of file selfuncs.c.

Referenced by convert_string_to_scalar().

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

◆ convert_string_datum()

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

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

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

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

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

◆ convert_timevalue_to_scalar()

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

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

4235 {
4236  switch (typid)
4237  {
4238  case TIMESTAMPOID:
4239  return DatumGetTimestamp(value);
4240  case TIMESTAMPTZOID:
4241  return DatumGetTimestampTz(value);
4242  case DATEOID:
4244  case INTERVALOID:
4245  {
4247 
4248  /*
4249  * Convert the month part of Interval to days using assumed
4250  * average month length of 365.25/12.0 days. Not too
4251  * accurate, but plenty good enough for our purposes.
4252  */
4253  return interval->time + interval->day * (double) USECS_PER_DAY +
4254  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4255  }
4256  case TIMEOID:
4257  return DatumGetTimeADT(value);
4258  case TIMETZOID:
4259  {
4260  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4261 
4262  /* use GMT-equivalent time */
4263  return (double) (timetz->time + (timetz->zone * 1000000.0));
4264  }
4265  }
4266 
4267  *failure = true;
4268  return 0;
4269 }
#define DatumGetDateADT(X)
Definition: date.h:53
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:29
#define DatumGetTimeTzADTP(X)
Definition: date.h:55
static struct @145 value
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:707
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 3724 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().

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

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

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

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

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

◆ eqjoinsel_semi()

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

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

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

◆ eqsel()

Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 222 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

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

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

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

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

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

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

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

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

◆ estimate_hashagg_tablesize()

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

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

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

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

Referenced by estimate_num_groups().

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

◆ estimate_num_groups()

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

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

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

◆ examine_simple_variable()

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

Definition at line 4691 of file selfuncs.c.

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

Referenced by examine_variable().

4693 {
4694  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4695 
4696  Assert(IsA(rte, RangeTblEntry));
4697 
4699  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4700  {
4701  /*
4702  * The hook took control of acquiring a stats tuple. If it did supply
4703  * a tuple, it'd better have supplied a freefunc.
4704  */
4705  if (HeapTupleIsValid(vardata->statsTuple) &&
4706  !vardata->freefunc)
4707  elog(ERROR, "no function provided to release variable stats with");
4708  }
4709  else if (rte->rtekind == RTE_RELATION)
4710  {
4711  /*
4712  * Plain table or parent of an inheritance appendrel, so look up the
4713  * column in pg_statistic
4714  */
4716  ObjectIdGetDatum(rte->relid),
4717  Int16GetDatum(var->varattno),
4718  BoolGetDatum(rte->inh));
4719  vardata->freefunc = ReleaseSysCache;
4720 
4721  if (HeapTupleIsValid(vardata->statsTuple))
4722  {
4723  Oid userid;
4724 
4725  /*
4726  * Check if user has permission to read this column. We require
4727  * all rows to be accessible, so there must be no securityQuals
4728  * from security barrier views or RLS policies. Use checkAsUser
4729  * if it's set, in case we're accessing the table via a view.
4730  */
4731  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4732 
4733  vardata->acl_ok =
4734  rte->securityQuals == NIL &&
4735  ((pg_class_aclcheck(rte->relid, userid,
4736  ACL_SELECT) == ACLCHECK_OK) ||
4737  (pg_attribute_aclcheck(rte->relid, var->varattno, userid,
4738  ACL_SELECT) == ACLCHECK_OK));
4739 
4740  /*
4741  * If the user doesn't have permissions to access an inheritance
4742  * child relation or specifically this attribute, check the
4743  * permissions of the table/column actually mentioned in the
4744  * query, since most likely the user does have that permission
4745  * (else the query will fail at runtime), and if the user can read
4746  * the column there then he can get the values of the child table
4747  * too. To do that, we must find out which of the root parent's
4748  * attributes the child relation's attribute corresponds to.
4749  */
4750  if (!vardata->acl_ok && var->varattno > 0 &&
4751  root->append_rel_array != NULL)
4752  {
4753  AppendRelInfo *appinfo;
4754  Index varno = var->varno;
4755  int varattno = var->varattno;
4756  bool found = false;
4757 
4758  appinfo = root->append_rel_array[varno];
4759 
4760  /*
4761  * Partitions are mapped to their immediate parent, not the
4762  * root parent, so must be ready to walk up multiple
4763  * AppendRelInfos. But stop if we hit a parent that is not
4764  * RTE_RELATION --- that's a flattened UNION ALL subquery, not
4765  * an inheritance parent.
4766  */
4767  while (appinfo &&
4768  planner_rt_fetch(appinfo->parent_relid,
4769  root)->rtekind == RTE_RELATION)
4770  {
4771  int parent_varattno;
4772 
4773  found = false;
4774  if (varattno <= 0 || varattno > appinfo->num_child_cols)
4775  break; /* safety check */
4776  parent_varattno = appinfo->parent_colnos[varattno - 1];
4777  if (parent_varattno == 0)
4778  break; /* Var is local to child */
4779 
4780  varno = appinfo->parent_relid;
4781  varattno = parent_varattno;
4782  found = true;
4783 
4784  /* If the parent is itself a child, continue up. */
4785  appinfo = root->append_rel_array[varno];
4786  }
4787 
4788  /*
4789  * In rare cases, the Var may be local to the child table, in
4790  * which case, we've got to live with having no access to this
4791  * column's stats.
4792  */
4793  if (!found)
4794  return;
4795 
4796  /* Repeat the access check on this parent rel & column */
4797  rte = planner_rt_fetch(varno, root);
4798  Assert(rte->rtekind == RTE_RELATION);
4799 
4800  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4801 
4802  vardata->acl_ok =
4803  rte->securityQuals == NIL &&
4804  ((pg_class_aclcheck(rte->relid, userid,
4805  ACL_SELECT) == ACLCHECK_OK) ||
4806  (pg_attribute_aclcheck(rte->relid, varattno, userid,
4807  ACL_SELECT) == ACLCHECK_OK));
4808  }
4809  }
4810  else
4811  {
4812  /* suppress any possible leakproofness checks later */
4813  vardata->acl_ok = true;
4814  }
4815  }
4816  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4817  {
4818  /*
4819  * Plain subquery (not one that was converted to an appendrel).
4820  */
4821  Query *subquery = rte->subquery;
4822  RelOptInfo *rel;
4823  TargetEntry *ste;
4824 
4825  /*
4826  * Punt if it's a whole-row var rather than a plain column reference.
4827  */
4828  if (var->varattno == InvalidAttrNumber)
4829  return;
4830 
4831  /*
4832  * Punt if subquery uses set operations or GROUP BY, as these will
4833  * mash underlying columns' stats beyond recognition. (Set ops are
4834  * particularly nasty; if we forged ahead, we would return stats
4835  * relevant to only the leftmost subselect...) DISTINCT is also
4836  * problematic, but we check that later because there is a possibility
4837  * of learning something even with it.
4838  */
4839  if (subquery->setOperations ||
4840  subquery->groupClause)
4841  return;
4842 
4843  /*
4844  * OK, fetch RelOptInfo for subquery. Note that we don't change the
4845  * rel returned in vardata, since caller expects it to be a rel of the
4846  * caller's query level. Because we might already be recursing, we
4847  * can't use that rel pointer either, but have to look up the Var's
4848  * rel afresh.
4849  */
4850  rel = find_base_rel(root, var->varno);
4851 
4852  /* If the subquery hasn't been planned yet, we have to punt */
4853  if (rel->subroot == NULL)
4854  return;
4855  Assert(IsA(rel->subroot, PlannerInfo));
4856 
4857  /*
4858  * Switch our attention to the subquery as mangled by the planner. It
4859  * was okay to look at the pre-planning version for the tests above,
4860  * but now we need a Var that will refer to the subroot's live
4861  * RelOptInfos. For instance, if any subquery pullup happened during
4862  * planning, Vars in the targetlist might have gotten replaced, and we
4863  * need to see the replacement expressions.
4864  */
4865  subquery = rel->subroot->parse;
4866  Assert(IsA(subquery, Query));
4867 
4868  /* Get the subquery output expression referenced by the upper Var */
4869  ste = get_tle_by_resno(subquery->targetList, var->varattno);
4870  if (ste == NULL || ste->resjunk)
4871  elog(ERROR, "subquery %s does not have attribute %d",
4872  rte->eref->aliasname, var->varattno);
4873  var = (Var *) ste->expr;
4874 
4875  /*
4876  * If subquery uses DISTINCT, we can't make use of any stats for the
4877  * variable ... but, if it's the only DISTINCT column, we are entitled
4878  * to consider it unique. We do the test this way so that it works
4879  * for cases involving DISTINCT ON.
4880  */
4881  if (subquery->distinctClause)
4882  {
4883  if (list_length(subquery->distinctClause) == 1 &&
4884  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4885  vardata->isunique = true;
4886  /* cannot go further */
4887  return;
4888  }
4889 
4890  /*
4891  * If the sub-query originated from a view with the security_barrier
4892  * attribute, we must not look at the variable's statistics, though it
4893  * seems all right to notice the existence of a DISTINCT clause. So
4894  * stop here.
4895  *
4896  * This is probably a harsher restriction than necessary; it's
4897  * certainly OK for the selectivity estimator (which is a C function,
4898  * and therefore omnipotent anyway) to look at the statistics. But
4899  * many selectivity estimators will happily *invoke the operator
4900  * function* to try to work out a good estimate - and that's not OK.
4901  * So for now, don't dig down for stats.
4902  */
4903  if (rte->security_barrier)
4904  return;
4905 
4906  /* Can only handle a simple Var of subquery's query level */
4907  if (var && IsA(var, Var) &&
4908  var->varlevelsup == 0)
4909  {
4910  /*
4911  * OK, recurse into the subquery. Note that the original setting
4912  * of vardata->isunique (which will surely be false) is left
4913  * unchanged in this situation. That's what we want, since even
4914  * if the underlying column is unique, the subquery may have
4915  * joined to other tables in a way that creates duplicates.
4916  */
4917  examine_simple_variable(rel->subroot, var, vardata);
4918  }
4919  }
4920  else
4921  {
4922  /*
4923  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4924  * won't see RTE_JOIN here because join alias Vars have already been
4925  * flattened.) There's not much we can do with function outputs, but
4926  * maybe someday try to be smarter about VALUES and/or CTEs.
4927  */
4928  }
4929 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Query * parse
Definition: pathnodes.h:179
Index varlevelsup
Definition: primnodes.h:177
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4515
int num_child_cols
Definition: pathnodes.h:2225
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:380
AttrNumber * parent_colnos
Definition: pathnodes.h:2226
List * securityQuals
Definition: parsenodes.h:1102
#define Int16GetDatum(X)
Definition: postgres.h:451
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
AttrNumber varattno
Definition: primnodes.h:172
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:167
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4691
List * targetList
Definition: parsenodes.h:140
PlannerInfo * subroot
Definition: pathnodes.h:687
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:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:147
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:211
Index varno
Definition: primnodes.h:170
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ACL_SELECT
Definition: parsenodes.h:75
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:219
unsigned int Index
Definition: c.h:476
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:739
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:4629
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:228
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
Index parent_relid
Definition: pathnodes.h:2189

◆ examine_variable()

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

Definition at line 4418 of file selfuncs.c.

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

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

4420 {
4421  Node *basenode;
4422  Relids varnos;
4423  RelOptInfo *onerel;
4424 
4425  /* Make sure we don't return dangling pointers in vardata */
4426  MemSet(vardata, 0, sizeof(VariableStatData));
4427 
4428  /* Save the exposed type of the expression */
4429  vardata->vartype = exprType(node);
4430 
4431  /* Look inside any binary-compatible relabeling */
4432 
4433  if (IsA(node, RelabelType))
4434  basenode = (Node *) ((RelabelType *) node)->arg;
4435  else
4436  basenode = node;
4437 
4438  /* Fast path for a simple Var */
4439 
4440  if (IsA(basenode, Var) &&
4441  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4442  {
4443  Var *var = (Var *) basenode;
4444 
4445  /* Set up result fields other than the stats tuple */
4446  vardata->var = basenode; /* return Var without relabeling */
4447  vardata->rel = find_base_rel(root, var->varno);
4448  vardata->atttype = var->vartype;
4449  vardata->atttypmod = var->vartypmod;
4450  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4451 
4452  /* Try to locate some stats */
4453  examine_simple_variable(root, var, vardata);
4454 
4455  return;
4456  }
4457 
4458  /*
4459  * Okay, it's a more complicated expression. Determine variable
4460  * membership. Note that when varRelid isn't zero, only vars of that
4461  * relation are considered "real" vars.
4462  */
4463  varnos = pull_varnos(basenode);
4464 
4465  onerel = NULL;
4466 
4467  switch (bms_membership(varnos))
4468  {
4469  case BMS_EMPTY_SET:
4470  /* No Vars at all ... must be pseudo-constant clause */
4471  break;
4472  case BMS_SINGLETON:
4473  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4474  {
4475  onerel = find_base_rel(root,
4476  (varRelid ? varRelid : bms_singleton_member(varnos)));
4477  vardata->rel = onerel;
4478  node = basenode; /* strip any relabeling */
4479  }
4480  /* else treat it as a constant */
4481  break;
4482  case BMS_MULTIPLE:
4483  if (varRelid == 0)
4484  {
4485  /* treat it as a variable of a join relation */
4486  vardata->rel = find_join_rel(root, varnos);
4487  node = basenode; /* strip any relabeling */
4488  }
4489  else if (bms_is_member(varRelid, varnos))
4490  {
4491  /* ignore the vars belonging to other relations */
4492  vardata->rel = find_base_rel(root, varRelid);
4493  node = basenode; /* strip any relabeling */
4494  /* note: no point in expressional-index search here */
4495  }
4496  /* else treat it as a constant */
4497  break;
4498  }
4499 
4500  bms_free(varnos);
4501 
4502  vardata->var = node;
4503  vardata->atttype = exprType(node);
4504  vardata->atttypmod = exprTypmod(node);
4505 
4506  if (onerel)
4507  {
4508  /*
4509  * We have an expression in vars of a single relation. Try to match
4510  * it to expressional index columns, in hopes of finding some
4511  * statistics.
4512  *
4513  * Note that we consider all index columns including INCLUDE columns,
4514  * since there could be stats for such columns. But the test for
4515  * uniqueness needs to be warier.
4516  *
4517  * XXX it's conceivable that there are multiple matches with different
4518  * index opfamilies; if so, we need to pick one that matches the
4519  * operator we are estimating for. FIXME later.
4520  */
4521  ListCell *ilist;
4522 
4523  foreach(ilist, onerel->indexlist)
4524  {
4525  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4526  ListCell *indexpr_item;
4527  int pos;
4528 
4529  indexpr_item = list_head(index->indexprs);
4530  if (indexpr_item == NULL)
4531  continue; /* no expressions here... */
4532 
4533  for (pos = 0; pos < index->ncolumns; pos++)
4534  {
4535  if (index->indexkeys[pos] == 0)
4536  {
4537  Node *indexkey;
4538 
4539  if (indexpr_item == NULL)
4540  elog(ERROR, "too few entries in indexprs list");
4541  indexkey = (Node *) lfirst(indexpr_item);
4542  if (indexkey && IsA(indexkey, RelabelType))
4543  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4544  if (equal(node, indexkey))
4545  {
4546  /*
4547  * Found a match ... is it a unique index? Tests here
4548  * should match has_unique_index().
4549  */
4550  if (index->unique &&
4551  index->nkeycolumns == 1 &&
4552  pos == 0 &&
4553  (index->indpred == NIL || index->predOK))
4554  vardata->isunique = true;
4555 
4556  /*
4557  * Has it got stats? We only consider stats for
4558  * non-partial indexes, since partial indexes probably
4559  * don't reflect whole-relation statistics; the above
4560  * check for uniqueness is the only info we take from
4561  * a partial index.
4562  *
4563  * An index stats hook, however, must make its own
4564  * decisions about what to do with partial indexes.
4565  */
4566  if (get_index_stats_hook &&
4567  (*get_index_stats_hook) (root, index->indexoid,
4568  pos + 1, vardata))
4569  {
4570  /*
4571  * The hook took control of acquiring a stats
4572  * tuple. If it did supply a tuple, it'd better
4573  * have supplied a freefunc.
4574  */
4575  if (HeapTupleIsValid(vardata->statsTuple) &&
4576  !vardata->freefunc)
4577  elog(ERROR, "no function provided to release variable stats with");
4578  }
4579  else if (index->indpred == NIL)
4580  {
4581  vardata->statsTuple =
4583  ObjectIdGetDatum(index->indexoid),
4584  Int16GetDatum(pos + 1),
4585  BoolGetDatum(false));
4586  vardata->freefunc = ReleaseSysCache;
4587 
4588  if (HeapTupleIsValid(vardata->statsTuple))
4589  {
4590  /* Get index's table for permission check */
4591  RangeTblEntry *rte;
4592  Oid userid;
4593 
4594  rte = planner_rt_fetch(index->rel->relid, root);
4595  Assert(rte->rtekind == RTE_RELATION);
4596 
4597  /*
4598  * Use checkAsUser if it's set, in case we're
4599  * accessing the table via a view.
4600  */
4601  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4602 
4603  /*
4604  * For simplicity, we insist on the whole
4605  * table being selectable, rather than trying
4606  * to identify which column(s) the index
4607  * depends on. Also require all rows to be
4608  * selectable --- there must be no
4609  * securityQuals from security barrier views
4610  * or RLS policies.
4611  */
4612  vardata->acl_ok =
4613  rte->securityQuals == NIL &&
4614  (pg_class_aclcheck(rte->relid, userid,
4615  ACL_SELECT) == ACLCHECK_OK);
4616 
4617  /*
4618  * If the user doesn't have permissions to
4619  * access an inheritance child relation, check
4620  * the permissions of the table actually
4621  * mentioned in the query, since most likely
4622  * the user does have that permission. Note
4623  * that whole-table select privilege on the
4624  * parent doesn't quite guarantee that the
4625  * user could read all columns of the child.
4626  * But in practice it's unlikely that any
4627  * interesting security violation could result
4628  * from allowing access to the expression
4629  * index's stats, so we allow it anyway. See
4630  * similar code in examine_simple_variable()
4631  * for additional comments.
4632  */
4633  if (!vardata->acl_ok &&
4634  root->append_rel_array != NULL)
4635  {
4636  AppendRelInfo *appinfo;
4637  Index varno = index->rel->relid;
4638 
4639  appinfo = root->append_rel_array[varno];
4640  while (appinfo &&
4641  planner_rt_fetch(appinfo->parent_relid,
4642  root)->rtekind == RTE_RELATION)
4643  {
4644  varno = appinfo->parent_relid;
4645  appinfo = root->append_rel_array[varno];
4646  }
4647  if (varno != index->rel->relid)
4648  {
4649  /* Repeat access check on this rel */
4650  rte = planner_rt_fetch(varno, root);
4651  Assert(rte->rtekind == RTE_RELATION);
4652 
4653  userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
4654 
4655  vardata->acl_ok =
4656  rte->securityQuals == NIL &&
4657  (pg_class_aclcheck(rte->relid,
4658  userid,
4659  ACL_SELECT) == ACLCHECK_OK);
4660  }
4661  }
4662  }
4663  else
4664  {
4665  /* suppress leakproofness checks later */
4666  vardata->acl_ok = true;
4667  }
4668  }
4669  if (vardata->statsTuple)
4670  break;
4671  }
4672  indexpr_item = lnext(index->indexprs, indexpr_item);
4673  }
4674  }
4675  if (vardata->statsTuple)
4676  break;
4677  }
4678  }
4679 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:428
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3011
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:380
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
List * securityQuals
Definition: parsenodes.h:1102
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:451
Definition: nodes.h:525
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
#define MemSet(start, val, len)
Definition: c.h:962
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:4691
int32 atttypmod
Definition: selfuncs.h:76
Definition: type.h:89
RelOptInfo * rel
Definition: pathnodes.h:793
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2024
#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:1138
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
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:671
Index varno
Definition: primnodes.h:170
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ACL_SELECT
Definition: parsenodes.h:75
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:577
struct AppendRelInfo ** append_rel_array
Definition: pathnodes.h:219
unsigned int Index
Definition: c.h:476
List * indexlist
Definition: pathnodes.h:680
#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:739
#define lfirst(lc)
Definition: pg_list.h:190
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int nkeycolumns
Definition: pathnodes.h:802
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:148
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4629
RTEKind rtekind
Definition: parsenodes.h:974
#define elog(elevel,...)
Definition: elog.h:228
void * arg
int * indexkeys
Definition: pathnodes.h:803
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363
Index parent_relid
Definition: pathnodes.h:2189
List * indpred
Definition: pathnodes.h:816
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
List * indexprs
Definition: pathnodes.h:815
int32 vartypmod
Definition: primnodes.h:175

◆ find_join_input_rel()

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

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

5532 {
5533  RelOptInfo *rel = NULL;
5534 
5535  switch (bms_membership(relids))
5536  {
5537  case BMS_EMPTY_SET:
5538  /* should not happen */
5539  break;
5540  case BMS_SINGLETON:
5541  rel = find_base_rel(root, bms_singleton_member(relids));
5542  break;
5543  case BMS_MULTIPLE:
5544  rel = find_join_rel(root, relids);
5545  break;
5546  }
5547 
5548  if (rel == NULL)
5549  elog(ERROR, "could not find RelOptInfo for given relids");
5550 
5551  return rel;
5552 }
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:228
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 5650 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().

5654 {
5655  IndexOptInfo *index = path->indexinfo;
5656  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
5657  List *indexOrderBys = path->indexorderbys;
5658  Cost indexStartupCost;
5659  Cost indexTotalCost;
5660  Selectivity indexSelectivity;
5661  double indexCorrelation;
5662  double numIndexPages;
5663  double numIndexTuples;
5664  double spc_random_page_cost;
5665  double num_sa_scans;
5666  double num_outer_scans;
5667  double num_scans;
5668  double qual_op_cost;
5669  double qual_arg_cost;
5670  List *selectivityQuals;
5671  ListCell *l;
5672 
5673  /*
5674  * If the index is partial, AND the index predicate with the explicitly
5675  * given indexquals to produce a more accurate idea of the index
5676  * selectivity.
5677  */
5678  selectivityQuals = add_predicate_to_index_quals(index, indexQuals);
5679 
5680  /*
5681  * Check for ScalarArrayOpExpr index quals, and estimate the number of
5682  * index scans that will be performed.
5683  */
5684  num_sa_scans = 1;
5685  foreach(l, indexQuals)
5686  {
5687  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
5688 
5689  if (IsA(rinfo->clause, ScalarArrayOpExpr))
5690  {
5691  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
5692  int alength = estimate_array_length(lsecond(saop->args));
5693 
5694  if (alength > 1)
5695  num_sa_scans *= alength;
5696  }
5697  }
5698 
5699  /* Estimate the fraction of main-table tuples that will be visited */
5700  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
5701  index->rel->relid,
5702  JOIN_INNER,
5703  NULL);
5704 
5705  /*
5706  * If caller didn't give us an estimate, estimate the number of index
5707  * tuples that will be visited. We do it in this rather peculiar-looking
5708  * way in order to get the right answer for partial indexes.
5709  */
5710  numIndexTuples = costs->numIndexTuples;
5711  if (numIndexTuples <= 0.0)
5712  {
5713  numIndexTuples = indexSelectivity * index->rel->tuples;
5714 
5715  /*
5716  * The above calculation counts all the tuples visited across all
5717  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
5718  * average per-indexscan number, so adjust. This is a handy place to
5719  * round to integer, too. (If caller supplied tuple estimate, it's
5720  * responsible for handling these considerations.)
5721  */
5722  numIndexTuples = rint(numIndexTuples / num_sa_scans);
5723  }
5724 
5725  /*
5726  * We can bound the number of tuples by the index size in any case. Also,
5727  * always estimate at least one tuple is touched, even when
5728  * indexSelectivity estimate is tiny.
5729  */
5730  if (numIndexTuples > index->tuples)
5731  numIndexTuples = index->tuples;
5732  if (numIndexTuples < 1.0)
5733  numIndexTuples = 1.0;
5734 
5735  /*
5736  * Estimate the number of index pages that will be retrieved.
5737  *
5738  * We use the simplistic method of taking a pro-rata fraction of the total
5739  * number of index pages. In effect, this counts only leaf pages and not
5740  * any overhead such as index metapage or upper tree levels.
5741  *
5742  * In practice access to upper index levels is often nearly free because
5743  * those tend to stay in cache under load; moreover, the cost involved is
5744  * highly dependent on index type. We therefore ignore such costs here
5745  * and leave it to the caller to add a suitable charge if needed.
5746  */
5747  if (index->pages > 1 && index->tuples > 1)
5748  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
5749  else
5750  numIndexPages = 1.0;
5751 
5752  /* fetch estimated page cost for tablespace containing index */
5754  &spc_random_page_cost,
5755  NULL);
5756 
5757  /*
5758  * Now compute the disk access costs.
5759  *
5760  * The above calculations are all per-index-scan. However, if we are in a
5761  * nestloop inner scan, we can expect the scan to be repeated (with
5762  * different search keys) for each row of the outer relation. Likewise,
5763  * ScalarArrayOpExpr quals result in multiple index scans. This creates
5764  * the potential for cache effects to reduce the number of disk page
5765  * fetches needed. We want to estimate the average per-scan I/O cost in
5766  * the presence of caching.
5767  *
5768  * We use the Mackert-Lohman formula (see costsize.c for details) to
5769  * estimate the total number of page fetches that occur. While this
5770  * wasn't what it was designed for, it seems a reasonable model anyway.
5771  * Note that we are counting pages not tuples anymore, so we take N = T =
5772  * index size, as if there were one "tuple" per page.
5773  */
5774  num_outer_scans = loop_count;
5775  num_scans = num_sa_scans * num_outer_scans;
5776 
5777  if (num_scans > 1)
5778  {
5779  double pages_fetched;
5780 
5781  /* total page fetches ignoring cache effects */
5782  pages_fetched = numIndexPages * num_scans;
5783 
5784  /* use Mackert and Lohman formula to adjust for cache effects */
5785  pages_fetched = index_pages_fetched(pages_fetched,
5786  index->pages,
5787  (double) index->pages,
5788  root);
5789 
5790  /*
5791  * Now compute the total disk access cost, and then report a pro-rated
5792  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
5793  * since that's internal to the indexscan.)
5794  */
5795  indexTotalCost = (pages_fetched * spc_random_page_cost)
5796  / num_outer_scans;
5797  }
5798  else
5799  {
5800  /*
5801  * For a single index scan, we just charge spc_random_page_cost per
5802  * page touched.
5803  */
5804  indexTotalCost = numIndexPages * spc_random_page_cost;
5805  }
5806 
5807  /*
5808  * CPU cost: any complex expressions in the indexquals will need to be
5809  * evaluated once at the start of the scan to reduce them to runtime keys
5810  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
5811  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
5812  * indexqual operator. Because we have numIndexTuples as a per-scan
5813  * number, we have to multiply by num_sa_scans to get the correct result
5814  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
5815  * ORDER BY expressions.
5816  *
5817  * Note: this neglects the possible costs of rechecking lossy operators.
5818  * Detecting that that might be needed seems more expensive than it's
5819  * worth, though, considering all the other inaccuracies here ...
5820  */
5821  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals) +
5822  index_other_operands_eval_cost(root, indexOrderBys);
5823  qual_op_cost = cpu_operator_cost *
5824  (list_length(indexQuals) + list_length(indexOrderBys));
5825 
5826  indexStartupCost = qual_arg_cost;
5827  indexTotalCost += qual_arg_cost;
5828  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
5829 
5830  /*
5831  * Generic assumption about index correlation: there isn't any.
5832  */
5833  indexCorrelation = 0.0;
5834 
5835  /*
5836  * Return everything to caller.
5837  */
5838  costs->indexStartupCost = indexStartupCost;
5839  costs->indexTotalCost = indexTotalCost;
5840  costs->indexSelectivity = indexSelectivity;
5841  costs->indexCorrelation = indexCorrelation;
5842  costs->numIndexPages = numIndexPages;
5843  costs->numIndexTuples = numIndexTuples;
5844  costs->spc_random_page_cost = spc_random_page_cost;
5845  costs->num_sa_scans = num_sa_scans;
5846 }
Selectivity indexSelectivity
Definition: selfuncs.h:106
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
IndexOptInfo * indexinfo
Definition: pathnodes.h:1179
double tuples
Definition: pathnodes.h:683
Oid reltablespace
Definition: pathnodes.h:792
List * indexclauses
Definition: pathnodes.h:1180
double Selectivity
Definition: nodes.h:658
double tuples
Definition: pathnodes.h:797
#define lsecond(l)
Definition: pg_list.h:200
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:796
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1891
RelOptInfo * rel
Definition: pathnodes.h:793
double num_sa_scans
Definition: selfuncs.h:113
double cpu_operator_cost
Definition: costsize.c:114
List * get_quals_from_indexclauses(List *indexclauses)
Definition: selfuncs.c:5566
Cost indexTotalCost
Definition: selfuncs.h:105
double rint(double x)
Definition: rint.c:21
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:671
Expr * clause
Definition: pathnodes.h:1945
double indexCorrelation
Definition: selfuncs.h:107
List * indexorderbys
Definition: pathnodes.h:1181
double spc_random_page_cost
Definition: selfuncs.h:112
double numIndexTuples
Definition: selfuncs.h:111
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5596
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
Cost indexStartupCost
Definition: selfuncs.h:104
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
double cpu_index_tuple_cost
Definition: costsize.c:113
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:825
double Cost
Definition: nodes.h:659
double numIndexPages
Definition: selfuncs.h:110
List * add_predicate_to_index_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:5868

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

5413 {
5414  bool have_data = false;
5415  SnapshotData SnapshotNonVacuumable;
5416  IndexScanDesc index_scan;
5417  Buffer vmbuffer = InvalidBuffer;
5418  ItemPointer tid;
5420  bool isnull[INDEX_MAX_KEYS];
5421  MemoryContext oldcontext;
5422 
5423  /*
5424  * We use the index-only-scan machinery for this. With mostly-static
5425  * tables that's a win because it avoids a heap visit. It's also a win
5426  * for dynamic data, but the reason is less obvious; read on for details.
5427  *
5428  * In principle, we should scan the index with our current active
5429  * snapshot, which is the best approximation we've got to what the query
5430  * will see when executed. But that won't be exact if a new snap is taken
5431  * before running the query, and it can be very expensive if a lot of
5432  * recently-dead or uncommitted rows exist at the beginning or end of the
5433  * index (because we'll laboriously fetch each one and reject it).
5434  * Instead, we use SnapshotNonVacuumable. That will accept recently-dead
5435  * and uncommitted rows as well as normal visible rows. On the other
5436  * hand, it will reject known-dead rows, and thus not give a bogus answer
5437  * when the extreme value has been deleted (unless the deletion was quite
5438  * recent); that case motivates not using SnapshotAny here.
5439  *
5440  * A crucial point here is that SnapshotNonVacuumable, with
5441  * RecentGlobalXmin as horizon, yields the inverse of the condition that
5442  * the indexscan will use to decide that index entries are killable (see
5443  * heap_hot_search_buffer()). Therefore, if the snapshot rejects a tuple
5444  * (or more precisely, all tuples of a HOT chain) and we have to continue
5445  * scanning past it, we know that the indexscan will mark that index entry
5446  * killed. That means that the next get_actual_variable_endpoint() call
5447  * will not have to re-consider that index entry. In this way we avoid
5448  * repetitive work when this function is used a lot during planning.
5449  *
5450  * But using SnapshotNonVacuumable creates a hazard of its own. In a
5451  * recently-created index, some index entries may point at "broken" HOT
5452  * chains in which not all the tuple versions contain data matching the
5453  * index entry. The live tuple version(s) certainly do match the index,
5454  * but SnapshotNonVacuumable can accept recently-dead tuple versions that
5455  * don't match. Hence, if we took data from the selected heap tuple, we
5456  * might get a bogus answer that's not close to the index extremal value,
5457  * or could even be NULL. We avoid this hazard because we take the data
5458  * from the index entry not the heap.
5459  */
5460  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5461 
5462  index_scan = index_beginscan(heapRel, indexRel,
5463  &SnapshotNonVacuumable,
5464  1, 0);
5465  /* Set it up for index-only scan */
5466  index_scan->xs_want_itup = true;
5467  index_rescan(index_scan, scankeys, 1, NULL, 0);
5468 
5469  /* Fetch first/next tuple in specified direction */
5470  while ((tid = index_getnext_tid(index_scan, indexscandir)) != NULL)
5471  {
5472  if (!VM_ALL_VISIBLE(heapRel,
5474  &vmbuffer))
5475  {
5476  /* Rats, we have to visit the heap to check visibility */
5477  if (!index_fetch_heap(index_scan, tableslot))
5478  continue; /* no visible tuple, try next index entry */
5479 
5480  /* We don't actually need the heap tuple for anything */
5481  ExecClearTuple(tableslot);
5482 
5483  /*
5484  * We don't care whether there's more than one visible tuple in
5485  * the HOT chain; if any are visible, that's good enough.
5486  */
5487  }
5488 
5489  /*
5490  * We expect that btree will return data in IndexTuple not HeapTuple
5491  * format. It's not lossy either.
5492  */
5493  if (!index_scan->xs_itup)
5494  elog(ERROR, "no data returned for index-only scan");
5495  if (index_scan->xs_recheck)
5496  elog(ERROR, "unexpected recheck indication from btree");
5497 
5498  /* OK to deconstruct the index tuple */
5499  index_deform_tuple(index_scan->xs_itup,
5500  index_scan->xs_itupdesc,
5501  values, isnull);
5502 
5503  /* Shouldn't have got a null, but be careful */
5504  if (isnull[0])
5505  elog(ERROR, "found unexpected null value in index \"%s\"",
5506  RelationGetRelationName(indexRel));
5507 
5508  /* Copy the index column value out to caller's context */
5509  oldcontext = MemoryContextSwitchTo(outercontext);
5510  *endpointDatum = datumCopy(values[0], typByVal, typLen);
5511  MemoryContextSwitchTo(oldcontext);
5512  have_data = true;
5513  break;
5514  }
5515 
5516  if (vmbuffer != InvalidBuffer)
5517  ReleaseBuffer(vmbuffer);
5518  index_endscan(index_scan);
5519 
5520  return have_data;
5521 }
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
IndexTuple xs_itup
Definition: relscan.h:127
struct TupleDescData * xs_itupdesc
Definition: relscan.h:128
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:289
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3365
#define InitNonVacuumableSnapshot(snapshotdata, xmin_horizon)
Definition: snapmgr.h:83
ItemPointer index_getnext_tid(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:509
#define ERROR
Definition: elog.h:43
TransactionId RecentGlobalXmin
Definition: snapmgr.c:168
#define RelationGetRelationName(relation)
Definition: rel.h:456
void index_deform_tuple(IndexTuple tup, TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:433
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:315
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
uintptr_t Datum
Definition: postgres.h:367
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:32
#define INDEX_MAX_KEYS
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define elog(elevel,...)
Definition: elog.h:228
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 5233 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().

5236 {
5237  bool have_data = false;
5238  RelOptInfo *rel = vardata->rel;
5239  RangeTblEntry *rte;
5240  ListCell *lc;
5241 
5242  /* No hope if no relation or it doesn't have indexes */
5243  if (rel == NULL || rel->indexlist == NIL)
5244  return false;
5245  /* If it has indexes it must be a plain relation */
5246  rte = root->simple_rte_array[rel->relid];
5247  Assert(rte->rtekind == RTE_RELATION);
5248 
5249  /* Search through the indexes to see if any match our problem */
5250  foreach(lc, rel->indexlist)
5251  {
5253  ScanDirection indexscandir;
5254 
5255  /* Ignore non-btree indexes */
5256  if (index->relam != BTREE_AM_OID)
5257  continue;
5258 
5259  /*
5260  * Ignore partial indexes --- we only want stats that cover the entire
5261  * relation.
5262  */
5263  if (index->indpred != NIL)
5264  continue;
5265 
5266  /*
5267  * The index list might include hypothetical indexes inserted by a
5268  * get_relation_info hook --- don't try to access them.
5269  */
5270  if (index->hypothetical)
5271  continue;
5272 
5273  /*
5274  * The first index column must match the desired variable and sort
5275  * operator --- but we can use a descending-order index.
5276  */
5277  if (!match_index_to_operand(vardata->var, 0, index))
5278  continue;
5279  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5280  {
5281  case BTLessStrategyNumber:
5282  if (index->reverse_sort[0])
5283  indexscandir = BackwardScanDirection;
5284  else
5285  indexscandir = ForwardScanDirection;
5286  break;
5288  if (index->reverse_sort[0])
5289  indexscandir = ForwardScanDirection;
5290  else
5291  indexscandir = BackwardScanDirection;
5292  break;
5293  default:
5294  /* index doesn't match the sortop */
5295  continue;
5296  }
5297 
5298  /*
5299  * Found a suitable index to extract data from. Set up some data that
5300  * can be used by both invocations of get_actual_variable_endpoint.
5301  */
5302  {
5303  MemoryContext tmpcontext;
5304  MemoryContext oldcontext;
5305  Relation heapRel;
5306  Relation indexRel;
5307  TupleTableSlot *slot;
5308  int16 typLen;
5309  bool typByVal;
5310  ScanKeyData scankeys[1];
5311 
5312  /* Make sure any cruft gets recycled when we're done */
5314  "get_actual_variable_range workspace",
5316  oldcontext = MemoryContextSwitchTo(tmpcontext);
5317 
5318  /*
5319  * Open the table and index so we can read from them. We should
5320  * already have some type of lock on each.
5321  */
5322  heapRel = table_open(rte->relid, NoLock);
5323  indexRel = index_open(index->indexoid, NoLock);
5324 
5325  /* build some stuff needed for indexscan execution */
5326  slot = table_slot_create(heapRel, NULL);
5327  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5328 
5329  /* set up an IS NOT NULL scan key so that we ignore nulls */
5330  ScanKeyEntryInitialize(&scankeys[0],
5332  1, /* index col to scan */
5333  InvalidStrategy, /* no strategy */
5334  InvalidOid, /* no strategy subtype */
5335  InvalidOid, /* no collation */
5336  InvalidOid, /* no reg proc for this */
5337  (Datum) 0); /* constant */
5338 
5339  /* If min is requested ... */
5340  if (min)
5341  {
5342  have_data = get_actual_variable_endpoint(heapRel,
5343  indexRel,
5344  indexscandir,
5345  scankeys,
5346  typLen,
5347  typByVal,
5348  slot,
5349  oldcontext,
5350  min);
5351  }
5352  else
5353  {
5354  /* If min not requested, assume index is nonempty */
5355  have_data = true;
5356  }
5357 
5358  /* If max is requested, and we didn't find the index is empty */
5359  if (max && have_data)
5360  {
5361  /* scan in the opposite direction; all else is the same */
5362  have_data = get_actual_variable_endpoint(heapRel,
5363  indexRel,
5364  -indexscandir,
5365  scankeys,
5366  typLen,
5367  typByVal,
5368  slot,
5369  oldcontext,
5370  max);
5371  }
5372 
5373  /* Clean everything up */
5375 
5376  index_close(indexRel, NoLock);
5377  table_close(heapRel, NoLock);
5378 
5379  MemoryContextSwitchTo(oldcontext);
5380  MemoryContextDelete(tmpcontext);
5381 
5382  /* And we're done */
5383  break;
5384  }
5385  }
5386 
5387  return have_data;
5388 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:77
signed short int16
Definition: c.h:346
#define InvalidStrategy
Definition: stratnum.h:24
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3806
RelOptInfo * rel
Definition: selfuncs.h:70
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Oid * sortopfamily
Definition: pathnodes.h:808
bool hypothetical
Definition: pathnodes.h:829
Definition: type.h:89
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define NoLock
Definition: lockdefs.h:34
void ScanKeyEntryInitialize(ScanKey entry, int flags, AttrNumber attributeNumber, StrategyNumber strategy, Oid subtype, Oid collation, RegProcedure procedure, Datum argument)
Definition: scankey.c:32
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
ScanDirection
Definition: sdir.h:22
#define SK_SEARCHNOTNULL
Definition: skey.h:122
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define SK_ISNULL
Definition: skey.h:115
Index relid
Definition: pathnodes.h:671
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:211
uintptr_t Datum
Definition: postgres.h:367
List * indexlist
Definition: pathnodes.h:680
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739
#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:5404
bool * reverse_sort
Definition: pathnodes.h:809
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: pathnodes.h:816
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 4356 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().

4359 {
4360  Node *left,
4361  *right;
4362 
4363  if (list_length(args) != 2)
4364  elog(ERROR, "join operator should take two arguments");
4365 
4366  left = (Node *) linitial(args);
4367  right = (Node *) lsecond(args);
4368 
4369  examine_variable(root, left, 0, vardata1);
4370  examine_variable(root, right, 0, vardata2);
4371 
4372  if (vardata1->rel &&
4373  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4374  *join_is_reversed = true; /* var1 is on RHS */
4375  else if (vardata2->rel &&
4376  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4377  *join_is_reversed = true; /* var2 is on LHS */
4378  else
4379  *join_is_reversed = false;
4380 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:525
#define lsecond(l)
Definition: pg_list.h:200
Relids syn_lefthand
Definition: pathnodes.h:2137
Relids syn_righthand
Definition: pathnodes.h:2138
#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:643
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4418
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:228

◆ get_quals_from_indexclauses()

List* get_quals_from_indexclauses ( List indexclauses)

Definition at line 5566 of file selfuncs.c.

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

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

5567 {
5568  List *result = NIL;
5569  ListCell *lc;
5570 
5571  foreach(lc, indexclauses)
5572  {
5573  IndexClause *iclause = lfirst_node(IndexClause, lc);
5574  ListCell *lc2;
5575 
5576  foreach(lc2, iclause->indexquals)
5577  {
5578  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5579 
5580  result = lappend(result, rinfo);
5581  }
5582  }
5583  return result;
5584 }
#define NIL
Definition: pg_list.h:65
#define lfirst_node(type, lc)
Definition: pg_list.h:193
List * indexquals
Definition: pathnodes.h:1226
List * lappend(List *list, void *datum)
Definition: list.c:322
Definition: pg_list.h:50

◆ get_restriction_variable()

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

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

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

◆ get_variable_numdistinct()

double get_variable_numdistinct ( VariableStatData vardata,
bool isdefault 
)

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

4968 {
4969  double stadistinct;
4970  double stanullfrac = 0.0;
4971  double ntuples;
4972 
4973  *isdefault = false;
4974 
4975  /*
4976  * Determine the stadistinct value to use. There are cases where we can
4977  * get an estimate even without a pg_statistic entry, or can get a better
4978  * value than is in pg_statistic. Grab stanullfrac too if we can find it
4979  * (otherwise, assume no nulls, for lack of any better idea).
4980  */
4981  if (HeapTupleIsValid(vardata->statsTuple))
4982  {
4983  /* Use the pg_statistic entry */
4984  Form_pg_statistic stats;
4985 
4986  stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
4987  stadistinct = stats->stadistinct;
4988  stanullfrac = stats->stanullfrac;
4989  }
4990  else if (vardata->vartype == BOOLOID)
4991  {
4992  /*
4993  * Special-case boolean columns: presumably, two distinct values.
4994  *
4995  * Are there any other datatypes we should wire in special estimates
4996  * for?
4997  */
4998  stadistinct = 2.0;
4999  }
5000  else if (vardata->rel && vardata->rel->rtekind == RTE_VALUES)
5001  {
5002  /*
5003  * If the Var represents a column of a VALUES RTE, assume it's unique.
5004  * This could of course be very wrong, but it should tend to be true
5005  * in well-written queries. We could consider examining the VALUES'
5006  * contents to get some real statistics; but that only works if the
5007  * entries are all constants, and it would be pretty expensive anyway.
5008  */
5009  stadistinct = -1.0; /* unique (and all non null) */
5010  }
5011  else
5012  {
5013  /*
5014  * We don't keep statistics for system columns, but in some cases we
5015  * can infer distinctness anyway.
5016  */
5017  if (vardata->var && IsA(vardata->var, Var))
5018  {
5019  switch (((Var *) vardata->var)->varattno)
5020  {
5022  stadistinct = -1.0; /* unique (and all non null) */
5023  break;
5025  stadistinct = 1.0; /* only 1 value */
5026  break;
5027  default:
5028  stadistinct = 0.0; /* means "unknown" */
5029  break;
5030  }
5031  }
5032  else
5033  stadistinct = 0.0; /* means "unknown" */
5034 
5035  /*
5036  * XXX consider using estimate_num_groups on expressions?
5037  */
5038  }
5039 
5040  /*
5041  * If there is a unique index or DISTINCT clause for the variable, assume
5042  * it is unique no matter what pg_statistic says; the statistics could be
5043  * out of date, or we might have found a partial unique index that proves
5044  * the var is unique for this query. However, we'd better still believe
5045  * the null-fraction statistic.
5046  */
5047  if (vardata->isunique)
5048  stadistinct = -1.0 * (1.0 - stanullfrac);
5049 
5050  /*
5051  * If we had an absolute estimate, use that.
5052  */
5053  if (stadistinct > 0.0)
5054  return clamp_row_est(stadistinct);
5055 
5056  /*
5057  * Otherwise we need to get the relation size; punt if not available.
5058  */
5059  if (vardata->rel == NULL)
5060  {
5061  *isdefault = true;
5062  return DEFAULT_N