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

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

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

5861 {
5862  List *predExtraQuals = NIL;
5863  ListCell *lc;
5864 
5865  if (index->indpred == NIL)
5866  return indexQuals;
5867 
5868  foreach(lc, index->indpred)
5869  {
5870  Node *predQual = (Node *) lfirst(lc);
5871  List *oneQual = list_make1(predQual);
5872 
5873  if (!predicate_implied_by(oneQual, indexQuals, false))
5874  predExtraQuals = list_concat(predExtraQuals, oneQual);
5875  }
5876  return list_concat(predExtraQuals, indexQuals);
5877 }
#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:3018
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:4959
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:4410
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:4410
#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 6971 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().

6975 {
6976  IndexOptInfo *index = path->indexinfo;
6977  List *indexQuals = get_quals_from_indexclauses(path->indexclauses);
6978  double numPages = index->pages;
6979  RelOptInfo *baserel = index->rel;
6980  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
6981  Cost spc_seq_page_cost;
6982  Cost spc_random_page_cost;
6983  double qual_arg_cost;
6984  double qualSelectivity;
6985  BrinStatsData statsData;
6986  double indexRanges;
6987  double minimalRanges;
6988  double estimatedRanges;
6989  double selec;
6990  Relation indexRel;
6991  ListCell *l;
6992  VariableStatData vardata;
6993 
6994  Assert(rte->rtekind == RTE_RELATION);
6995 
6996  /* fetch estimated page cost for the tablespace containing the index */
6998  &spc_random_page_cost,
6999  &spc_seq_page_cost);
7000 
7001  /*
7002  * Obtain some data from the index itself, if possible. Otherwise invent
7003  * some plausible internal statistics based on the relation page count.
7004  */
7005  if (!index->hypothetical)
7006  {
7007  /*
7008  * A lock should have already been obtained on the index in plancat.c.
7009  */
7010  indexRel = index_open(index->indexoid, NoLock);
7011  brinGetStats(indexRel, &statsData);
7012  index_close(indexRel, NoLock);
7013 
7014  /* work out the actual number of ranges in the index */
7015  indexRanges = Max(ceil((double) baserel->pages /
7016  statsData.pagesPerRange), 1.0);
7017  }
7018  else
7019  {
7020  /*
7021  * Assume default number of pages per range, and estimate the number
7022  * of ranges based on that.
7023  */
7024  indexRanges = Max(ceil((double) baserel->pages /
7026 
7028  statsData.revmapNumPages = (indexRanges / REVMAP_PAGE_MAXITEMS) + 1;
7029  }
7030 
7031  /*
7032  * Compute index correlation
7033  *
7034  * Because we can use all index quals equally when scanning, we can use
7035  * the largest correlation (in absolute value) among columns used by the
7036  * query. Start at zero, the worst possible case. If we cannot find any
7037  * correlation statistics, we will keep it as 0.
7038  */
7039  *indexCorrelation = 0;
7040 
7041  foreach(l, path->indexclauses)
7042  {
7043  IndexClause *iclause = lfirst_node(IndexClause, l);
7044  AttrNumber attnum = index->indexkeys[iclause->indexcol];
7045 
7046  /* attempt to lookup stats in relation for this index column */
7047  if (attnum != 0)
7048  {
7049  /* Simple variable -- look to stats for the underlying table */
7051  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7052  {
7053  /*
7054  * The hook took control of acquiring a stats tuple. If it
7055  * did supply a tuple, it'd better have supplied a freefunc.
7056  */
7057  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7058  elog(ERROR,
7059  "no function provided to release variable stats with");
7060  }
7061  else
7062  {
7063  vardata.statsTuple =
7065  ObjectIdGetDatum(rte->relid),
7066  Int16GetDatum(attnum),
7067  BoolGetDatum(false));
7068  vardata.freefunc = ReleaseSysCache;
7069  }
7070  }
7071  else
7072  {
7073  /*
7074  * Looks like we've found an expression column in the index. Let's
7075  * see if there's any stats for it.
7076  */
7077 
7078  /* get the attnum from the 0-based index. */
7079  attnum = iclause->indexcol + 1;
7080 
7081  if (get_index_stats_hook &&
7082  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7083  {
7084  /*
7085  * The hook took control of acquiring a stats tuple. If it
7086  * did supply a tuple, it'd better have supplied a freefunc.
7087  */
7088  if (HeapTupleIsValid(vardata.statsTuple) &&
7089  !vardata.freefunc)
7090  elog(ERROR, "no function provided to release variable stats with");
7091  }
7092  else
7093  {
7095  ObjectIdGetDatum(index->indexoid),
7096  Int16GetDatum(attnum),
7097  BoolGetDatum(false));
7098  vardata.freefunc = ReleaseSysCache;
7099  }
7100  }
7101 
7102  if (HeapTupleIsValid(vardata.statsTuple))
7103  {
7104  AttStatsSlot sslot;
7105 
7106  if (get_attstatsslot(&sslot, vardata.statsTuple,
7107  STATISTIC_KIND_CORRELATION, InvalidOid,
7109  {
7110  double varCorrelation = 0.0;
7111 
7112  if (sslot.nnumbers > 0)
7113  varCorrelation = Abs(sslot.numbers[0]);
7114 
7115  if (varCorrelation > *indexCorrelation)
7116  *indexCorrelation = varCorrelation;
7117 
7118  free_attstatsslot(&sslot);
7119  }
7120  }
7121 
7122  ReleaseVariableStats(vardata);
7123  }
7124 
7125  qualSelectivity = clauselist_selectivity(root, indexQuals,
7126  baserel->relid,
7127  JOIN_INNER, NULL);
7128 
7129  /*
7130  * Now calculate the minimum possible ranges we could match with if all of
7131  * the rows were in the perfect order in the table's heap.
7132  */
7133  minimalRanges = ceil(indexRanges * qualSelectivity);
7134 
7135  /*
7136  * Now estimate the number of ranges that we'll touch by using the
7137  * indexCorrelation from the stats. Careful not to divide by zero (note
7138  * we're using the absolute value of the correlation).
7139  */
7140  if (*indexCorrelation < 1.0e-10)
7141  estimatedRanges = indexRanges;
7142  else
7143  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7144 
7145  /* we expect to visit this portion of the table */
7146  selec = estimatedRanges / indexRanges;
7147 
7148  CLAMP_PROBABILITY(selec);
7149 
7150  *indexSelectivity = selec;
7151 
7152  /*
7153  * Compute the index qual costs, much as in genericcostestimate, to add to
7154  * the index costs. We can disregard indexorderbys, since BRIN doesn't
7155  * support those.
7156  */
7157  qual_arg_cost = index_other_operands_eval_cost(root, indexQuals);
7158 
7159  /*
7160  * Compute the startup cost as the cost to read the whole revmap
7161  * sequentially, including the cost to execute the index quals.
7162  */
7163  *indexStartupCost =
7164  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7165  *indexStartupCost += qual_arg_cost;
7166 
7167  /*
7168  * To read a BRIN index there might be a bit of back and forth over
7169  * regular pages, as revmap might point to them out of sequential order;
7170  * calculate the total cost as reading the whole index in random order.
7171  */
7172  *indexTotalCost = *indexStartupCost +
7173  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7174 
7175  /*
7176  * Charge a small amount per range tuple which we expect to match to. This
7177  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7178  * will set a bit for each page in the range when we find a matching
7179  * range, so we must multiply the charge by the number of pages in the
7180  * range.
7181  */
7182  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7183  statsData.pagesPerRange;
7184 
7185  *indexPages = index->pages;
7186 }
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:920
#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:926
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:5558
#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:914
Cost index_other_operands_eval_cost(PlannerInfo *root, List *indexquals)
Definition: selfuncs.c:5588
#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:738
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:1083
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 5881 of file selfuncs.c.

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

Referenced by bthandler().

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

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

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

Referenced by convert_to_scalar().

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

◆ convert_numeric_to_scalar()

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

Definition at line 3862 of file selfuncs.c.

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

Referenced by convert_to_scalar().

3863 {
3864  switch (typid)
3865  {
3866  case BOOLOID:
3867  return (double) DatumGetBool(value);
3868  case INT2OID:
3869  return (double) DatumGetInt16(value);
3870  case INT4OID:
3871  return (double) DatumGetInt32(value);
3872  case INT8OID:
3873  return (double) DatumGetInt64(value);
3874  case FLOAT4OID:
3875  return (double) DatumGetFloat4(value);
3876  case FLOAT8OID:
3877  return (double) DatumGetFloat8(value);
3878  case NUMERICOID:
3879  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3880  return (double)
3882  value));
3883  case OIDOID:
3884  case REGPROCOID:
3885  case REGPROCEDUREOID:
3886  case REGOPEROID:
3887  case REGOPERATOROID:
3888  case REGCLASSOID:
3889  case REGTYPEOID:
3890  case REGCONFIGOID:
3891  case REGDICTIONARYOID:
3892  case REGROLEOID:
3893  case REGNAMESPACEOID:
3894  /* we can treat OIDs as integers... */
3895  return (double) DatumGetObjectId(value);
3896  }
3897 
3898  *failure = true;
3899  return 0;
3900 }
#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:3634

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

Referenced by convert_bytea_to_scalar().

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

Referenced by convert_string_to_scalar().

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

◆ convert_string_datum()

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

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

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

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

◆ convert_timevalue_to_scalar()

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

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

4227 {
4228  switch (typid)
4229  {
4230  case TIMESTAMPOID:
4231  return DatumGetTimestamp(value);
4232  case TIMESTAMPTZOID:
4233  return DatumGetTimestampTz(value);
4234  case DATEOID:
4236  case INTERVALOID:
4237  {
4239 
4240  /*
4241  * Convert the month part of Interval to days using assumed
4242  * average month length of 365.25/12.0 days. Not too
4243  * accurate, but plenty good enough for our purposes.
4244  */
4245  return interval->time + interval->day * (double) USECS_PER_DAY +
4246  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4247  }
4248  case TIMEOID:
4249  return DatumGetTimeADT(value);
4250  case TIMETZOID:
4251  {
4252  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4253 
4254  /* use GMT-equivalent time */
4255  return (double) (timetz->time + (timetz->zone * 1000000.0));
4256  }
4257  }
4258 
4259  *failure = true;
4260  return 0;
4261 }
#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 3716 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().

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

◆ 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:4930
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:356
#define Min(x, y)
Definition: c.h:920
#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:644
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:491
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4348
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4959
#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:5523
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:920
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
#define OidIsValid(objectId)
Definition: c.h:644
#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:491

◆ 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:4288
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:644
#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:4959
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:914
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4410
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(), AggClauseCosts::numAggs, Path::pathtarget, AggClauseCosts::transitionSpace, and PathTarget::width.

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

3528 {
3529  Size hashentrysize = hash_agg_entry_size(
3530  agg_costs->numAggs, path->pathtarget->width, agg_costs->transitionSpace);
3531 
3532  /*
3533  * Note that this disregards the effect of fill-factor and growth policy
3534  * of the hash table. That's probably ok, given that the default
3535  * fill-factor is relatively high. It'd be hard to meaningfully factor in
3536  * "double-in-size" growth policies here.
3537  */
3538  return hashentrysize * dNumGroups;
3539 }
PathTarget * pathtarget
Definition: pathnodes.h:1117
Size hash_agg_entry_size(int numAggs, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1477
size_t Size
Definition: c.h:466
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 3560 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().

3562 {
3563  ListCell *lc;
3564  Bitmapset *attnums = NULL;
3565  int nmatches;
3566  Oid statOid = InvalidOid;
3567  MVNDistinct *stats;
3568  Bitmapset *matched = NULL;
3569 
3570  /* bail out immediately if the table has no extended statistics */
3571  if (!rel->statlist)
3572  return false;
3573 
3574  /* Determine the attnums we're looking for */
3575  foreach(lc, *varinfos)
3576  {
3577  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3579 
3580  Assert(varinfo->rel == rel);
3581 
3582  if (!IsA(varinfo->var, Var))
3583  continue;
3584 
3585  attnum = ((Var *) varinfo->var)->varattno;
3586 
3587  if (!AttrNumberIsForUserDefinedAttr(attnum))
3588  continue;
3589 
3590  attnums = bms_add_member(attnums, attnum);
3591  }
3592 
3593  /* look for the ndistinct statistics matching the most vars */
3594  nmatches = 1; /* we require at least two matches */
3595  foreach(lc, rel->statlist)
3596  {
3597  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3598  Bitmapset *shared;
3599  int nshared;
3600 
3601  /* skip statistics of other kinds */
3602  if (info->kind != STATS_EXT_NDISTINCT)
3603  continue;
3604 
3605  /* compute attnums shared by the vars and the statistics object */
3606  shared = bms_intersect(info->keys, attnums);
3607  nshared = bms_num_members(shared);
3608 
3609  /*
3610  * Does this statistics object match more columns than the currently
3611  * best object? If so, use this one instead.
3612  *
3613  * XXX This should break ties using name of the object, or something
3614  * like that, to make the outcome stable.
3615  */
3616  if (nshared > nmatches)
3617  {
3618  statOid = info->statOid;
3619  nmatches = nshared;
3620  matched = shared;
3621  }
3622  }
3623 
3624  /* No match? */
3625  if (statOid == InvalidOid)
3626  return false;
3627  Assert(nmatches > 1 && matched != NULL);
3628 
3629  stats = statext_ndistinct_load(statOid);
3630 
3631  /*
3632  * If we have a match, search it for the specific item that matches (there
3633  * must be one), and construct the output values.
3634  */
3635  if (stats)
3636  {
3637  int i;
3638  List *newlist = NIL;
3639  MVNDistinctItem *item = NULL;
3640 
3641  /* Find the specific item that exactly matches the combination */
3642  for (i = 0; i < stats->nitems; i++)
3643  {
3644  MVNDistinctItem *tmpitem = &stats->items[i];
3645 
3646  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3647  {
3648  item = tmpitem;
3649  break;
3650  }
3651  }
3652 
3653  /* make sure we found an item */
3654  if (!item)
3655  elog(ERROR, "corrupt MVNDistinct entry");
3656 
3657  /* Form the output varinfo list, keeping only unmatched ones */
3658  foreach(lc, *varinfos)
3659  {
3660  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3662 
3663  if (!IsA(varinfo->var, Var))
3664  {
3665  newlist = lappend(newlist, varinfo);
3666  continue;
3667  }
3668 
3669  attnum = ((Var *) varinfo->var)->varattno;
3670 
3671  if (!AttrNumberIsForUserDefinedAttr(attnum))
3672  continue;
3673 
3674  if (!bms_is_member(attnum, matched))
3675  newlist = lappend(newlist, varinfo);
3676  }
3677 
3678  *varinfos = newlist;
3679  *ndistinct = item->ndistinct;
3680  return true;
3681  }
3682 
3683  return false;
3684 }
#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:181
#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:738
#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:568
#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:723
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:3560
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:4410
#define Assert(condition)
Definition: c.h:738
#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 4683 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().

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

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

◆ find_join_input_rel()

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

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

5524 {
5525  RelOptInfo *rel = NULL;
5526 
5527  switch (bms_membership(relids))
5528  {
5529  case BMS_EMPTY_SET:
5530  /* should not happen */
5531  break;
5532  case BMS_SINGLETON:
5533  rel = find_base_rel(root, bms_singleton_member(relids));
5534  break;
5535  case BMS_MULTIPLE:
5536  rel = find_join_rel(root, relids);
5537  break;
5538  }
5539 
5540  if (rel == NULL)
5541  elog(ERROR, "could not find RelOptInfo for given relids");
5542 
5543  return rel;
5544 }
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 5642 of file selfuncs.c.

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

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

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

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

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

5228 {
5229  bool have_data = false;
5230  RelOptInfo *rel = vardata->rel;
5231  RangeTblEntry *rte;
5232  ListCell *lc;
5233 
5234  /* No hope if no relation or it doesn't have indexes */
5235  if (rel == NULL || rel->indexlist == NIL)
5236  return false;
5237  /* If it has indexes it must be a plain relation */
5238  rte = root->simple_rte_array[rel->relid];
5239  Assert(rte->rtekind == RTE_RELATION);
5240 
5241  /* Search through the indexes to see if any match our problem */
5242  foreach(lc, rel->indexlist)
5243  {
5245  ScanDirection indexscandir;
5246 
5247  /* Ignore non-btree indexes */
5248  if (index->relam != BTREE_AM_OID)
5249  continue;
5250 
5251  /*
5252  * Ignore partial indexes --- we only want stats that cover the entire
5253  * relation.
5254  */
5255  if (index->indpred != NIL)
5256  continue;
5257 
5258  /*
5259  * The index list might include hypothetical indexes inserted by a
5260  * get_relation_info hook --- don't try to access them.
5261  */
5262  if (index->hypothetical)
5263  continue;
5264 
5265  /*
5266  * The first index column must match the desired variable and sort
5267  * operator --- but we can use a descending-order index.
5268  */
5269  if (!match_index_to_operand(vardata->var, 0, index))
5270  continue;
5271  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5272  {
5273  case BTLessStrategyNumber:
5274  if (index->reverse_sort[0])
5275  indexscandir = BackwardScanDirection;
5276  else
5277  indexscandir = ForwardScanDirection;
5278  break;
5280  if (index->reverse_sort[0])
5281  indexscandir = ForwardScanDirection;
5282  else
5283  indexscandir = BackwardScanDirection;
5284  break;
5285  default:
5286  /* index doesn't match the sortop */
5287  continue;
5288  }
5289 
5290  /*
5291  * Found a suitable index to extract data from. Set up some data that
5292  * can be used by both invocations of get_actual_variable_endpoint.
5293  */
5294  {
5295  MemoryContext tmpcontext;
5296  MemoryContext oldcontext;
5297  Relation heapRel;
5298  Relation indexRel;
5299  TupleTableSlot *slot;
5300  int16 typLen;
5301  bool typByVal;
5302  ScanKeyData scankeys[1];
5303 
5304  /* Make sure any cruft gets recycled when we're done */
5306  "get_actual_variable_range workspace",
5308  oldcontext = MemoryContextSwitchTo(tmpcontext);
5309 
5310  /*
5311  * Open the table and index so we can read from them. We should
5312  * already have some type of lock on each.
5313  */
5314  heapRel = table_open(rte->relid, NoLock);
5315  indexRel = index_open(index->indexoid, NoLock);
5316 
5317  /* build some stuff needed for indexscan execution */
5318  slot = table_slot_create(heapRel, NULL);
5319  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5320 
5321  /* set up an IS NOT NULL scan key so that we ignore nulls */
5322  ScanKeyEntryInitialize(&scankeys[0],
5324  1, /* index col to scan */
5325  InvalidStrategy, /* no strategy */
5326  InvalidOid, /* no strategy subtype */
5327  InvalidOid, /* no collation */
5328  InvalidOid, /* no reg proc for this */
5329  (Datum) 0); /* constant */
5330 
5331  /* If min is requested ... */
5332  if (min)
5333  {
5334  have_data = get_actual_variable_endpoint(heapRel,
5335  indexRel,
5336  indexscandir,
5337  scankeys,
5338  typLen,
5339  typByVal,
5340  slot,
5341  oldcontext,
5342  min);
5343  }
5344  else
5345  {
5346  /* If min not requested, assume index is nonempty */
5347  have_data = true;
5348  }
5349 
5350  /* If max is requested, and we didn't find the index is empty */
5351  if (max && have_data)
5352  {
5353  /* scan in the opposite direction; all else is the same */
5354  have_data = get_actual_variable_endpoint(heapRel,
5355  indexRel,
5356  -indexscandir,
5357  scankeys,
5358  typLen,
5359  typByVal,
5360  slot,
5361  oldcontext,
5362  max);
5363  }
5364 
5365  /* Clean everything up */
5367 
5368  index_close(indexRel, NoLock);
5369  table_close(heapRel, NoLock);
5370 
5371  MemoryContextSwitchTo(oldcontext);
5372  MemoryContextDelete(tmpcontext);
5373 
5374  /* And we're done */
5375  break;
5376  }
5377  }
5378 
5379  return have_data;
5380 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:77
signed short int16
Definition: c.h:354
#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:738
#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:5396
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 4348 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().

4351 {
4352  Node *left,
4353  *right;
4354 
4355  if (list_length(args) != 2)
4356  elog(ERROR, "join operator should take two arguments");
4357 
4358  left = (Node *) linitial(args);
4359  right = (Node *) lsecond(args);
4360 
4361  examine_variable(root, left, 0, vardata1);
4362  examine_variable(root, right, 0, vardata2);
4363 
4364  if (vardata1->rel &&
4365  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4366  *join_is_reversed = true; /* var1 is on RHS */
4367  else if (vardata2->rel &&
4368  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4369  *join_is_reversed = true; /* var2 is on LHS */
4370  else
4371  *join_is_reversed = false;
4372 }
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:4410
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 5558 of file selfuncs.c.

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

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

5559 {
5560  List *result = NIL;
5561  ListCell *lc;
5562 
5563  foreach(lc, indexclauses)
5564  {
5565  IndexClause *iclause = lfirst_node(IndexClause, lc);
5566  ListCell *lc2;
5567 
5568  foreach(lc2, iclause->indexquals)
5569  {
5570  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
5571 
5572  result = lappend(result, rinfo);
5573  }
5574  }
5575  return result;
5576 }
#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 4288 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().

4291 {
4292  Node *left,
4293  *right;
4294  VariableStatData rdata;
4295 
4296  /* Fail if not a binary opclause (probably shouldn't happen) */
4297  if (list_length(args) != 2)
4298  return false;
4299 
4300  left = (Node *) linitial(args);
4301  right = (Node *) lsecond(args);
4302 
4303  /*
4304  * Examine both sides. Note that when varRelid is nonzero, Vars of other
4305  * relations will be treated as pseudoconstants.
4306  */
4307  examine_variable(root, left, varRelid, vardata);
4308  examine_variable(root, right, varRelid, &rdata);
4309 
4310  /*
4311  * If one side is a variable and the other not, we win.
4312  */
4313  if (vardata->rel && rdata.rel == NULL)
4314  {
4315  *varonleft = true;
4316  *other = estimate_expression_value(root, rdata.var);
4317  /* Assume we need no ReleaseVariableStats(rdata) here */
4318  return true;
4319  }
4320 
4321  if (vardata->rel == NULL && rdata.rel)
4322  {
4323  *varonleft = false;
4324  *other = estimate_expression_value(root, vardata->var);
4325  /* Assume we need no ReleaseVariableStats(*vardata) here */
4326  *vardata = rdata;
4327  return true;
4328  }
4329 
4330  /* Oops, clause has wrong structure (probably var op var) */
4331  ReleaseVariableStats(*vardata);
4332  ReleaseVariableStats(rdata);
4333 
4334  return false;
4335 }
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2285
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:4410
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 4959 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().

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