PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
selfuncs.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <float.h>
#include <math.h>
#include "access/brin.h"
#include "access/gin.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/predtest.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "parser/parse_clause.h"
#include "parser/parse_coerce.h"
#include "parser/parsetree.h"
#include "statistics/statistics.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/bytea.h"
#include "utils/date.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/index_selfuncs.h"
#include "utils/lsyscache.h"
#include "utils/nabstime.h"
#include "utils/pg_locale.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/spccache.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/tqual.h"
#include "utils/typcache.h"
#include "utils/varlena.h"
Include dependency graph for selfuncs.c:

Go to the source code of this file.

Data Structures

struct  GroupVarInfo
 
struct  GinQualCounts
 

Macros

#define FIXED_CHAR_SEL   0.20 /* about 1/5 */
 
#define CHAR_RANGE_SEL   0.25
 
#define ANY_CHAR_SEL   0.9 /* not 1, since it won't match end-of-string */
 
#define FULL_WILDCARD_SEL   5.0
 
#define PARTIAL_WILDCARD_SEL   2.0
 

Functions

static double eqsel_internal (PG_FUNCTION_ARGS, bool negate)
 
static double var_eq_const (VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
 
static double var_eq_non_const (VariableStatData *vardata, Oid operator, Node *other, bool varonleft, bool negate)
 
static double ineq_histogram_selectivity (PlannerInfo *root, VariableStatData *vardata, FmgrInfo *opproc, bool isgt, Datum constval, Oid consttype)
 
static double eqjoinsel_inner (Oid operator, VariableStatData *vardata1, VariableStatData *vardata2)
 
static double eqjoinsel_semi (Oid operator, VariableStatData *vardata1, VariableStatData *vardata2, 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, double *scaledvalue, Datum lobound, Datum hibound, Oid boundstypid, double *scaledlobound, double *scaledhibound)
 
static double convert_numeric_to_scalar (Datum value, Oid typid)
 
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)
 
static double convert_timevalue_to_scalar (Datum value, Oid typid)
 
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 RelOptInfofind_join_input_rel (PlannerInfo *root, Relids relids)
 
static Selectivity prefix_selectivity (PlannerInfo *root, VariableStatData *vardata, Oid vartype, Oid opfamily, Const *prefixcon)
 
static Selectivity like_selectivity (const char *patt, int pattlen, bool case_insensitive)
 
static Selectivity regex_selectivity (const char *patt, int pattlen, bool case_insensitive, int fixed_prefix_len)
 
static Datum string_to_datum (const char *str, Oid datatype)
 
static Conststring_to_const (const char *str, Oid datatype)
 
static Conststring_to_bytea_const (const char *str, size_t str_len)
 
static Listadd_predicate_to_quals (IndexOptInfo *index, List *indexQuals)
 
Datum eqsel (PG_FUNCTION_ARGS)
 
Datum neqsel (PG_FUNCTION_ARGS)
 
static double scalarineqsel (PlannerInfo *root, Oid operator, bool isgt, 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)
 
Datum scalarltsel (PG_FUNCTION_ARGS)
 
Datum scalargtsel (PG_FUNCTION_ARGS)
 
static double patternsel (PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 
Datum regexeqsel (PG_FUNCTION_ARGS)
 
Datum icregexeqsel (PG_FUNCTION_ARGS)
 
Datum likesel (PG_FUNCTION_ARGS)
 
Datum iclikesel (PG_FUNCTION_ARGS)
 
Datum regexnesel (PG_FUNCTION_ARGS)
 
Datum icregexnesel (PG_FUNCTION_ARGS)
 
Datum nlikesel (PG_FUNCTION_ARGS)
 
Datum icnlikesel (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 scalargtjoinsel (PG_FUNCTION_ARGS)
 
static double patternjoinsel (PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 
Datum regexeqjoinsel (PG_FUNCTION_ARGS)
 
Datum icregexeqjoinsel (PG_FUNCTION_ARGS)
 
Datum likejoinsel (PG_FUNCTION_ARGS)
 
Datum iclikejoinsel (PG_FUNCTION_ARGS)
 
Datum regexnejoinsel (PG_FUNCTION_ARGS)
 
Datum icregexnejoinsel (PG_FUNCTION_ARGS)
 
Datum nlikejoinsel (PG_FUNCTION_ARGS)
 
Datum icnlikejoinsel (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)
 
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)
 
static int pattern_char_isalpha (char c, bool is_multibyte, pg_locale_t locale, bool locale_is_c)
 
static Pattern_Prefix_Status like_fixed_prefix (Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
 
static Pattern_Prefix_Status regex_fixed_prefix (Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
 
Pattern_Prefix_Status pattern_fixed_prefix (Const *patt, Pattern_Type ptype, Oid collation, Const **prefix, Selectivity *rest_selec)
 
static Selectivity regex_selectivity_sub (const char *patt, int pattlen, bool case_insensitive)
 
static bool byte_increment (unsigned char *ptr, int len)
 
Constmake_greater_string (const Const *str_const, FmgrInfo *ltproc, Oid collation)
 
Listdeconstruct_indexquals (IndexPath *path)
 
static Cost other_operands_eval_cost (PlannerInfo *root, List *qinfos)
 
static Cost orderby_operands_eval_cost (PlannerInfo *root, IndexPath *path)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
 
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, IndexQualInfo *qinfo, GinQualCounts *counts)
 
static bool gincost_scalararrayopexpr (PlannerInfo *root, IndexOptInfo *index, IndexQualInfo *qinfo, 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
 

Macro Definition Documentation

#define ANY_CHAR_SEL   0.9 /* not 1, since it won't match end-of-string */

Definition at line 5875 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity_sub().

#define CHAR_RANGE_SEL   0.25

Definition at line 5874 of file selfuncs.c.

Referenced by regex_selectivity_sub().

#define FIXED_CHAR_SEL   0.20 /* about 1/5 */

Definition at line 5873 of file selfuncs.c.

Referenced by like_selectivity(), regex_selectivity(), and regex_selectivity_sub().

#define FULL_WILDCARD_SEL   5.0

Definition at line 5876 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity().

#define PARTIAL_WILDCARD_SEL   2.0

Definition at line 5877 of file selfuncs.c.

Referenced by regex_selectivity_sub().

Function Documentation

static List * add_predicate_to_quals ( IndexOptInfo index,
List indexQuals 
)
static

Definition at line 6687 of file selfuncs.c.

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

Referenced by btcostestimate(), and genericcostestimate().

6688 {
6689  List *predExtraQuals = NIL;
6690  ListCell *lc;
6691 
6692  if (index->indpred == NIL)
6693  return indexQuals;
6694 
6695  foreach(lc, index->indpred)
6696  {
6697  Node *predQual = (Node *) lfirst(lc);
6698  List *oneQual = list_make1(predQual);
6699 
6700  if (!predicate_implied_by(oneQual, indexQuals, false))
6701  predExtraQuals = list_concat(predExtraQuals, oneQual);
6702  }
6703  /* list_concat avoids modifying the passed-in indexQuals list */
6704  return list_concat(predExtraQuals, indexQuals);
6705 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
Definition: nodes.h:509
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define list_make1(x1)
Definition: pg_list.h:139
#define lfirst(lc)
Definition: pg_list.h:106
List * indpred
Definition: relation.h:654
Definition: pg_list.h:45
static List* add_unique_group_var ( PlannerInfo root,
List varinfos,
Node var,
VariableStatData vardata 
)
static

Definition at line 3151 of file selfuncs.c.

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

Referenced by estimate_num_groups().

3153 {
3154  GroupVarInfo *varinfo;
3155  double ndistinct;
3156  bool isdefault;
3157  ListCell *lc;
3158 
3159  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3160 
3161  /* cannot use foreach here because of possible list_delete */
3162  lc = list_head(varinfos);
3163  while (lc)
3164  {
3165  varinfo = (GroupVarInfo *) lfirst(lc);
3166 
3167  /* must advance lc before list_delete possibly pfree's it */
3168  lc = lnext(lc);
3169 
3170  /* Drop exact duplicates */
3171  if (equal(var, varinfo->var))
3172  return varinfos;
3173 
3174  /*
3175  * Drop known-equal vars, but only if they belong to different
3176  * relations (see comments for estimate_num_groups)
3177  */
3178  if (vardata->rel != varinfo->rel &&
3179  exprs_known_equal(root, var, varinfo->var))
3180  {
3181  if (varinfo->ndistinct <= ndistinct)
3182  {
3183  /* Keep older item, forget new one */
3184  return varinfos;
3185  }
3186  else
3187  {
3188  /* Delete the older item */
3189  varinfos = list_delete_ptr(varinfos, varinfo);
3190  }
3191  }
3192  }
3193 
3194  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3195 
3196  varinfo->var = var;
3197  varinfo->rel = vardata->rel;
3198  varinfo->ndistinct = ndistinct;
3199  varinfos = lappend(varinfos, varinfo);
3200  return varinfos;
3201 }
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:1945
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2962
RelOptInfo * rel
Definition: selfuncs.h:70
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
double ndistinct
Definition: selfuncs.c:3147
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4979
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
Node * var
Definition: selfuncs.c:3145
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
void * palloc(Size size)
Definition: mcxt.c:849
RelOptInfo * rel
Definition: selfuncs.c:3146
Selectivity booltestsel ( PlannerInfo root,
BoolTestType  booltesttype,
Node arg,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1517 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, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by clause_selectivity().

1519 {
1520  VariableStatData vardata;
1521  double selec;
1522 
1523  examine_variable(root, arg, varRelid, &vardata);
1524 
1525  if (HeapTupleIsValid(vardata.statsTuple))
1526  {
1527  Form_pg_statistic stats;
1528  double freq_null;
1529  AttStatsSlot sslot;
1530 
1531  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1532  freq_null = stats->stanullfrac;
1533 
1534  if (get_attstatsslot(&sslot, vardata.statsTuple,
1537  && sslot.nnumbers > 0)
1538  {
1539  double freq_true;
1540  double freq_false;
1541 
1542  /*
1543  * Get first MCV frequency and derive frequency for true.
1544  */
1545  if (DatumGetBool(sslot.values[0]))
1546  freq_true = sslot.numbers[0];
1547  else
1548  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1549 
1550  /*
1551  * Next derive frequency for false. Then use these as appropriate
1552  * to derive frequency for each case.
1553  */
1554  freq_false = 1.0 - freq_true - freq_null;
1555 
1556  switch (booltesttype)
1557  {
1558  case IS_UNKNOWN:
1559  /* select only NULL values */
1560  selec = freq_null;
1561  break;
1562  case IS_NOT_UNKNOWN:
1563  /* select non-NULL values */
1564  selec = 1.0 - freq_null;
1565  break;
1566  case IS_TRUE:
1567  /* select only TRUE values */
1568  selec = freq_true;
1569  break;
1570  case IS_NOT_TRUE:
1571  /* select non-TRUE values */
1572  selec = 1.0 - freq_true;
1573  break;
1574  case IS_FALSE:
1575  /* select only FALSE values */
1576  selec = freq_false;
1577  break;
1578  case IS_NOT_FALSE:
1579  /* select non-FALSE values */
1580  selec = 1.0 - freq_false;
1581  break;
1582  default:
1583  elog(ERROR, "unrecognized booltesttype: %d",
1584  (int) booltesttype);
1585  selec = 0.0; /* Keep compiler quiet */
1586  break;
1587  }
1588 
1589  free_attstatsslot(&sslot);
1590  }
1591  else
1592  {
1593  /*
1594  * No most-common-value info available. Still have null fraction
1595  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1596  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1597  */
1598  switch (booltesttype)
1599  {
1600  case IS_UNKNOWN:
1601  /* select only NULL values */
1602  selec = freq_null;
1603  break;
1604  case IS_NOT_UNKNOWN:
1605  /* select non-NULL values */
1606  selec = 1.0 - freq_null;
1607  break;
1608  case IS_TRUE:
1609  case IS_FALSE:
1610  /* Assume we select half of the non-NULL values */
1611  selec = (1.0 - freq_null) / 2.0;
1612  break;
1613  case IS_NOT_TRUE:
1614  case IS_NOT_FALSE:
1615  /* Assume we select NULLs plus half of the non-NULLs */
1616  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1617  selec = (freq_null + 1.0) / 2.0;
1618  break;
1619  default:
1620  elog(ERROR, "unrecognized booltesttype: %d",
1621  (int) booltesttype);
1622  selec = 0.0; /* Keep compiler quiet */
1623  break;
1624  }
1625  }
1626  }
1627  else
1628  {
1629  /*
1630  * If we can't get variable statistics for the argument, perhaps
1631  * clause_selectivity can do something with it. We ignore the
1632  * possibility of a NULL value when using clause_selectivity, and just
1633  * assume the value is either TRUE or FALSE.
1634  */
1635  switch (booltesttype)
1636  {
1637  case IS_UNKNOWN:
1638  selec = DEFAULT_UNK_SEL;
1639  break;
1640  case IS_NOT_UNKNOWN:
1641  selec = DEFAULT_NOT_UNK_SEL;
1642  break;
1643  case IS_TRUE:
1644  case IS_NOT_FALSE:
1645  selec = (double) clause_selectivity(root, arg,
1646  varRelid,
1647  jointype, sjinfo);
1648  break;
1649  case IS_FALSE:
1650  case IS_NOT_TRUE:
1651  selec = 1.0 - (double) clause_selectivity(root, arg,
1652  varRelid,
1653  jointype, sjinfo);
1654  break;
1655  default:
1656  elog(ERROR, "unrecognized booltesttype: %d",
1657  (int) booltesttype);
1658  selec = 0.0; /* Keep compiler quiet */
1659  break;
1660  }
1661  }
1662 
1663  ReleaseVariableStats(vardata);
1664 
1665  /* result should be in range, but make sure... */
1666  CLAMP_PROBABILITY(selec);
1667 
1668  return (Selectivity) selec;
1669 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define ATTSTATSSLOT_VALUES
Definition: lsyscache.h:39
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double Selectivity
Definition: nodes.h:639
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#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:572
float4 * numbers
Definition: lsyscache.h:52
#define DatumGetBool(X)
Definition: postgres.h:399
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
#define DEFAULT_UNK_SEL
Definition: selfuncs.h:49
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4572
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
Datum * values
Definition: lsyscache.h:49
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
#define elog
Definition: elog.h:219
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
Selectivity boolvarsel ( PlannerInfo root,
Node arg,
int  varRelid 
)

Definition at line 1478 of file selfuncs.c.

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

Referenced by clause_selectivity().

1479 {
1480  VariableStatData vardata;
1481  double selec;
1482 
1483  examine_variable(root, arg, varRelid, &vardata);
1484  if (HeapTupleIsValid(vardata.statsTuple))
1485  {
1486  /*
1487  * A boolean variable V is equivalent to the clause V = 't', so we
1488  * compute the selectivity as if that is what we have.
1489  */
1490  selec = var_eq_const(&vardata, BooleanEqualOperator,
1491  BoolGetDatum(true), false, true, false);
1492  }
1493  else if (is_funcclause(arg))
1494  {
1495  /*
1496  * If we have no stats and it's a function call, estimate 0.3333333.
1497  * This seems a pretty unprincipled choice, but Postgres has been
1498  * using that estimate for function calls since 1992. The hoariness
1499  * of this behavior suggests that we should not be in too much hurry
1500  * to use another value.
1501  */
1502  selec = 0.3333333;
1503  }
1504  else
1505  {
1506  /* Otherwise, the default estimate is 0.5 */
1507  selec = 0.5;
1508  }
1509  ReleaseVariableStats(vardata);
1510  return selec;
1511 }
HeapTuple statsTuple
Definition: selfuncs.h:71
#define is_funcclause(clause)
Definition: clauses.h:21
#define BooleanEqualOperator
Definition: pg_operator.h:114
static double var_eq_const(VariableStatData *vardata, Oid operator, Datum constval, bool constisnull, bool varonleft, bool negate)
Definition: selfuncs.c:296
#define BoolGetDatum(X)
Definition: postgres.h:408
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4572
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
void brincostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 7789 of file selfuncs.c.

References Abs, AccessShareLock, Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum, brinGetStats(), CLAMP_PROBABILITY, clauselist_selectivity(), cpu_operator_cost, deconstruct_indexquals(), elog, ERROR, free_attstatsslot(), VariableStatData::freefunc, get_attstatsslot(), get_index_stats_hook, get_relation_stats_hook, get_tablespace_page_costs(), HeapTupleIsValid, index_close(), index_open(), IndexQualInfo::indexcol, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, IndexPath::indexquals, Int16GetDatum, InvalidOid, JOIN_INNER, lfirst, Max, Min, AttStatsSlot::nnumbers, NULL, AttStatsSlot::numbers, ObjectIdGetDatum, orderby_operands_eval_cost(), other_operands_eval_cost(), RelOptInfo::pages, IndexOptInfo::pages, BrinStatsData::pagesPerRange, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, IndexOptInfo::reltablespace, BrinStatsData::revmapNumPages, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3, STATISTIC_KIND_CORRELATION, STATRELATTINH, and VariableStatData::statsTuple.

Referenced by brinhandler().

7793 {
7794  IndexOptInfo *index = path->indexinfo;
7795  List *indexQuals = path->indexquals;
7796  double numPages = index->pages;
7797  RelOptInfo *baserel = index->rel;
7798  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7799  List *qinfos;
7800  Cost spc_seq_page_cost;
7801  Cost spc_random_page_cost;
7802  double qual_arg_cost;
7803  double qualSelectivity;
7804  BrinStatsData statsData;
7805  double indexRanges;
7806  double minimalRanges;
7807  double estimatedRanges;
7808  double selec;
7809  Relation indexRel;
7810  ListCell *l;
7811  VariableStatData vardata;
7812 
7813  Assert(rte->rtekind == RTE_RELATION);
7814 
7815  /* fetch estimated page cost for the tablespace containing the index */
7817  &spc_random_page_cost,
7818  &spc_seq_page_cost);
7819 
7820  /*
7821  * Obtain some data from the index itself.
7822  */
7823  indexRel = index_open(index->indexoid, AccessShareLock);
7824  brinGetStats(indexRel, &statsData);
7825  index_close(indexRel, AccessShareLock);
7826 
7827  /*
7828  * Compute index correlation
7829  *
7830  * Because we can use all index quals equally when scanning, we can use
7831  * the largest correlation (in absolute value) among columns used by the
7832  * query. Start at zero, the worst possible case. If we cannot find any
7833  * correlation statistics, we will keep it as 0.
7834  */
7835  *indexCorrelation = 0;
7836 
7837  qinfos = deconstruct_indexquals(path);
7838  foreach(l, qinfos)
7839  {
7840  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(l);
7841  AttrNumber attnum = index->indexkeys[qinfo->indexcol];
7842 
7843  /* attempt to lookup stats in relation for this index column */
7844  if (attnum != 0)
7845  {
7846  /* Simple variable -- look to stats for the underlying table */
7848  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7849  {
7850  /*
7851  * The hook took control of acquiring a stats tuple. If it
7852  * did supply a tuple, it'd better have supplied a freefunc.
7853  */
7854  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7855  elog(ERROR,
7856  "no function provided to release variable stats with");
7857  }
7858  else
7859  {
7860  vardata.statsTuple =
7862  ObjectIdGetDatum(rte->relid),
7863  Int16GetDatum(attnum),
7864  BoolGetDatum(false));
7865  vardata.freefunc = ReleaseSysCache;
7866  }
7867  }
7868  else
7869  {
7870  /*
7871  * Looks like we've found an expression column in the index. Let's
7872  * see if there's any stats for it.
7873  */
7874 
7875  /* get the attnum from the 0-based index. */
7876  attnum = qinfo->indexcol + 1;
7877 
7878  if (get_index_stats_hook &&
7879  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7880  {
7881  /*
7882  * The hook took control of acquiring a stats tuple. If it
7883  * did supply a tuple, it'd better have supplied a freefunc.
7884  */
7885  if (HeapTupleIsValid(vardata.statsTuple) &&
7886  !vardata.freefunc)
7887  elog(ERROR, "no function provided to release variable stats with");
7888  }
7889  else
7890  {
7892  ObjectIdGetDatum(index->indexoid),
7893  Int16GetDatum(attnum),
7894  BoolGetDatum(false));
7895  vardata.freefunc = ReleaseSysCache;
7896  }
7897  }
7898 
7899  if (HeapTupleIsValid(vardata.statsTuple))
7900  {
7901  AttStatsSlot sslot;
7902 
7903  if (get_attstatsslot(&sslot, vardata.statsTuple,
7906  {
7907  double varCorrelation = 0.0;
7908 
7909  if (sslot.nnumbers > 0)
7910  varCorrelation = Abs(sslot.numbers[0]);
7911 
7912  if (varCorrelation > *indexCorrelation)
7913  *indexCorrelation = varCorrelation;
7914 
7915  free_attstatsslot(&sslot);
7916  }
7917  }
7918 
7919  ReleaseVariableStats(vardata);
7920  }
7921 
7922  qualSelectivity = clauselist_selectivity(root, indexQuals,
7923  baserel->relid,
7924  JOIN_INNER, NULL);
7925 
7926  /* work out the actual number of ranges in the index */
7927  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
7928  1.0);
7929 
7930  /*
7931  * Now calculate the minimum possible ranges we could match with if all of
7932  * the rows were in the perfect order in the table's heap.
7933  */
7934  minimalRanges = ceil(indexRanges * qualSelectivity);
7935 
7936  /*
7937  * Now estimate the number of ranges that we'll touch by using the
7938  * indexCorrelation from the stats. Careful not to divide by zero (note
7939  * we're using the absolute value of the correlation).
7940  */
7941  if (*indexCorrelation < 1.0e-10)
7942  estimatedRanges = indexRanges;
7943  else
7944  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7945 
7946  /* we expect to visit this portion of the table */
7947  selec = estimatedRanges / indexRanges;
7948 
7949  CLAMP_PROBABILITY(selec);
7950 
7951  *indexSelectivity = selec;
7952 
7953  /*
7954  * Compute the index qual costs, much as in genericcostestimate, to add to
7955  * the index costs.
7956  */
7957  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
7958  orderby_operands_eval_cost(root, path);
7959 
7960  /*
7961  * Compute the startup cost as the cost to read the whole revmap
7962  * sequentially, including the cost to execute the index quals.
7963  */
7964  *indexStartupCost =
7965  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7966  *indexStartupCost += qual_arg_cost;
7967 
7968  /*
7969  * To read a BRIN index there might be a bit of back and forth over
7970  * regular pages, as revmap might point to them out of sequential order;
7971  * calculate the total cost as reading the whole index in random order.
7972  */
7973  *indexTotalCost = *indexStartupCost +
7974  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7975 
7976  /*
7977  * Charge a small amount per range tuple which we expect to match to. This
7978  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7979  * will set a bit for each page in the range when we find a matching
7980  * range, so we must multiply the charge by the number of pages in the
7981  * range.
7982  */
7983  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7984  statsData.pagesPerRange;
7985 
7986  *indexPages = index->pages;
7987 }
IndexOptInfo * indexinfo
Definition: relation.h:1031
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
#define Min(x, y)
Definition: c.h:807
#define Int16GetDatum(X)
Definition: postgres.h:457
#define AccessShareLock
Definition: lockdefs.h:36
Oid reltablespace
Definition: relation.h:632
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6414
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6319
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6439
#define Abs(x)
Definition: c.h:813
Definition: type.h:89
BlockNumber pages
Definition: relation.h:636
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
List * indexquals
Definition: relation.h:1033
RelOptInfo * rel
Definition: relation.h:633
#define planner_rt_fetch(rti, root)
Definition: relation.h:325
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define STATISTIC_KIND_CORRELATION
Definition: pg_statistic.h:233
float4 * numbers
Definition: lsyscache.h:52
double cpu_operator_cost
Definition: costsize.c:108
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:154
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:553
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
BlockNumber pagesPerRange
Definition: brin.h:34
#define Max(x, y)
Definition: c.h:801
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
BlockNumber pages
Definition: relation.h:564
#define NULL
Definition: c.h:229
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:155
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
RTEKind rtekind
Definition: parsenodes.h:944
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:160
int * indexkeys
Definition: relation.h:642
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:631
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
double Cost
Definition: nodes.h:640
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1066
BlockNumber revmapNumPages
Definition: brin.h:35
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
void btcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

Definition at line 6709 of file selfuncs.c.

References add_predicate_to_quals(), Assert, ATTSTATSSLOT_NUMBERS, BoolGetDatum, BTEqualStrategyNumber, BTLessStrategyNumber, RestrictInfo::clause, IndexQualInfo::clause_op, clauselist_selectivity(), cpu_operator_cost, deconstruct_indexquals(), 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, IndexQualInfo::indexcol, GenericCosts::indexCorrelation, IndexPath::indexinfo, IndexOptInfo::indexkeys, IndexOptInfo::indexoid, GenericCosts::indexSelectivity, GenericCosts::indexStartupCost, GenericCosts::indexTotalCost, RangeTblEntry::inh, Int16GetDatum, InvalidOid, IS_NULL, IsA, JOIN_INNER, lappend(), lfirst, MemSet, IndexOptInfo::ncolumns, NIL, AttStatsSlot::nnumbers, NULL, NullTest::nulltesttype, GenericCosts::num_sa_scans, AttStatsSlot::numbers, GenericCosts::numIndexPages, GenericCosts::numIndexTuples, ObjectIdGetDatum, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, IndexQualInfo::other_operand, planner_rt_fetch, IndexOptInfo::rel, ReleaseSysCache(), ReleaseVariableStats, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, IndexQualInfo::rinfo, rint(), RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3, STATISTIC_KIND_CORRELATION, STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by bthandler().

6713 {
6714  IndexOptInfo *index = path->indexinfo;
6715  List *qinfos;
6716  GenericCosts costs;
6717  Oid relid;
6718  AttrNumber colnum;
6719  VariableStatData vardata;
6720  double numIndexTuples;
6721  Cost descentCost;
6722  List *indexBoundQuals;
6723  int indexcol;
6724  bool eqQualHere;
6725  bool found_saop;
6726  bool found_is_null_op;
6727  double num_sa_scans;
6728  ListCell *lc;
6729 
6730  /* Do preliminary analysis of indexquals */
6731  qinfos = deconstruct_indexquals(path);
6732 
6733  /*
6734  * For a btree scan, only leading '=' quals plus inequality quals for the
6735  * immediately next attribute contribute to index selectivity (these are
6736  * the "boundary quals" that determine the starting and stopping points of
6737  * the index scan). Additional quals can suppress visits to the heap, so
6738  * it's OK to count them in indexSelectivity, but they should not count
6739  * for estimating numIndexTuples. So we must examine the given indexquals
6740  * to find out which ones count as boundary quals. We rely on the
6741  * knowledge that they are given in index column order.
6742  *
6743  * For a RowCompareExpr, we consider only the first column, just as
6744  * rowcomparesel() does.
6745  *
6746  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6747  * index scans not one, but the ScalarArrayOpExpr's operator can be
6748  * considered to act the same as it normally does.
6749  */
6750  indexBoundQuals = NIL;
6751  indexcol = 0;
6752  eqQualHere = false;
6753  found_saop = false;
6754  found_is_null_op = false;
6755  num_sa_scans = 1;
6756  foreach(lc, qinfos)
6757  {
6758  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6759  RestrictInfo *rinfo = qinfo->rinfo;
6760  Expr *clause = rinfo->clause;
6761  Oid clause_op;
6762  int op_strategy;
6763 
6764  if (indexcol != qinfo->indexcol)
6765  {
6766  /* Beginning of a new column's quals */
6767  if (!eqQualHere)
6768  break; /* done if no '=' qual for indexcol */
6769  eqQualHere = false;
6770  indexcol++;
6771  if (indexcol != qinfo->indexcol)
6772  break; /* no quals at all for indexcol */
6773  }
6774 
6775  if (IsA(clause, ScalarArrayOpExpr))
6776  {
6777  int alength = estimate_array_length(qinfo->other_operand);
6778 
6779  found_saop = true;
6780  /* count up number of SA scans induced by indexBoundQuals only */
6781  if (alength > 1)
6782  num_sa_scans *= alength;
6783  }
6784  else if (IsA(clause, NullTest))
6785  {
6786  NullTest *nt = (NullTest *) clause;
6787 
6788  if (nt->nulltesttype == IS_NULL)
6789  {
6790  found_is_null_op = true;
6791  /* IS NULL is like = for selectivity determination purposes */
6792  eqQualHere = true;
6793  }
6794  }
6795 
6796  /*
6797  * We would need to commute the clause_op if not varonleft, except
6798  * that we only care if it's equality or not, so that refinement is
6799  * unnecessary.
6800  */
6801  clause_op = qinfo->clause_op;
6802 
6803  /* check for equality operator */
6804  if (OidIsValid(clause_op))
6805  {
6806  op_strategy = get_op_opfamily_strategy(clause_op,
6807  index->opfamily[indexcol]);
6808  Assert(op_strategy != 0); /* not a member of opfamily?? */
6809  if (op_strategy == BTEqualStrategyNumber)
6810  eqQualHere = true;
6811  }
6812 
6813  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6814  }
6815 
6816  /*
6817  * If index is unique and we found an '=' clause for each column, we can
6818  * just assume numIndexTuples = 1 and skip the expensive
6819  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6820  * NullTest invalidates that theory, even though it sets eqQualHere.
6821  */
6822  if (index->unique &&
6823  indexcol == index->ncolumns - 1 &&
6824  eqQualHere &&
6825  !found_saop &&
6826  !found_is_null_op)
6827  numIndexTuples = 1.0;
6828  else
6829  {
6830  List *selectivityQuals;
6831  Selectivity btreeSelectivity;
6832 
6833  /*
6834  * If the index is partial, AND the index predicate with the
6835  * index-bound quals to produce a more accurate idea of the number of
6836  * rows covered by the bound conditions.
6837  */
6838  selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
6839 
6840  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6841  index->rel->relid,
6842  JOIN_INNER,
6843  NULL);
6844  numIndexTuples = btreeSelectivity * index->rel->tuples;
6845 
6846  /*
6847  * As in genericcostestimate(), we have to adjust for any
6848  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6849  * to integer.
6850  */
6851  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6852  }
6853 
6854  /*
6855  * Now do generic index cost estimation.
6856  */
6857  MemSet(&costs, 0, sizeof(costs));
6858  costs.numIndexTuples = numIndexTuples;
6859 
6860  genericcostestimate(root, path, loop_count, qinfos, &costs);
6861 
6862  /*
6863  * Add a CPU-cost component to represent the costs of initial btree
6864  * descent. We don't charge any I/O cost for touching upper btree levels,
6865  * since they tend to stay in cache, but we still have to do about log2(N)
6866  * comparisons to descend a btree of N leaf tuples. We charge one
6867  * cpu_operator_cost per comparison.
6868  *
6869  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6870  * ones after the first one are not startup cost so far as the overall
6871  * plan is concerned, so add them only to "total" cost.
6872  */
6873  if (index->tuples > 1) /* avoid computing log(0) */
6874  {
6875  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6876  costs.indexStartupCost += descentCost;
6877  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6878  }
6879 
6880  /*
6881  * Even though we're not charging I/O cost for touching upper btree pages,
6882  * it's still reasonable to charge some CPU cost per page descended
6883  * through. Moreover, if we had no such charge at all, bloated indexes
6884  * would appear to have the same search cost as unbloated ones, at least
6885  * in cases where only a single leaf page is expected to be visited. This
6886  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6887  * touched. The number of such pages is btree tree height plus one (ie,
6888  * we charge for the leaf page too). As above, charge once per SA scan.
6889  */
6890  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6891  costs.indexStartupCost += descentCost;
6892  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6893 
6894  /*
6895  * If we can get an estimate of the first column's ordering correlation C
6896  * from pg_statistic, estimate the index correlation as C for a
6897  * single-column index, or C * 0.75 for multiple columns. (The idea here
6898  * is that multiple columns dilute the importance of the first column's
6899  * ordering, but don't negate it entirely. Before 8.0 we divided the
6900  * correlation by the number of columns, but that seems too strong.)
6901  */
6902  MemSet(&vardata, 0, sizeof(vardata));
6903 
6904  if (index->indexkeys[0] != 0)
6905  {
6906  /* Simple variable --- look to stats for the underlying table */
6907  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6908 
6909  Assert(rte->rtekind == RTE_RELATION);
6910  relid = rte->relid;
6911  Assert(relid != InvalidOid);
6912  colnum = index->indexkeys[0];
6913 
6915  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6916  {
6917  /*
6918  * The hook took control of acquiring a stats tuple. If it did
6919  * supply a tuple, it'd better have supplied a freefunc.
6920  */
6921  if (HeapTupleIsValid(vardata.statsTuple) &&
6922  !vardata.freefunc)
6923  elog(ERROR, "no function provided to release variable stats with");
6924  }
6925  else
6926  {
6928  ObjectIdGetDatum(relid),
6929  Int16GetDatum(colnum),
6930  BoolGetDatum(rte->inh));
6931  vardata.freefunc = ReleaseSysCache;
6932  }
6933  }
6934  else
6935  {
6936  /* Expression --- maybe there are stats for the index itself */
6937  relid = index->indexoid;
6938  colnum = 1;
6939 
6940  if (get_index_stats_hook &&
6941  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6942  {
6943  /*
6944  * The hook took control of acquiring a stats tuple. If it did
6945  * supply a tuple, it'd better have supplied a freefunc.
6946  */
6947  if (HeapTupleIsValid(vardata.statsTuple) &&
6948  !vardata.freefunc)
6949  elog(ERROR, "no function provided to release variable stats with");
6950  }
6951  else
6952  {
6954  ObjectIdGetDatum(relid),
6955  Int16GetDatum(colnum),
6956  BoolGetDatum(false));
6957  vardata.freefunc = ReleaseSysCache;
6958  }
6959  }
6960 
6961  if (HeapTupleIsValid(vardata.statsTuple))
6962  {
6963  Oid sortop;
6964  AttStatsSlot sslot;
6965 
6966  sortop = get_opfamily_member(index->opfamily[0],
6967  index->opcintype[0],
6968  index->opcintype[0],
6970  if (OidIsValid(sortop) &&
6971  get_attstatsslot(&sslot, vardata.statsTuple,
6974  {
6975  double varCorrelation;
6976 
6977  Assert(sslot.nnumbers == 1);
6978  varCorrelation = sslot.numbers[0];
6979 
6980  if (index->reverse_sort[0])
6981  varCorrelation = -varCorrelation;
6982 
6983  if (index->ncolumns > 1)
6984  costs.indexCorrelation = varCorrelation * 0.75;
6985  else
6986  costs.indexCorrelation = varCorrelation;
6987 
6988  free_attstatsslot(&sslot);
6989  }
6990  }
6991 
6992  ReleaseVariableStats(vardata);
6993 
6994  *indexStartupCost = costs.indexStartupCost;
6995  *indexTotalCost = costs.indexTotalCost;
6996  *indexSelectivity = costs.indexSelectivity;
6997  *indexCorrelation = costs.indexCorrelation;
6998  *indexPages = costs.numIndexPages;
6999 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
IndexOptInfo * indexinfo
Definition: relation.h:1031
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:565
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6687
#define Int16GetDatum(X)
Definition: postgres.h:457
#define MemSet(start, val, len)
Definition: c.h:858
double Selectivity
Definition: nodes.h:639
double tuples
Definition: relation.h:637
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: relation.h:638
#define OidIsValid(objectId)
Definition: c.h:538
RestrictInfo * rinfo
Definition: selfuncs.h:106
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6319
bool unique
Definition: relation.h:665
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2094
RelOptInfo * rel
Definition: relation.h:633
#define planner_rt_fetch(rti, root)
Definition: relation.h:325
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
double num_sa_scans
Definition: selfuncs.h:138
#define STATISTIC_KIND_CORRELATION
Definition: pg_statistic.h:233
float4 * numbers
Definition: lsyscache.h:52
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
double cpu_operator_cost
Definition: costsize.c:108
Cost indexTotalCost
Definition: selfuncs.h:130
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:154
double rint(double x)
Definition: rint.c:22
int ncolumns
Definition: relation.h:641
Index relid
Definition: relation.h:553
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1747
double indexCorrelation
Definition: selfuncs.h:132
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
NullTestType nulltesttype
Definition: primnodes.h:1181
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
double numIndexTuples
Definition: selfuncs.h:136
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:155
Oid * opcintype
Definition: relation.h:645
Cost indexStartupCost
Definition: selfuncs.h:129
Oid * opfamily
Definition: relation.h:644
RTEKind rtekind
Definition: parsenodes.h:944
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
Node * other_operand
Definition: selfuncs.h:110
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:160
int * indexkeys
Definition: relation.h:642
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:631
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
bool * reverse_sort
Definition: relation.h:647
#define BTLessStrategyNumber
Definition: stratnum.h:29
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define BTEqualStrategyNumber
Definition: stratnum.h:31
double Cost
Definition: nodes.h:640
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
Definition: selfuncs.c:6468
double numIndexPages
Definition: selfuncs.h:135
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
static bool byte_increment ( unsigned char *  ptr,
int  len 
)
static

Definition at line 6043 of file selfuncs.c.

Referenced by make_greater_string().

6044 {
6045  if (*ptr >= 255)
6046  return false;
6047  (*ptr)++;
6048  return true;
6049 }
static void convert_bytea_to_scalar ( Datum  value,
double *  scaledvalue,
Datum  lobound,
double *  scaledlobound,
Datum  hibound,
double *  scaledhibound 
)
static

Definition at line 4286 of file selfuncs.c.

References convert_one_bytea_to_scalar(), DatumGetPointer, i, Min, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by convert_to_scalar().

4292 {
4293  int rangelo,
4294  rangehi,
4295  valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
4296  loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
4297  hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
4298  i,
4299  minlen;
4300  unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
4301  *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
4302  *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4303 
4304  /*
4305  * Assume bytea data is uniformly distributed across all byte values.
4306  */
4307  rangelo = 0;
4308  rangehi = 255;
4309 
4310  /*
4311  * Now strip any common prefix of the three strings.
4312  */
4313  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4314  for (i = 0; i < minlen; i++)
4315  {
4316  if (*lostr != *histr || *lostr != *valstr)
4317  break;
4318  lostr++, histr++, valstr++;
4319  loboundlen--, hiboundlen--, valuelen--;
4320  }
4321 
4322  /*
4323  * Now we can do the conversions.
4324  */
4325  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4326  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4327  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4328 }
#define VARDATA(PTR)
Definition: postgres.h:303
#define VARSIZE(PTR)
Definition: postgres.h:304
#define VARHDRSZ
Definition: c.h:445
#define Min(x, y)
Definition: c.h:807
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4331
static struct @121 value
#define DatumGetPointer(X)
Definition: postgres.h:555
int i
static double convert_numeric_to_scalar ( Datum  value,
Oid  typid 
)
static

Definition at line 3994 of file selfuncs.c.

References BOOLOID, DatumGetBool, DatumGetFloat4, DatumGetFloat8, DatumGetInt16, DatumGetInt32, DatumGetInt64, DatumGetObjectId, DirectFunctionCall1, elog, ERROR, FLOAT4OID, FLOAT8OID, INT2OID, INT4OID, INT8OID, numeric_float8_no_overflow(), NUMERICOID, OIDOID, REGCLASSOID, REGCONFIGOID, REGDICTIONARYOID, REGNAMESPACEOID, REGOPERATOROID, REGOPEROID, REGPROCEDUREOID, REGPROCOID, REGROLEOID, and REGTYPEOID.

Referenced by convert_to_scalar().

3995 {
3996  switch (typid)
3997  {
3998  case BOOLOID:
3999  return (double) DatumGetBool(value);
4000  case INT2OID:
4001  return (double) DatumGetInt16(value);
4002  case INT4OID:
4003  return (double) DatumGetInt32(value);
4004  case INT8OID:
4005  return (double) DatumGetInt64(value);
4006  case FLOAT4OID:
4007  return (double) DatumGetFloat4(value);
4008  case FLOAT8OID:
4009  return (double) DatumGetFloat8(value);
4010  case NUMERICOID:
4011  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4012  return (double)
4014  value));
4015  case OIDOID:
4016  case REGPROCOID:
4017  case REGPROCEDUREOID:
4018  case REGOPEROID:
4019  case REGOPERATOROID:
4020  case REGCLASSOID:
4021  case REGTYPEOID:
4022  case REGCONFIGOID:
4023  case REGDICTIONARYOID:
4024  case REGROLEOID:
4025  case REGNAMESPACEOID:
4026  /* we can treat OIDs as integers... */
4027  return (double) DatumGetObjectId(value);
4028  }
4029 
4030  /*
4031  * Can't get here unless someone tries to use scalarltsel/scalargtsel on
4032  * an operator with one numeric and one non-numeric operand.
4033  */
4034  elog(ERROR, "unsupported type: %u", typid);
4035  return 0;
4036 }
#define REGCLASSOID
Definition: pg_type.h:577
#define DatumGetInt32(X)
Definition: postgres.h:478
#define REGROLEOID
Definition: pg_type.h:585
#define OIDOID
Definition: pg_type.h:328
#define NUMERICOID
Definition: pg_type.h:554
#define DatumGetObjectId(X)
Definition: postgres.h:506
#define INT4OID
Definition: pg_type.h:316
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
#define REGTYPEOID
Definition: pg_type.h:581
#define REGOPEROID
Definition: pg_type.h:569
#define ERROR
Definition: elog.h:43
static struct @121 value
#define DatumGetInt64(X)
Definition: postgres.h:613
#define INT2OID
Definition: pg_type.h:308
#define DatumGetInt16(X)
Definition: postgres.h:450
#define DatumGetBool(X)
Definition: postgres.h:399
#define REGDICTIONARYOID
Definition: pg_type.h:627
#define FLOAT4OID
Definition: pg_type.h:416
#define DatumGetFloat8(X)
Definition: postgres.h:734
#define INT8OID
Definition: pg_type.h:304
#define DatumGetFloat4(X)
Definition: postgres.h:686
Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS)
Definition: numeric.c:3118
#define FLOAT8OID
Definition: pg_type.h:419
#define BOOLOID
Definition: pg_type.h:288
#define REGCONFIGOID
Definition: pg_type.h:624
#define elog
Definition: elog.h:219
#define REGPROCEDUREOID
Definition: pg_type.h:565
#define REGNAMESPACEOID
Definition: pg_type.h:589
#define REGOPERATOROID
Definition: pg_type.h:573
#define REGPROCOID
Definition: pg_type.h:320
static double convert_one_bytea_to_scalar ( unsigned char *  value,
int  valuelen,
int  rangelo,
int  rangehi 
)
static

Definition at line 4331 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

4333 {
4334  double num,
4335  denom,
4336  base;
4337 
4338  if (valuelen <= 0)
4339  return 0.0; /* empty string has scalar value 0 */
4340 
4341  /*
4342  * Since base is 256, need not consider more than about 10 chars (even
4343  * this many seems like overkill)
4344  */
4345  if (valuelen > 10)
4346  valuelen = 10;
4347 
4348  /* Convert initial characters to fraction */
4349  base = rangehi - rangelo + 1;
4350  num = 0.0;
4351  denom = base;
4352  while (valuelen-- > 0)
4353  {
4354  int ch = *value++;
4355 
4356  if (ch < rangelo)
4357  ch = rangelo - 1;
4358  else if (ch > rangehi)
4359  ch = rangehi + 1;
4360  num += ((double) (ch - rangelo)) / denom;
4361  denom *= base;
4362  }
4363 
4364  return num;
4365 }
static struct @121 value
static double convert_one_string_to_scalar ( char *  value,
int  rangelo,
int  rangehi 
)
static

Definition at line 4139 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4140 {
4141  int slen = strlen(value);
4142  double num,
4143  denom,
4144  base;
4145 
4146  if (slen <= 0)
4147  return 0.0; /* empty string has scalar value 0 */
4148 
4149  /*
4150  * There seems little point in considering more than a dozen bytes from
4151  * the string. Since base is at least 10, that will give us nominal
4152  * resolution of at least 12 decimal digits, which is surely far more
4153  * precision than this estimation technique has got anyway (especially in
4154  * non-C locales). Also, even with the maximum possible base of 256, this
4155  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4156  * overflow on any known machine.
4157  */
4158  if (slen > 12)
4159  slen = 12;
4160 
4161  /* Convert initial characters to fraction */
4162  base = rangehi - rangelo + 1;
4163  num = 0.0;
4164  denom = base;
4165  while (slen-- > 0)
4166  {
4167  int ch = (unsigned char) *value++;
4168 
4169  if (ch < rangelo)
4170  ch = rangelo - 1;
4171  else if (ch > rangehi)
4172  ch = rangehi + 1;
4173  num += ((double) (ch - rangelo)) / denom;
4174  denom *= base;
4175  }
4176 
4177  return num;
4178 }
static struct @121 value
static char * convert_string_datum ( Datum  value,
Oid  typid 
)
static

Definition at line 4187 of file selfuncs.c.

References Assert, BPCHAROID, CHAROID, DatumGetChar, DatumGetPointer, DEFAULT_COLLATION_OID, elog, ERROR, lc_collate_is_c(), NAMEOID, NameStr, NULL, palloc(), pfree(), PG_USED_FOR_ASSERTS_ONLY, pstrdup(), TextDatumGetCString, TEXTOID, val, and VARCHAROID.

Referenced by convert_to_scalar().

4188 {
4189  char *val;
4190 
4191  switch (typid)
4192  {
4193  case CHAROID:
4194  val = (char *) palloc(2);
4195  val[0] = DatumGetChar(value);
4196  val[1] = '\0';
4197  break;
4198  case BPCHAROID:
4199  case VARCHAROID:
4200  case TEXTOID:
4201  val = TextDatumGetCString(value);
4202  break;
4203  case NAMEOID:
4204  {
4206 
4207  val = pstrdup(NameStr(*nm));
4208  break;
4209  }
4210  default:
4211 
4212  /*
4213  * Can't get here unless someone tries to use scalarltsel on an
4214  * operator with one string and one non-string operand.
4215  */
4216  elog(ERROR, "unsupported type: %u", typid);
4217  return NULL;
4218  }
4219 
4221  {
4222  char *xfrmstr;
4223  size_t xfrmlen;
4224  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4225 
4226  /*
4227  * XXX: We could guess at a suitable output buffer size and only call
4228  * strxfrm twice if our guess is too small.
4229  *
4230  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4231  * bogus data or set an error. This is not really a problem unless it
4232  * crashes since it will only give an estimation error and nothing
4233  * fatal.
4234  */
4235 #if _MSC_VER == 1400 /* VS.Net 2005 */
4236 
4237  /*
4238  *
4239  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4240  */
4241  {
4242  char x[1];
4243 
4244  xfrmlen = strxfrm(x, val, 0);
4245  }
4246 #else
4247  xfrmlen = strxfrm(NULL, val, 0);
4248 #endif
4249 #ifdef WIN32
4250 
4251  /*
4252  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4253  * of trying to allocate this much memory (and fail), just return the
4254  * original string unmodified as if we were in the C locale.
4255  */
4256  if (xfrmlen == INT_MAX)
4257  return val;
4258 #endif
4259  xfrmstr = (char *) palloc(xfrmlen + 1);
4260  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4261 
4262  /*
4263  * Some systems (e.g., glibc) can return a smaller value from the
4264  * second call than the first; thus the Assert must be <= not ==.
4265  */
4266  Assert(xfrmlen2 <= xfrmlen);
4267  pfree(val);
4268  val = xfrmstr;
4269  }
4270 
4271  return val;
4272 }
#define BPCHAROID
Definition: pg_type.h:504
#define NAMEOID
Definition: pg_type.h:300
#define TEXTOID
Definition: pg_type.h:324
char * pstrdup(const char *in)
Definition: mcxt.c:1077
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1128
static struct @121 value
Definition: c.h:493
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define VARCHAROID
Definition: pg_type.h:507
#define TextDatumGetCString(d)
Definition: builtins.h:92
#define DatumGetChar(X)
Definition: postgres.h:415
#define CHAROID
Definition: pg_type.h:296
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define DatumGetPointer(X)
Definition: postgres.h:555
void * palloc(Size size)
Definition: mcxt.c:849
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:991
long val
Definition: informix.c:689
static void convert_string_to_scalar ( char *  value,
double *  scaledvalue,
char *  lobound,
double *  scaledlobound,
char *  hibound,
double *  scaledhibound 
)
static

Definition at line 4059 of file selfuncs.c.

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

4065 {
4066  int rangelo,
4067  rangehi;
4068  char *sptr;
4069 
4070  rangelo = rangehi = (unsigned char) hibound[0];
4071  for (sptr = lobound; *sptr; sptr++)
4072  {
4073  if (rangelo > (unsigned char) *sptr)
4074  rangelo = (unsigned char) *sptr;
4075  if (rangehi < (unsigned char) *sptr)
4076  rangehi = (unsigned char) *sptr;
4077  }
4078  for (sptr = hibound; *sptr; sptr++)
4079  {
4080  if (rangelo > (unsigned char) *sptr)
4081  rangelo = (unsigned char) *sptr;
4082  if (rangehi < (unsigned char) *sptr)
4083  rangehi = (unsigned char) *sptr;
4084  }
4085  /* If range includes any upper-case ASCII chars, make it include all */
4086  if (rangelo <= 'Z' && rangehi >= 'A')
4087  {
4088  if (rangelo > 'A')
4089  rangelo = 'A';
4090  if (rangehi < 'Z')
4091  rangehi = 'Z';
4092  }
4093  /* Ditto lower-case */
4094  if (rangelo <= 'z' && rangehi >= 'a')
4095  {
4096  if (rangelo > 'a')
4097  rangelo = 'a';
4098  if (rangehi < 'z')
4099  rangehi = 'z';
4100  }
4101  /* Ditto digits */
4102  if (rangelo <= '9' && rangehi >= '0')
4103  {
4104  if (rangelo > '0')
4105  rangelo = '0';
4106  if (rangehi < '9')
4107  rangehi = '9';
4108  }
4109 
4110  /*
4111  * If range includes less than 10 chars, assume we have not got enough
4112  * data, and make it include regular ASCII set.
4113  */
4114  if (rangehi - rangelo < 9)
4115  {
4116  rangelo = ' ';
4117  rangehi = 127;
4118  }
4119 
4120  /*
4121  * Now strip any common prefix of the three strings.
4122  */
4123  while (*lobound)
4124  {
4125  if (*lobound != *hibound || *lobound != *value)
4126  break;
4127  lobound++, hibound++, value++;
4128  }
4129 
4130  /*
4131  * Now we can do the conversions.
4132  */
4133  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4134  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4135  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4136 }
static struct @121 value
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4139
static double convert_timevalue_to_scalar ( Datum  value,
Oid  typid 
)
static

Definition at line 4371 of file selfuncs.c.

References abstime_timestamp(), ABSTIMEOID, TimeIntervalData::data, date2timestamp_no_overflow(), DATEOID, DatumGetDateADT, DatumGetIntervalP, DatumGetRelativeTime, DatumGetTimeADT, DatumGetTimeInterval, DatumGetTimestamp, DatumGetTimestampTz, DatumGetTimeTzADTP, Interval::day, DAYS_PER_YEAR, DirectFunctionCall1, elog, ERROR, INTERVALOID, Interval::month, MONTHS_PER_YEAR, RELTIMEOID, TimeIntervalData::status, TimeTzADT::time, Interval::time, TIMEOID, TIMESTAMPOID, TIMESTAMPTZOID, TIMETZOID, TINTERVALOID, USECS_PER_DAY, and TimeTzADT::zone.

Referenced by convert_to_scalar().

4372 {
4373  switch (typid)
4374  {
4375  case TIMESTAMPOID:
4376  return DatumGetTimestamp(value);
4377  case TIMESTAMPTZOID:
4378  return DatumGetTimestampTz(value);
4379  case ABSTIMEOID:
4381  value));
4382  case DATEOID:
4384  case INTERVALOID:
4385  {
4387 
4388  /*
4389  * Convert the month part of Interval to days using assumed
4390  * average month length of 365.25/12.0 days. Not too
4391  * accurate, but plenty good enough for our purposes.
4392  */
4393  return interval->time + interval->day * (double) USECS_PER_DAY +
4394  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4395  }
4396  case RELTIMEOID:
4397  return (DatumGetRelativeTime(value) * 1000000.0);
4398  case TINTERVALOID:
4399  {
4401 
4402  if (tinterval->status != 0)
4403  return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4404  return 0; /* for lack of a better idea */
4405  }
4406  case TIMEOID:
4407  return DatumGetTimeADT(value);
4408  case TIMETZOID:
4409  {
4410  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4411 
4412  /* use GMT-equivalent time */
4413  return (double) (timetz->time + (timetz->zone * 1000000.0));
4414  }
4415  }
4416 
4417  /*
4418  * Can't get here unless someone tries to use scalarltsel/scalargtsel on
4419  * an operator with one timevalue and one non-timevalue operand.
4420  */
4421  elog(ERROR, "unsupported type: %u", typid);
4422  return 0;
4423 }
#define TIMESTAMPTZOID
Definition: pg_type.h:525
#define TIMEOID
Definition: pg_type.h:514
#define DATEOID
Definition: pg_type.h:511
#define DatumGetDateADT(X)
Definition: date.h:52
#define DatumGetIntervalP(X)
Definition: timestamp.h:29
TimeADT time
Definition: date.h:28
#define DatumGetTimeTzADTP(X)
Definition: date.h:54
#define TINTERVALOID
Definition: pg_type.h:428
double date2timestamp_no_overflow(DateADT dateVal)
Definition: date.c:658
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
int32 day
Definition: timestamp.h:47
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define DAYS_PER_YEAR
Definition: timestamp.h:68
#define TIMESTAMPOID
Definition: pg_type.h:519
#define ERROR
Definition: elog.h:43
int32 zone
Definition: date.h:29
#define DatumGetRelativeTime(X)
Definition: nabstime.h:51
static struct @121 value
#define DatumGetTimestampTz(X)
Definition: timestamp.h:28
#define INTERVALOID
Definition: pg_type.h:529
TimeOffset time
Definition: timestamp.h:45
#define USECS_PER_DAY
Definition: timestamp.h:91
int32 month
Definition: timestamp.h:48
Datum abstime_timestamp(PG_FUNCTION_ARGS)
Definition: nabstime.c:467
#define DatumGetTimeADT(X)
Definition: date.h:53
AbsoluteTime data[2]
Definition: nabstime.h:42
#define TIMETZOID
Definition: pg_type.h:536
#define DatumGetTimeInterval(X)
Definition: nabstime.h:52
#define elog
Definition: elog.h:219
#define ABSTIMEOID
Definition: pg_type.h:422
Definition: date.h:26
#define DatumGetTimestamp(X)
Definition: timestamp.h:27
#define RELTIMEOID
Definition: pg_type.h:425
static bool convert_to_scalar ( Datum  value,
Oid  valuetypid,
double *  scaledvalue,
Datum  lobound,
Datum  hibound,
Oid  boundstypid,
double *  scaledlobound,
double *  scaledhibound 
)
static

Definition at line 3876 of file selfuncs.c.

References ABSTIMEOID, BOOLOID, BPCHAROID, BYTEAOID, CHAROID, CIDROID, convert_bytea_to_scalar(), convert_network_to_scalar(), convert_numeric_to_scalar(), convert_string_datum(), convert_string_to_scalar(), convert_timevalue_to_scalar(), DATEOID, FLOAT4OID, FLOAT8OID, INETOID, INT2OID, INT4OID, INT8OID, INTERVALOID, MACADDR8OID, MACADDROID, NAMEOID, NUMERICOID, OIDOID, pfree(), REGCLASSOID, REGCONFIGOID, REGDICTIONARYOID, REGNAMESPACEOID, REGOPERATOROID, REGOPEROID, REGPROCEDUREOID, REGPROCOID, REGROLEOID, REGTYPEOID, RELTIMEOID, TEXTOID, TIMEOID, TIMESTAMPOID, TIMESTAMPTZOID, TIMETZOID, TINTERVALOID, and VARCHAROID.

Referenced by ineq_histogram_selectivity().

3879 {
3880  /*
3881  * Both the valuetypid and the boundstypid should exactly match the
3882  * declared input type(s) of the operator we are invoked for, so we just
3883  * error out if either is not recognized.
3884  *
3885  * XXX The histogram we are interpolating between points of could belong
3886  * to a column that's only binary-compatible with the declared type. In
3887  * essence we are assuming that the semantics of binary-compatible types
3888  * are enough alike that we can use a histogram generated with one type's
3889  * operators to estimate selectivity for the other's. This is outright
3890  * wrong in some cases --- in particular signed versus unsigned
3891  * interpretation could trip us up. But it's useful enough in the
3892  * majority of cases that we do it anyway. Should think about more
3893  * rigorous ways to do it.
3894  */
3895  switch (valuetypid)
3896  {
3897  /*
3898  * Built-in numeric types
3899  */
3900  case BOOLOID:
3901  case INT2OID:
3902  case INT4OID:
3903  case INT8OID:
3904  case FLOAT4OID:
3905  case FLOAT8OID:
3906  case NUMERICOID:
3907  case OIDOID:
3908  case REGPROCOID:
3909  case REGPROCEDUREOID:
3910  case REGOPEROID:
3911  case REGOPERATOROID:
3912  case REGCLASSOID:
3913  case REGTYPEOID:
3914  case REGCONFIGOID:
3915  case REGDICTIONARYOID:
3916  case REGROLEOID:
3917  case REGNAMESPACEOID:
3918  *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
3919  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
3920  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
3921  return true;
3922 
3923  /*
3924  * Built-in string types
3925  */
3926  case CHAROID:
3927  case BPCHAROID:
3928  case VARCHAROID:
3929  case TEXTOID:
3930  case NAMEOID:
3931  {
3932  char *valstr = convert_string_datum(value, valuetypid);
3933  char *lostr = convert_string_datum(lobound, boundstypid);
3934  char *histr = convert_string_datum(hibound, boundstypid);
3935 
3936  convert_string_to_scalar(valstr, scaledvalue,
3937  lostr, scaledlobound,
3938  histr, scaledhibound);
3939  pfree(valstr);
3940  pfree(lostr);
3941  pfree(histr);
3942  return true;
3943  }
3944 
3945  /*
3946  * Built-in bytea type
3947  */
3948  case BYTEAOID:
3949  {
3950  convert_bytea_to_scalar(value, scaledvalue,
3951  lobound, scaledlobound,
3952  hibound, scaledhibound);
3953  return true;
3954  }
3955 
3956  /*
3957  * Built-in time types
3958  */
3959  case TIMESTAMPOID:
3960  case TIMESTAMPTZOID:
3961  case ABSTIMEOID:
3962  case DATEOID:
3963  case INTERVALOID:
3964  case RELTIMEOID:
3965  case TINTERVALOID:
3966  case TIMEOID:
3967  case TIMETZOID:
3968  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
3969  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
3970  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
3971  return true;
3972 
3973  /*
3974  * Built-in network types
3975  */
3976  case INETOID:
3977  case CIDROID:
3978  case MACADDROID:
3979  case MACADDR8OID:
3980  *scaledvalue = convert_network_to_scalar(value, valuetypid);
3981  *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
3982  *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
3983  return true;
3984  }
3985  /* Don't know how to convert */
3986  *scaledvalue = *scaledlobound = *scaledhibound = 0;
3987  return false;
3988 }
#define CIDROID
Definition: pg_type.h:451
#define TIMESTAMPTZOID
Definition: pg_type.h:525
#define TIMEOID
Definition: pg_type.h:514
#define REGCLASSOID
Definition: pg_type.h:577
#define BPCHAROID
Definition: pg_type.h:504
#define DATEOID
Definition: pg_type.h:511
#define NAMEOID
Definition: pg_type.h:300
#define REGROLEOID
Definition: pg_type.h:585
#define OIDOID
Definition: pg_type.h:328
#define TEXTOID
Definition: pg_type.h:324
#define INETOID
Definition: pg_type.h:448
#define NUMERICOID
Definition: pg_type.h:554
static double convert_numeric_to_scalar(Datum value, Oid typid)
Definition: selfuncs.c:3994
#define INT4OID
Definition: pg_type.h:316
#define TINTERVALOID
Definition: pg_type.h:428
#define REGTYPEOID
Definition: pg_type.h:581
#define REGOPEROID
Definition: pg_type.h:569
void pfree(void *pointer)
Definition: mcxt.c:950
#define TIMESTAMPOID
Definition: pg_type.h:519
static struct @121 value
double convert_network_to_scalar(Datum value, Oid typid)
Definition: network.c:897
#define INT2OID
Definition: pg_type.h:308
#define INTERVALOID
Definition: pg_type.h:529
#define REGDICTIONARYOID
Definition: pg_type.h:627
#define VARCHAROID
Definition: pg_type.h:507
#define FLOAT4OID
Definition: pg_type.h:416
#define CHAROID
Definition: pg_type.h:296
#define INT8OID
Definition: pg_type.h:304
static char * convert_string_datum(Datum value, Oid typid)
Definition: selfuncs.c:4187
#define TIMETZOID
Definition: pg_type.h:536
#define FLOAT8OID
Definition: pg_type.h:419
#define BOOLOID
Definition: pg_type.h:288
static double convert_timevalue_to_scalar(Datum value, Oid typid)
Definition: selfuncs.c:4371
#define BYTEAOID
Definition: pg_type.h:292
#define REGCONFIGOID
Definition: pg_type.h:624
#define MACADDR8OID
Definition: pg_type.h:454
static void convert_bytea_to_scalar(Datum value, double *scaledvalue, Datum lobound, double *scaledlobound, Datum hibound, double *scaledhibound)
Definition: selfuncs.c:4286
#define MACADDROID
Definition: pg_type.h:445
#define REGPROCEDUREOID
Definition: pg_type.h:565
#define ABSTIMEOID
Definition: pg_type.h:422
#define REGNAMESPACEOID
Definition: pg_type.h:589
static void convert_string_to_scalar(char *value, double *scaledvalue, char *lobound, double *scaledlobound, char *hibound, double *scaledhibound)
Definition: selfuncs.c:4059
#define REGOPERATOROID
Definition: pg_type.h:573
#define REGPROCOID
Definition: pg_type.h:320
#define RELTIMEOID
Definition: pg_type.h:425
List* deconstruct_indexquals ( IndexPath path)

Definition at line 6319 of file selfuncs.c.

References arg, ScalarArrayOpExpr::args, Assert, RestrictInfo::clause, IndexQualInfo::clause_op, elog, ERROR, forboth, get_leftop(), get_rightop(), IndexQualInfo::indexcol, IndexPath::indexinfo, IndexPath::indexqualcols, IndexPath::indexquals, InvalidOid, IsA, lappend(), RowCompareExpr::largs, lfirst_int, lfirst_node, linitial, linitial_oid, lsecond, match_index_to_operand(), NIL, nodeTag, NULL, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, IndexQualInfo::other_operand, palloc(), RowCompareExpr::rargs, result, IndexQualInfo::rinfo, and IndexQualInfo::varonleft.

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

6320 {
6321  List *result = NIL;
6322  IndexOptInfo *index = path->indexinfo;
6323  ListCell *lcc,
6324  *lci;
6325 
6326  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6327  {
6328  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6329  int indexcol = lfirst_int(lci);
6330  Expr *clause;
6331  Node *leftop,
6332  *rightop;
6333  IndexQualInfo *qinfo;
6334 
6335  clause = rinfo->clause;
6336 
6337  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6338  qinfo->rinfo = rinfo;
6339  qinfo->indexcol = indexcol;
6340 
6341  if (IsA(clause, OpExpr))
6342  {
6343  qinfo->clause_op = ((OpExpr *) clause)->opno;
6344  leftop = get_leftop(clause);
6345  rightop = get_rightop(clause);
6346  if (match_index_to_operand(leftop, indexcol, index))
6347  {
6348  qinfo->varonleft = true;
6349  qinfo->other_operand = rightop;
6350  }
6351  else
6352  {
6353  Assert(match_index_to_operand(rightop, indexcol, index));
6354  qinfo->varonleft = false;
6355  qinfo->other_operand = leftop;
6356  }
6357  }
6358  else if (IsA(clause, RowCompareExpr))
6359  {
6360  RowCompareExpr *rc = (RowCompareExpr *) clause;
6361 
6362  qinfo->clause_op = linitial_oid(rc->opnos);
6363  /* Examine only first columns to determine left/right sides */
6365  indexcol, index))
6366  {
6367  qinfo->varonleft = true;
6368  qinfo->other_operand = (Node *) rc->rargs;
6369  }
6370  else
6371  {
6373  indexcol, index));
6374  qinfo->varonleft = false;
6375  qinfo->other_operand = (Node *) rc->largs;
6376  }
6377  }
6378  else if (IsA(clause, ScalarArrayOpExpr))
6379  {
6380  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6381 
6382  qinfo->clause_op = saop->opno;
6383  /* index column is always on the left in this case */
6385  indexcol, index));
6386  qinfo->varonleft = true;
6387  qinfo->other_operand = (Node *) lsecond(saop->args);
6388  }
6389  else if (IsA(clause, NullTest))
6390  {
6391  qinfo->clause_op = InvalidOid;
6392  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6393  indexcol, index));
6394  qinfo->varonleft = true;
6395  qinfo->other_operand = NULL;
6396  }
6397  else
6398  {
6399  elog(ERROR, "unsupported indexqual type: %d",
6400  (int) nodeTag(clause));
6401  }
6402 
6403  result = lappend(result, qinfo);
6404  }
6405  return result;
6406 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
IndexOptInfo * indexinfo
Definition: relation.h:1031
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3180
Definition: nodes.h:509
return result
Definition: formatting.c:1633
RestrictInfo * rinfo
Definition: selfuncs.h:106
#define lsecond(l)
Definition: pg_list.h:116
Definition: type.h:89
List * indexquals
Definition: relation.h:1033
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
Node * get_leftop(const Expr *clause)
Definition: clauses.c:199
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1747
bool varonleft
Definition: selfuncs.h:108
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define linitial_oid(l)
Definition: pg_list.h:113
#define nodeTag(nodeptr)
Definition: nodes.h:514
Node * get_rightop(const Expr *clause)
Definition: clauses.c:216
List * indexqualcols
Definition: relation.h:1034
void * palloc(Size size)
Definition: mcxt.c:849
Node * other_operand
Definition: selfuncs.h:110
void * arg
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Datum eqjoinsel ( PG_FUNCTION_ARGS  )

Definition at line 2199 of file selfuncs.c.

References generate_unaccent_rules::args, CLAMP_PROBABILITY, elog, eqjoinsel_inner(), eqjoinsel_semi(), ERROR, find_join_input_rel(), get_commutator(), get_join_variables(), JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, SpecialJoinInfo::jointype, SpecialJoinInfo::min_righthand, PG_GETARG_INT16, PG_GETARG_OID, PG_GETARG_POINTER, PG_RETURN_FLOAT8, and ReleaseVariableStats.

Referenced by neqjoinsel().

2200 {
2201  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2202  Oid operator = PG_GETARG_OID(1);
2203  List *args = (List *) PG_GETARG_POINTER(2);
2204 
2205 #ifdef NOT_USED
2206  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2207 #endif
2209  double selec;
2210  VariableStatData vardata1;
2211  VariableStatData vardata2;
2212  bool join_is_reversed;
2213  RelOptInfo *inner_rel;
2214 
2215  get_join_variables(root, args, sjinfo,
2216  &vardata1, &vardata2, &join_is_reversed);
2217 
2218  switch (sjinfo->jointype)
2219  {
2220  case JOIN_INNER:
2221  case JOIN_LEFT:
2222  case JOIN_FULL:
2223  selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2224  break;
2225  case JOIN_SEMI:
2226  case JOIN_ANTI:
2227 
2228  /*
2229  * Look up the join's inner relation. min_righthand is sufficient
2230  * information because neither SEMI nor ANTI joins permit any
2231  * reassociation into or out of their RHS, so the righthand will
2232  * always be exactly that set of rels.
2233  */
2234  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2235 
2236  if (!join_is_reversed)
2237  selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
2238  inner_rel);
2239  else
2240  selec = eqjoinsel_semi(get_commutator(operator),
2241  &vardata2, &vardata1,
2242  inner_rel);
2243  break;
2244  default:
2245  /* other values not expected here */
2246  elog(ERROR, "unrecognized join type: %d",
2247  (int) sjinfo->jointype);
2248  selec = 0; /* keep compiler quiet */
2249  break;
2250  }
2251 
2252  ReleaseVariableStats(vardata1);
2253  ReleaseVariableStats(vardata2);
2254 
2255  CLAMP_PROBABILITY(selec);
2256 
2257  PG_RETURN_FLOAT8((float8) selec);
2258 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Relids min_righthand
Definition: relation.h:1920
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:326
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:241
unsigned int Oid
Definition: postgres_ext.h:31
JoinType
Definition: nodes.h:673
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:381
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4510
#define PG_GETARG_OID(n)
Definition: fmgr.h:240
static double eqjoinsel_semi(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2, RelOptInfo *inner_rel)
Definition: selfuncs.c:2484
#define PG_GETARG_INT16(n)
Definition: fmgr.h:236
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:5472
JoinType jointype
Definition: relation.h:1923
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
static double eqjoinsel_inner(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2)
Definition: selfuncs.c:2267
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
static double eqjoinsel_inner ( Oid  operator,
VariableStatData vardata1,
VariableStatData vardata2 
)
static

Definition at line 2267 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool, DEFAULT_COLLATION_OID, fmgr_info(), free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), get_opcode(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, NULL, AttStatsSlot::numbers, AttStatsSlot::nvalues, palloc0(), pfree(), STATISTIC_KIND_MCV, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by eqjoinsel().

2269 {
2270  double selec;
2271  double nd1;
2272  double nd2;
2273  bool isdefault1;
2274  bool isdefault2;
2275  Oid opfuncoid;
2276  Form_pg_statistic stats1 = NULL;
2277  Form_pg_statistic stats2 = NULL;
2278  bool have_mcvs1 = false;
2279  bool have_mcvs2 = false;
2280  AttStatsSlot sslot1;
2281  AttStatsSlot sslot2;
2282 
2283  nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2284  nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2285 
2286  opfuncoid = get_opcode(operator);
2287 
2288  memset(&sslot1, 0, sizeof(sslot1));
2289  memset(&sslot2, 0, sizeof(sslot2));
2290 
2291  if (HeapTupleIsValid(vardata1->statsTuple))
2292  {
2293  /* note we allow use of nullfrac regardless of security check */
2294  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2295  if (statistic_proc_security_check(vardata1, opfuncoid))
2296  have_mcvs1 = get_attstatsslot(&sslot1, vardata1->statsTuple,
2299  }
2300 
2301  if (HeapTupleIsValid(vardata2->statsTuple))
2302  {
2303  /* note we allow use of nullfrac regardless of security check */
2304  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2305  if (statistic_proc_security_check(vardata2, opfuncoid))
2306  have_mcvs2 = get_attstatsslot(&sslot2, vardata2->statsTuple,
2309  }
2310 
2311  if (have_mcvs1 && have_mcvs2)
2312  {
2313  /*
2314  * We have most-common-value lists for both relations. Run through
2315  * the lists to see which MCVs actually join to each other with the
2316  * given operator. This allows us to determine the exact join
2317  * selectivity for the portion of the relations represented by the MCV
2318  * lists. We still have to estimate for the remaining population, but
2319  * in a skewed distribution this gives us a big leg up in accuracy.
2320  * For motivation see the analysis in Y. Ioannidis and S.
2321  * Christodoulakis, "On the propagation of errors in the size of join
2322  * results", Technical Report 1018, Computer Science Dept., University
2323  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2324  */
2325  FmgrInfo eqproc;
2326  bool *hasmatch1;
2327  bool *hasmatch2;
2328  double nullfrac1 = stats1->stanullfrac;
2329  double nullfrac2 = stats2->stanullfrac;
2330  double matchprodfreq,
2331  matchfreq1,
2332  matchfreq2,
2333  unmatchfreq1,
2334  unmatchfreq2,
2335  otherfreq1,
2336  otherfreq2,
2337  totalsel1,
2338  totalsel2;
2339  int i,
2340  nmatches;
2341 
2342  fmgr_info(opfuncoid, &eqproc);
2343  hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
2344  hasmatch2 = (bool *) palloc0(sslot2.nvalues * sizeof(bool));
2345 
2346  /*
2347  * Note we assume that each MCV will match at most one member of the
2348  * other MCV list. If the operator isn't really equality, there could
2349  * be multiple matches --- but we don't look for them, both for speed
2350  * and because the math wouldn't add up...
2351  */
2352  matchprodfreq = 0.0;
2353  nmatches = 0;
2354  for (i = 0; i < sslot1.nvalues; i++)
2355  {
2356  int j;
2357 
2358  for (j = 0; j < sslot2.nvalues; j++)
2359  {
2360  if (hasmatch2[j])
2361  continue;
2362  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2364  sslot1.values[i],
2365  sslot2.values[j])))
2366  {
2367  hasmatch1[i] = hasmatch2[j] = true;
2368  matchprodfreq += sslot1.numbers[i] * sslot2.numbers[j];
2369  nmatches++;
2370  break;
2371  }
2372  }
2373  }
2374  CLAMP_PROBABILITY(matchprodfreq);
2375  /* Sum up frequencies of matched and unmatched MCVs */
2376  matchfreq1 = unmatchfreq1 = 0.0;
2377  for (i = 0; i < sslot1.nvalues; i++)
2378  {
2379  if (hasmatch1[i])
2380  matchfreq1 += sslot1.numbers[i];
2381  else
2382  unmatchfreq1 += sslot1.numbers[i];
2383  }
2384  CLAMP_PROBABILITY(matchfreq1);
2385  CLAMP_PROBABILITY(unmatchfreq1);
2386  matchfreq2 = unmatchfreq2 = 0.0;
2387  for (i = 0; i < sslot2.nvalues; i++)
2388  {
2389  if (hasmatch2[i])
2390  matchfreq2 += sslot2.numbers[i];
2391  else
2392  unmatchfreq2 += sslot2.numbers[i];
2393  }
2394  CLAMP_PROBABILITY(matchfreq2);
2395  CLAMP_PROBABILITY(unmatchfreq2);
2396  pfree(hasmatch1);
2397  pfree(hasmatch2);
2398 
2399  /*
2400  * Compute total frequency of non-null values that are not in the MCV
2401  * lists.
2402  */
2403  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2404  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2405  CLAMP_PROBABILITY(otherfreq1);
2406  CLAMP_PROBABILITY(otherfreq2);
2407 
2408  /*
2409  * We can estimate the total selectivity from the point of view of
2410  * relation 1 as: the known selectivity for matched MCVs, plus
2411  * unmatched MCVs that are assumed to match against random members of
2412  * relation 2's non-MCV population, plus non-MCV values that are
2413  * assumed to match against random members of relation 2's unmatched
2414  * MCVs plus non-MCV values.
2415  */
2416  totalsel1 = matchprodfreq;
2417  if (nd2 > sslot2.nvalues)
2418  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2.nvalues);
2419  if (nd2 > nmatches)
2420  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2421  (nd2 - nmatches);
2422  /* Same estimate from the point of view of relation 2. */
2423  totalsel2 = matchprodfreq;
2424  if (nd1 > sslot1.nvalues)
2425  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1.nvalues);
2426  if (nd1 > nmatches)
2427  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2428  (nd1 - nmatches);
2429 
2430  /*
2431  * Use the smaller of the two estimates. This can be justified in
2432  * essentially the same terms as given below for the no-stats case: to
2433  * a first approximation, we are estimating from the point of view of
2434  * the relation with smaller nd.
2435  */
2436  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2437  }
2438  else
2439  {
2440  /*
2441  * We do not have MCV lists for both sides. Estimate the join
2442  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2443  * is plausible if we assume that the join operator is strict and the
2444  * non-null values are about equally distributed: a given non-null
2445  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2446  * of rel2, so total join rows are at most
2447  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2448  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2449  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2450  * with MIN() is an upper bound. Using the MIN() means we estimate
2451  * from the point of view of the relation with smaller nd (since the
2452  * larger nd is determining the MIN). It is reasonable to assume that
2453  * most tuples in this rel will have join partners, so the bound is
2454  * probably reasonably tight and should be taken as-is.
2455  *
2456  * XXX Can we be smarter if we have an MCV list for just one side? It
2457  * seems that if we assume equal distribution for the other side, we
2458  * end up with the same answer anyway.
2459  */
2460  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2461  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2462 
2463  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2464  if (nd1 > nd2)
2465  selec /= nd1;
2466  else
2467  selec /= nd2;
2468  }
2469 
2470  free_attstatsslot(&sslot1);
2471  free_attstatsslot(&sslot2);
2472 
2473  return selec;
2474 }
Definition: fmgr.h:56
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#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:4950
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1047
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:950
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4979
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
float4 * numbers
Definition: lsyscache.h:52
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define DatumGetBool(X)
Definition: postgres.h:399
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
void * palloc0(Size size)
Definition: mcxt.c:878
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
static double eqjoinsel_semi ( Oid  operator,
VariableStatData vardata1,
VariableStatData vardata2,
RelOptInfo inner_rel 
)
static

Definition at line 2484 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, ATTSTATSSLOT_VALUES, CLAMP_PROBABILITY, DatumGetBool, DEFAULT_COLLATION_OID, fmgr_info(), free_attstatsslot(), FunctionCall2Coll(), get_attstatsslot(), get_opcode(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, i, InvalidOid, Min, NULL, AttStatsSlot::numbers, AttStatsSlot::nvalues, OidIsValid, palloc0(), pfree(), VariableStatData::rel, RelOptInfo::rows, STATISTIC_KIND_MCV, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by eqjoinsel().

2487 {
2488  double selec;
2489  double nd1;
2490  double nd2;
2491  bool isdefault1;
2492  bool isdefault2;
2493  Oid opfuncoid;
2494  Form_pg_statistic stats1 = NULL;
2495  bool have_mcvs1 = false;
2496  bool have_mcvs2 = false;
2497  AttStatsSlot sslot1;
2498  AttStatsSlot sslot2;
2499 
2500  nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2501  nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2502 
2503  opfuncoid = OidIsValid(operator) ? get_opcode(operator) : InvalidOid;
2504 
2505  memset(&sslot1, 0, sizeof(sslot1));
2506  memset(&sslot2, 0, sizeof(sslot2));
2507 
2508  /*
2509  * We clamp nd2 to be not more than what we estimate the inner relation's
2510  * size to be. This is intuitively somewhat reasonable since obviously
2511  * there can't be more than that many distinct values coming from the
2512  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2513  * likewise) is that this is the only pathway by which restriction clauses
2514  * applied to the inner rel will affect the join result size estimate,
2515  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2516  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2517  * the selectivity of outer-rel restrictions.
2518  *
2519  * We can apply this clamping both with respect to the base relation from
2520  * which the join variable comes (if there is just one), and to the
2521  * immediate inner input relation of the current join.
2522  *
2523  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2524  * great, maybe, but it didn't come out of nowhere either. This is most
2525  * helpful when the inner relation is empty and consequently has no stats.
2526  */
2527  if (vardata2->rel)
2528  {
2529  if (nd2 >= vardata2->rel->rows)
2530  {
2531  nd2 = vardata2->rel->rows;
2532  isdefault2 = false;
2533  }
2534  }
2535  if (nd2 >= inner_rel->rows)
2536  {
2537  nd2 = inner_rel->rows;
2538  isdefault2 = false;
2539  }
2540 
2541  if (HeapTupleIsValid(vardata1->statsTuple))
2542  {
2543  /* note we allow use of nullfrac regardless of security check */
2544  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2545  if (statistic_proc_security_check(vardata1, opfuncoid))
2546  have_mcvs1 = get_attstatsslot(&sslot1, vardata1->statsTuple,
2549  }
2550 
2551  if (HeapTupleIsValid(vardata2->statsTuple) &&
2552  statistic_proc_security_check(vardata2, opfuncoid))
2553  {
2554  have_mcvs2 = get_attstatsslot(&sslot2, vardata2->statsTuple,
2557  /* note: currently don't need stanumbers from RHS */
2558  }
2559 
2560  if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2561  {
2562  /*
2563  * We have most-common-value lists for both relations. Run through
2564  * the lists to see which MCVs actually join to each other with the
2565  * given operator. This allows us to determine the exact join
2566  * selectivity for the portion of the relations represented by the MCV
2567  * lists. We still have to estimate for the remaining population, but
2568  * in a skewed distribution this gives us a big leg up in accuracy.
2569  */
2570  FmgrInfo eqproc;
2571  bool *hasmatch1;
2572  bool *hasmatch2;
2573  double nullfrac1 = stats1->stanullfrac;
2574  double matchfreq1,
2575  uncertainfrac,
2576  uncertain;
2577  int i,
2578  nmatches,
2579  clamped_nvalues2;
2580 
2581  /*
2582  * The clamping above could have resulted in nd2 being less than
2583  * sslot2.nvalues; in which case, we assume that precisely the nd2
2584  * most common values in the relation will appear in the join input,
2585  * and so compare to only the first nd2 members of the MCV list. Of
2586  * course this is frequently wrong, but it's the best bet we can make.
2587  */
2588  clamped_nvalues2 = Min(sslot2.nvalues, nd2);
2589 
2590  fmgr_info(opfuncoid, &eqproc);
2591  hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
2592  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2593 
2594  /*
2595  * Note we assume that each MCV will match at most one member of the
2596  * other MCV list. If the operator isn't really equality, there could
2597  * be multiple matches --- but we don't look for them, both for speed
2598  * and because the math wouldn't add up...
2599  */
2600  nmatches = 0;
2601  for (i = 0; i < sslot1.nvalues; i++)
2602  {
2603  int j;
2604 
2605  for (j = 0; j < clamped_nvalues2; j++)
2606  {
2607  if (hasmatch2[j])
2608  continue;
2609  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2611  sslot1.values[i],
2612  sslot2.values[j])))
2613  {
2614  hasmatch1[i] = hasmatch2[j] = true;
2615  nmatches++;
2616  break;
2617  }
2618  }
2619  }
2620  /* Sum up frequencies of matched MCVs */
2621  matchfreq1 = 0.0;
2622  for (i = 0; i < sslot1.nvalues; i++)
2623  {
2624  if (hasmatch1[i])
2625  matchfreq1 += sslot1.numbers[i];
2626  }
2627  CLAMP_PROBABILITY(matchfreq1);
2628  pfree(hasmatch1);
2629  pfree(hasmatch2);
2630 
2631  /*
2632  * Now we need to estimate the fraction of relation 1 that has at
2633  * least one join partner. We know for certain that the matched MCVs
2634  * do, so that gives us a lower bound, but we're really in the dark
2635  * about everything else. Our crude approach is: if nd1 <= nd2 then
2636  * assume all non-null rel1 rows have join partners, else assume for
2637  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2638  * can discount the known-matched MCVs from the distinct-values counts
2639  * before doing the division.
2640  *
2641  * Crude as the above is, it's completely useless if we don't have
2642  * reliable ndistinct values for both sides. Hence, if either nd1 or
2643  * nd2 is default, punt and assume half of the uncertain rows have
2644  * join partners.
2645  */
2646  if (!isdefault1 && !isdefault2)
2647  {
2648  nd1 -= nmatches;
2649  nd2 -= nmatches;
2650  if (nd1 <= nd2 || nd2 < 0)
2651  uncertainfrac = 1.0;
2652  else
2653  uncertainfrac = nd2 / nd1;
2654  }
2655  else
2656  uncertainfrac = 0.5;
2657  uncertain = 1.0 - matchfreq1 - nullfrac1;
2658  CLAMP_PROBABILITY(uncertain);
2659  selec = matchfreq1 + uncertainfrac * uncertain;
2660  }
2661  else
2662  {
2663  /*
2664  * Without MCV lists for both sides, we can only use the heuristic
2665  * about nd1 vs nd2.
2666  */
2667  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2668 
2669  if (!isdefault1 && !isdefault2)
2670  {
2671  if (nd1 <= nd2 || nd2 < 0)
2672  selec = 1.0 - nullfrac1;
2673  else
2674  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2675  }
2676  else
2677  selec = 0.5 * (1.0 - nullfrac1);
2678  }
2679 
2680  free_attstatsslot(&sslot1);
2681  free_attstatsslot(&sslot2);
2682 
2683  return selec;
2684 }
Definition: fmgr.h:56
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#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:4950
RelOptInfo * rel
Definition: selfuncs.h:70
#define Min(x, y)
Definition: c.h:807
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1047
unsigned int Oid
Definition: postgres_ext.h:31
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define OidIsValid(objectId)
Definition: c.h:538
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:950
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4979
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
float4 * numbers
Definition: lsyscache.h:52
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
#define DatumGetBool(X)
Definition: postgres.h:399
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
void * palloc0(Size size)
Definition: mcxt.c:878
double rows
Definition: relation.h:528
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
Datum * values
Definition: lsyscache.h:49
int i
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
Datum eqsel ( PG_FUNCTION_ARGS  )

Definition at line 229 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

230 {
231  PG_RETURN_FLOAT8((float8) eqsel_internal(fcinfo, false));
232 }
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:326
static double eqsel_internal(PG_FUNCTION_ARGS, bool negate)
Definition: selfuncs.c:238
double float8
Definition: c.h:381
static double eqsel_internal ( PG_FUNCTION_ARGS  ,
bool  negate 
)
static

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

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

Definition at line 2094 of file selfuncs.c.

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

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

2095 {
2096  /* look through any binary-compatible relabeling of arrayexpr */
2097  arrayexpr = strip_array_coercion(arrayexpr);
2098 
2099  if (arrayexpr && IsA(arrayexpr, Const))
2100  {
2101  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2102  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2103  ArrayType *arrayval;
2104 
2105  if (arrayisnull)
2106  return 0;
2107  arrayval = DatumGetArrayTypeP(arraydatum);
2108  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2109  }
2110  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2111  !((ArrayExpr *) arrayexpr)->multidims)
2112  {
2113  return list_length(((ArrayExpr *) arrayexpr)->elements);
2114  }
2115  else
2116  {
2117  /* default guess --- see also scalararraysel */
2118  return 10;
2119  }
2120 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:275
uintptr_t Datum
Definition: postgres.h:372
static int list_length(const List *l)
Definition: pg_list.h:89
#define ARR_NDIM(a)
Definition: array.h:271
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1751
#define DatumGetArrayTypeP(X)
Definition: array.h:242
void estimate_hash_bucket_stats ( PlannerInfo root,
Node hashkey,
double  nbuckets,
Selectivity mcv_freq,
Selectivity bucketsize_frac 
)

Definition at line 3605 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, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by final_cost_hashjoin().

3608 {
3609  VariableStatData vardata;
3610  double estfract,
3611  ndistinct,
3612  stanullfrac,
3613  avgfreq;
3614  bool isdefault;
3615  AttStatsSlot sslot;
3616 
3617  examine_variable(root, hashkey, 0, &vardata);
3618 
3619  /* Look up the frequency of the most common value, if available */
3620  *mcv_freq = 0.0;
3621 
3622  if (HeapTupleIsValid(vardata.statsTuple))
3623  {
3624  if (get_attstatsslot(&sslot, vardata.statsTuple,
3627  {
3628  /*
3629  * The first MCV stat is for the most common value.
3630  */
3631  if (sslot.nnumbers > 0)
3632  *mcv_freq = sslot.numbers[0];
3633  free_attstatsslot(&sslot);
3634  }
3635  }
3636 
3637  /* Get number of distinct values */
3638  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3639 
3640  /*
3641  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3642  * mcv_freq is known to be even higher than that, use it instead.
3643  */
3644  if (isdefault)
3645  {
3646  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3647  ReleaseVariableStats(vardata);
3648  return;
3649  }
3650 
3651  /* Get fraction that are null */
3652  if (HeapTupleIsValid(vardata.statsTuple))
3653  {
3654  Form_pg_statistic stats;
3655 
3656  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3657  stanullfrac = stats->stanullfrac;
3658  }
3659  else
3660  stanullfrac = 0.0;
3661 
3662  /* Compute avg freq of all distinct data values in raw relation */
3663  avgfreq = (1.0 - stanullfrac) / ndistinct;
3664 
3665  /*
3666  * Adjust ndistinct to account for restriction clauses. Observe we are
3667  * assuming that the data distribution is affected uniformly by the
3668  * restriction clauses!
3669  *
3670  * XXX Possibly better way, but much more expensive: multiply by
3671  * selectivity of rel's restriction clauses that mention the target Var.
3672  */
3673  if (vardata.rel && vardata.rel->tuples > 0)
3674  {
3675  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3676  ndistinct = clamp_row_est(ndistinct);
3677  }
3678 
3679  /*
3680  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3681  * number of buckets is less than the expected number of distinct values;
3682  * otherwise it is 1/ndistinct.
3683  */
3684  if (ndistinct > nbuckets)
3685  estfract = 1.0 / nbuckets;
3686  else
3687  estfract = 1.0 / ndistinct;
3688 
3689  /*
3690  * Adjust estimated bucketsize upward to account for skewed distribution.
3691  */
3692  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3693  estfract *= *mcv_freq / avgfreq;
3694 
3695  /*
3696  * Clamp bucketsize to sane range (the above adjustment could easily
3697  * produce an out-of-range result). We set the lower bound a little above
3698  * zero, since zero isn't a very sane result.
3699  */
3700  if (estfract < 1.0e-6)
3701  estfract = 1.0e-6;
3702  else if (estfract > 1.0)
3703  estfract = 1.0;
3704 
3705  *bucketsize_frac = (Selectivity) estfract;
3706 
3707  ReleaseVariableStats(vardata);
3708 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:565
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:639
FormData_pg_statistic * Form_pg_statistic
Definition: pg_statistic.h:129
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:4979
float4 * numbers
Definition: lsyscache.h:52
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
double rows
Definition: relation.h:528
#define InvalidOid
Definition: postgres_ext.h:36
#define Max(x, y)
Definition: c.h:801
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4572
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
double clamp_row_est(double nrows)
Definition: costsize.c:173
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
static bool estimate_multivariate_ndistinct ( PlannerInfo root,
RelOptInfo rel,
List **  varinfos,
double *  ndistinct 
)
static

Definition at line 3729 of file selfuncs.c.

References Assert, 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, NULL, GroupVarInfo::rel, statext_ndistinct_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, STATS_EXT_NDISTINCT, and GroupVarInfo::var.

Referenced by estimate_num_groups().

3731 {
3732  ListCell *lc;
3733  Bitmapset *attnums = NULL;
3734  int nmatches;
3735  Oid statOid = InvalidOid;
3736  MVNDistinct *stats;
3737  Bitmapset *matched = NULL;
3738 
3739  /* bail out immediately if the table has no extended statistics */
3740  if (!rel->statlist)
3741  return false;
3742 
3743  /* Determine the attnums we're looking for */
3744  foreach(lc, *varinfos)
3745  {
3746  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3747 
3748  Assert(varinfo->rel == rel);
3749 
3750  if (IsA(varinfo->var, Var))
3751  {
3752  attnums = bms_add_member(attnums,
3753  ((Var *) varinfo->var)->varattno);
3754  }
3755  }
3756 
3757  /* look for the ndistinct statistics matching the most vars */
3758  nmatches = 1; /* we require at least two matches */
3759  foreach(lc, rel->statlist)
3760  {
3761  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3762  Bitmapset *shared;
3763  int nshared;
3764 
3765  /* skip statistics of other kinds */
3766  if (info->kind != STATS_EXT_NDISTINCT)
3767  continue;
3768 
3769  /* compute attnums shared by the vars and the statistics object */
3770  shared = bms_intersect(info->keys, attnums);
3771  nshared = bms_num_members(shared);
3772 
3773  /*
3774  * Does this statistics object match more columns than the currently
3775  * best object? If so, use this one instead.
3776  *
3777  * XXX This should break ties using name of the object, or something
3778  * like that, to make the outcome stable.
3779  */
3780  if (nshared > nmatches)
3781  {
3782  statOid = info->statOid;
3783  nmatches = nshared;
3784  matched = shared;
3785  }
3786  }
3787 
3788  /* No match? */
3789  if (statOid == InvalidOid)
3790  return false;
3791  Assert(nmatches > 1 && matched != NULL);
3792 
3793  stats = statext_ndistinct_load(statOid);
3794 
3795  /*
3796  * If we have a match, search it for the specific item that matches (there
3797  * must be one), and construct the output values.
3798  */
3799  if (stats)
3800  {
3801  int i;
3802  List *newlist = NIL;
3803  MVNDistinctItem *item = NULL;
3804 
3805  /* Find the specific item that exactly matches the combination */
3806  for (i = 0; i < stats->nitems; i++)
3807  {
3808  MVNDistinctItem *tmpitem = &stats->items[i];
3809 
3810  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3811  {
3812  item = tmpitem;
3813  break;
3814  }
3815  }
3816 
3817  /* make sure we found an item */
3818  if (!item)
3819  elog(ERROR, "corrupt MVNDistinct entry");
3820 
3821  /* Form the output varinfo list, keeping only unmatched ones */
3822  foreach(lc, *varinfos)
3823  {
3824  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3825  AttrNumber attnum;
3826 
3827  if (!IsA(varinfo->var, Var))
3828  {
3829  newlist = lappend(newlist, varinfo);
3830  continue;
3831  }
3832 
3833  attnum = ((Var *) varinfo->var)->varattno;
3834  if (!bms_is_member(attnum, matched))
3835  newlist = lappend(newlist, varinfo);
3836  }
3837 
3838  *varinfos = newlist;
3839  *ndistinct = item->ndistinct;
3840  return true;
3841  }
3842 
3843  return false;
3844 }
#define NIL
Definition: pg_list.h:69
#define STATS_EXT_NDISTINCT
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
List * statlist
Definition: relation.h:563
MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER]
Definition: statistics.h:42
double ndistinct
Definition: statistics.h:28
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
#define ERROR
Definition: elog.h:43
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:605
Node * var
Definition: selfuncs.c:3145
uint32 nitems
Definition: statistics.h:41
List * lappend(List *list, void *datum)
Definition: list.c:128
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:252
#define InvalidOid
Definition: postgres_ext.h:36
BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:345
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * attrs
Definition: statistics.h:29
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
Bitmapset * keys
Definition: relation.h:725
int i
#define elog
Definition: elog.h:219
MVNDistinct * statext_ndistinct_load(Oid mvoid)
Definition: mvdistinct.c:127
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
int16 AttrNumber
Definition: attnum.h:21
RelOptInfo * rel
Definition: selfuncs.c:3146
double estimate_num_groups ( PlannerInfo root,
List groupExprs,
double  input_rows,
List **  pgset 
)

Definition at line 3269 of file selfuncs.c.

References add_unique_group_var(), Assert, BOOLOID, clamp_row_est(), contain_volatile_functions(), estimate_multivariate_ndistinct(), examine_variable(), exprType(), for_each_cell, HeapTupleIsValid, i, IS_SIMPLE_REL, VariableStatData::isunique, lcons(), lfirst, linitial, list_head(), list_length(), list_member_int(), lnext, 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().

3271 {
3272  List *varinfos = NIL;
3273  double numdistinct;
3274  ListCell *l;
3275  int i;
3276 
3277  /*
3278  * We don't ever want to return an estimate of zero groups, as that tends
3279  * to lead to division-by-zero and other unpleasantness. The input_rows
3280  * estimate is usually already at least 1, but clamp it just in case it
3281  * isn't.
3282  */
3283  input_rows = clamp_row_est(input_rows);
3284 
3285  /*
3286  * If no grouping columns, there's exactly one group. (This can't happen
3287  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3288  * corner cases with set operations.)
3289  */
3290  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3291  return 1.0;
3292 
3293  /*
3294  * Count groups derived from boolean grouping expressions. For other
3295  * expressions, find the unique Vars used, treating an expression as a Var
3296  * if we can find stats for it. For each one, record the statistical
3297  * estimate of number of distinct values (total in its table, without
3298  * regard for filtering).
3299  */
3300  numdistinct = 1.0;
3301 
3302  i = 0;
3303  foreach(l, groupExprs)
3304  {
3305  Node *groupexpr = (Node *) lfirst(l);
3306  VariableStatData vardata;
3307  List *varshere;
3308  ListCell *l2;
3309 
3310  /* is expression in this grouping set? */
3311  if (pgset && !list_member_int(*pgset, i++))
3312  continue;
3313 
3314  /* Short-circuit for expressions returning boolean */
3315  if (exprType(groupexpr) == BOOLOID)
3316  {
3317  numdistinct *= 2.0;
3318  continue;
3319  }
3320 
3321  /*
3322  * If examine_variable is able to deduce anything about the GROUP BY
3323  * expression, treat it as a single variable even if it's really more
3324  * complicated.
3325  */
3326  examine_variable(root, groupexpr, 0, &vardata);
3327  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3328  {
3329  varinfos = add_unique_group_var(root, varinfos,
3330  groupexpr, &vardata);
3331  ReleaseVariableStats(vardata);
3332  continue;
3333  }
3334  ReleaseVariableStats(vardata);
3335 
3336  /*
3337  * Else pull out the component Vars. Handle PlaceHolderVars by
3338  * recursing into their arguments (effectively assuming that the
3339  * PlaceHolderVar doesn't change the number of groups, which boils
3340  * down to ignoring the possible addition of nulls to the result set).
3341  */
3342  varshere = pull_var_clause(groupexpr,
3346 
3347  /*
3348  * If we find any variable-free GROUP BY item, then either it is a
3349  * constant (and we can ignore it) or it contains a volatile function;
3350  * in the latter case we punt and assume that each input row will
3351  * yield a distinct group.
3352  */
3353  if (varshere == NIL)
3354  {
3355  if (contain_volatile_functions(groupexpr))
3356  return input_rows;
3357  continue;
3358  }
3359 
3360  /*
3361  * Else add variables to varinfos list
3362  */
3363  foreach(l2, varshere)
3364  {
3365  Node *var = (Node *) lfirst(l2);
3366 
3367  examine_variable(root, var, 0, &vardata);
3368  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3369  ReleaseVariableStats(vardata);
3370  }
3371  }
3372 
3373  /*
3374  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3375  * list.
3376  */
3377  if (varinfos == NIL)
3378  {
3379  /* Guard against out-of-range answers */
3380  if (numdistinct > input_rows)
3381  numdistinct = input_rows;
3382  return numdistinct;
3383  }
3384 
3385  /*
3386  * Group Vars by relation and estimate total numdistinct.
3387  *
3388  * For each iteration of the outer loop, we process the frontmost Var in
3389  * varinfos, plus all other Vars in the same relation. We remove these
3390  * Vars from the newvarinfos list for the next iteration. This is the
3391  * easiest way to group Vars of same rel together.
3392  */
3393  do
3394  {
3395  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3396  RelOptInfo *rel = varinfo1->rel;
3397  double reldistinct = 1;
3398  double relmaxndistinct = reldistinct;
3399  int relvarcount = 0;
3400  List *newvarinfos = NIL;
3401  List *relvarinfos = NIL;
3402 
3403  /*
3404  * Split the list of varinfos in two - one for the current rel, one
3405  * for remaining Vars on other rels.
3406  */
3407  relvarinfos = lcons(varinfo1, relvarinfos);
3408  for_each_cell(l, lnext(list_head(varinfos)))
3409  {
3410  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3411 
3412  if (varinfo2->rel == varinfo1->rel)
3413  {
3414  /* varinfos on current rel */
3415  relvarinfos = lcons(varinfo2, relvarinfos);
3416  }
3417  else
3418  {
3419  /* not time to process varinfo2 yet */
3420  newvarinfos = lcons(varinfo2, newvarinfos);
3421  }
3422  }
3423 
3424  /*
3425  * Get the numdistinct estimate for the Vars of this rel. We
3426  * iteratively search for multivariate n-distinct with maximum number
3427  * of vars; assuming that each var group is independent of the others,
3428  * we multiply them together. Any remaining relvarinfos after no more
3429  * multivariate matches are found are assumed independent too, so
3430  * their individual ndistinct estimates are multiplied also.
3431  *
3432  * While iterating, count how many separate numdistinct values we
3433  * apply. We apply a fudge factor below, but only if we multiplied
3434  * more than one such values.
3435  */
3436  while (relvarinfos)
3437  {
3438  double mvndistinct;
3439 
3440  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3441  &mvndistinct))
3442  {
3443  reldistinct *= mvndistinct;
3444  if (relmaxndistinct < mvndistinct)
3445  relmaxndistinct = mvndistinct;
3446  relvarcount++;
3447  }
3448  else
3449  {
3450  foreach(l, relvarinfos)
3451  {
3452  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3453 
3454  reldistinct *= varinfo2->ndistinct;
3455  if (relmaxndistinct < varinfo2->ndistinct)
3456  relmaxndistinct = varinfo2->ndistinct;
3457  relvarcount++;
3458  }
3459 
3460  /* we're done with this relation */
3461  relvarinfos = NIL;
3462  }
3463  }
3464 
3465  /*
3466  * Sanity check --- don't divide by zero if empty relation.
3467  */
3468  Assert(IS_SIMPLE_REL(rel));
3469  if (rel->tuples > 0)
3470  {
3471  /*
3472  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3473  * fudge factor is because the Vars are probably correlated but we
3474  * don't know by how much. We should never clamp to less than the
3475  * largest ndistinct value for any of the Vars, though, since
3476  * there will surely be at least that many groups.
3477  */
3478  double clamp = rel->tuples;
3479 
3480  if (relvarcount > 1)
3481  {
3482  clamp *= 0.1;
3483  if (clamp < relmaxndistinct)
3484  {
3485  clamp = relmaxndistinct;
3486  /* for sanity in case some ndistinct is too large: */
3487  if (clamp > rel->tuples)
3488  clamp = rel->tuples;
3489  }
3490  }
3491  if (reldistinct > clamp)
3492  reldistinct = clamp;
3493 
3494  /*
3495  * Update the estimate based on the restriction selectivity,
3496  * guarding against division by zero when reldistinct is zero.
3497  * Also skip this if we know that we are returning all rows.
3498  */
3499  if (reldistinct > 0 && rel->rows < rel->tuples)
3500  {
3501  /*
3502  * Given a table containing N rows with n distinct values in a
3503  * uniform distribution, if we select p rows at random then
3504  * the expected number of distinct values selected is
3505  *
3506  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3507  *
3508  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3509  *
3510  * See "Approximating block accesses in database
3511  * organizations", S. B. Yao, Communications of the ACM,
3512  * Volume 20 Issue 4, April 1977 Pages 260-261.
3513  *
3514  * Alternatively, re-arranging the terms from the factorials,
3515  * this may be written as
3516  *
3517  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3518  *
3519  * This form of the formula is more efficient to compute in
3520  * the common case where p is larger than N/n. Additionally,
3521  * as pointed out by Dell'Era, if i << N for all terms in the
3522  * product, it can be approximated by
3523  *
3524  * n * (1 - ((N-p)/N)^(N/n))
3525  *
3526  * See "Expected distinct values when selecting from a bag
3527  * without replacement", Alberto Dell'Era,
3528  * http://www.adellera.it/investigations/distinct_balls/.
3529  *
3530  * The condition i << N is equivalent to n >> 1, so this is a
3531  * good approximation when the number of distinct values in
3532  * the table is large. It turns out that this formula also
3533  * works well even when n is small.
3534  */
3535  reldistinct *=
3536  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3537  rel->tuples / reldistinct));
3538  }
3539  reldistinct = clamp_row_est(reldistinct);
3540 
3541  /*
3542  * Update estimate of total distinct groups.
3543  */
3544  numdistinct *= reldistinct;
3545  }
3546 
3547  varinfos = newvarinfos;
3548  } while (varinfos != NIL);
3549 
3550  numdistinct = ceil(numdistinct);
3551 
3552  /* Guard against out-of-range answers */
3553  if (numdistinct > input_rows)
3554  numdistinct = input_rows;
3555  if (numdistinct < 1.0)
3556  numdistinct = 1.0;
3557 
3558  return numdistinct;
3559 }
#define NIL
Definition: pg_list.h:69
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
HeapTuple statsTuple
Definition: selfuncs.h:71
double tuples
Definition: relation.h:565
Definition: nodes.h:509
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
double ndistinct
Definition: selfuncs.c:3147
#define PVC_RECURSE_PLACEHOLDERS
Definition: var.h:26
#define IS_SIMPLE_REL(rel)
Definition: relation.h:505
#define linitial(l)
Definition: pg_list.h:111
bool list_member_int(const List *list, int datum)
Definition: list.c:485
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
static bool estimate_multivariate_ndistinct(PlannerInfo *root, RelOptInfo *rel, List **varinfos, double *ndistinct)
Definition: selfuncs.c:3729
#define lnext(lc)
Definition: pg_list.h:105
static List * add_unique_group_var(PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
Definition: selfuncs.c:3151
double rows
Definition: relation.h:528
List * lcons(void *datum, List *list)
Definition: list.c:259
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4572
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
#define BOOLOID
Definition: pg_type.h:288
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
int i
double clamp_row_est(double nrows)
Definition: costsize.c:173
Definition: pg_list.h:45
RelOptInfo * rel
Definition: selfuncs.c:3146
static void examine_simple_variable ( PlannerInfo root,
Var var,
VariableStatData vardata 
)
static

Definition at line 4783 of file selfuncs.c.

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, Alias::aliasname, Assert, BoolGetDatum, 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(), NULL, ObjectIdGetDatum, PlannerInfo::parse, pg_attribute_aclcheck(), pg_class_aclcheck(), ReleaseSysCache(), RangeTblEntry::relid, TargetEntry::resjunk, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, SearchSysCache3, RangeTblEntry::security_barrier, 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().

4785 {
4786  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4787 
4788  Assert(IsA(rte, RangeTblEntry));
4789 
4791  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4792  {
4793  /*
4794  * The hook took control of acquiring a stats tuple. If it did supply
4795  * a tuple, it'd better have supplied a freefunc.
4796  */
4797  if (HeapTupleIsValid(vardata->statsTuple) &&
4798  !vardata->freefunc)
4799  elog(ERROR, "no function provided to release variable stats with");
4800  }
4801  else if (rte->rtekind == RTE_RELATION)
4802  {
4803  /*
4804  * Plain table or parent of an inheritance appendrel, so look up the
4805  * column in pg_statistic
4806  */
4808  ObjectIdGetDatum(rte->relid),
4809  Int16GetDatum(var->varattno),
4810  BoolGetDatum(rte->inh));
4811  vardata->freefunc = ReleaseSysCache;
4812 
4813  if (HeapTupleIsValid(vardata->statsTuple))
4814  {
4815  /* check if user has permission to read this column */
4816  vardata->acl_ok =
4818  ACL_SELECT) == ACLCHECK_OK) ||
4820  ACL_SELECT) == ACLCHECK_OK);
4821  }
4822  else
4823  {
4824  /* suppress any possible leakproofness checks later */
4825  vardata->acl_ok = true;
4826  }
4827  }
4828  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4829  {
4830  /*
4831  * Plain subquery (not one that was converted to an appendrel).
4832  */
4833  Query *subquery = rte->subquery;
4834  RelOptInfo *rel;
4835  TargetEntry *ste;
4836 
4837  /*
4838  * Punt if it's a whole-row var rather than a plain column reference.
4839  */
4840  if (var->varattno == InvalidAttrNumber)
4841  return;
4842 
4843  /*
4844  * Punt if subquery uses set operations or GROUP BY, as these will
4845  * mash underlying columns' stats beyond recognition. (Set ops are
4846  * particularly nasty; if we forged ahead, we would return stats
4847  * relevant to only the leftmost subselect...) DISTINCT is also
4848  * problematic, but we check that later because there is a possibility
4849  * of learning something even with it.
4850  */
4851  if (subquery->setOperations ||
4852  subquery->groupClause)
4853  return;
4854 
4855  /*
4856  * OK, fetch RelOptInfo for subquery. Note that we don't change the
4857  * rel returned in vardata, since caller expects it to be a rel of the
4858  * caller's query level. Because we might already be recursing, we
4859  * can't use that rel pointer either, but have to look up the Var's
4860  * rel afresh.
4861  */
4862  rel = find_base_rel(root, var->varno);
4863 
4864  /* If the subquery hasn't been planned yet, we have to punt */
4865  if (rel->subroot == NULL)
4866  return;
4867  Assert(IsA(rel->subroot, PlannerInfo));
4868 
4869  /*
4870  * Switch our attention to the subquery as mangled by the planner. It
4871  * was okay to look at the pre-planning version for the tests above,
4872  * but now we need a Var that will refer to the subroot's live
4873  * RelOptInfos. For instance, if any subquery pullup happened during
4874  * planning, Vars in the targetlist might have gotten replaced, and we
4875  * need to see the replacement expressions.
4876  */
4877  subquery = rel->subroot->parse;
4878  Assert(IsA(subquery, Query));
4879 
4880  /* Get the subquery output expression referenced by the upper Var */
4881  ste = get_tle_by_resno(subquery->targetList, var->varattno);
4882  if (ste == NULL || ste->resjunk)
4883  elog(ERROR, "subquery %s does not have attribute %d",
4884  rte->eref->aliasname, var->varattno);
4885  var = (Var *) ste->expr;
4886 
4887  /*
4888  * If subquery uses DISTINCT, we can't make use of any stats for the
4889  * variable ... but, if it's the only DISTINCT column, we are entitled
4890  * to consider it unique. We do the test this way so that it works
4891  * for cases involving DISTINCT ON.
4892  */
4893  if (subquery->distinctClause)
4894  {
4895  if (list_length(subquery->distinctClause) == 1 &&
4896  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4897  vardata->isunique = true;
4898  /* cannot go further */
4899  return;
4900  }
4901 
4902  /*
4903  * If the sub-query originated from a view with the security_barrier
4904  * attribute, we must not look at the variable's statistics, though it
4905  * seems all right to notice the existence of a DISTINCT clause. So
4906  * stop here.
4907  *
4908  * This is probably a harsher restriction than necessary; it's
4909  * certainly OK for the selectivity estimator (which is a C function,
4910  * and therefore omnipotent anyway) to look at the statistics. But
4911  * many selectivity estimators will happily *invoke the operator
4912  * function* to try to work out a good estimate - and that's not OK.
4913  * So for now, don't dig down for stats.
4914  */
4915  if (rte->security_barrier)
4916  return;
4917 
4918  /* Can only handle a simple Var of subquery's query level */
4919  if (var && IsA(var, Var) &&
4920  var->varlevelsup == 0)
4921  {
4922  /*
4923  * OK, recurse into the subquery. Note that the original setting
4924  * of vardata->isunique (which will surely be false) is left
4925  * unchanged in this situation. That's what we want, since even
4926  * if the underlying column is unique, the subquery may have
4927  * joined to other tables in a way that creates duplicates.
4928  */
4929  examine_simple_variable(rel->subroot, var, vardata);
4930  }
4931  }
4932  else
4933  {
4934  /*
4935  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4936  * won't see RTE_JOIN here because join alias Vars have already been
4937  * flattened.) There's not much we can do with function outputs, but
4938  * maybe someday try to be smarter about VALUES and/or CTEs.
4939  */
4940  }
4941 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:155
Index varlevelsup
Definition: primnodes.h:173
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
#define Int16GetDatum(X)
Definition: postgres.h:457
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4783
List * targetList
Definition: parsenodes.h:138
PlannerInfo * subroot
Definition: relation.h:567
bool resjunk
Definition: primnodes.h:1375
List * distinctClause
Definition: parsenodes.h:154
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:154
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
Index varno
Definition: primnodes.h:166
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define ACL_SELECT
Definition: parsenodes.h:73
bool security_barrier
Definition: parsenodes.h:968
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1368
static int list_length(const List *l)
Definition: pg_list.h:89
#define InvalidAttrNumber
Definition: attnum.h:23
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
RTEKind rtekind
Definition: parsenodes.h:944
Node * setOperations
Definition: parsenodes.h:163
Query * subquery
Definition: parsenodes.h:967
List * groupClause
Definition: parsenodes.h:146
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:160
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1043
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:243
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
void examine_variable ( PlannerInfo root,
Node node,
int  varRelid,
VariableStatData vardata 
)

Definition at line 4572 of file selfuncs.c.

References VariableStatData::acl_ok, ACL_SELECT, ACLCHECK_OK, arg, Assert, VariableStatData::atttype, VariableStatData::atttypmod, BMS_EMPTY_SET, bms_free(), bms_is_member(), bms_membership(), BMS_MULTIPLE, BMS_SINGLETON, bms_singleton_member(), BoolGetDatum, 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, NULL, ObjectIdGetDatum, pg_class_aclcheck(), planner_rt_fetch, IndexOptInfo::predOK, pull_varnos(), VariableStatData::rel, IndexOptInfo::rel, ReleaseSysCache(), RelOptInfo::relid, RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3, 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().

4574 {
4575  Node *basenode;
4576  Relids varnos;
4577  RelOptInfo *onerel;
4578 
4579  /* Make sure we don't return dangling pointers in vardata */
4580  MemSet(vardata, 0, sizeof(VariableStatData));
4581 
4582  /* Save the exposed type of the expression */
4583  vardata->vartype = exprType(node);
4584 
4585  /* Look inside any binary-compatible relabeling */
4586 
4587  if (IsA(node, RelabelType))
4588  basenode = (Node *) ((RelabelType *) node)->arg;
4589  else
4590  basenode = node;
4591 
4592  /* Fast path for a simple Var */
4593 
4594  if (IsA(basenode, Var) &&
4595  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4596  {
4597  Var *var = (Var *) basenode;
4598 
4599  /* Set up result fields other than the stats tuple */
4600  vardata->var = basenode; /* return Var without relabeling */
4601  vardata->rel = find_base_rel(root, var->varno);
4602  vardata->atttype = var->vartype;
4603  vardata->atttypmod = var->vartypmod;
4604  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4605 
4606  /* Try to locate some stats */
4607  examine_simple_variable(root, var, vardata);
4608 
4609  return;
4610  }
4611 
4612  /*
4613  * Okay, it's a more complicated expression. Determine variable
4614  * membership. Note that when varRelid isn't zero, only vars of that
4615  * relation are considered "real" vars.
4616  */
4617  varnos = pull_varnos(basenode);
4618 
4619  onerel = NULL;
4620 
4621  switch (bms_membership(varnos))
4622  {
4623  case BMS_EMPTY_SET:
4624  /* No Vars at all ... must be pseudo-constant clause */
4625  break;
4626  case BMS_SINGLETON:
4627  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4628  {
4629  onerel = find_base_rel(root,
4630  (varRelid ? varRelid : bms_singleton_member(varnos)));
4631  vardata->rel = onerel;
4632  node = basenode; /* strip any relabeling */
4633  }
4634  /* else treat it as a constant */
4635  break;
4636  case BMS_MULTIPLE:
4637  if (varRelid == 0)
4638  {
4639  /* treat it as a variable of a join relation */
4640  vardata->rel = find_join_rel(root, varnos);
4641  node = basenode; /* strip any relabeling */
4642  }
4643  else if (bms_is_member(varRelid, varnos))
4644  {
4645  /* ignore the vars belonging to other relations */
4646  vardata->rel = find_base_rel(root, varRelid);
4647  node = basenode; /* strip any relabeling */
4648  /* note: no point in expressional-index search here */
4649  }
4650  /* else treat it as a constant */
4651  break;
4652  }
4653 
4654  bms_free(varnos);
4655 
4656  vardata->var = node;
4657  vardata->atttype = exprType(node);
4658  vardata->atttypmod = exprTypmod(node);
4659 
4660  if (onerel)
4661  {
4662  /*
4663  * We have an expression in vars of a single relation. Try to match
4664  * it to expressional index columns, in hopes of finding some
4665  * statistics.
4666  *
4667  * XXX it's conceivable that there are multiple matches with different
4668  * index opfamilies; if so, we need to pick one that matches the
4669  * operator we are estimating for. FIXME later.
4670  */
4671  ListCell *ilist;
4672 
4673  foreach(ilist, onerel->indexlist)
4674  {
4675  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4676  ListCell *indexpr_item;
4677  int pos;
4678 
4679  indexpr_item = list_head(index->indexprs);
4680  if (indexpr_item == NULL)
4681  continue; /* no expressions here... */
4682 
4683  for (pos = 0; pos < index->ncolumns; pos++)
4684  {
4685  if (index->indexkeys[pos] == 0)
4686  {
4687  Node *indexkey;
4688 
4689  if (indexpr_item == NULL)
4690  elog(ERROR, "too few entries in indexprs list");
4691  indexkey = (Node *) lfirst(indexpr_item);
4692  if (indexkey && IsA(indexkey, RelabelType))
4693  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4694  if (equal(node, indexkey))
4695  {
4696  /*
4697  * Found a match ... is it a unique index? Tests here
4698  * should match has_unique_index().
4699  */
4700  if (index->unique &&
4701  index->ncolumns == 1 &&
4702  (index->indpred == NIL || index->predOK))
4703  vardata->isunique = true;
4704 
4705  /*
4706  * Has it got stats? We only consider stats for
4707  * non-partial indexes, since partial indexes probably
4708  * don't reflect whole-relation statistics; the above
4709  * check for uniqueness is the only info we take from
4710  * a partial index.
4711  *
4712  * An index stats hook, however, must make its own
4713  * decisions about what to do with partial indexes.
4714  */
4715  if (get_index_stats_hook &&
4716  (*get_index_stats_hook) (root, index->indexoid,
4717  pos + 1, vardata))
4718  {
4719  /*
4720  * The hook took control of acquiring a stats
4721  * tuple. If it did supply a tuple, it'd better
4722  * have supplied a freefunc.
4723  */
4724  if (HeapTupleIsValid(vardata->statsTuple) &&
4725  !vardata->freefunc)
4726  elog(ERROR, "no function provided to release variable stats with");
4727  }
4728  else if (index->indpred == NIL)
4729  {
4730  vardata->statsTuple =
4732  ObjectIdGetDatum(index->indexoid),
4733  Int16GetDatum(pos + 1),
4734  BoolGetDatum(false));
4735  vardata->freefunc = ReleaseSysCache;
4736 
4737  if (HeapTupleIsValid(vardata->statsTuple))
4738  {
4739  /* Get index's table for permission check */
4740  RangeTblEntry *rte;
4741 
4742  rte = planner_rt_fetch(index->rel->relid, root);
4743  Assert(rte->rtekind == RTE_RELATION);
4744 
4745  /*
4746  * For simplicity, we insist on the whole
4747  * table being selectable, rather than trying
4748  * to identify which column(s) the index
4749  * depends on.
4750  */
4751  vardata->acl_ok =
4753  ACL_SELECT) == ACLCHECK_OK);
4754  }
4755  else
4756  {
4757  /* suppress leakproofness checks later */
4758  vardata->acl_ok = true;
4759  }
4760  }
4761  if (vardata->statsTuple)
4762  break;
4763  }
4764  indexpr_item = lnext(indexpr_item);
4765  }
4766  }
4767  if (vardata->statsTuple)
4768  break;
4769  }
4770  }
4771 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
bool predOK
Definition: relation.h:664
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:308
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2962
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:457
Definition: nodes.h:509
#define MemSet(start, val, len)
Definition: c.h:858
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4783
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:665
Definition: type.h:89
RelOptInfo * rel
Definition: relation.h:633
#define planner_rt_fetch(rti, root)
Definition: relation.h:325
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1734
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:170
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int ncolumns
Definition: relation.h:641
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: relation.h:553
Index varno
Definition: primnodes.h:166
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:634
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define ACL_SELECT
Definition: parsenodes.h:73
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:526
List * indexlist
Definition: relation.h:562
#define BoolGetDatum(X)
Definition: postgres.h:408
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:155
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
RTEKind rtekind
Definition: parsenodes.h:944
#define SearchSysCache3(cacheId, key1, key2, key3)
Definition: syscache.h:160
void * arg
int * indexkeys
Definition: relation.h:642
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:631
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:243
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
List * indpred
Definition: relation.h:654
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
List * indexprs
Definition: relation.h:653
int32 vartypmod
Definition: primnodes.h:171
static RelOptInfo * find_join_input_rel ( PlannerInfo root,
Relids  relids 
)
static

Definition at line 5472 of file selfuncs.c.

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

Referenced by eqjoinsel().

5473 {
5474  RelOptInfo *rel = NULL;
5475 
5476  switch (bms_membership(relids))
5477  {
5478  case BMS_EMPTY_SET:
5479  /* should not happen */
5480  break;
5481  case BMS_SINGLETON:
5482  rel = find_base_rel(root, bms_singleton_member(relids));
5483  break;
5484  case BMS_MULTIPLE:
5485  rel = find_join_rel(root, relids);
5486  break;
5487  }
5488 
5489  if (rel == NULL)
5490  elog(ERROR, "could not find RelOptInfo for given relids");
5491 
5492  return rel;
5493 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:308
#define ERROR
Definition: elog.h:43
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:634
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:526
#define NULL
Definition: c.h:229
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:243
void genericcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
List qinfos,
GenericCosts costs 
)

Definition at line 6468 of file selfuncs.c.

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

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

6473 {
6474  IndexOptInfo *index = path->indexinfo;
6475  List *indexQuals = path->indexquals;
6476  List *indexOrderBys = path->indexorderbys;
6477  Cost indexStartupCost;
6478  Cost indexTotalCost;
6479  Selectivity indexSelectivity;
6480  double indexCorrelation;
6481  double numIndexPages;
6482  double numIndexTuples;
6483  double spc_random_page_cost;
6484  double num_sa_scans;
6485  double num_outer_scans;
6486  double num_scans;
6487  double qual_op_cost;
6488  double qual_arg_cost;
6489  List *selectivityQuals;
6490  ListCell *l;
6491 
6492  /*
6493  * If the index is partial, AND the index predicate with the explicitly
6494  * given indexquals to produce a more accurate idea of the index
6495  * selectivity.
6496  */
6497  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6498 
6499  /*
6500  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6501  * index scans that will be performed.
6502  */
6503  num_sa_scans = 1;
6504  foreach(l, indexQuals)
6505  {
6506  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6507 
6508  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6509  {
6510  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6511  int alength = estimate_array_length(lsecond(saop->args));
6512 
6513  if (alength > 1)
6514  num_sa_scans *= alength;
6515  }
6516  }
6517 
6518  /* Estimate the fraction of main-table tuples that will be visited */
6519  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6520  index->rel->relid,
6521  JOIN_INNER,
6522  NULL);
6523 
6524  /*
6525  * If caller didn't give us an estimate, estimate the number of index
6526  * tuples that will be visited. We do it in this rather peculiar-looking
6527  * way in order to get the right answer for partial indexes.
6528  */
6529  numIndexTuples = costs->numIndexTuples;
6530  if (numIndexTuples <= 0.0)
6531  {
6532  numIndexTuples = indexSelectivity * index->rel->tuples;
6533 
6534  /*
6535  * The above calculation counts all the tuples visited across all
6536  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6537  * average per-indexscan number, so adjust. This is a handy place to
6538  * round to integer, too. (If caller supplied tuple estimate, it's
6539  * responsible for handling these considerations.)
6540  */
6541  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6542  }
6543 
6544  /*
6545  * We can bound the number of tuples by the index size in any case. Also,
6546  * always estimate at least one tuple is touched, even when
6547  * indexSelectivity estimate is tiny.
6548  */
6549  if (numIndexTuples > index->tuples)
6550  numIndexTuples = index->tuples;
6551  if (numIndexTuples < 1.0)
6552  numIndexTuples = 1.0;
6553 
6554  /*
6555  * Estimate the number of index pages that will be retrieved.
6556  *
6557  * We use the simplistic method of taking a pro-rata fraction of the total
6558  * number of index pages. In effect, this counts only leaf pages and not
6559  * any overhead such as index metapage or upper tree levels.
6560  *
6561  * In practice access to upper index levels is often nearly free because
6562  * those tend to stay in cache under load; moreover, the cost involved is
6563  * highly dependent on index type. We therefore ignore such costs here
6564  * and leave it to the caller to add a suitable charge if needed.
6565  */
6566  if (index->pages > 1 && index->tuples > 1)
6567  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6568  else
6569  numIndexPages = 1.0;
6570 
6571  /* fetch estimated page cost for tablespace containing index */
6573  &spc_random_page_cost,
6574  NULL);
6575 
6576  /*
6577  * Now compute the disk access costs.
6578  *
6579  * The above calculations are all per-index-scan. However, if we are in a
6580  * nestloop inner scan, we can expect the scan to be repeated (with
6581  * different search keys) for each row of the outer relation. Likewise,
6582  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6583  * the potential for cache effects to reduce the number of disk page
6584  * fetches needed. We want to estimate the average per-scan I/O cost in
6585  * the presence of caching.
6586  *
6587  * We use the Mackert-Lohman formula (see costsize.c for details) to
6588  * estimate the total number of page fetches that occur. While this
6589  * wasn't what it was designed for, it seems a reasonable model anyway.
6590  * Note that we are counting pages not tuples anymore, so we take N = T =
6591  * index size, as if there were one "tuple" per page.
6592  */
6593  num_outer_scans = loop_count;
6594  num_scans = num_sa_scans * num_outer_scans;
6595 
6596  if (num_scans > 1)
6597  {
6598  double pages_fetched;
6599 
6600  /* total page fetches ignoring cache effects */
6601  pages_fetched = numIndexPages * num_scans;
6602 
6603  /* use Mackert and Lohman formula to adjust for cache effects */
6604  pages_fetched = index_pages_fetched(pages_fetched,
6605  index->pages,
6606  (double) index->pages,
6607  root);
6608 
6609  /*
6610  * Now compute the total disk access cost, and then report a pro-rated
6611  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6612  * since that's internal to the indexscan.)
6613  */
6614  indexTotalCost = (pages_fetched * spc_random_page_cost)
6615  / num_outer_scans;
6616  }
6617  else
6618  {
6619  /*
6620  * For a single index scan, we just charge spc_random_page_cost per
6621  * page touched.
6622  */
6623  indexTotalCost = numIndexPages * spc_random_page_cost;
6624  }
6625 
6626  /*
6627  * CPU cost: any complex expressions in the indexquals will need to be
6628  * evaluated once at the start of the scan to reduce them to runtime keys
6629  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6630  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6631  * indexqual operator. Because we have numIndexTuples as a per-scan
6632  * number, we have to multiply by num_sa_scans to get the correct result
6633  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6634  * ORDER BY expressions.
6635  *
6636  * Note: this neglects the possible costs of rechecking lossy operators.
6637  * Detecting that that might be needed seems more expensive than it's
6638  * worth, though, considering all the other inaccuracies here ...
6639  */
6640  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6641  orderby_operands_eval_cost(root, path);
6642  qual_op_cost = cpu_operator_cost *
6643  (list_length(indexQuals) + list_length(indexOrderBys));
6644 
6645  indexStartupCost = qual_arg_cost;
6646  indexTotalCost += qual_arg_cost;
6647  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6648 
6649  /*
6650  * Generic assumption about index correlation: there isn't any.
6651  */
6652  indexCorrelation = 0.0;
6653 
6654  /*
6655  * Return everything to caller.
6656  */
6657  costs->indexStartupCost = indexStartupCost;
6658  costs->indexTotalCost = indexTotalCost;
6659  costs->indexSelectivity = indexSelectivity;
6660  costs->indexCorrelation = indexCorrelation;
6661  costs->numIndexPages = numIndexPages;
6662  costs->numIndexTuples = numIndexTuples;
6663  costs->spc_random_page_cost = spc_random_page_cost;
6664  costs->num_sa_scans = num_sa_scans;
6665 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
IndexOptInfo * indexinfo
Definition: relation.h:1031
double tuples
Definition: relation.h:565
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6687
Oid reltablespace
Definition: relation.h:632
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6414
double Selectivity
Definition: nodes.h:639
double tuples
Definition: relation.h:637
#define lsecond(l)
Definition: pg_list.h:116
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6439
Definition: type.h:89
BlockNumber pages
Definition: relation.h:636
List * indexquals
Definition: relation.h:1033
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2094
RelOptInfo * rel
Definition: relation.h:633
double num_sa_scans
Definition: selfuncs.h:138
double cpu_operator_cost
Definition: costsize.c:108
Cost indexTotalCost
Definition: selfuncs.h:130
double rint(double x)
Definition: rint.c:22
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:553
Expr * clause
Definition: relation.h:1747
double indexCorrelation
Definition: selfuncs.h:132
List * indexorderbys
Definition: relation.h:1035
double spc_random_page_cost
Definition: selfuncs.h:137
double numIndexTuples
Definition: selfuncs.h:136
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Cost indexStartupCost
Definition: selfuncs.h:129
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
Definition: pg_list.h:45
double cpu_index_tuple_cost
Definition: costsize.c:107
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:813
double Cost
Definition: nodes.h:640
double numIndexPages
Definition: selfuncs.h:135
static bool get_actual_variable_range ( PlannerInfo root,
VariableStatData vardata,
Oid  sortop,
Datum min,
Datum max 
)
static

Definition at line 5246 of file selfuncs.c.

References AccessShareLock, Assert, VariableStatData::atttype, BackwardScanDirection, BTGreaterStrategyNumber, BTLessStrategyNumber, BTREE_AM_OID, BuildIndexInfo(), CreateExecutorState(), datumCopy(), ExprContext::ecxt_per_tuple_memory, ExprContext::ecxt_scantuple, elog, ERROR, ExecDropSingleTupleTableSlot(), ExecStoreTuple(), FormIndexDatum(), ForwardScanDirection, FreeExecutorState(), get_op_opfamily_strategy(), get_typlenbyval(), GetPerTupleExprContext, heap_close, heap_open(), IndexOptInfo::hypothetical, index_beginscan(), index_close(), index_endscan(), index_getnext(), INDEX_MAX_KEYS, index_open(), index_rescan(), RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indpred, InitDirtySnapshot, InvalidBuffer, InvalidOid, InvalidStrategy, lfirst, MakeSingleTupleTableSlot(), match_index_to_operand(), MemoryContextSwitchTo(), NIL, NoLock, NULL, VariableStatData::rel, IndexOptInfo::relam, RelationGetDescr, RelationGetRelationName, RelOptInfo::relid, RangeTblEntry::relid, IndexOptInfo::reverse_sort, RTE_RELATION, RangeTblEntry::rtekind, ScanKeyEntryInitialize(), PlannerInfo::simple_rte_array, SK_ISNULL, SK_SEARCHNOTNULL, IndexOptInfo::sortopfamily, values, and VariableStatData::var.

Referenced by get_variable_range(), and ineq_histogram_selectivity().

5249 {
5250  bool have_data = false;
5251  RelOptInfo *rel = vardata->rel;
5252  RangeTblEntry *rte;
5253  ListCell *lc;
5254 
5255  /* No hope if no relation or it doesn't have indexes */
5256  if (rel == NULL || rel->indexlist == NIL)
5257  return false;
5258  /* If it has indexes it must be a plain relation */
5259  rte = root->simple_rte_array[rel->relid];
5260  Assert(rte->rtekind == RTE_RELATION);
5261 
5262  /* Search through the indexes to see if any match our problem */
5263  foreach(lc, rel->indexlist)
5264  {
5266  ScanDirection indexscandir;
5267 
5268  /* Ignore non-btree indexes */
5269  if (index->relam != BTREE_AM_OID)
5270  continue;
5271 
5272  /*
5273  * Ignore partial indexes --- we only want stats that cover the entire
5274  * relation.
5275  */
5276  if (index->indpred != NIL)
5277  continue;
5278 
5279  /*
5280  * The index list might include hypothetical indexes inserted by a
5281  * get_relation_info hook --- don't try to access them.
5282  */
5283  if (index->hypothetical)
5284  continue;
5285 
5286  /*
5287  * The first index column must match the desired variable and sort
5288  * operator --- but we can use a descending-order index.
5289  */
5290  if (!match_index_to_operand(vardata->var, 0, index))
5291  continue;
5292  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5293  {
5294  case BTLessStrategyNumber:
5295  if (index->reverse_sort[0])
5296  indexscandir = BackwardScanDirection;
5297  else
5298  indexscandir = ForwardScanDirection;
5299  break;
5301  if (index->reverse_sort[0])
5302  indexscandir = ForwardScanDirection;
5303  else
5304  indexscandir = BackwardScanDirection;
5305  break;
5306  default:
5307  /* index doesn't match the sortop */
5308  continue;
5309  }
5310 
5311  /*
5312  * Found a suitable index to extract data from. We'll need an EState
5313  * and a bunch of other infrastructure.
5314  */
5315  {
5316  EState *estate;
5317  ExprContext *econtext;
5318  MemoryContext tmpcontext;
5319  MemoryContext oldcontext;
5320  Relation heapRel;
5321  Relation indexRel;
5322  IndexInfo *indexInfo;
5323  TupleTableSlot *slot;
5324  int16 typLen;
5325  bool typByVal;
5326  ScanKeyData scankeys[1];
5327  IndexScanDesc index_scan;
5328  HeapTuple tup;
5330  bool isnull[INDEX_MAX_KEYS];
5331  SnapshotData SnapshotDirty;
5332 
5333  estate = CreateExecutorState();
5334  econtext = GetPerTupleExprContext(estate);
5335  /* Make sure any cruft is generated in the econtext's memory */
5336  tmpcontext = econtext->ecxt_per_tuple_memory;
5337  oldcontext = MemoryContextSwitchTo(tmpcontext);
5338 
5339  /*
5340  * Open the table and index so we can read from them. We should
5341  * already have at least AccessShareLock on the table, but not
5342  * necessarily on the index.
5343  */
5344  heapRel = heap_open(rte->relid, NoLock);
5345  indexRel = index_open(index->indexoid, AccessShareLock);
5346 
5347  /* extract index key information from the index's pg_index info */
5348  indexInfo = BuildIndexInfo(indexRel);
5349 
5350  /* some other stuff */
5351  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
5352  econtext->ecxt_scantuple = slot;
5353  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5354  InitDirtySnapshot(SnapshotDirty);
5355 
5356  /* set up an IS NOT NULL scan key so that we ignore nulls */
5357  ScanKeyEntryInitialize(&scankeys[0],
5359  1, /* index col to scan */
5360  InvalidStrategy, /* no strategy */
5361  InvalidOid, /* no strategy subtype */
5362  InvalidOid, /* no collation */
5363  InvalidOid, /* no reg proc for this */
5364  (Datum) 0); /* constant */
5365 
5366  have_data = true;
5367 
5368  /* If min is requested ... */
5369  if (min)
5370  {
5371  /*
5372  * In principle, we should scan the index with our current
5373  * active snapshot, which is the best approximation we've got
5374  * to what the query will see when executed. But that won't
5375  * be exact if a new snap is taken before running the query,
5376  * and it can be very expensive if a lot of uncommitted rows
5377  * exist at the end of the index (because we'll laboriously
5378  * fetch each one and reject it). What seems like a good
5379  * compromise is to use SnapshotDirty. That will accept
5380  * uncommitted rows, and thus avoid fetching multiple heap
5381  * tuples in this scenario. On the other hand, it will reject
5382  * known-dead rows, and thus not give a bogus answer when the
5383  * extreme value has been deleted; that case motivates not
5384  * using SnapshotAny here.
5385  */
5386  index_scan = index_beginscan(heapRel, indexRel, &SnapshotDirty,
5387  1, 0);
5388  index_rescan(index_scan, scankeys, 1, NULL, 0);
5389 
5390  /* Fetch first tuple in sortop's direction */
5391  if ((tup = index_getnext(index_scan,
5392  indexscandir)) != NULL)
5393  {
5394  /* Extract the index column values from the heap tuple */
5395  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5396  FormIndexDatum(indexInfo, slot, estate,
5397  values, isnull);
5398 
5399  /* Shouldn't have got a null, but be careful */
5400  if (isnull[0])
5401  elog(ERROR, "found unexpected null value in index \"%s\"",
5402  RelationGetRelationName(indexRel));
5403 
5404  /* Copy the index column value out to caller's context */
5405  MemoryContextSwitchTo(oldcontext);
5406  *min = datumCopy(values[0], typByVal, typLen);
5407  MemoryContextSwitchTo(tmpcontext);
5408  }
5409  else
5410  have_data = false;
5411 
5412  index_endscan(index_scan);
5413  }
5414 
5415  /* If max is requested, and we didn't find the index is empty */
5416  if (max && have_data)
5417  {
5418  index_scan = index_beginscan(heapRel, indexRel, &SnapshotDirty,
5419  1, 0);
5420  index_rescan(index_scan, scankeys, 1, NULL, 0);
5421 
5422  /* Fetch first tuple in reverse direction */
5423  if ((tup = index_getnext(index_scan,
5424  -indexscandir)) != NULL)
5425  {
5426  /* Extract the index column values from the heap tuple */
5427  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5428  FormIndexDatum(indexInfo, slot, estate,
5429  values, isnull);
5430 
5431  /* Shouldn't have got a null, but be careful */
5432  if (isnull[0])
5433  elog(ERROR, "found unexpected null value in index \"%s\"",
5434  RelationGetRelationName(indexRel));
5435 
5436  /* Copy the index column value out to caller's context */
5437  MemoryContextSwitchTo(oldcontext);
5438  *max = datumCopy(values[0], typByVal, typLen);
5439  MemoryContextSwitchTo(tmpcontext);
5440  }
5441  else
5442  have_data = false;
5443 
5444  index_endscan(index_scan);
5445  }
5446 
5447  /* Clean everything up */
5449 
5450  index_close(indexRel, AccessShareLock);
5451  heap_close(heapRel, NoLock);
5452 
5453  MemoryContextSwitchTo(oldcontext);
5454  FreeExecutorState(estate);
5455 
5456  /* And we're done */
5457  break;
5458  }
5459  }
5460 
5461  return have_data;
5462 }
signed short int16
Definition: c.h:255
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1771
#define InvalidStrategy
Definition: stratnum.h:24
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define RelationGetDescr(relation)
Definition: rel.h:428
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3180
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:203
RelOptInfo * rel
Definition: selfuncs.h:70
#define BTREE_AM_OID
Definition: pg_am.h:70
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define InvalidBuffer
Definition: buf.h:25
void index_rescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
Definition: indexam.c:310
Oid * sortopfamily
Definition: relation.h:646
bool hypothetical
Definition: relation.h:667
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1642
Definition: type.h:89
void FreeExecutorState(EState *estate)
Definition: execUtils.c:183
#define GetPerTupleExprContext(estate)
Definition: executor.h:475
#define ERROR
Definition: elog.h:43
#define InitDirtySnapshot(snapshotdata)
Definition: tqual.h:100
#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:216
ScanDirection
Definition: sdir.h:22
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define SK_SEARCHNOTNULL
Definition: skey.h:122
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:199
void index_endscan(IndexScanDesc scan)
Definition: indexam.c:340
#define SK_ISNULL
Definition: skey.h:115
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:80
Index relid
Definition: relation.h:553
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
List * indexlist
Definition: relation.h:562
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
#define INDEX_MAX_KEYS
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2001
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
RTEKind rtekind
Definition: parsenodes.h:944
static Datum values[MAXATTR]
Definition: bootstrap.c:163
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:631
bool * reverse_sort
Definition: relation.h:647
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:654
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
HeapTuple index_getnext(IndexScanDesc scan, ScanDirection direction)
Definition: indexam.c:659
IndexScanDesc index_beginscan(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, int norderbys)
Definition: indexam.c:221
void get_join_variables ( PlannerInfo root,
List args,
SpecialJoinInfo sjinfo,
VariableStatData vardata1,
VariableStatData vardata2,
bool join_is_reversed 
)

Definition at line 4510 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(), and networkjoinsel().

4513 {
4514  Node *left,
4515  *right;
4516 
4517  if (list_length(args) != 2)
4518  elog(ERROR, "join operator should take two arguments");
4519 
4520  left = (Node *) linitial(args);
4521  right = (Node *) lsecond(args);
4522 
4523  examine_variable(root, left, 0, vardata1);
4524  examine_variable(root, right, 0, vardata2);
4525 
4526  if (vardata1->rel &&
4527  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4528  *join_is_reversed = true; /* var1 is on RHS */
4529  else if (vardata2->rel &&
4530  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4531  *join_is_reversed = true; /* var2 is on LHS */
4532  else
4533  *join_is_reversed = false;