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/acl.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 5861 of file selfuncs.c.

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

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

5862 {
5863  List *predExtraQuals = NIL;
5864  ListCell *lc;
5865 
5866  if (index->indpred == NIL)
5867  return indexQuals;
5868 
5869  foreach(lc, index->indpred)
5870  {
5871  Node *predQual = (Node *) lfirst(lc);
5872  List *oneQual = list_make1(predQual);
5873 
5874  if (!predicate_implied_by(oneQual, indexQuals, false))
5875  predExtraQuals = list_concat(predExtraQuals, oneQual);
5876  }
5877  return list_concat(predExtraQuals, indexQuals);
5878 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:526
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 2932 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().

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

◆ booltestsel()

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

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

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

◆ boolvarsel()

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

Definition at line 1269 of file selfuncs.c.

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

Referenced by clause_selectivity().

1270 {
1271  VariableStatData vardata;
1272  double selec;
1273 
1274  examine_variable(root, arg, varRelid, &vardata);
1275  if (HeapTupleIsValid(vardata.statsTuple))
1276  {
1277  /*
1278  * A boolean variable V is equivalent to the clause V = 't', so we
1279  * compute the selectivity as if that is what we have.
1280  */
1281  selec = var_eq_const(&vardata, BooleanEqualOperator,
1282  BoolGetDatum(true), false, true, false);
1283  }
1284  else
1285  {
1286  /* Otherwise, the default estimate is 0.5 */
1287  selec = 0.5;
1288  }
1289  ReleaseVariableStats(vardata);
1290  return selec;
1291 }
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:290
#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:4411
#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 6972 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().

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

◆ btcostestimate()

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

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

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

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

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

Referenced by convert_to_scalar().

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

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

Referenced by convert_to_scalar().

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

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

Referenced by convert_bytea_to_scalar().

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

◆ convert_one_string_to_scalar()

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

Definition at line 4004 of file selfuncs.c.

Referenced by convert_string_to_scalar().

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

◆ convert_string_datum()

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

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

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

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

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

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

◆ convert_timevalue_to_scalar()

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

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

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

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

◆ eqjoinsel()

Datum eqjoinsel ( PG_FUNCTION_ARGS  )

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

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

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

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

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

References eqsel_internal(), and PG_RETURN_FLOAT8.

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

◆ eqsel_internal()

static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

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

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

◆ estimate_array_length()

int estimate_array_length ( Node arrayexpr)

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

1893 {
1894  /* look through any binary-compatible relabeling of arrayexpr */
1895  arrayexpr = strip_array_coercion(arrayexpr);
1896 
1897  if (arrayexpr && IsA(arrayexpr, Const))
1898  {
1899  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
1900  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
1901  ArrayType *arrayval;
1902 
1903  if (arrayisnull)
1904  return 0;
1905  arrayval = DatumGetArrayTypeP(arraydatum);
1906  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1907  }
1908  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
1909  !((ArrayExpr *) arrayexpr)->multidims)
1910  {
1911  return list_length(((ArrayExpr *) arrayexpr)->elements);
1912  }
1913  else
1914  {
1915  /* default guess --- see also scalararraysel */
1916  return 10;
1917  }
1918 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:577
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:1540
#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 3408 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().

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

◆ estimate_hashagg_tablesize()

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

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

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

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

◆ estimate_num_groups()

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

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

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

◆ examine_simple_variable()

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

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

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

◆ examine_variable()

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

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

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

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

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

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

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

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

4352 {
4353  Node *left,
4354  *right;
4355 
4356  if (list_length(args) != 2)
4357  elog(ERROR, "join operator should take two arguments");
4358 
4359  left = (Node *) linitial(args);
4360  right = (Node *) lsecond(args);
4361 
4362  examine_variable(root, left, 0, vardata1);
4363  examine_variable(root, right, 0, vardata2);
4364 
4365  if (vardata1->rel &&
4366  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4367  *join_is_reversed = true; /* var1 is on RHS */
4368  else if (vardata2->rel &&
4369  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4370  *join_is_reversed = true; /* var2 is on LHS */
4371  else
4372  *join_is_reversed = false;
4373 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:526
#define lsecond(l)
Definition: pg_list.h:200
Relids syn_lefthand
Definition: pathnodes.h:2139
Relids syn_righthand
Definition: pathnodes.h:2140
#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:4411
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:214

◆ get_quals_from_indexclauses()

List* get_quals_from_indexclauses ( List indexclauses)

Definition at line 5559 of file selfuncs.c.

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

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

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

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

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