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)
 
Selectivity estimate_hash_bucketsize (PlannerInfo *root, Node *hashkey, double nbuckets)
 
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 5848 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity_sub().

#define CHAR_RANGE_SEL   0.25

Definition at line 5847 of file selfuncs.c.

Referenced by regex_selectivity_sub().

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

Definition at line 5846 of file selfuncs.c.

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

#define FULL_WILDCARD_SEL   5.0

Definition at line 5849 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity().

#define PARTIAL_WILDCARD_SEL   2.0

Definition at line 5850 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 6660 of file selfuncs.c.

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

Referenced by btcostestimate(), and genericcostestimate().

6661 {
6662  List *predExtraQuals = NIL;
6663  ListCell *lc;
6664 
6665  if (index->indpred == NIL)
6666  return indexQuals;
6667 
6668  foreach(lc, index->indpred)
6669  {
6670  Node *predQual = (Node *) lfirst(lc);
6671  List *oneQual = list_make1(predQual);
6672 
6673  if (!predicate_implied_by(oneQual, indexQuals, false))
6674  predExtraQuals = list_concat(predExtraQuals, oneQual);
6675  }
6676  /* list_concat avoids modifying the passed-in indexQuals list */
6677  return list_concat(predExtraQuals, indexQuals);
6678 }
#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:1944
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:4963
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:4556
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:4556
#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 7762 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().

7766 {
7767  IndexOptInfo *index = path->indexinfo;
7768  List *indexQuals = path->indexquals;
7769  double numPages = index->pages;
7770  RelOptInfo *baserel = index->rel;
7771  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7772  List *qinfos;
7773  Cost spc_seq_page_cost;
7774  Cost spc_random_page_cost;
7775  double qual_arg_cost;
7776  double qualSelectivity;
7777  BrinStatsData statsData;
7778  double indexRanges;
7779  double minimalRanges;
7780  double estimatedRanges;
7781  double selec;
7782  Relation indexRel;
7783  ListCell *l;
7784  VariableStatData vardata;
7785 
7786  Assert(rte->rtekind == RTE_RELATION);
7787 
7788  /* fetch estimated page cost for the tablespace containing the index */
7790  &spc_random_page_cost,
7791  &spc_seq_page_cost);
7792 
7793  /*
7794  * Obtain some data from the index itself.
7795  */
7796  indexRel = index_open(index->indexoid, AccessShareLock);
7797  brinGetStats(indexRel, &statsData);
7798  index_close(indexRel, AccessShareLock);
7799 
7800  /*
7801  * Compute index correlation
7802  *
7803  * Because we can use all index quals equally when scanning, we can use
7804  * the largest correlation (in absolute value) among columns used by the
7805  * query. Start at zero, the worst possible case. If we cannot find any
7806  * correlation statistics, we will keep it as 0.
7807  */
7808  *indexCorrelation = 0;
7809 
7810  qinfos = deconstruct_indexquals(path);
7811  foreach(l, qinfos)
7812  {
7813  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(l);
7814  AttrNumber attnum = index->indexkeys[qinfo->indexcol];
7815 
7816  /* attempt to lookup stats in relation for this index column */
7817  if (attnum != 0)
7818  {
7819  /* Simple variable -- look to stats for the underlying table */
7821  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7822  {
7823  /*
7824  * The hook took control of acquiring a stats tuple. If it
7825  * did supply a tuple, it'd better have supplied a freefunc.
7826  */
7827  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7828  elog(ERROR,
7829  "no function provided to release variable stats with");
7830  }
7831  else
7832  {
7833  vardata.statsTuple =
7835  ObjectIdGetDatum(rte->relid),
7836  Int16GetDatum(attnum),
7837  BoolGetDatum(false));
7838  vardata.freefunc = ReleaseSysCache;
7839  }
7840  }
7841  else
7842  {
7843  /*
7844  * Looks like we've found an expression column in the index. Let's
7845  * see if there's any stats for it.
7846  */
7847 
7848  /* get the attnum from the 0-based index. */
7849  attnum = qinfo->indexcol + 1;
7850 
7851  if (get_index_stats_hook &&
7852  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7853  {
7854  /*
7855  * The hook took control of acquiring a stats tuple. If it
7856  * did supply a tuple, it'd better have supplied a freefunc.
7857  */
7858  if (HeapTupleIsValid(vardata.statsTuple) &&
7859  !vardata.freefunc)
7860  elog(ERROR, "no function provided to release variable stats with");
7861  }
7862  else
7863  {
7865  ObjectIdGetDatum(index->indexoid),
7866  Int16GetDatum(attnum),
7867  BoolGetDatum(false));
7868  vardata.freefunc = ReleaseSysCache;
7869  }
7870  }
7871 
7872  if (HeapTupleIsValid(vardata.statsTuple))
7873  {
7874  AttStatsSlot sslot;
7875 
7876  if (get_attstatsslot(&sslot, vardata.statsTuple,
7879  {
7880  double varCorrelation = 0.0;
7881 
7882  if (sslot.nnumbers > 0)
7883  varCorrelation = Abs(sslot.numbers[0]);
7884 
7885  if (varCorrelation > *indexCorrelation)
7886  *indexCorrelation = varCorrelation;
7887 
7888  free_attstatsslot(&sslot);
7889  }
7890  }
7891 
7892  ReleaseVariableStats(vardata);
7893  }
7894 
7895  qualSelectivity = clauselist_selectivity(root, indexQuals,
7896  baserel->relid,
7897  JOIN_INNER, NULL);
7898 
7899  /* work out the actual number of ranges in the index */
7900  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
7901  1.0);
7902 
7903  /*
7904  * Now calculate the minimum possible ranges we could match with if all of
7905  * the rows were in the perfect order in the table's heap.
7906  */
7907  minimalRanges = ceil(indexRanges * qualSelectivity);
7908 
7909  /*
7910  * Now estimate the number of ranges that we'll touch by using the
7911  * indexCorrelation from the stats. Careful not to divide by zero (note
7912  * we're using the absolute value of the correlation).
7913  */
7914  if (*indexCorrelation < 1.0e-10)
7915  estimatedRanges = indexRanges;
7916  else
7917  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
7918 
7919  /* we expect to visit this portion of the table */
7920  selec = estimatedRanges / indexRanges;
7921 
7922  CLAMP_PROBABILITY(selec);
7923 
7924  *indexSelectivity = selec;
7925 
7926  /*
7927  * Compute the index qual costs, much as in genericcostestimate, to add to
7928  * the index costs.
7929  */
7930  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
7931  orderby_operands_eval_cost(root, path);
7932 
7933  /*
7934  * Compute the startup cost as the cost to read the whole revmap
7935  * sequentially, including the cost to execute the index quals.
7936  */
7937  *indexStartupCost =
7938  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
7939  *indexStartupCost += qual_arg_cost;
7940 
7941  /*
7942  * To read a BRIN index there might be a bit of back and forth over
7943  * regular pages, as revmap might point to them out of sequential order;
7944  * calculate the total cost as reading the whole index in random order.
7945  */
7946  *indexTotalCost = *indexStartupCost +
7947  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
7948 
7949  /*
7950  * Charge a small amount per range tuple which we expect to match to. This
7951  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
7952  * will set a bit for each page in the range when we find a matching
7953  * range, so we must multiply the charge by the number of pages in the
7954  * range.
7955  */
7956  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
7957  statsData.pagesPerRange;
7958 
7959  *indexPages = index->pages;
7960 }
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:806
#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:6387
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6292
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6412
#define Abs(x)
Definition: c.h:812
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:800
#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:675
#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:936
#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:1064
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 6682 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().

6686 {
6687  IndexOptInfo *index = path->indexinfo;
6688  List *qinfos;
6689  GenericCosts costs;
6690  Oid relid;
6691  AttrNumber colnum;
6692  VariableStatData vardata;
6693  double numIndexTuples;
6694  Cost descentCost;
6695  List *indexBoundQuals;
6696  int indexcol;
6697  bool eqQualHere;
6698  bool found_saop;
6699  bool found_is_null_op;
6700  double num_sa_scans;
6701  ListCell *lc;
6702 
6703  /* Do preliminary analysis of indexquals */
6704  qinfos = deconstruct_indexquals(path);
6705 
6706  /*
6707  * For a btree scan, only leading '=' quals plus inequality quals for the
6708  * immediately next attribute contribute to index selectivity (these are
6709  * the "boundary quals" that determine the starting and stopping points of
6710  * the index scan). Additional quals can suppress visits to the heap, so
6711  * it's OK to count them in indexSelectivity, but they should not count
6712  * for estimating numIndexTuples. So we must examine the given indexquals
6713  * to find out which ones count as boundary quals. We rely on the
6714  * knowledge that they are given in index column order.
6715  *
6716  * For a RowCompareExpr, we consider only the first column, just as
6717  * rowcomparesel() does.
6718  *
6719  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6720  * index scans not one, but the ScalarArrayOpExpr's operator can be
6721  * considered to act the same as it normally does.
6722  */
6723  indexBoundQuals = NIL;
6724  indexcol = 0;
6725  eqQualHere = false;
6726  found_saop = false;
6727  found_is_null_op = false;
6728  num_sa_scans = 1;
6729  foreach(lc, qinfos)
6730  {
6731  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6732  RestrictInfo *rinfo = qinfo->rinfo;
6733  Expr *clause = rinfo->clause;
6734  Oid clause_op;
6735  int op_strategy;
6736 
6737  if (indexcol != qinfo->indexcol)
6738  {
6739  /* Beginning of a new column's quals */
6740  if (!eqQualHere)
6741  break; /* done if no '=' qual for indexcol */
6742  eqQualHere = false;
6743  indexcol++;
6744  if (indexcol != qinfo->indexcol)
6745  break; /* no quals at all for indexcol */
6746  }
6747 
6748  if (IsA(clause, ScalarArrayOpExpr))
6749  {
6750  int alength = estimate_array_length(qinfo->other_operand);
6751 
6752  found_saop = true;
6753  /* count up number of SA scans induced by indexBoundQuals only */
6754  if (alength > 1)
6755  num_sa_scans *= alength;
6756  }
6757  else if (IsA(clause, NullTest))
6758  {
6759  NullTest *nt = (NullTest *) clause;
6760 
6761  if (nt->nulltesttype == IS_NULL)
6762  {
6763  found_is_null_op = true;
6764  /* IS NULL is like = for selectivity determination purposes */
6765  eqQualHere = true;
6766  }
6767  }
6768 
6769  /*
6770  * We would need to commute the clause_op if not varonleft, except
6771  * that we only care if it's equality or not, so that refinement is
6772  * unnecessary.
6773  */
6774  clause_op = qinfo->clause_op;
6775 
6776  /* check for equality operator */
6777  if (OidIsValid(clause_op))
6778  {
6779  op_strategy = get_op_opfamily_strategy(clause_op,
6780  index->opfamily[indexcol]);
6781  Assert(op_strategy != 0); /* not a member of opfamily?? */
6782  if (op_strategy == BTEqualStrategyNumber)
6783  eqQualHere = true;
6784  }
6785 
6786  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6787  }
6788 
6789  /*
6790  * If index is unique and we found an '=' clause for each column, we can
6791  * just assume numIndexTuples = 1 and skip the expensive
6792  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6793  * NullTest invalidates that theory, even though it sets eqQualHere.
6794  */
6795  if (index->unique &&
6796  indexcol == index->ncolumns - 1 &&
6797  eqQualHere &&
6798  !found_saop &&
6799  !found_is_null_op)
6800  numIndexTuples = 1.0;
6801  else
6802  {
6803  List *selectivityQuals;
6804  Selectivity btreeSelectivity;
6805 
6806  /*
6807  * If the index is partial, AND the index predicate with the
6808  * index-bound quals to produce a more accurate idea of the number of
6809  * rows covered by the bound conditions.
6810  */
6811  selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
6812 
6813  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6814  index->rel->relid,
6815  JOIN_INNER,
6816  NULL);
6817  numIndexTuples = btreeSelectivity * index->rel->tuples;
6818 
6819  /*
6820  * As in genericcostestimate(), we have to adjust for any
6821  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6822  * to integer.
6823  */
6824  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6825  }
6826 
6827  /*
6828  * Now do generic index cost estimation.
6829  */
6830  MemSet(&costs, 0, sizeof(costs));
6831  costs.numIndexTuples = numIndexTuples;
6832 
6833  genericcostestimate(root, path, loop_count, qinfos, &costs);
6834 
6835  /*
6836  * Add a CPU-cost component to represent the costs of initial btree
6837  * descent. We don't charge any I/O cost for touching upper btree levels,
6838  * since they tend to stay in cache, but we still have to do about log2(N)
6839  * comparisons to descend a btree of N leaf tuples. We charge one
6840  * cpu_operator_cost per comparison.
6841  *
6842  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6843  * ones after the first one are not startup cost so far as the overall
6844  * plan is concerned, so add them only to "total" cost.
6845  */
6846  if (index->tuples > 1) /* avoid computing log(0) */
6847  {
6848  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6849  costs.indexStartupCost += descentCost;
6850  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6851  }
6852 
6853  /*
6854  * Even though we're not charging I/O cost for touching upper btree pages,
6855  * it's still reasonable to charge some CPU cost per page descended
6856  * through. Moreover, if we had no such charge at all, bloated indexes
6857  * would appear to have the same search cost as unbloated ones, at least
6858  * in cases where only a single leaf page is expected to be visited. This
6859  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6860  * touched. The number of such pages is btree tree height plus one (ie,
6861  * we charge for the leaf page too). As above, charge once per SA scan.
6862  */
6863  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6864  costs.indexStartupCost += descentCost;
6865  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6866 
6867  /*
6868  * If we can get an estimate of the first column's ordering correlation C
6869  * from pg_statistic, estimate the index correlation as C for a
6870  * single-column index, or C * 0.75 for multiple columns. (The idea here
6871  * is that multiple columns dilute the importance of the first column's
6872  * ordering, but don't negate it entirely. Before 8.0 we divided the
6873  * correlation by the number of columns, but that seems too strong.)
6874  */
6875  MemSet(&vardata, 0, sizeof(vardata));
6876 
6877  if (index->indexkeys[0] != 0)
6878  {
6879  /* Simple variable --- look to stats for the underlying table */
6880  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
6881 
6882  Assert(rte->rtekind == RTE_RELATION);
6883  relid = rte->relid;
6884  Assert(relid != InvalidOid);
6885  colnum = index->indexkeys[0];
6886 
6888  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
6889  {
6890  /*
6891  * The hook took control of acquiring a stats tuple. If it did
6892  * supply a tuple, it'd better have supplied a freefunc.
6893  */
6894  if (HeapTupleIsValid(vardata.statsTuple) &&
6895  !vardata.freefunc)
6896  elog(ERROR, "no function provided to release variable stats with");
6897  }
6898  else
6899  {
6901  ObjectIdGetDatum(relid),
6902  Int16GetDatum(colnum),
6903  BoolGetDatum(rte->inh));
6904  vardata.freefunc = ReleaseSysCache;
6905  }
6906  }
6907  else
6908  {
6909  /* Expression --- maybe there are stats for the index itself */
6910  relid = index->indexoid;
6911  colnum = 1;
6912 
6913  if (get_index_stats_hook &&
6914  (*get_index_stats_hook) (root, relid, colnum, &vardata))
6915  {
6916  /*
6917  * The hook took control of acquiring a stats tuple. If it did
6918  * supply a tuple, it'd better have supplied a freefunc.
6919  */
6920  if (HeapTupleIsValid(vardata.statsTuple) &&
6921  !vardata.freefunc)
6922  elog(ERROR, "no function provided to release variable stats with");
6923  }
6924  else
6925  {
6927  ObjectIdGetDatum(relid),
6928  Int16GetDatum(colnum),
6929  BoolGetDatum(false));
6930  vardata.freefunc = ReleaseSysCache;
6931  }
6932  }
6933 
6934  if (HeapTupleIsValid(vardata.statsTuple))
6935  {
6936  Oid sortop;
6937  AttStatsSlot sslot;
6938 
6939  sortop = get_opfamily_member(index->opfamily[0],
6940  index->opcintype[0],
6941  index->opcintype[0],
6943  if (OidIsValid(sortop) &&
6944  get_attstatsslot(&sslot, vardata.statsTuple,
6947  {
6948  double varCorrelation;
6949 
6950  Assert(sslot.nnumbers == 1);
6951  varCorrelation = sslot.numbers[0];
6952 
6953  if (index->reverse_sort[0])
6954  varCorrelation = -varCorrelation;
6955 
6956  if (index->ncolumns > 1)
6957  costs.indexCorrelation = varCorrelation * 0.75;
6958  else
6959  costs.indexCorrelation = varCorrelation;
6960 
6961  free_attstatsslot(&sslot);
6962  }
6963  }
6964 
6965  ReleaseVariableStats(vardata);
6966 
6967  *indexStartupCost = costs.indexStartupCost;
6968  *indexTotalCost = costs.indexTotalCost;
6969  *indexSelectivity = costs.indexSelectivity;
6970  *indexCorrelation = costs.indexCorrelation;
6971  *indexPages = costs.numIndexPages;
6972 }
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:6660
#define Int16GetDatum(X)
Definition: postgres.h:457
#define MemSet(start, val, len)
Definition: c.h:857
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:6292
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:675
#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:936
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:6441
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 6016 of file selfuncs.c.

Referenced by make_greater_string().

6017 {
6018  if (*ptr >= 255)
6019  return false;
6020  (*ptr)++;
6021  return true;
6022 }
static void convert_bytea_to_scalar ( Datum  value,
double *  scaledvalue,
Datum  lobound,
double *  scaledlobound,
Datum  hibound,
double *  scaledhibound 
)
static

Definition at line 4270 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4276 {
4277  int rangelo,
4278  rangehi,
4279  valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
4280  loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
4281  hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
4282  i,
4283  minlen;
4284  unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
4285  *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
4286  *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4287 
4288  /*
4289  * Assume bytea data is uniformly distributed across all byte values.
4290  */
4291  rangelo = 0;
4292  rangehi = 255;
4293 
4294  /*
4295  * Now strip any common prefix of the three strings.
4296  */
4297  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4298  for (i = 0; i < minlen; i++)
4299  {
4300  if (*lostr != *histr || *lostr != *valstr)
4301  break;
4302  lostr++, histr++, valstr++;
4303  loboundlen--, hiboundlen--, valuelen--;
4304  }
4305 
4306  /*
4307  * Now we can do the conversions.
4308  */
4309  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4310  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4311  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4312 }
#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:806
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4315
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 3978 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().

3979 {
3980  switch (typid)
3981  {
3982  case BOOLOID:
3983  return (double) DatumGetBool(value);
3984  case INT2OID:
3985  return (double) DatumGetInt16(value);
3986  case INT4OID:
3987  return (double) DatumGetInt32(value);
3988  case INT8OID:
3989  return (double) DatumGetInt64(value);
3990  case FLOAT4OID:
3991  return (double) DatumGetFloat4(value);
3992  case FLOAT8OID:
3993  return (double) DatumGetFloat8(value);
3994  case NUMERICOID:
3995  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
3996  return (double)
3998  value));
3999  case OIDOID:
4000  case REGPROCOID:
4001  case REGPROCEDUREOID:
4002  case REGOPEROID:
4003  case REGOPERATOROID:
4004  case REGCLASSOID:
4005  case REGTYPEOID:
4006  case REGCONFIGOID:
4007  case REGDICTIONARYOID:
4008  case REGROLEOID:
4009  case REGNAMESPACEOID:
4010  /* we can treat OIDs as integers... */
4011  return (double) DatumGetObjectId(value);
4012  }
4013 
4014  /*
4015  * Can't get here unless someone tries to use scalarltsel/scalargtsel on
4016  * an operator with one numeric and one non-numeric operand.
4017  */
4018  elog(ERROR, "unsupported type: %u", typid);
4019  return 0;
4020 }
#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 4315 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

4317 {
4318  double num,
4319  denom,
4320  base;
4321 
4322  if (valuelen <= 0)
4323  return 0.0; /* empty string has scalar value 0 */
4324 
4325  /*
4326  * Since base is 256, need not consider more than about 10 chars (even
4327  * this many seems like overkill)
4328  */
4329  if (valuelen > 10)
4330  valuelen = 10;
4331 
4332  /* Convert initial characters to fraction */
4333  base = rangehi - rangelo + 1;
4334  num = 0.0;
4335  denom = base;
4336  while (valuelen-- > 0)
4337  {
4338  int ch = *value++;
4339 
4340  if (ch < rangelo)
4341  ch = rangelo - 1;
4342  else if (ch > rangehi)
4343  ch = rangehi + 1;
4344  num += ((double) (ch - rangelo)) / denom;
4345  denom *= base;
4346  }
4347 
4348  return num;
4349 }
static struct @121 value
static double convert_one_string_to_scalar ( char *  value,
int  rangelo,
int  rangehi 
)
static

Definition at line 4123 of file selfuncs.c.

Referenced by convert_string_to_scalar().

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

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

4172 {
4173  char *val;
4174 
4175  switch (typid)
4176  {
4177  case CHAROID:
4178  val = (char *) palloc(2);
4179  val[0] = DatumGetChar(value);
4180  val[1] = '\0';
4181  break;
4182  case BPCHAROID:
4183  case VARCHAROID:
4184  case TEXTOID:
4185  val = TextDatumGetCString(value);
4186  break;
4187  case NAMEOID:
4188  {
4190 
4191  val = pstrdup(NameStr(*nm));
4192  break;
4193  }
4194  default:
4195 
4196  /*
4197  * Can't get here unless someone tries to use scalarltsel on an
4198  * operator with one string and one non-string operand.
4199  */
4200  elog(ERROR, "unsupported type: %u", typid);
4201  return NULL;
4202  }
4203 
4205  {
4206  char *xfrmstr;
4207  size_t xfrmlen;
4208  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4209 
4210  /*
4211  * XXX: We could guess at a suitable output buffer size and only call
4212  * strxfrm twice if our guess is too small.
4213  *
4214  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4215  * bogus data or set an error. This is not really a problem unless it
4216  * crashes since it will only give an estimation error and nothing
4217  * fatal.
4218  */
4219 #if _MSC_VER == 1400 /* VS.Net 2005 */
4220 
4221  /*
4222  *
4223  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4224  */
4225  {
4226  char x[1];
4227 
4228  xfrmlen = strxfrm(x, val, 0);
4229  }
4230 #else
4231  xfrmlen = strxfrm(NULL, val, 0);
4232 #endif
4233 #ifdef WIN32
4234 
4235  /*
4236  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4237  * of trying to allocate this much memory (and fail), just return the
4238  * original string unmodified as if we were in the C locale.
4239  */
4240  if (xfrmlen == INT_MAX)
4241  return val;
4242 #endif
4243  xfrmstr = (char *) palloc(xfrmlen + 1);
4244  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4245 
4246  /*
4247  * Some systems (e.g., glibc) can return a smaller value from the
4248  * second call than the first; thus the Assert must be <= not ==.
4249  */
4250  Assert(xfrmlen2 <= xfrmlen);
4251  pfree(val);
4252  val = xfrmstr;
4253  }
4254 
4255  return val;
4256 }
#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:675
#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:990
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 4043 of file selfuncs.c.

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

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

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

4356 {
4357  switch (typid)
4358  {
4359  case TIMESTAMPOID:
4360  return DatumGetTimestamp(value);
4361  case TIMESTAMPTZOID:
4362  return DatumGetTimestampTz(value);
4363  case ABSTIMEOID:
4365  value));
4366  case DATEOID:
4368  case INTERVALOID:
4369  {
4371 
4372  /*
4373  * Convert the month part of Interval to days using assumed
4374  * average month length of 365.25/12.0 days. Not too
4375  * accurate, but plenty good enough for our purposes.
4376  */
4377  return interval->time + interval->day * (double) USECS_PER_DAY +
4378  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4379  }
4380  case RELTIMEOID:
4381  return (DatumGetRelativeTime(value) * 1000000.0);
4382  case TINTERVALOID:
4383  {
4385 
4386  if (tinterval->status != 0)
4387  return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4388  return 0; /* for lack of a better idea */
4389  }
4390  case TIMEOID:
4391  return DatumGetTimeADT(value);
4392  case TIMETZOID:
4393  {
4394  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4395 
4396  /* use GMT-equivalent time */
4397  return (double) (timetz->time + (timetz->zone * 1000000.0));
4398  }
4399  }
4400 
4401  /*
4402  * Can't get here unless someone tries to use scalarltsel/scalargtsel on
4403  * an operator with one timevalue and one non-timevalue operand.
4404  */
4405  elog(ERROR, "unsupported type: %u", typid);
4406  return 0;
4407 }
#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 3860 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().

3863 {
3864  /*
3865  * Both the valuetypid and the boundstypid should exactly match the
3866  * declared input type(s) of the operator we are invoked for, so we just
3867  * error out if either is not recognized.
3868  *
3869  * XXX The histogram we are interpolating between points of could belong
3870  * to a column that's only binary-compatible with the declared type. In
3871  * essence we are assuming that the semantics of binary-compatible types
3872  * are enough alike that we can use a histogram generated with one type's
3873  * operators to estimate selectivity for the other's. This is outright
3874  * wrong in some cases --- in particular signed versus unsigned
3875  * interpretation could trip us up. But it's useful enough in the
3876  * majority of cases that we do it anyway. Should think about more
3877  * rigorous ways to do it.
3878  */
3879  switch (valuetypid)
3880  {
3881  /*
3882  * Built-in numeric types
3883  */
3884  case BOOLOID:
3885  case INT2OID:
3886  case INT4OID:
3887  case INT8OID:
3888  case FLOAT4OID:
3889  case FLOAT8OID:
3890  case NUMERICOID:
3891  case OIDOID:
3892  case REGPROCOID:
3893  case REGPROCEDUREOID:
3894  case REGOPEROID:
3895  case REGOPERATOROID:
3896  case REGCLASSOID:
3897  case REGTYPEOID:
3898  case REGCONFIGOID:
3899  case REGDICTIONARYOID:
3900  case REGROLEOID:
3901  case REGNAMESPACEOID:
3902  *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
3903  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
3904  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
3905  return true;
3906 
3907  /*
3908  * Built-in string types
3909  */
3910  case CHAROID:
3911  case BPCHAROID:
3912  case VARCHAROID:
3913  case TEXTOID:
3914  case NAMEOID:
3915  {
3916  char *valstr = convert_string_datum(value, valuetypid);
3917  char *lostr = convert_string_datum(lobound, boundstypid);
3918  char *histr = convert_string_datum(hibound, boundstypid);
3919 
3920  convert_string_to_scalar(valstr, scaledvalue,
3921  lostr, scaledlobound,
3922  histr, scaledhibound);
3923  pfree(valstr);
3924  pfree(lostr);
3925  pfree(histr);
3926  return true;
3927  }
3928 
3929  /*
3930  * Built-in bytea type
3931  */
3932  case BYTEAOID:
3933  {
3934  convert_bytea_to_scalar(value, scaledvalue,
3935  lobound, scaledlobound,
3936  hibound, scaledhibound);
3937  return true;
3938  }
3939 
3940  /*
3941  * Built-in time types
3942  */
3943  case TIMESTAMPOID:
3944  case TIMESTAMPTZOID:
3945  case ABSTIMEOID:
3946  case DATEOID:
3947  case INTERVALOID:
3948  case RELTIMEOID:
3949  case TINTERVALOID:
3950  case TIMEOID:
3951  case TIMETZOID:
3952  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
3953  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
3954  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
3955  return true;
3956 
3957  /*
3958  * Built-in network types
3959  */
3960  case INETOID:
3961  case CIDROID:
3962  case MACADDROID:
3963  case MACADDR8OID:
3964  *scaledvalue = convert_network_to_scalar(value, valuetypid);
3965  *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
3966  *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
3967  return true;
3968  }
3969  /* Don't know how to convert */
3970  *scaledvalue = *scaledlobound = *scaledhibound = 0;
3971  return false;
3972 }
#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:3978
#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:4171
#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:4355
#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:4270
#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:4043
#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 6292 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().

6293 {
6294  List *result = NIL;
6295  IndexOptInfo *index = path->indexinfo;
6296  ListCell *lcc,
6297  *lci;
6298 
6299  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6300  {
6301  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6302  int indexcol = lfirst_int(lci);
6303  Expr *clause;
6304  Node *leftop,
6305  *rightop;
6306  IndexQualInfo *qinfo;
6307 
6308  clause = rinfo->clause;
6309 
6310  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6311  qinfo->rinfo = rinfo;
6312  qinfo->indexcol = indexcol;
6313 
6314  if (IsA(clause, OpExpr))
6315  {
6316  qinfo->clause_op = ((OpExpr *) clause)->opno;
6317  leftop = get_leftop(clause);
6318  rightop = get_rightop(clause);
6319  if (match_index_to_operand(leftop, indexcol, index))
6320  {
6321  qinfo->varonleft = true;
6322  qinfo->other_operand = rightop;
6323  }
6324  else
6325  {
6326  Assert(match_index_to_operand(rightop, indexcol, index));
6327  qinfo->varonleft = false;
6328  qinfo->other_operand = leftop;
6329  }
6330  }
6331  else if (IsA(clause, RowCompareExpr))
6332  {
6333  RowCompareExpr *rc = (RowCompareExpr *) clause;
6334 
6335  qinfo->clause_op = linitial_oid(rc->opnos);
6336  /* Examine only first columns to determine left/right sides */
6338  indexcol, index))
6339  {
6340  qinfo->varonleft = true;
6341  qinfo->other_operand = (Node *) rc->rargs;
6342  }
6343  else
6344  {
6346  indexcol, index));
6347  qinfo->varonleft = false;
6348  qinfo->other_operand = (Node *) rc->largs;
6349  }
6350  }
6351  else if (IsA(clause, ScalarArrayOpExpr))
6352  {
6353  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6354 
6355  qinfo->clause_op = saop->opno;
6356  /* index column is always on the left in this case */
6358  indexcol, index));
6359  qinfo->varonleft = true;
6360  qinfo->other_operand = (Node *) lsecond(saop->args);
6361  }
6362  else if (IsA(clause, NullTest))
6363  {
6364  qinfo->clause_op = InvalidOid;
6365  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6366  indexcol, index));
6367  qinfo->varonleft = true;
6368  qinfo->other_operand = NULL;
6369  }
6370  else
6371  {
6372  elog(ERROR, "unsupported indexqual type: %d",
6373  (int) nodeTag(clause));
6374  }
6375 
6376  result = lappend(result, qinfo);
6377  }
6378  return result;
6379 }
#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:675
#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:1918
#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:4494
#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:5445
JoinType jointype
Definition: relation.h:1921
#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:4934
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:4963
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:4934
RelOptInfo * rel
Definition: selfuncs.h:70
#define Min(x, y)
Definition: c.h:806
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:4963
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:4434
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
Selectivity estimate_hash_bucketsize ( PlannerInfo root,
Node hashkey,
double  nbuckets 
)

Definition at line 3592 of file selfuncs.c.

References ATTSTATSSLOT_NUMBERS, clamp_row_est(), examine_variable(), free_attstatsslot(), get_attstatsslot(), get_variable_numdistinct(), GETSTRUCT, HeapTupleIsValid, InvalidOid, AttStatsSlot::nnumbers, AttStatsSlot::numbers, VariableStatData::rel, ReleaseVariableStats, RelOptInfo::rows, STATISTIC_KIND_MCV, VariableStatData::statsTuple, and RelOptInfo::tuples.

Referenced by final_cost_hashjoin().

3593 {
3594  VariableStatData vardata;
3595  double estfract,
3596  ndistinct,
3597  stanullfrac,
3598  mcvfreq,
3599  avgfreq;
3600  bool isdefault;
3601  AttStatsSlot sslot;
3602 
3603  examine_variable(root, hashkey, 0, &vardata);
3604 
3605  /* Get number of distinct values */
3606  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3607 
3608  /* If ndistinct isn't real, punt and return 0.1, per comments above */
3609  if (isdefault)
3610  {
3611  ReleaseVariableStats(vardata);
3612  return (Selectivity) 0.1;
3613  }
3614 
3615  /* Get fraction that are null */
3616  if (HeapTupleIsValid(vardata.statsTuple))
3617  {
3618  Form_pg_statistic stats;
3619 
3620  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3621  stanullfrac = stats->stanullfrac;
3622  }
3623  else
3624  stanullfrac = 0.0;
3625 
3626  /* Compute avg freq of all distinct data values in raw relation */
3627  avgfreq = (1.0 - stanullfrac) / ndistinct;
3628 
3629  /*
3630  * Adjust ndistinct to account for restriction clauses. Observe we are
3631  * assuming that the data distribution is affected uniformly by the
3632  * restriction clauses!
3633  *
3634  * XXX Possibly better way, but much more expensive: multiply by
3635  * selectivity of rel's restriction clauses that mention the target Var.
3636  */
3637  if (vardata.rel && vardata.rel->tuples > 0)
3638  {
3639  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3640  ndistinct = clamp_row_est(ndistinct);
3641  }
3642 
3643  /*
3644  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3645  * number of buckets is less than the expected number of distinct values;
3646  * otherwise it is 1/ndistinct.
3647  */
3648  if (ndistinct > nbuckets)
3649  estfract = 1.0 / nbuckets;
3650  else
3651  estfract = 1.0 / ndistinct;
3652 
3653  /*
3654  * Look up the frequency of the most common value, if available.
3655  */
3656  mcvfreq = 0.0;
3657 
3658  if (HeapTupleIsValid(vardata.statsTuple))
3659  {
3660  if (get_attstatsslot(&sslot, vardata.statsTuple,
3663  {
3664  /*
3665  * The first MCV stat is for the most common value.
3666  */
3667  if (sslot.nnumbers > 0)
3668  mcvfreq = sslot.numbers[0];
3669  free_attstatsslot(&sslot);
3670  }
3671  }
3672 
3673  /*
3674  * Adjust estimated bucketsize upward to account for skewed distribution.
3675  */
3676  if (avgfreq > 0.0 && mcvfreq > avgfreq)
3677  estfract *= mcvfreq / avgfreq;
3678 
3679  /*
3680  * Clamp bucketsize to sane range (the above adjustment could easily
3681  * produce an out-of-range result). We set the lower bound a little above
3682  * zero, since zero isn't a very sane result.
3683  */
3684  if (estfract < 1.0e-6)
3685  estfract = 1.0e-6;
3686  else if (estfract > 1.0)
3687  estfract = 1.0;
3688 
3689  ReleaseVariableStats(vardata);
3690 
3691  return (Selectivity) estfract;
3692 }
#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:4963
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 HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4556
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 3713 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().

3715 {
3716  ListCell *lc;
3717  Bitmapset *attnums = NULL;
3718  int nmatches;
3719  Oid statOid = InvalidOid;
3720  MVNDistinct *stats;
3721  Bitmapset *matched = NULL;
3722 
3723  /* bail out immediately if the table has no extended statistics */
3724  if (!rel->statlist)
3725  return false;
3726 
3727  /* Determine the attnums we're looking for */
3728  foreach(lc, *varinfos)
3729  {
3730  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3731 
3732  Assert(varinfo->rel == rel);
3733 
3734  if (IsA(varinfo->var, Var))
3735  {
3736  attnums = bms_add_member(attnums,
3737  ((Var *) varinfo->var)->varattno);
3738  }
3739  }
3740 
3741  /* look for the ndistinct statistics matching the most vars */
3742  nmatches = 1; /* we require at least two matches */
3743  foreach(lc, rel->statlist)
3744  {
3745  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3746  Bitmapset *shared;
3747  int nshared;
3748 
3749  /* skip statistics of other kinds */
3750  if (info->kind != STATS_EXT_NDISTINCT)
3751  continue;
3752 
3753  /* compute attnums shared by the vars and the statistics object */
3754  shared = bms_intersect(info->keys, attnums);
3755  nshared = bms_num_members(shared);
3756 
3757  /*
3758  * Does this statistics object match more columns than the currently
3759  * best object? If so, use this one instead.
3760  *
3761  * XXX This should break ties using name of the object, or something
3762  * like that, to make the outcome stable.
3763  */
3764  if (nshared > nmatches)
3765  {
3766  statOid = info->statOid;
3767  nmatches = nshared;
3768  matched = shared;
3769  }
3770  }
3771 
3772  /* No match? */
3773  if (statOid == InvalidOid)
3774  return false;
3775  Assert(nmatches > 1 && matched != NULL);
3776 
3777  stats = statext_ndistinct_load(statOid);
3778 
3779  /*
3780  * If we have a match, search it for the specific item that matches (there
3781  * must be one), and construct the output values.
3782  */
3783  if (stats)
3784  {
3785  int i;
3786  List *newlist = NIL;
3787  MVNDistinctItem *item = NULL;
3788 
3789  /* Find the specific item that exactly matches the combination */
3790  for (i = 0; i < stats->nitems; i++)
3791  {
3792  MVNDistinctItem *tmpitem = &stats->items[i];
3793 
3794  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3795  {
3796  item = tmpitem;
3797  break;
3798  }
3799  }
3800 
3801  /* make sure we found an item */
3802  if (!item)
3803  elog(ERROR, "corrupt MVNDistinct entry");
3804 
3805  /* Form the output varinfo list, keeping only unmatched ones */
3806  foreach(lc, *varinfos)
3807  {
3808  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3809  AttrNumber attnum;
3810 
3811  if (!IsA(varinfo->var, Var))
3812  {
3813  newlist = lappend(newlist, varinfo);
3814  continue;
3815  }
3816 
3817  attnum = ((Var *) varinfo->var)->varattno;
3818  if (!bms_is_member(attnum, matched))
3819  newlist = lappend(newlist, varinfo);
3820  }
3821 
3822  *varinfos = newlist;
3823  *ndistinct = item->ndistinct;
3824  return true;
3825  }
3826 
3827  return false;
3828 }
#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:675
#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:951
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:3713
#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:4556
#define Assert(condition)
Definition: c.h:675
#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 4767 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().

4769 {
4770  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4771 
4772  Assert(IsA(rte, RangeTblEntry));
4773 
4775  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4776  {
4777  /*
4778  * The hook took control of acquiring a stats tuple. If it did supply
4779  * a tuple, it'd better have supplied a freefunc.
4780  */
4781  if (HeapTupleIsValid(vardata->statsTuple) &&
4782  !vardata->freefunc)
4783  elog(ERROR, "no function provided to release variable stats with");
4784  }
4785  else if (rte->rtekind == RTE_RELATION)
4786  {
4787  /*
4788  * Plain table or parent of an inheritance appendrel, so look up the
4789  * column in pg_statistic
4790  */
4792  ObjectIdGetDatum(rte->relid),
4793  Int16GetDatum(var->varattno),
4794  BoolGetDatum(rte->inh));
4795  vardata->freefunc = ReleaseSysCache;
4796 
4797  if (HeapTupleIsValid(vardata->statsTuple))
4798  {
4799  /* check if user has permission to read this column */
4800  vardata->acl_ok =
4802  ACL_SELECT) == ACLCHECK_OK) ||
4804  ACL_SELECT) == ACLCHECK_OK);
4805  }
4806  else
4807  {
4808  /* suppress any possible leakproofness checks later */
4809  vardata->acl_ok = true;
4810  }
4811  }
4812  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4813  {
4814  /*
4815  * Plain subquery (not one that was converted to an appendrel).
4816  */
4817  Query *subquery = rte->subquery;
4818  RelOptInfo *rel;
4819  TargetEntry *ste;
4820 
4821  /*
4822  * Punt if it's a whole-row var rather than a plain column reference.
4823  */
4824  if (var->varattno == InvalidAttrNumber)
4825  return;
4826 
4827  /*
4828  * Punt if subquery uses set operations or GROUP BY, as these will
4829  * mash underlying columns' stats beyond recognition. (Set ops are
4830  * particularly nasty; if we forged ahead, we would return stats
4831  * relevant to only the leftmost subselect...) DISTINCT is also
4832  * problematic, but we check that later because there is a possibility
4833  * of learning something even with it.
4834  */
4835  if (subquery->setOperations ||
4836  subquery->groupClause)
4837  return;
4838 
4839  /*
4840  * OK, fetch RelOptInfo for subquery. Note that we don't change the
4841  * rel returned in vardata, since caller expects it to be a rel of the
4842  * caller's query level. Because we might already be recursing, we
4843  * can't use that rel pointer either, but have to look up the Var's
4844  * rel afresh.
4845  */
4846  rel = find_base_rel(root, var->varno);
4847 
4848  /* If the subquery hasn't been planned yet, we have to punt */
4849  if (rel->subroot == NULL)
4850  return;
4851  Assert(IsA(rel->subroot, PlannerInfo));
4852 
4853  /*
4854  * Switch our attention to the subquery as mangled by the planner. It
4855  * was okay to look at the pre-planning version for the tests above,
4856  * but now we need a Var that will refer to the subroot's live
4857  * RelOptInfos. For instance, if any subquery pullup happened during
4858  * planning, Vars in the targetlist might have gotten replaced, and we
4859  * need to see the replacement expressions.
4860  */
4861  subquery = rel->subroot->parse;
4862  Assert(IsA(subquery, Query));
4863 
4864  /* Get the subquery output expression referenced by the upper Var */
4865  ste = get_tle_by_resno(subquery->targetList, var->varattno);
4866  if (ste == NULL || ste->resjunk)
4867  elog(ERROR, "subquery %s does not have attribute %d",
4868  rte->eref->aliasname, var->varattno);
4869  var = (Var *) ste->expr;
4870 
4871  /*
4872  * If subquery uses DISTINCT, we can't make use of any stats for the
4873  * variable ... but, if it's the only DISTINCT column, we are entitled
4874  * to consider it unique. We do the test this way so that it works
4875  * for cases involving DISTINCT ON.
4876  */
4877  if (subquery->distinctClause)
4878  {
4879  if (list_length(subquery->distinctClause) == 1 &&
4880  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4881  vardata->isunique = true;
4882  /* cannot go further */
4883  return;
4884  }
4885 
4886  /*
4887  * If the sub-query originated from a view with the security_barrier
4888  * attribute, we must not look at the variable's statistics, though it
4889  * seems all right to notice the existence of a DISTINCT clause. So
4890  * stop here.
4891  *
4892  * This is probably a harsher restriction than necessary; it's
4893  * certainly OK for the selectivity estimator (which is a C function,
4894  * and therefore omnipotent anyway) to look at the statistics. But
4895  * many selectivity estimators will happily *invoke the operator
4896  * function* to try to work out a good estimate - and that's not OK.
4897  * So for now, don't dig down for stats.
4898  */
4899  if (rte->security_barrier)
4900  return;
4901 
4902  /* Can only handle a simple Var of subquery's query level */
4903  if (var && IsA(var, Var) &&
4904  var->varlevelsup == 0)
4905  {
4906  /*
4907  * OK, recurse into the subquery. Note that the original setting
4908  * of vardata->isunique (which will surely be false) is left
4909  * unchanged in this situation. That's what we want, since even
4910  * if the underlying column is unique, the subquery may have
4911  * joined to other tables in a way that creates duplicates.
4912  */
4913  examine_simple_variable(rel->subroot, var, vardata);
4914  }
4915  }
4916  else
4917  {
4918  /*
4919  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
4920  * won't see RTE_JOIN here because join alias Vars have already been
4921  * flattened.) There's not much we can do with function outputs, but
4922  * maybe someday try to be smarter about VALUES and/or CTEs.
4923  */
4924  }
4925 }
#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:283
#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:4767
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:960
#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:675
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:936
Node * setOperations
Definition: parsenodes.h:163
Query * subquery
Definition: parsenodes.h:959
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:1035
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 4556 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_bucketsize(), estimate_num_groups(), get_join_variables(), get_restriction_variable(), mergejoinscansel(), nulltestsel(), and scalararraysel_containment().

4558 {
4559  Node *basenode;
4560  Relids varnos;
4561  RelOptInfo *onerel;
4562 
4563  /* Make sure we don't return dangling pointers in vardata */
4564  MemSet(vardata, 0, sizeof(VariableStatData));
4565 
4566  /* Save the exposed type of the expression */
4567  vardata->vartype = exprType(node);
4568 
4569  /* Look inside any binary-compatible relabeling */
4570 
4571  if (IsA(node, RelabelType))
4572  basenode = (Node *) ((RelabelType *) node)->arg;
4573  else
4574  basenode = node;
4575 
4576  /* Fast path for a simple Var */
4577 
4578  if (IsA(basenode, Var) &&
4579  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4580  {
4581  Var *var = (Var *) basenode;
4582 
4583  /* Set up result fields other than the stats tuple */
4584  vardata->var = basenode; /* return Var without relabeling */
4585  vardata->rel = find_base_rel(root, var->varno);
4586  vardata->atttype = var->vartype;
4587  vardata->atttypmod = var->vartypmod;
4588  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4589 
4590  /* Try to locate some stats */
4591  examine_simple_variable(root, var, vardata);
4592 
4593  return;
4594  }
4595 
4596  /*
4597  * Okay, it's a more complicated expression. Determine variable
4598  * membership. Note that when varRelid isn't zero, only vars of that
4599  * relation are considered "real" vars.
4600  */
4601  varnos = pull_varnos(basenode);
4602 
4603  onerel = NULL;
4604 
4605  switch (bms_membership(varnos))
4606  {
4607  case BMS_EMPTY_SET:
4608  /* No Vars at all ... must be pseudo-constant clause */
4609  break;
4610  case BMS_SINGLETON:
4611  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4612  {
4613  onerel = find_base_rel(root,
4614  (varRelid ? varRelid : bms_singleton_member(varnos)));
4615  vardata->rel = onerel;
4616  node = basenode; /* strip any relabeling */
4617  }
4618  /* else treat it as a constant */
4619  break;
4620  case BMS_MULTIPLE:
4621  if (varRelid == 0)
4622  {
4623  /* treat it as a variable of a join relation */
4624  vardata->rel = find_join_rel(root, varnos);
4625  node = basenode; /* strip any relabeling */
4626  }
4627  else if (bms_is_member(varRelid, varnos))
4628  {
4629  /* ignore the vars belonging to other relations */
4630  vardata->rel = find_base_rel(root, varRelid);
4631  node = basenode; /* strip any relabeling */
4632  /* note: no point in expressional-index search here */
4633  }
4634  /* else treat it as a constant */
4635  break;
4636  }
4637 
4638  bms_free(varnos);
4639 
4640  vardata->var = node;
4641  vardata->atttype = exprType(node);
4642  vardata->atttypmod = exprTypmod(node);
4643 
4644  if (onerel)
4645  {
4646  /*
4647  * We have an expression in vars of a single relation. Try to match
4648  * it to expressional index columns, in hopes of finding some
4649  * statistics.
4650  *
4651  * XXX it's conceivable that there are multiple matches with different
4652  * index opfamilies; if so, we need to pick one that matches the
4653  * operator we are estimating for. FIXME later.
4654  */
4655  ListCell *ilist;
4656 
4657  foreach(ilist, onerel->indexlist)
4658  {
4659  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4660  ListCell *indexpr_item;
4661  int pos;
4662 
4663  indexpr_item = list_head(index->indexprs);
4664  if (indexpr_item == NULL)
4665  continue; /* no expressions here... */
4666 
4667  for (pos = 0; pos < index->ncolumns; pos++)
4668  {
4669  if (index->indexkeys[pos] == 0)
4670  {
4671  Node *indexkey;
4672 
4673  if (indexpr_item == NULL)
4674  elog(ERROR, "too few entries in indexprs list");
4675  indexkey = (Node *) lfirst(indexpr_item);
4676  if (indexkey && IsA(indexkey, RelabelType))
4677  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4678  if (equal(node, indexkey))
4679  {
4680  /*
4681  * Found a match ... is it a unique index? Tests here
4682  * should match has_unique_index().
4683  */
4684  if (index->unique &&
4685  index->ncolumns == 1 &&
4686  (index->indpred == NIL || index->predOK))
4687  vardata->isunique = true;
4688 
4689  /*
4690  * Has it got stats? We only consider stats for
4691  * non-partial indexes, since partial indexes probably
4692  * don't reflect whole-relation statistics; the above
4693  * check for uniqueness is the only info we take from
4694  * a partial index.
4695  *
4696  * An index stats hook, however, must make its own
4697  * decisions about what to do with partial indexes.
4698  */
4699  if (get_index_stats_hook &&
4700  (*get_index_stats_hook) (root, index->indexoid,
4701  pos + 1, vardata))
4702  {
4703  /*
4704  * The hook took control of acquiring a stats
4705  * tuple. If it did supply a tuple, it'd better
4706  * have supplied a freefunc.
4707  */
4708  if (HeapTupleIsValid(vardata->statsTuple) &&
4709  !vardata->freefunc)
4710  elog(ERROR, "no function provided to release variable stats with");
4711  }
4712  else if (index->indpred == NIL)
4713  {
4714  vardata->statsTuple =
4716  ObjectIdGetDatum(index->indexoid),
4717  Int16GetDatum(pos + 1),
4718  BoolGetDatum(false));
4719  vardata->freefunc = ReleaseSysCache;
4720 
4721  if (HeapTupleIsValid(vardata->statsTuple))
4722  {
4723  /* Get index's table for permission check */
4724  RangeTblEntry *rte;
4725 
4726  rte = planner_rt_fetch(index->rel->relid, root);
4727  Assert(rte->rtekind == RTE_RELATION);
4728 
4729  /*
4730  * For simplicity, we insist on the whole
4731  * table being selectable, rather than trying
4732  * to identify which column(s) the index
4733  * depends on.
4734  */
4735  vardata->acl_ok =
4737  ACL_SELECT) == ACLCHECK_OK);
4738  }
4739  else
4740  {
4741  /* suppress leakproofness checks later */
4742  vardata->acl_ok = true;
4743  }
4744  }
4745  if (vardata->statsTuple)
4746  break;
4747  }
4748  indexpr_item = lnext(indexpr_item);
4749  }
4750  }
4751  if (vardata->statsTuple)
4752  break;
4753  }
4754  }
4755 }
#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:283
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:857
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4767
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:1733
#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:675
#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:936
#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 5445 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().

5446 {
5447  RelOptInfo *rel = NULL;
5448 
5449  switch (bms_membership(relids))
5450  {
5451  case BMS_EMPTY_SET:
5452  /* should not happen */
5453  break;
5454  case BMS_SINGLETON:
5455  rel = find_base_rel(root, bms_singleton_member(relids));
5456  break;
5457  case BMS_MULTIPLE:
5458  rel = find_join_rel(root, relids);
5459  break;
5460  }
5461 
5462  if (rel == NULL)
5463  elog(ERROR, "could not find RelOptInfo for given relids");
5464 
5465  return rel;
5466 }
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 6441 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().

6446 {
6447  IndexOptInfo *index = path->indexinfo;
6448  List *indexQuals = path->indexquals;
6449  List *indexOrderBys = path->indexorderbys;
6450  Cost indexStartupCost;
6451  Cost indexTotalCost;
6452  Selectivity indexSelectivity;
6453  double indexCorrelation;
6454  double numIndexPages;
6455  double numIndexTuples;
6456  double spc_random_page_cost;
6457  double num_sa_scans;
6458  double num_outer_scans;
6459  double num_scans;
6460  double qual_op_cost;
6461  double qual_arg_cost;
6462  List *selectivityQuals;
6463  ListCell *l;
6464 
6465  /*
6466  * If the index is partial, AND the index predicate with the explicitly
6467  * given indexquals to produce a more accurate idea of the index
6468  * selectivity.
6469  */
6470  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6471 
6472  /*
6473  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6474  * index scans that will be performed.
6475  */
6476  num_sa_scans = 1;
6477  foreach(l, indexQuals)
6478  {
6479  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6480 
6481  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6482  {
6483  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6484  int alength = estimate_array_length(lsecond(saop->args));
6485 
6486  if (alength > 1)
6487  num_sa_scans *= alength;
6488  }
6489  }
6490 
6491  /* Estimate the fraction of main-table tuples that will be visited */
6492  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6493  index->rel->relid,
6494  JOIN_INNER,
6495  NULL);
6496 
6497  /*
6498  * If caller didn't give us an estimate, estimate the number of index
6499  * tuples that will be visited. We do it in this rather peculiar-looking
6500  * way in order to get the right answer for partial indexes.
6501  */
6502  numIndexTuples = costs->numIndexTuples;
6503  if (numIndexTuples <= 0.0)
6504  {
6505  numIndexTuples = indexSelectivity * index->rel->tuples;
6506 
6507  /*
6508  * The above calculation counts all the tuples visited across all
6509  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6510  * average per-indexscan number, so adjust. This is a handy place to
6511  * round to integer, too. (If caller supplied tuple estimate, it's
6512  * responsible for handling these considerations.)
6513  */
6514  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6515  }
6516 
6517  /*
6518  * We can bound the number of tuples by the index size in any case. Also,
6519  * always estimate at least one tuple is touched, even when
6520  * indexSelectivity estimate is tiny.
6521  */
6522  if (numIndexTuples > index->tuples)
6523  numIndexTuples = index->tuples;
6524  if (numIndexTuples < 1.0)
6525  numIndexTuples = 1.0;
6526 
6527  /*
6528  * Estimate the number of index pages that will be retrieved.
6529  *
6530  * We use the simplistic method of taking a pro-rata fraction of the total
6531  * number of index pages. In effect, this counts only leaf pages and not
6532  * any overhead such as index metapage or upper tree levels.
6533  *
6534  * In practice access to upper index levels is often nearly free because
6535  * those tend to stay in cache under load; moreover, the cost involved is
6536  * highly dependent on index type. We therefore ignore such costs here
6537  * and leave it to the caller to add a suitable charge if needed.
6538  */
6539  if (index->pages > 1 && index->tuples > 1)
6540  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6541  else
6542  numIndexPages = 1.0;
6543 
6544  /* fetch estimated page cost for tablespace containing index */
6546  &spc_random_page_cost,
6547  NULL);
6548 
6549  /*
6550  * Now compute the disk access costs.
6551  *
6552  * The above calculations are all per-index-scan. However, if we are in a
6553  * nestloop inner scan, we can expect the scan to be repeated (with
6554  * different search keys) for each row of the outer relation. Likewise,
6555  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6556  * the potential for cache effects to reduce the number of disk page
6557  * fetches needed. We want to estimate the average per-scan I/O cost in
6558  * the presence of caching.
6559  *
6560  * We use the Mackert-Lohman formula (see costsize.c for details) to
6561  * estimate the total number of page fetches that occur. While this
6562  * wasn't what it was designed for, it seems a reasonable model anyway.
6563  * Note that we are counting pages not tuples anymore, so we take N = T =
6564  * index size, as if there were one "tuple" per page.
6565  */
6566  num_outer_scans = loop_count;
6567  num_scans = num_sa_scans * num_outer_scans;
6568 
6569  if (num_scans > 1)
6570  {
6571  double pages_fetched;
6572 
6573  /* total page fetches ignoring cache effects */
6574  pages_fetched = numIndexPages * num_scans;
6575 
6576  /* use Mackert and Lohman formula to adjust for cache effects */
6577  pages_fetched = index_pages_fetched(pages_fetched,
6578  index->pages,
6579  (double) index->pages,
6580  root);
6581 
6582  /*
6583  * Now compute the total disk access cost, and then report a pro-rated
6584  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6585  * since that's internal to the indexscan.)
6586  */
6587  indexTotalCost = (pages_fetched * spc_random_page_cost)
6588  / num_outer_scans;
6589  }
6590  else
6591  {
6592  /*
6593  * For a single index scan, we just charge spc_random_page_cost per
6594  * page touched.
6595  */
6596  indexTotalCost = numIndexPages * spc_random_page_cost;
6597  }
6598 
6599  /*
6600  * CPU cost: any complex expressions in the indexquals will need to be
6601  * evaluated once at the start of the scan to reduce them to runtime keys
6602  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6603  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6604  * indexqual operator. Because we have numIndexTuples as a per-scan
6605  * number, we have to multiply by num_sa_scans to get the correct result
6606  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6607  * ORDER BY expressions.
6608  *
6609  * Note: this neglects the possible costs of rechecking lossy operators.
6610  * Detecting that that might be needed seems more expensive than it's
6611  * worth, though, considering all the other inaccuracies here ...
6612  */
6613  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6614  orderby_operands_eval_cost(root, path);
6615  qual_op_cost = cpu_operator_cost *
6616  (list_length(indexQuals) + list_length(indexOrderBys));
6617 
6618  indexStartupCost = qual_arg_cost;
6619  indexTotalCost += qual_arg_cost;
6620  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6621 
6622  /*
6623  * Generic assumption about index correlation: there isn't any.
6624  */
6625  indexCorrelation = 0.0;
6626 
6627  /*
6628  * Return everything to caller.
6629  */
6630  costs->indexStartupCost = indexStartupCost;
6631  costs->indexTotalCost = indexTotalCost;
6632  costs->indexSelectivity = indexSelectivity;
6633  costs->indexCorrelation = indexCorrelation;
6634  costs->numIndexPages = numIndexPages;
6635  costs->numIndexTuples = numIndexTuples;
6636  costs->spc_random_page_cost = spc_random_page_cost;
6637  costs->num_sa_scans = num_sa_scans;
6638 }
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:6660
Oid reltablespace
Definition: relation.h:632
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6387
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:6412
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 5219 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().

5222 {
5223  bool have_data = false;
5224  RelOptInfo *rel = vardata->rel;
5225  RangeTblEntry *rte;
5226  ListCell *lc;
5227 
5228  /* No hope if no relation or it doesn't have indexes */
5229  if (rel == NULL || rel->indexlist == NIL)
5230  return false;
5231  /* If it has indexes it must be a plain relation */
5232  rte = root->simple_rte_array[rel->relid];
5233  Assert(rte->rtekind == RTE_RELATION);
5234 
5235  /* Search through the indexes to see if any match our problem */
5236  foreach(lc, rel->indexlist)
5237  {
5239  ScanDirection indexscandir;
5240 
5241  /* Ignore non-btree indexes */
5242  if (index->relam != BTREE_AM_OID)
5243  continue;
5244 
5245  /*
5246  * Ignore partial indexes --- we only want stats that cover the entire
5247  * relation.
5248  */
5249  if (index->indpred != NIL)
5250  continue;
5251 
5252  /*
5253  * The index list might include hypothetical indexes inserted by a
5254  * get_relation_info hook --- don't try to access them.
5255  */
5256  if (index->hypothetical)
5257  continue;
5258 
5259  /*
5260  * The first index column must match the desired variable and sort
5261  * operator --- but we can use a descending-order index.
5262  */
5263  if (!match_index_to_operand(vardata->var, 0, index))
5264  continue;
5265  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5266  {
5267  case BTLessStrategyNumber:
5268  if (index->reverse_sort[0])
5269  indexscandir = BackwardScanDirection;
5270  else
5271  indexscandir = ForwardScanDirection;
5272  break;
5274  if (index->reverse_sort[0])
5275  indexscandir = ForwardScanDirection;
5276  else
5277  indexscandir = BackwardScanDirection;
5278  break;
5279  default:
5280  /* index doesn't match the sortop */
5281  continue;
5282  }
5283 
5284  /*
5285  * Found a suitable index to extract data from. We'll need an EState
5286  * and a bunch of other infrastructure.
5287  */
5288  {
5289  EState *estate;
5290  ExprContext *econtext;
5291  MemoryContext tmpcontext;
5292  MemoryContext oldcontext;
5293  Relation heapRel;
5294  Relation indexRel;
5295  IndexInfo *indexInfo;
5296  TupleTableSlot *slot;
5297  int16 typLen;
5298  bool typByVal;
5299  ScanKeyData scankeys[1];
5300  IndexScanDesc index_scan;
5301  HeapTuple tup;
5303  bool isnull[INDEX_MAX_KEYS];
5304  SnapshotData SnapshotDirty;
5305 
5306  estate = CreateExecutorState();
5307  econtext = GetPerTupleExprContext(estate);
5308  /* Make sure any cruft is generated in the econtext's memory */
5309  tmpcontext = econtext->ecxt_per_tuple_memory;
5310  oldcontext = MemoryContextSwitchTo(tmpcontext);
5311 
5312  /*
5313  * Open the table and index so we can read from them. We should
5314  * already have at least AccessShareLock on the table, but not
5315  * necessarily on the index.
5316  */
5317  heapRel = heap_open(rte->relid, NoLock);
5318  indexRel = index_open(index->indexoid, AccessShareLock);
5319 
5320  /* extract index key information from the index's pg_index info */
5321  indexInfo = BuildIndexInfo(indexRel);
5322 
5323  /* some other stuff */
5324  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
5325  econtext->ecxt_scantuple = slot;
5326  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5327  InitDirtySnapshot(SnapshotDirty);
5328 
5329  /* set up an IS NOT NULL scan key so that we ignore nulls */
5330  ScanKeyEntryInitialize(&scankeys[0],
5332  1, /* index col to scan */
5333  InvalidStrategy, /* no strategy */
5334  InvalidOid, /* no strategy subtype */
5335  InvalidOid, /* no collation */
5336  InvalidOid, /* no reg proc for this */
5337  (Datum) 0); /* constant */
5338 
5339  have_data = true;
5340 
5341  /* If min is requested ... */
5342  if (min)
5343  {
5344  /*
5345  * In principle, we should scan the index with our current
5346  * active snapshot, which is the best approximation we've got
5347  * to what the query will see when executed. But that won't
5348  * be exact if a new snap is taken before running the query,
5349  * and it can be very expensive if a lot of uncommitted rows
5350  * exist at the end of the index (because we'll laboriously
5351  * fetch each one and reject it). What seems like a good
5352  * compromise is to use SnapshotDirty. That will accept
5353  * uncommitted rows, and thus avoid fetching multiple heap
5354  * tuples in this scenario. On the other hand, it will reject
5355  * known-dead rows, and thus not give a bogus answer when the
5356  * extreme value has been deleted; that case motivates not
5357  * using SnapshotAny here.
5358  */
5359  index_scan = index_beginscan(heapRel, indexRel, &SnapshotDirty,
5360  1, 0);
5361  index_rescan(index_scan, scankeys, 1, NULL, 0);
5362 
5363  /* Fetch first tuple in sortop's direction */
5364  if ((tup = index_getnext(index_scan,
5365  indexscandir)) != NULL)
5366  {
5367  /* Extract the index column values from the heap tuple */
5368  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5369  FormIndexDatum(indexInfo, slot, estate,
5370  values, isnull);
5371 
5372  /* Shouldn't have got a null, but be careful */
5373  if (isnull[0])
5374  elog(ERROR, "found unexpected null value in index \"%s\"",
5375  RelationGetRelationName(indexRel));
5376 
5377  /* Copy the index column value out to caller's context */
5378  MemoryContextSwitchTo(oldcontext);
5379  *min = datumCopy(values[0], typByVal, typLen);
5380  MemoryContextSwitchTo(tmpcontext);
5381  }
5382  else
5383  have_data = false;
5384 
5385  index_endscan(index_scan);
5386  }
5387 
5388  /* If max is requested, and we didn't find the index is empty */
5389  if (max && have_data)
5390  {
5391  index_scan = index_beginscan(heapRel, indexRel, &SnapshotDirty,
5392  1, 0);
5393  index_rescan(index_scan, scankeys, 1, NULL, 0);
5394 
5395  /* Fetch first tuple in reverse direction */
5396  if ((tup = index_getnext(index_scan,
5397  -indexscandir)) != NULL)
5398  {
5399  /* Extract the index column values from the heap tuple */
5400  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5401  FormIndexDatum(indexInfo, slot, estate,
5402  values, isnull);
5403 
5404  /* Shouldn't have got a null, but be careful */
5405  if (isnull[0])
5406  elog(ERROR, "found unexpected null value in index \"%s\"",
5407  RelationGetRelationName(indexRel));
5408 
5409  /* Copy the index column value out to caller's context */
5410  MemoryContextSwitchTo(oldcontext);
5411  *max = datumCopy(values[0], typByVal, typLen);
5412  MemoryContextSwitchTo(tmpcontext);
5413  }
5414  else
5415  have_data = false;
5416 
5417  index_endscan(index_scan);
5418  }
5419 
5420  /* Clean everything up */
5422 
5423  index_close(indexRel, AccessShareLock);
5424  heap_close(heapRel, NoLock);
5425 
5426  MemoryContextSwitchTo(oldcontext);
5427  FreeExecutorState(estate);
5428 
5429  /* And we're done */
5430  break;
5431  }
5432  }
5433 
5434  return have_data;
5435 }
signed short int16
Definition: c.h:255
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1765
#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:1640
Definition: type.h:89
void FreeExecutorState(EState *estate)
Definition: execUtils.c:178
#define GetPerTupleExprContext(estate)
Definition: executor.h:456
#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:1284
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:675
#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:936
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 4494 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().

4497 {
4498  Node *left,
4499  *right;
4500 
4501  if (list_length(args) != 2)
4502  elog(ERROR, "join operator should take two arguments");
4503 
4504  left = (Node *) linitial(args);
4505  right = (Node *) lsecond(args);
4506 
4507  examine_variable(root, left, 0, vardata1);
4508  examine_variable(root, right, 0, vardata2);
4509 
4510  if (vardata1->rel &&
4511  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4512  *join_is_reversed = true; /* var1 is on RHS */
4513  else if (vardata2->rel &&
4514  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4515  *join_is_reversed = true; /* var2 is on LHS */
4516  else
4517  *join_is_reversed = false;
4518 }
RelOptInfo * rel
Definition: selfuncs.h:70
Definition: nodes.h:509
#define lsecond(l)
Definition: pg_list.h:116