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/snapmgr.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, bool iseq, 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, bool iseq, VariableStatData *vardata, Datum constval, Oid consttype)
 
double mcv_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Datum constval, bool varonleft, double *sumcommonp)
 
double histogram_selectivity (VariableStatData *vardata, FmgrInfo *opproc, Datum constval, bool varonleft, int min_hist_size, int n_skip, int *hist_size)
 
static Datum scalarineqsel_wrapper (PG_FUNCTION_ARGS, bool isgt, bool iseq)
 
Datum scalarltsel (PG_FUNCTION_ARGS)
 
Datum scalarlesel (PG_FUNCTION_ARGS)
 
Datum scalargtsel (PG_FUNCTION_ARGS)
 
Datum scalargesel (PG_FUNCTION_ARGS)
 
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 scalarlejoinsel (PG_FUNCTION_ARGS)
 
Datum scalargtjoinsel (PG_FUNCTION_ARGS)
 
Datum scalargejoinsel (PG_FUNCTION_ARGS)
 
static double patternjoinsel (PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 
Datum regexeqjoinsel (PG_FUNCTION_ARGS)
 
Datum icregexeqjoinsel (PG_FUNCTION_ARGS)
 
Datum likejoinsel (PG_FUNCTION_ARGS)
 
Datum iclikejoinsel (PG_FUNCTION_ARGS)
 
Datum regexnejoinsel (PG_FUNCTION_ARGS)
 
Datum icregexnejoinsel (PG_FUNCTION_ARGS)
 
Datum nlikejoinsel (PG_FUNCTION_ARGS)
 
Datum icnlikejoinsel (PG_FUNCTION_ARGS)
 
void mergejoinscansel (PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
 
static Listadd_unique_group_var (PlannerInfo *root, List *varinfos, Node *var, VariableStatData *vardata)
 
double estimate_num_groups (PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
 
void estimate_hash_bucket_stats (PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
 
bool get_restriction_variable (PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
 
void get_join_variables (PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
 
void examine_variable (PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
 
bool statistic_proc_security_check (VariableStatData *vardata, Oid func_oid)
 
double get_variable_numdistinct (VariableStatData *vardata, bool *isdefault)
 
static int pattern_char_isalpha (char c, bool is_multibyte, pg_locale_t locale, bool locale_is_c)
 
static Pattern_Prefix_Status like_fixed_prefix (Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
 
static Pattern_Prefix_Status regex_fixed_prefix (Const *patt_const, bool case_insensitive, Oid collation, Const **prefix_const, Selectivity *rest_selec)
 
Pattern_Prefix_Status pattern_fixed_prefix (Const *patt, Pattern_Type ptype, Oid collation, Const **prefix, Selectivity *rest_selec)
 
static Selectivity regex_selectivity_sub (const char *patt, int pattlen, bool case_insensitive)
 
static bool byte_increment (unsigned char *ptr, int len)
 
Constmake_greater_string (const Const *str_const, FmgrInfo *ltproc, Oid collation)
 
Listdeconstruct_indexquals (IndexPath *path)
 
static Cost other_operands_eval_cost (PlannerInfo *root, List *qinfos)
 
static Cost orderby_operands_eval_cost (PlannerInfo *root, IndexPath *path)
 
void genericcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
 
void btcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void hashcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void gistcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void spgcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
static bool gincost_pattern (IndexOptInfo *index, int indexcol, Oid clause_op, Datum query, GinQualCounts *counts)
 
static bool gincost_opexpr (PlannerInfo *root, IndexOptInfo *index, IndexQualInfo *qinfo, GinQualCounts *counts)
 
static bool gincost_scalararrayopexpr (PlannerInfo *root, IndexOptInfo *index, IndexQualInfo *qinfo, double numIndexEntries, GinQualCounts *counts)
 
void gincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 
void brincostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
 

Variables

get_relation_stats_hook_type get_relation_stats_hook = NULL
 
get_index_stats_hook_type get_index_stats_hook = NULL
 

Macro Definition Documentation

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

Definition at line 5981 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity_sub().

#define CHAR_RANGE_SEL   0.25

Definition at line 5980 of file selfuncs.c.

Referenced by regex_selectivity_sub().

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

Definition at line 5979 of file selfuncs.c.

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

#define FULL_WILDCARD_SEL   5.0

Definition at line 5982 of file selfuncs.c.

Referenced by like_selectivity(), and regex_selectivity().

#define PARTIAL_WILDCARD_SEL   2.0

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

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

Referenced by btcostestimate(), and genericcostestimate().

6794 {
6795  List *predExtraQuals = NIL;
6796  ListCell *lc;
6797 
6798  if (index->indpred == NIL)
6799  return indexQuals;
6800 
6801  foreach(lc, index->indpred)
6802  {
6803  Node *predQual = (Node *) lfirst(lc);
6804  List *oneQual = list_make1(predQual);
6805 
6806  if (!predicate_implied_by(oneQual, indexQuals, false))
6807  predExtraQuals = list_concat(predExtraQuals, oneQual);
6808  }
6809  /* list_concat avoids modifying the passed-in indexQuals list */
6810  return list_concat(predExtraQuals, indexQuals);
6811 }
#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:510
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:742
Definition: pg_list.h:45
static List* add_unique_group_var ( PlannerInfo root,
List varinfos,
Node var,
VariableStatData vardata 
)
static

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

3244 {
3245  GroupVarInfo *varinfo;
3246  double ndistinct;
3247  bool isdefault;
3248  ListCell *lc;
3249 
3250  ndistinct = get_variable_numdistinct(vardata, &isdefault);
3251 
3252  /* cannot use foreach here because of possible list_delete */
3253  lc = list_head(varinfos);
3254  while (lc)
3255  {
3256  varinfo = (GroupVarInfo *) lfirst(lc);
3257 
3258  /* must advance lc before list_delete possibly pfree's it */
3259  lc = lnext(lc);
3260 
3261  /* Drop exact duplicates */
3262  if (equal(var, varinfo->var))
3263  return varinfos;
3264 
3265  /*
3266  * Drop known-equal vars, but only if they belong to different
3267  * relations (see comments for estimate_num_groups)
3268  */
3269  if (vardata->rel != varinfo->rel &&
3270  exprs_known_equal(root, var, varinfo->var))
3271  {
3272  if (varinfo->ndistinct <= ndistinct)
3273  {
3274  /* Keep older item, forget new one */
3275  return varinfos;
3276  }
3277  else
3278  {
3279  /* Delete the older item */
3280  varinfos = list_delete_ptr(varinfos, varinfo);
3281  }
3282  }
3283  }
3284 
3285  varinfo = (GroupVarInfo *) palloc(sizeof(GroupVarInfo));
3286 
3287  varinfo->var = var;
3288  varinfo->rel = vardata->rel;
3289  varinfo->ndistinct = ndistinct;
3290  varinfos = lappend(varinfos, varinfo);
3291  return varinfos;
3292 }
bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2)
Definition: equivclass.c:1983
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2972
RelOptInfo * rel
Definition: selfuncs.h:70
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
double ndistinct
Definition: selfuncs.c:3238
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5070
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
Node * var
Definition: selfuncs.c:3236
#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:848
RelOptInfo * rel
Definition: selfuncs.c:3237
Selectivity booltestsel ( PlannerInfo root,
BoolTestType  booltesttype,
Node arg,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

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

1583 {
1584  VariableStatData vardata;
1585  double selec;
1586 
1587  examine_variable(root, arg, varRelid, &vardata);
1588 
1589  if (HeapTupleIsValid(vardata.statsTuple))
1590  {
1591  Form_pg_statistic stats;
1592  double freq_null;
1593  AttStatsSlot sslot;
1594 
1595  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
1596  freq_null = stats->stanullfrac;
1597 
1598  if (get_attstatsslot(&sslot, vardata.statsTuple,
1601  && sslot.nnumbers > 0)
1602  {
1603  double freq_true;
1604  double freq_false;
1605 
1606  /*
1607  * Get first MCV frequency and derive frequency for true.
1608  */
1609  if (DatumGetBool(sslot.values[0]))
1610  freq_true = sslot.numbers[0];
1611  else
1612  freq_true = 1.0 - sslot.numbers[0] - freq_null;
1613 
1614  /*
1615  * Next derive frequency for false. Then use these as appropriate
1616  * to derive frequency for each case.
1617  */
1618  freq_false = 1.0 - freq_true - freq_null;
1619 
1620  switch (booltesttype)
1621  {
1622  case IS_UNKNOWN:
1623  /* select only NULL values */
1624  selec = freq_null;
1625  break;
1626  case IS_NOT_UNKNOWN:
1627  /* select non-NULL values */
1628  selec = 1.0 - freq_null;
1629  break;
1630  case IS_TRUE:
1631  /* select only TRUE values */
1632  selec = freq_true;
1633  break;
1634  case IS_NOT_TRUE:
1635  /* select non-TRUE values */
1636  selec = 1.0 - freq_true;
1637  break;
1638  case IS_FALSE:
1639  /* select only FALSE values */
1640  selec = freq_false;
1641  break;
1642  case IS_NOT_FALSE:
1643  /* select non-FALSE values */
1644  selec = 1.0 - freq_false;
1645  break;
1646  default:
1647  elog(ERROR, "unrecognized booltesttype: %d",
1648  (int) booltesttype);
1649  selec = 0.0; /* Keep compiler quiet */
1650  break;
1651  }
1652 
1653  free_attstatsslot(&sslot);
1654  }
1655  else
1656  {
1657  /*
1658  * No most-common-value info available. Still have null fraction
1659  * information, so use it for IS [NOT] UNKNOWN. Otherwise adjust
1660  * for null fraction and assume a 50-50 split of TRUE and FALSE.
1661  */
1662  switch (booltesttype)
1663  {
1664  case IS_UNKNOWN:
1665  /* select only NULL values */
1666  selec = freq_null;
1667  break;
1668  case IS_NOT_UNKNOWN:
1669  /* select non-NULL values */
1670  selec = 1.0 - freq_null;
1671  break;
1672  case IS_TRUE:
1673  case IS_FALSE:
1674  /* Assume we select half of the non-NULL values */
1675  selec = (1.0 - freq_null) / 2.0;
1676  break;
1677  case IS_NOT_TRUE:
1678  case IS_NOT_FALSE:
1679  /* Assume we select NULLs plus half of the non-NULLs */
1680  /* equiv. to freq_null + (1.0 - freq_null) / 2.0 */
1681  selec = (freq_null + 1.0) / 2.0;
1682  break;
1683  default:
1684  elog(ERROR, "unrecognized booltesttype: %d",
1685  (int) booltesttype);
1686  selec = 0.0; /* Keep compiler quiet */
1687  break;
1688  }
1689  }
1690  }
1691  else
1692  {
1693  /*
1694  * If we can't get variable statistics for the argument, perhaps
1695  * clause_selectivity can do something with it. We ignore the
1696  * possibility of a NULL value when using clause_selectivity, and just
1697  * assume the value is either TRUE or FALSE.
1698  */
1699  switch (booltesttype)
1700  {
1701  case IS_UNKNOWN:
1702  selec = DEFAULT_UNK_SEL;
1703  break;
1704  case IS_NOT_UNKNOWN:
1705  selec = DEFAULT_NOT_UNK_SEL;
1706  break;
1707  case IS_TRUE:
1708  case IS_NOT_FALSE:
1709  selec = (double) clause_selectivity(root, arg,
1710  varRelid,
1711  jointype, sjinfo);
1712  break;
1713  case IS_FALSE:
1714  case IS_NOT_TRUE:
1715  selec = 1.0 - (double) clause_selectivity(root, arg,
1716  varRelid,
1717  jointype, sjinfo);
1718  break;
1719  default:
1720  elog(ERROR, "unrecognized booltesttype: %d",
1721  (int) booltesttype);
1722  selec = 0.0; /* Keep compiler quiet */
1723  break;
1724  }
1725  }
1726 
1727  ReleaseVariableStats(vardata);
1728 
1729  /* result should be in range, but make sure... */
1730  CLAMP_PROBABILITY(selec);
1731 
1732  return (Selectivity) selec;
1733 }
#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:640
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:574
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:4663
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 1542 of file selfuncs.c.

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

Referenced by clause_selectivity().

1543 {
1544  VariableStatData vardata;
1545  double selec;
1546 
1547  examine_variable(root, arg, varRelid, &vardata);
1548  if (HeapTupleIsValid(vardata.statsTuple))
1549  {
1550  /*
1551  * A boolean variable V is equivalent to the clause V = 't', so we
1552  * compute the selectivity as if that is what we have.
1553  */
1554  selec = var_eq_const(&vardata, BooleanEqualOperator,
1555  BoolGetDatum(true), false, true, false);
1556  }
1557  else if (is_funcclause(arg))
1558  {
1559  /*
1560  * If we have no stats and it's a function call, estimate 0.3333333.
1561  * This seems a pretty unprincipled choice, but Postgres has been
1562  * using that estimate for function calls since 1992. The hoariness
1563  * of this behavior suggests that we should not be in too much hurry
1564  * to use another value.
1565  */
1566  selec = 0.3333333;
1567  }
1568  else
1569  {
1570  /* Otherwise, the default estimate is 0.5 */
1571  selec = 0.5;
1572  }
1573  ReleaseVariableStats(vardata);
1574  return selec;
1575 }
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:297
#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:4663
#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 7895 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, 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().

7899 {
7900  IndexOptInfo *index = path->indexinfo;
7901  List *indexQuals = path->indexquals;
7902  double numPages = index->pages;
7903  RelOptInfo *baserel = index->rel;
7904  RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
7905  List *qinfos;
7906  Cost spc_seq_page_cost;
7907  Cost spc_random_page_cost;
7908  double qual_arg_cost;
7909  double qualSelectivity;
7910  BrinStatsData statsData;
7911  double indexRanges;
7912  double minimalRanges;
7913  double estimatedRanges;
7914  double selec;
7915  Relation indexRel;
7916  ListCell *l;
7917  VariableStatData vardata;
7918 
7919  Assert(rte->rtekind == RTE_RELATION);
7920 
7921  /* fetch estimated page cost for the tablespace containing the index */
7923  &spc_random_page_cost,
7924  &spc_seq_page_cost);
7925 
7926  /*
7927  * Obtain some data from the index itself.
7928  */
7929  indexRel = index_open(index->indexoid, AccessShareLock);
7930  brinGetStats(indexRel, &statsData);
7931  index_close(indexRel, AccessShareLock);
7932 
7933  /*
7934  * Compute index correlation
7935  *
7936  * Because we can use all index quals equally when scanning, we can use
7937  * the largest correlation (in absolute value) among columns used by the
7938  * query. Start at zero, the worst possible case. If we cannot find any
7939  * correlation statistics, we will keep it as 0.
7940  */
7941  *indexCorrelation = 0;
7942 
7943  qinfos = deconstruct_indexquals(path);
7944  foreach(l, qinfos)
7945  {
7946  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(l);
7947  AttrNumber attnum = index->indexkeys[qinfo->indexcol];
7948 
7949  /* attempt to lookup stats in relation for this index column */
7950  if (attnum != 0)
7951  {
7952  /* Simple variable -- look to stats for the underlying table */
7954  (*get_relation_stats_hook) (root, rte, attnum, &vardata))
7955  {
7956  /*
7957  * The hook took control of acquiring a stats tuple. If it
7958  * did supply a tuple, it'd better have supplied a freefunc.
7959  */
7960  if (HeapTupleIsValid(vardata.statsTuple) && !vardata.freefunc)
7961  elog(ERROR,
7962  "no function provided to release variable stats with");
7963  }
7964  else
7965  {
7966  vardata.statsTuple =
7968  ObjectIdGetDatum(rte->relid),
7969  Int16GetDatum(attnum),
7970  BoolGetDatum(false));
7971  vardata.freefunc = ReleaseSysCache;
7972  }
7973  }
7974  else
7975  {
7976  /*
7977  * Looks like we've found an expression column in the index. Let's
7978  * see if there's any stats for it.
7979  */
7980 
7981  /* get the attnum from the 0-based index. */
7982  attnum = qinfo->indexcol + 1;
7983 
7984  if (get_index_stats_hook &&
7985  (*get_index_stats_hook) (root, index->indexoid, attnum, &vardata))
7986  {
7987  /*
7988  * The hook took control of acquiring a stats tuple. If it
7989  * did supply a tuple, it'd better have supplied a freefunc.
7990  */
7991  if (HeapTupleIsValid(vardata.statsTuple) &&
7992  !vardata.freefunc)
7993  elog(ERROR, "no function provided to release variable stats with");
7994  }
7995  else
7996  {
7998  ObjectIdGetDatum(index->indexoid),
7999  Int16GetDatum(attnum),
8000  BoolGetDatum(false));
8001  vardata.freefunc = ReleaseSysCache;
8002  }
8003  }
8004 
8005  if (HeapTupleIsValid(vardata.statsTuple))
8006  {
8007  AttStatsSlot sslot;
8008 
8009  if (get_attstatsslot(&sslot, vardata.statsTuple,
8012  {
8013  double varCorrelation = 0.0;
8014 
8015  if (sslot.nnumbers > 0)
8016  varCorrelation = Abs(sslot.numbers[0]);
8017 
8018  if (varCorrelation > *indexCorrelation)
8019  *indexCorrelation = varCorrelation;
8020 
8021  free_attstatsslot(&sslot);
8022  }
8023  }
8024 
8025  ReleaseVariableStats(vardata);
8026  }
8027 
8028  qualSelectivity = clauselist_selectivity(root, indexQuals,
8029  baserel->relid,
8030  JOIN_INNER, NULL);
8031 
8032  /* work out the actual number of ranges in the index */
8033  indexRanges = Max(ceil((double) baserel->pages / statsData.pagesPerRange),
8034  1.0);
8035 
8036  /*
8037  * Now calculate the minimum possible ranges we could match with if all of
8038  * the rows were in the perfect order in the table's heap.
8039  */
8040  minimalRanges = ceil(indexRanges * qualSelectivity);
8041 
8042  /*
8043  * Now estimate the number of ranges that we'll touch by using the
8044  * indexCorrelation from the stats. Careful not to divide by zero (note
8045  * we're using the absolute value of the correlation).
8046  */
8047  if (*indexCorrelation < 1.0e-10)
8048  estimatedRanges = indexRanges;
8049  else
8050  estimatedRanges = Min(minimalRanges / *indexCorrelation, indexRanges);
8051 
8052  /* we expect to visit this portion of the table */
8053  selec = estimatedRanges / indexRanges;
8054 
8055  CLAMP_PROBABILITY(selec);
8056 
8057  *indexSelectivity = selec;
8058 
8059  /*
8060  * Compute the index qual costs, much as in genericcostestimate, to add to
8061  * the index costs.
8062  */
8063  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
8064  orderby_operands_eval_cost(root, path);
8065 
8066  /*
8067  * Compute the startup cost as the cost to read the whole revmap
8068  * sequentially, including the cost to execute the index quals.
8069  */
8070  *indexStartupCost =
8071  spc_seq_page_cost * statsData.revmapNumPages * loop_count;
8072  *indexStartupCost += qual_arg_cost;
8073 
8074  /*
8075  * To read a BRIN index there might be a bit of back and forth over
8076  * regular pages, as revmap might point to them out of sequential order;
8077  * calculate the total cost as reading the whole index in random order.
8078  */
8079  *indexTotalCost = *indexStartupCost +
8080  spc_random_page_cost * (numPages - statsData.revmapNumPages) * loop_count;
8081 
8082  /*
8083  * Charge a small amount per range tuple which we expect to match to. This
8084  * is meant to reflect the costs of manipulating the bitmap. The BRIN scan
8085  * will set a bit for each page in the range when we find a matching
8086  * range, so we must multiply the charge by the number of pages in the
8087  * range.
8088  */
8089  *indexTotalCost += 0.1 * cpu_operator_cost * estimatedRanges *
8090  statsData.pagesPerRange;
8091 
8092  *indexPages = index->pages;
8093 }
IndexOptInfo * indexinfo
Definition: relation.h:1119
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
#define Min(x, y)
Definition: c.h:812
#define Int16GetDatum(X)
Definition: postgres.h:457
#define AccessShareLock
Definition: lockdefs.h:36
Oid reltablespace
Definition: relation.h:720
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6520
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6425
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6545
#define Abs(x)
Definition: c.h:818
Definition: type.h:89
BlockNumber pages
Definition: relation.h:724
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
List * indexquals
Definition: relation.h:1121
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
#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:155
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:613
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#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:806
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
BlockNumber pages
Definition: relation.h:624
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
RTEKind rtekind
Definition: parsenodes.h:945
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
e
Definition: preproc-init.c:82
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
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:641
void brinGetStats(Relation index, BrinStatsData *stats)
Definition: brin.c:1066
BlockNumber revmapNumPages
Definition: brin.h:35
void free_attstatsslot(AttStatsSlot *sslot)
Definition: lsyscache.c:3011
void btcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
Cost indexStartupCost,
Cost indexTotalCost,
Selectivity indexSelectivity,
double *  indexCorrelation,
double *  indexPages 
)

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

6819 {
6820  IndexOptInfo *index = path->indexinfo;
6821  List *qinfos;
6822  GenericCosts costs;
6823  Oid relid;
6824  AttrNumber colnum;
6825  VariableStatData vardata;
6826  double numIndexTuples;
6827  Cost descentCost;
6828  List *indexBoundQuals;
6829  int indexcol;
6830  bool eqQualHere;
6831  bool found_saop;
6832  bool found_is_null_op;
6833  double num_sa_scans;
6834  ListCell *lc;
6835 
6836  /* Do preliminary analysis of indexquals */
6837  qinfos = deconstruct_indexquals(path);
6838 
6839  /*
6840  * For a btree scan, only leading '=' quals plus inequality quals for the
6841  * immediately next attribute contribute to index selectivity (these are
6842  * the "boundary quals" that determine the starting and stopping points of
6843  * the index scan). Additional quals can suppress visits to the heap, so
6844  * it's OK to count them in indexSelectivity, but they should not count
6845  * for estimating numIndexTuples. So we must examine the given indexquals
6846  * to find out which ones count as boundary quals. We rely on the
6847  * knowledge that they are given in index column order.
6848  *
6849  * For a RowCompareExpr, we consider only the first column, just as
6850  * rowcomparesel() does.
6851  *
6852  * If there's a ScalarArrayOpExpr in the quals, we'll actually perform N
6853  * index scans not one, but the ScalarArrayOpExpr's operator can be
6854  * considered to act the same as it normally does.
6855  */
6856  indexBoundQuals = NIL;
6857  indexcol = 0;
6858  eqQualHere = false;
6859  found_saop = false;
6860  found_is_null_op = false;
6861  num_sa_scans = 1;
6862  foreach(lc, qinfos)
6863  {
6864  IndexQualInfo *qinfo = (IndexQualInfo *) lfirst(lc);
6865  RestrictInfo *rinfo = qinfo->rinfo;
6866  Expr *clause = rinfo->clause;
6867  Oid clause_op;
6868  int op_strategy;
6869 
6870  if (indexcol != qinfo->indexcol)
6871  {
6872  /* Beginning of a new column's quals */
6873  if (!eqQualHere)
6874  break; /* done if no '=' qual for indexcol */
6875  eqQualHere = false;
6876  indexcol++;
6877  if (indexcol != qinfo->indexcol)
6878  break; /* no quals at all for indexcol */
6879  }
6880 
6881  if (IsA(clause, ScalarArrayOpExpr))
6882  {
6883  int alength = estimate_array_length(qinfo->other_operand);
6884 
6885  found_saop = true;
6886  /* count up number of SA scans induced by indexBoundQuals only */
6887  if (alength > 1)
6888  num_sa_scans *= alength;
6889  }
6890  else if (IsA(clause, NullTest))
6891  {
6892  NullTest *nt = (NullTest *) clause;
6893 
6894  if (nt->nulltesttype == IS_NULL)
6895  {
6896  found_is_null_op = true;
6897  /* IS NULL is like = for selectivity determination purposes */
6898  eqQualHere = true;
6899  }
6900  }
6901 
6902  /*
6903  * We would need to commute the clause_op if not varonleft, except
6904  * that we only care if it's equality or not, so that refinement is
6905  * unnecessary.
6906  */
6907  clause_op = qinfo->clause_op;
6908 
6909  /* check for equality operator */
6910  if (OidIsValid(clause_op))
6911  {
6912  op_strategy = get_op_opfamily_strategy(clause_op,
6913  index->opfamily[indexcol]);
6914  Assert(op_strategy != 0); /* not a member of opfamily?? */
6915  if (op_strategy == BTEqualStrategyNumber)
6916  eqQualHere = true;
6917  }
6918 
6919  indexBoundQuals = lappend(indexBoundQuals, rinfo);
6920  }
6921 
6922  /*
6923  * If index is unique and we found an '=' clause for each column, we can
6924  * just assume numIndexTuples = 1 and skip the expensive
6925  * clauselist_selectivity calculations. However, a ScalarArrayOp or
6926  * NullTest invalidates that theory, even though it sets eqQualHere.
6927  */
6928  if (index->unique &&
6929  indexcol == index->ncolumns - 1 &&
6930  eqQualHere &&
6931  !found_saop &&
6932  !found_is_null_op)
6933  numIndexTuples = 1.0;
6934  else
6935  {
6936  List *selectivityQuals;
6937  Selectivity btreeSelectivity;
6938 
6939  /*
6940  * If the index is partial, AND the index predicate with the
6941  * index-bound quals to produce a more accurate idea of the number of
6942  * rows covered by the bound conditions.
6943  */
6944  selectivityQuals = add_predicate_to_quals(index, indexBoundQuals);
6945 
6946  btreeSelectivity = clauselist_selectivity(root, selectivityQuals,
6947  index->rel->relid,
6948  JOIN_INNER,
6949  NULL);
6950  numIndexTuples = btreeSelectivity * index->rel->tuples;
6951 
6952  /*
6953  * As in genericcostestimate(), we have to adjust for any
6954  * ScalarArrayOpExpr quals included in indexBoundQuals, and then round
6955  * to integer.
6956  */
6957  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6958  }
6959 
6960  /*
6961  * Now do generic index cost estimation.
6962  */
6963  MemSet(&costs, 0, sizeof(costs));
6964  costs.numIndexTuples = numIndexTuples;
6965 
6966  genericcostestimate(root, path, loop_count, qinfos, &costs);
6967 
6968  /*
6969  * Add a CPU-cost component to represent the costs of initial btree
6970  * descent. We don't charge any I/O cost for touching upper btree levels,
6971  * since they tend to stay in cache, but we still have to do about log2(N)
6972  * comparisons to descend a btree of N leaf tuples. We charge one
6973  * cpu_operator_cost per comparison.
6974  *
6975  * If there are ScalarArrayOpExprs, charge this once per SA scan. The
6976  * ones after the first one are not startup cost so far as the overall
6977  * plan is concerned, so add them only to "total" cost.
6978  */
6979  if (index->tuples > 1) /* avoid computing log(0) */
6980  {
6981  descentCost = ceil(log(index->tuples) / log(2.0)) * cpu_operator_cost;
6982  costs.indexStartupCost += descentCost;
6983  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6984  }
6985 
6986  /*
6987  * Even though we're not charging I/O cost for touching upper btree pages,
6988  * it's still reasonable to charge some CPU cost per page descended
6989  * through. Moreover, if we had no such charge at all, bloated indexes
6990  * would appear to have the same search cost as unbloated ones, at least
6991  * in cases where only a single leaf page is expected to be visited. This
6992  * cost is somewhat arbitrarily set at 50x cpu_operator_cost per page
6993  * touched. The number of such pages is btree tree height plus one (ie,
6994  * we charge for the leaf page too). As above, charge once per SA scan.
6995  */
6996  descentCost = (index->tree_height + 1) * 50.0 * cpu_operator_cost;
6997  costs.indexStartupCost += descentCost;
6998  costs.indexTotalCost += costs.num_sa_scans * descentCost;
6999 
7000  /*
7001  * If we can get an estimate of the first column's ordering correlation C
7002  * from pg_statistic, estimate the index correlation as C for a
7003  * single-column index, or C * 0.75 for multiple columns. (The idea here
7004  * is that multiple columns dilute the importance of the first column's
7005  * ordering, but don't negate it entirely. Before 8.0 we divided the
7006  * correlation by the number of columns, but that seems too strong.)
7007  */
7008  MemSet(&vardata, 0, sizeof(vardata));
7009 
7010  if (index->indexkeys[0] != 0)
7011  {
7012  /* Simple variable --- look to stats for the underlying table */
7013  RangeTblEntry *rte = planner_rt_fetch(index->rel->relid, root);
7014 
7015  Assert(rte->rtekind == RTE_RELATION);
7016  relid = rte->relid;
7017  Assert(relid != InvalidOid);
7018  colnum = index->indexkeys[0];
7019 
7021  (*get_relation_stats_hook) (root, rte, colnum, &vardata))
7022  {
7023  /*
7024  * The hook took control of acquiring a stats tuple. If it did
7025  * supply a tuple, it'd better have supplied a freefunc.
7026  */
7027  if (HeapTupleIsValid(vardata.statsTuple) &&
7028  !vardata.freefunc)
7029  elog(ERROR, "no function provided to release variable stats with");
7030  }
7031  else
7032  {
7034  ObjectIdGetDatum(relid),
7035  Int16GetDatum(colnum),
7036  BoolGetDatum(rte->inh));
7037  vardata.freefunc = ReleaseSysCache;
7038  }
7039  }
7040  else
7041  {
7042  /* Expression --- maybe there are stats for the index itself */
7043  relid = index->indexoid;
7044  colnum = 1;
7045 
7046  if (get_index_stats_hook &&
7047  (*get_index_stats_hook) (root, relid, colnum, &vardata))
7048  {
7049  /*
7050  * The hook took control of acquiring a stats tuple. If it did
7051  * supply a tuple, it'd better have supplied a freefunc.
7052  */
7053  if (HeapTupleIsValid(vardata.statsTuple) &&
7054  !vardata.freefunc)
7055  elog(ERROR, "no function provided to release variable stats with");
7056  }
7057  else
7058  {
7060  ObjectIdGetDatum(relid),
7061  Int16GetDatum(colnum),
7062  BoolGetDatum(false));
7063  vardata.freefunc = ReleaseSysCache;
7064  }
7065  }
7066 
7067  if (HeapTupleIsValid(vardata.statsTuple))
7068  {
7069  Oid sortop;
7070  AttStatsSlot sslot;
7071 
7072  sortop = get_opfamily_member(index->opfamily[0],
7073  index->opcintype[0],
7074  index->opcintype[0],
7076  if (OidIsValid(sortop) &&
7077  get_attstatsslot(&sslot, vardata.statsTuple,
7080  {
7081  double varCorrelation;
7082 
7083  Assert(sslot.nnumbers == 1);
7084  varCorrelation = sslot.numbers[0];
7085 
7086  if (index->reverse_sort[0])
7087  varCorrelation = -varCorrelation;
7088 
7089  if (index->ncolumns > 1)
7090  costs.indexCorrelation = varCorrelation * 0.75;
7091  else
7092  costs.indexCorrelation = varCorrelation;
7093 
7094  free_attstatsslot(&sslot);
7095  }
7096  }
7097 
7098  ReleaseVariableStats(vardata);
7099 
7100  *indexStartupCost = costs.indexStartupCost;
7101  *indexTotalCost = costs.indexTotalCost;
7102  *indexSelectivity = costs.indexSelectivity;
7103  *indexCorrelation = costs.indexCorrelation;
7104  *indexPages = costs.numIndexPages;
7105 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
IndexOptInfo * indexinfo
Definition: relation.h:1119
HeapTuple statsTuple
Definition: selfuncs.h:71
int nnumbers
Definition: lsyscache.h:53
double tuples
Definition: relation.h:625
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6793
#define Int16GetDatum(X)
Definition: postgres.h:457
#define MemSet(start, val, len)
Definition: c.h:863
double Selectivity
Definition: nodes.h:640
double tuples
Definition: relation.h:725
unsigned int Oid
Definition: postgres_ext.h:31
int tree_height
Definition: relation.h:726
#define OidIsValid(objectId)
Definition: c.h:532
RestrictInfo * rinfo
Definition: selfuncs.h:106
List * deconstruct_indexquals(IndexPath *path)
Definition: selfuncs.c:6425
bool unique
Definition: relation.h:753
Definition: type.h:89
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2167
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
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:155
double rint(double x)
Definition: rint.c:22
int ncolumns
Definition: relation.h:729
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1835
double indexCorrelation
Definition: selfuncs.h:132
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
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
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
Definition: lsyscache.c:2895
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
get_index_stats_hook_type get_index_stats_hook
Definition: selfuncs.c:156
Oid * opcintype
Definition: relation.h:733
Cost indexStartupCost
Definition: selfuncs.h:129
Oid * opfamily
Definition: relation.h:732
RTEKind rtekind
Definition: parsenodes.h:945
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
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
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:735
#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:641
void genericcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, List *qinfos, GenericCosts *costs)
Definition: selfuncs.c:6574
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 6149 of file selfuncs.c.

Referenced by make_greater_string().

6150 {
6151  if (*ptr >= 255)
6152  return false;
6153  (*ptr)++;
6154  return true;
6155 }
static void convert_bytea_to_scalar ( Datum  value,
double *  scaledvalue,
Datum  lobound,
double *  scaledlobound,
Datum  hibound,
double *  scaledhibound 
)
static

Definition at line 4377 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4383 {
4384  int rangelo,
4385  rangehi,
4386  valuelen = VARSIZE(DatumGetPointer(value)) - VARHDRSZ,
4387  loboundlen = VARSIZE(DatumGetPointer(lobound)) - VARHDRSZ,
4388  hiboundlen = VARSIZE(DatumGetPointer(hibound)) - VARHDRSZ,
4389  i,
4390  minlen;
4391  unsigned char *valstr = (unsigned char *) VARDATA(DatumGetPointer(value)),
4392  *lostr = (unsigned char *) VARDATA(DatumGetPointer(lobound)),
4393  *histr = (unsigned char *) VARDATA(DatumGetPointer(hibound));
4394 
4395  /*
4396  * Assume bytea data is uniformly distributed across all byte values.
4397  */
4398  rangelo = 0;
4399  rangehi = 255;
4400 
4401  /*
4402  * Now strip any common prefix of the three strings.
4403  */
4404  minlen = Min(Min(valuelen, loboundlen), hiboundlen);
4405  for (i = 0; i < minlen; i++)
4406  {
4407  if (*lostr != *histr || *lostr != *valstr)
4408  break;
4409  lostr++, histr++, valstr++;
4410  loboundlen--, hiboundlen--, valuelen--;
4411  }
4412 
4413  /*
4414  * Now we can do the conversions.
4415  */
4416  *scaledvalue = convert_one_bytea_to_scalar(valstr, valuelen, rangelo, rangehi);
4417  *scaledlobound = convert_one_bytea_to_scalar(lostr, loboundlen, rangelo, rangehi);
4418  *scaledhibound = convert_one_bytea_to_scalar(histr, hiboundlen, rangelo, rangehi);
4419 }
#define VARDATA(PTR)
Definition: postgres.h:303
#define VARSIZE(PTR)
Definition: postgres.h:304
#define VARHDRSZ
Definition: c.h:439
#define Min(x, y)
Definition: c.h:812
static double convert_one_bytea_to_scalar(unsigned char *value, int valuelen, int rangelo, int rangehi)
Definition: selfuncs.c:4422
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 4085 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().

4086 {
4087  switch (typid)
4088  {
4089  case BOOLOID:
4090  return (double) DatumGetBool(value);
4091  case INT2OID:
4092  return (double) DatumGetInt16(value);
4093  case INT4OID:
4094  return (double) DatumGetInt32(value);
4095  case INT8OID:
4096  return (double) DatumGetInt64(value);
4097  case FLOAT4OID:
4098  return (double) DatumGetFloat4(value);
4099  case FLOAT8OID:
4100  return (double) DatumGetFloat8(value);
4101  case NUMERICOID:
4102  /* Note: out-of-range values will be clamped to +-HUGE_VAL */
4103  return (double)
4105  value));
4106  case OIDOID:
4107  case REGPROCOID:
4108  case REGPROCEDUREOID:
4109  case REGOPEROID:
4110  case REGOPERATOROID:
4111  case REGCLASSOID:
4112  case REGTYPEOID:
4113  case REGCONFIGOID:
4114  case REGDICTIONARYOID:
4115  case REGROLEOID:
4116  case REGNAMESPACEOID:
4117  /* we can treat OIDs as integers... */
4118  return (double) DatumGetObjectId(value);
4119  }
4120 
4121  /*
4122  * Can't get here unless someone tries to use scalarineqsel() on an
4123  * operator with one numeric and one non-numeric operand.
4124  */
4125  elog(ERROR, "unsupported type: %u", typid);
4126  return 0;
4127 }
#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:585
#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:3193
#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 4422 of file selfuncs.c.

Referenced by convert_bytea_to_scalar().

4424 {
4425  double num,
4426  denom,
4427  base;
4428 
4429  if (valuelen <= 0)
4430  return 0.0; /* empty string has scalar value 0 */
4431 
4432  /*
4433  * Since base is 256, need not consider more than about 10 chars (even
4434  * this many seems like overkill)
4435  */
4436  if (valuelen > 10)
4437  valuelen = 10;
4438 
4439  /* Convert initial characters to fraction */
4440  base = rangehi - rangelo + 1;
4441  num = 0.0;
4442  denom = base;
4443  while (valuelen-- > 0)
4444  {
4445  int ch = *value++;
4446 
4447  if (ch < rangelo)
4448  ch = rangelo - 1;
4449  else if (ch > rangehi)
4450  ch = rangehi + 1;
4451  num += ((double) (ch - rangelo)) / denom;
4452  denom *= base;
4453  }
4454 
4455  return num;
4456 }
static struct @121 value
static double convert_one_string_to_scalar ( char *  value,
int  rangelo,
int  rangehi 
)
static

Definition at line 4230 of file selfuncs.c.

Referenced by convert_string_to_scalar().

4231 {
4232  int slen = strlen(value);
4233  double num,
4234  denom,
4235  base;
4236 
4237  if (slen <= 0)
4238  return 0.0; /* empty string has scalar value 0 */
4239 
4240  /*
4241  * There seems little point in considering more than a dozen bytes from
4242  * the string. Since base is at least 10, that will give us nominal
4243  * resolution of at least 12 decimal digits, which is surely far more
4244  * precision than this estimation technique has got anyway (especially in
4245  * non-C locales). Also, even with the maximum possible base of 256, this
4246  * ensures denom cannot grow larger than 256^13 = 2.03e31, which will not
4247  * overflow on any known machine.
4248  */
4249  if (slen > 12)
4250  slen = 12;
4251 
4252  /* Convert initial characters to fraction */
4253  base = rangehi - rangelo + 1;
4254  num = 0.0;
4255  denom = base;
4256  while (slen-- > 0)
4257  {
4258  int ch = (unsigned char) *value++;
4259 
4260  if (ch < rangelo)
4261  ch = rangelo - 1;
4262  else if (ch > rangehi)
4263  ch = rangehi + 1;
4264  num += ((double) (ch - rangelo)) / denom;
4265  denom *= base;
4266  }
4267 
4268  return num;
4269 }
static struct @121 value
static char * convert_string_datum ( Datum  value,
Oid  typid 
)
static

Definition at line 4278 of file selfuncs.c.

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

Referenced by convert_to_scalar().

4279 {
4280  char *val;
4281 
4282  switch (typid)
4283  {
4284  case CHAROID:
4285  val = (char *) palloc(2);
4286  val[0] = DatumGetChar(value);
4287  val[1] = '\0';
4288  break;
4289  case BPCHAROID:
4290  case VARCHAROID:
4291  case TEXTOID:
4292  val = TextDatumGetCString(value);
4293  break;
4294  case NAMEOID:
4295  {
4297 
4298  val = pstrdup(NameStr(*nm));
4299  break;
4300  }
4301  default:
4302 
4303  /*
4304  * Can't get here unless someone tries to use scalarineqsel() on
4305  * an operator with one string and one non-string operand.
4306  */
4307  elog(ERROR, "unsupported type: %u", typid);
4308  return NULL;
4309  }
4310 
4312  {
4313  char *xfrmstr;
4314  size_t xfrmlen;
4315  size_t xfrmlen2 PG_USED_FOR_ASSERTS_ONLY;
4316 
4317  /*
4318  * XXX: We could guess at a suitable output buffer size and only call
4319  * strxfrm twice if our guess is too small.
4320  *
4321  * XXX: strxfrm doesn't support UTF-8 encoding on Win32, it can return
4322  * bogus data or set an error. This is not really a problem unless it
4323  * crashes since it will only give an estimation error and nothing
4324  * fatal.
4325  */
4326 #if _MSC_VER == 1400 /* VS.Net 2005 */
4327 
4328  /*
4329  *
4330  * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99694
4331  */
4332  {
4333  char x[1];
4334 
4335  xfrmlen = strxfrm(x, val, 0);
4336  }
4337 #else
4338  xfrmlen = strxfrm(NULL, val, 0);
4339 #endif
4340 #ifdef WIN32
4341 
4342  /*
4343  * On Windows, strxfrm returns INT_MAX when an error occurs. Instead
4344  * of trying to allocate this much memory (and fail), just return the
4345  * original string unmodified as if we were in the C locale.
4346  */
4347  if (xfrmlen == INT_MAX)
4348  return val;
4349 #endif
4350  xfrmstr = (char *) palloc(xfrmlen + 1);
4351  xfrmlen2 = strxfrm(xfrmstr, val, xfrmlen + 1);
4352 
4353  /*
4354  * Some systems (e.g., glibc) can return a smaller value from the
4355  * second call than the first; thus the Assert must be <= not ==.
4356  */
4357  Assert(xfrmlen2 <= xfrmlen);
4358  pfree(val);
4359  val = xfrmstr;
4360  }
4361 
4362  return val;
4363 }
#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:1076
void pfree(void *pointer)
Definition: mcxt.c:949
#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:487
#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 Assert(condition)
Definition: c.h:681
#define DatumGetPointer(X)
Definition: postgres.h:555
void * palloc(Size size)
Definition: mcxt.c:848
#define NameStr(name)
Definition: c.h:493
#define elog
Definition: elog.h:219
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:996
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 4150 of file selfuncs.c.

References convert_one_string_to_scalar().

Referenced by convert_to_scalar().

4156 {
4157  int rangelo,
4158  rangehi;
4159  char *sptr;
4160 
4161  rangelo = rangehi = (unsigned char) hibound[0];
4162  for (sptr = lobound; *sptr; sptr++)
4163  {
4164  if (rangelo > (unsigned char) *sptr)
4165  rangelo = (unsigned char) *sptr;
4166  if (rangehi < (unsigned char) *sptr)
4167  rangehi = (unsigned char) *sptr;
4168  }
4169  for (sptr = hibound; *sptr; sptr++)
4170  {
4171  if (rangelo > (unsigned char) *sptr)
4172  rangelo = (unsigned char) *sptr;
4173  if (rangehi < (unsigned char) *sptr)
4174  rangehi = (unsigned char) *sptr;
4175  }
4176  /* If range includes any upper-case ASCII chars, make it include all */
4177  if (rangelo <= 'Z' && rangehi >= 'A')
4178  {
4179  if (rangelo > 'A')
4180  rangelo = 'A';
4181  if (rangehi < 'Z')
4182  rangehi = 'Z';
4183  }
4184  /* Ditto lower-case */
4185  if (rangelo <= 'z' && rangehi >= 'a')
4186  {
4187  if (rangelo > 'a')
4188  rangelo = 'a';
4189  if (rangehi < 'z')
4190  rangehi = 'z';
4191  }
4192  /* Ditto digits */
4193  if (rangelo <= '9' && rangehi >= '0')
4194  {
4195  if (rangelo > '0')
4196  rangelo = '0';
4197  if (rangehi < '9')
4198  rangehi = '9';
4199  }
4200 
4201  /*
4202  * If range includes less than 10 chars, assume we have not got enough
4203  * data, and make it include regular ASCII set.
4204  */
4205  if (rangehi - rangelo < 9)
4206  {
4207  rangelo = ' ';
4208  rangehi = 127;
4209  }
4210 
4211  /*
4212  * Now strip any common prefix of the three strings.
4213  */
4214  while (*lobound)
4215  {
4216  if (*lobound != *hibound || *lobound != *value)
4217  break;
4218  lobound++, hibound++, value++;
4219  }
4220 
4221  /*
4222  * Now we can do the conversions.
4223  */
4224  *scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
4225  *scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
4226  *scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
4227 }
static struct @121 value
static double convert_one_string_to_scalar(char *value, int rangelo, int rangehi)
Definition: selfuncs.c:4230
static double convert_timevalue_to_scalar ( Datum  value,
Oid  typid 
)
static

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

4463 {
4464  switch (typid)
4465  {
4466  case TIMESTAMPOID:
4467  return DatumGetTimestamp(value);
4468  case TIMESTAMPTZOID:
4469  return DatumGetTimestampTz(value);
4470  case ABSTIMEOID:
4472  value));
4473  case DATEOID:
4475  case INTERVALOID:
4476  {
4478 
4479  /*
4480  * Convert the month part of Interval to days using assumed
4481  * average month length of 365.25/12.0 days. Not too
4482  * accurate, but plenty good enough for our purposes.
4483  */
4484  return interval->time + interval->day * (double) USECS_PER_DAY +
4485  interval->month * ((DAYS_PER_YEAR / (double) MONTHS_PER_YEAR) * USECS_PER_DAY);
4486  }
4487  case RELTIMEOID:
4488  return (DatumGetRelativeTime(value) * 1000000.0);
4489  case TINTERVALOID:
4490  {
4492 
4493  if (tinterval->status != 0)
4494  return ((tinterval->data[1] - tinterval->data[0]) * 1000000.0);
4495  return 0; /* for lack of a better idea */
4496  }
4497  case TIMEOID:
4498  return DatumGetTimeADT(value);
4499  case TIMETZOID:
4500  {
4501  TimeTzADT *timetz = DatumGetTimeTzADTP(value);
4502 
4503  /* use GMT-equivalent time */
4504  return (double) (timetz->time + (timetz->zone * 1000000.0));
4505  }
4506  }
4507 
4508  /*
4509  * Can't get here unless someone tries to use scalarineqsel() on an
4510  * operator with one timevalue and one non-timevalue operand.
4511  */
4512  elog(ERROR, "unsupported type: %u", typid);
4513  return 0;
4514 }
#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:585
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 3967 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().

3970 {
3971  /*
3972  * Both the valuetypid and the boundstypid should exactly match the
3973  * declared input type(s) of the operator we are invoked for, so we just
3974  * error out if either is not recognized.
3975  *
3976  * XXX The histogram we are interpolating between points of could belong
3977  * to a column that's only binary-compatible with the declared type. In
3978  * essence we are assuming that the semantics of binary-compatible types
3979  * are enough alike that we can use a histogram generated with one type's
3980  * operators to estimate selectivity for the other's. This is outright
3981  * wrong in some cases --- in particular signed versus unsigned
3982  * interpretation could trip us up. But it's useful enough in the
3983  * majority of cases that we do it anyway. Should think about more
3984  * rigorous ways to do it.
3985  */
3986  switch (valuetypid)
3987  {
3988  /*
3989  * Built-in numeric types
3990  */
3991  case BOOLOID:
3992  case INT2OID:
3993  case INT4OID:
3994  case INT8OID:
3995  case FLOAT4OID:
3996  case FLOAT8OID:
3997  case NUMERICOID:
3998  case OIDOID:
3999  case REGPROCOID:
4000  case REGPROCEDUREOID:
4001  case REGOPEROID:
4002  case REGOPERATOROID:
4003  case REGCLASSOID:
4004  case REGTYPEOID:
4005  case REGCONFIGOID:
4006  case REGDICTIONARYOID:
4007  case REGROLEOID:
4008  case REGNAMESPACEOID:
4009  *scaledvalue = convert_numeric_to_scalar(value, valuetypid);
4010  *scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
4011  *scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
4012  return true;
4013 
4014  /*
4015  * Built-in string types
4016  */
4017  case CHAROID:
4018  case BPCHAROID:
4019  case VARCHAROID:
4020  case TEXTOID:
4021  case NAMEOID:
4022  {
4023  char *valstr = convert_string_datum(value, valuetypid);
4024  char *lostr = convert_string_datum(lobound, boundstypid);
4025  char *histr = convert_string_datum(hibound, boundstypid);
4026 
4027  convert_string_to_scalar(valstr, scaledvalue,
4028  lostr, scaledlobound,
4029  histr, scaledhibound);
4030  pfree(valstr);
4031  pfree(lostr);
4032  pfree(histr);
4033  return true;
4034  }
4035 
4036  /*
4037  * Built-in bytea type
4038  */
4039  case BYTEAOID:
4040  {
4041  convert_bytea_to_scalar(value, scaledvalue,
4042  lobound, scaledlobound,
4043  hibound, scaledhibound);
4044  return true;
4045  }
4046 
4047  /*
4048  * Built-in time types
4049  */
4050  case TIMESTAMPOID:
4051  case TIMESTAMPTZOID:
4052  case ABSTIMEOID:
4053  case DATEOID:
4054  case INTERVALOID:
4055  case RELTIMEOID:
4056  case TINTERVALOID:
4057  case TIMEOID:
4058  case TIMETZOID:
4059  *scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
4060  *scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
4061  *scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
4062  return true;
4063 
4064  /*
4065  * Built-in network types
4066  */
4067  case INETOID:
4068  case CIDROID:
4069  case MACADDROID:
4070  case MACADDR8OID:
4071  *scaledvalue = convert_network_to_scalar(value, valuetypid);
4072  *scaledlobound = convert_network_to_scalar(lobound, boundstypid);
4073  *scaledhibound = convert_network_to_scalar(hibound, boundstypid);
4074  return true;
4075  }
4076  /* Don't know how to convert */
4077  *scaledvalue = *scaledlobound = *scaledhibound = 0;
4078  return false;
4079 }
#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:4085
#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:949
#define TIMESTAMPOID
Definition: pg_type.h:519
static struct @121 value
double convert_network_to_scalar(Datum value, Oid typid)
Definition: network.c:907
#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:4278
#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:4462
#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:4377
#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:4150
#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 6425 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, ScalarArrayOpExpr::opno, RowCompareExpr::opnos, IndexQualInfo::other_operand, palloc(), RowCompareExpr::rargs, IndexQualInfo::rinfo, and IndexQualInfo::varonleft.

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

6426 {
6427  List *result = NIL;
6428  IndexOptInfo *index = path->indexinfo;
6429  ListCell *lcc,
6430  *lci;
6431 
6432  forboth(lcc, path->indexquals, lci, path->indexqualcols)
6433  {
6434  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lcc);
6435  int indexcol = lfirst_int(lci);
6436  Expr *clause;
6437  Node *leftop,
6438  *rightop;
6439  IndexQualInfo *qinfo;
6440 
6441  clause = rinfo->clause;
6442 
6443  qinfo = (IndexQualInfo *) palloc(sizeof(IndexQualInfo));
6444  qinfo->rinfo = rinfo;
6445  qinfo->indexcol = indexcol;
6446 
6447  if (IsA(clause, OpExpr))
6448  {
6449  qinfo->clause_op = ((OpExpr *) clause)->opno;
6450  leftop = get_leftop(clause);
6451  rightop = get_rightop(clause);
6452  if (match_index_to_operand(leftop, indexcol, index))
6453  {
6454  qinfo->varonleft = true;
6455  qinfo->other_operand = rightop;
6456  }
6457  else
6458  {
6459  Assert(match_index_to_operand(rightop, indexcol, index));
6460  qinfo->varonleft = false;
6461  qinfo->other_operand = leftop;
6462  }
6463  }
6464  else if (IsA(clause, RowCompareExpr))
6465  {
6466  RowCompareExpr *rc = (RowCompareExpr *) clause;
6467 
6468  qinfo->clause_op = linitial_oid(rc->opnos);
6469  /* Examine only first columns to determine left/right sides */
6471  indexcol, index))
6472  {
6473  qinfo->varonleft = true;
6474  qinfo->other_operand = (Node *) rc->rargs;
6475  }
6476  else
6477  {
6479  indexcol, index));
6480  qinfo->varonleft = false;
6481  qinfo->other_operand = (Node *) rc->largs;
6482  }
6483  }
6484  else if (IsA(clause, ScalarArrayOpExpr))
6485  {
6486  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
6487 
6488  qinfo->clause_op = saop->opno;
6489  /* index column is always on the left in this case */
6491  indexcol, index));
6492  qinfo->varonleft = true;
6493  qinfo->other_operand = (Node *) lsecond(saop->args);
6494  }
6495  else if (IsA(clause, NullTest))
6496  {
6497  qinfo->clause_op = InvalidOid;
6498  Assert(match_index_to_operand((Node *) ((NullTest *) clause)->arg,
6499  indexcol, index));
6500  qinfo->varonleft = true;
6501  qinfo->other_operand = NULL;
6502  }
6503  else
6504  {
6505  elog(ERROR, "unsupported indexqual type: %d",
6506  (int) nodeTag(clause));
6507  }
6508 
6509  result = lappend(result, qinfo);
6510  }
6511  return result;
6512 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
IndexOptInfo * indexinfo
Definition: relation.h:1119
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3180
Definition: nodes.h:510
RestrictInfo * rinfo
Definition: selfuncs.h:106
#define lsecond(l)
Definition: pg_list.h:116
Definition: type.h:89
List * indexquals
Definition: relation.h:1121
#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:1835
bool varonleft
Definition: selfuncs.h:108
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:681
#define linitial_oid(l)
Definition: pg_list.h:113
#define nodeTag(nodeptr)
Definition: nodes.h:515
Node * get_rightop(const Expr *clause)
Definition: clauses.c:216
List * indexqualcols
Definition: relation.h:1122
void * palloc(Size size)
Definition: mcxt.c:848
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 2272 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().

2273 {
2274  PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2275  Oid operator = PG_GETARG_OID(1);
2276  List *args = (List *) PG_GETARG_POINTER(2);
2277 
2278 #ifdef NOT_USED
2279  JoinType jointype = (JoinType) PG_GETARG_INT16(3);
2280 #endif
2282  double selec;
2283  VariableStatData vardata1;
2284  VariableStatData vardata2;
2285  bool join_is_reversed;
2286  RelOptInfo *inner_rel;
2287 
2288  get_join_variables(root, args, sjinfo,
2289  &vardata1, &vardata2, &join_is_reversed);
2290 
2291  switch (sjinfo->jointype)
2292  {
2293  case JOIN_INNER:
2294  case JOIN_LEFT:
2295  case JOIN_FULL:
2296  selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
2297  break;
2298  case JOIN_SEMI:
2299  case JOIN_ANTI:
2300 
2301  /*
2302  * Look up the join's inner relation. min_righthand is sufficient
2303  * information because neither SEMI nor ANTI joins permit any
2304  * reassociation into or out of their RHS, so the righthand will
2305  * always be exactly that set of rels.
2306  */
2307  inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
2308 
2309  if (!join_is_reversed)
2310  selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
2311  inner_rel);
2312  else
2313  selec = eqjoinsel_semi(get_commutator(operator),
2314  &vardata2, &vardata1,
2315  inner_rel);
2316  break;
2317  default:
2318  /* other values not expected here */
2319  elog(ERROR, "unrecognized join type: %d",
2320  (int) sjinfo->jointype);
2321  selec = 0; /* keep compiler quiet */
2322  break;
2323  }
2324 
2325  ReleaseVariableStats(vardata1);
2326  ReleaseVariableStats(vardata2);
2327 
2328  CLAMP_PROBABILITY(selec);
2329 
2330  PG_RETURN_FLOAT8((float8) selec);
2331 }
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1313
Relids min_righthand
Definition: relation.h:2008
#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:674
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:375
void get_join_variables(PlannerInfo *root, List *args, SpecialJoinInfo *sjinfo, VariableStatData *vardata1, VariableStatData *vardata2, bool *join_is_reversed)
Definition: selfuncs.c:4601
#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:2557
#define PG_GETARG_INT16(n)
Definition: fmgr.h:236
static RelOptInfo * find_join_input_rel(PlannerInfo *root, Relids relids)
Definition: selfuncs.c:5576
JoinType jointype
Definition: relation.h:2011
#define ReleaseVariableStats(vardata)
Definition: selfuncs.h:81
static double eqjoinsel_inner(Oid operator, VariableStatData *vardata1, VariableStatData *vardata2)
Definition: selfuncs.c:2340
#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 2340 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, AttStatsSlot::numbers, AttStatsSlot::nvalues, palloc0(), pfree(), STATISTIC_KIND_MCV, statistic_proc_security_check(), VariableStatData::statsTuple, and AttStatsSlot::values.

Referenced by eqjoinsel().

2342 {
2343  double selec;
2344  double nd1;
2345  double nd2;
2346  bool isdefault1;
2347  bool isdefault2;
2348  Oid opfuncoid;
2349  Form_pg_statistic stats1 = NULL;
2350  Form_pg_statistic stats2 = NULL;
2351  bool have_mcvs1 = false;
2352  bool have_mcvs2 = false;
2353  AttStatsSlot sslot1;
2354  AttStatsSlot sslot2;
2355 
2356  nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2357  nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2358 
2359  opfuncoid = get_opcode(operator);
2360 
2361  memset(&sslot1, 0, sizeof(sslot1));
2362  memset(&sslot2, 0, sizeof(sslot2));
2363 
2364  if (HeapTupleIsValid(vardata1->statsTuple))
2365  {
2366  /* note we allow use of nullfrac regardless of security check */
2367  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2368  if (statistic_proc_security_check(vardata1, opfuncoid))
2369  have_mcvs1 = get_attstatsslot(&sslot1, vardata1->statsTuple,
2372  }
2373 
2374  if (HeapTupleIsValid(vardata2->statsTuple))
2375  {
2376  /* note we allow use of nullfrac regardless of security check */
2377  stats2 = (Form_pg_statistic) GETSTRUCT(vardata2->statsTuple);
2378  if (statistic_proc_security_check(vardata2, opfuncoid))
2379  have_mcvs2 = get_attstatsslot(&sslot2, vardata2->statsTuple,
2382  }
2383 
2384  if (have_mcvs1 && have_mcvs2)
2385  {
2386  /*
2387  * We have most-common-value lists for both relations. Run through
2388  * the lists to see which MCVs actually join to each other with the
2389  * given operator. This allows us to determine the exact join
2390  * selectivity for the portion of the relations represented by the MCV
2391  * lists. We still have to estimate for the remaining population, but
2392  * in a skewed distribution this gives us a big leg up in accuracy.
2393  * For motivation see the analysis in Y. Ioannidis and S.
2394  * Christodoulakis, "On the propagation of errors in the size of join
2395  * results", Technical Report 1018, Computer Science Dept., University
2396  * of Wisconsin, Madison, March 1991 (available from ftp.cs.wisc.edu).
2397  */
2398  FmgrInfo eqproc;
2399  bool *hasmatch1;
2400  bool *hasmatch2;
2401  double nullfrac1 = stats1->stanullfrac;
2402  double nullfrac2 = stats2->stanullfrac;
2403  double matchprodfreq,
2404  matchfreq1,
2405  matchfreq2,
2406  unmatchfreq1,
2407  unmatchfreq2,
2408  otherfreq1,
2409  otherfreq2,
2410  totalsel1,
2411  totalsel2;
2412  int i,
2413  nmatches;
2414 
2415  fmgr_info(opfuncoid, &eqproc);
2416  hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
2417  hasmatch2 = (bool *) palloc0(sslot2.nvalues * sizeof(bool));
2418 
2419  /*
2420  * Note we assume that each MCV will match at most one member of the
2421  * other MCV list. If the operator isn't really equality, there could
2422  * be multiple matches --- but we don't look for them, both for speed
2423  * and because the math wouldn't add up...
2424  */
2425  matchprodfreq = 0.0;
2426  nmatches = 0;
2427  for (i = 0; i < sslot1.nvalues; i++)
2428  {
2429  int j;
2430 
2431  for (j = 0; j < sslot2.nvalues; j++)
2432  {
2433  if (hasmatch2[j])
2434  continue;
2435  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2437  sslot1.values[i],
2438  sslot2.values[j])))
2439  {
2440  hasmatch1[i] = hasmatch2[j] = true;
2441  matchprodfreq += sslot1.numbers[i] * sslot2.numbers[j];
2442  nmatches++;
2443  break;
2444  }
2445  }
2446  }
2447  CLAMP_PROBABILITY(matchprodfreq);
2448  /* Sum up frequencies of matched and unmatched MCVs */
2449  matchfreq1 = unmatchfreq1 = 0.0;
2450  for (i = 0; i < sslot1.nvalues; i++)
2451  {
2452  if (hasmatch1[i])
2453  matchfreq1 += sslot1.numbers[i];
2454  else
2455  unmatchfreq1 += sslot1.numbers[i];
2456  }
2457  CLAMP_PROBABILITY(matchfreq1);
2458  CLAMP_PROBABILITY(unmatchfreq1);
2459  matchfreq2 = unmatchfreq2 = 0.0;
2460  for (i = 0; i < sslot2.nvalues; i++)
2461  {
2462  if (hasmatch2[i])
2463  matchfreq2 += sslot2.numbers[i];
2464  else
2465  unmatchfreq2 += sslot2.numbers[i];
2466  }
2467  CLAMP_PROBABILITY(matchfreq2);
2468  CLAMP_PROBABILITY(unmatchfreq2);
2469  pfree(hasmatch1);
2470  pfree(hasmatch2);
2471 
2472  /*
2473  * Compute total frequency of non-null values that are not in the MCV
2474  * lists.
2475  */
2476  otherfreq1 = 1.0 - nullfrac1 - matchfreq1 - unmatchfreq1;
2477  otherfreq2 = 1.0 - nullfrac2 - matchfreq2 - unmatchfreq2;
2478  CLAMP_PROBABILITY(otherfreq1);
2479  CLAMP_PROBABILITY(otherfreq2);
2480 
2481  /*
2482  * We can estimate the total selectivity from the point of view of
2483  * relation 1 as: the known selectivity for matched MCVs, plus
2484  * unmatched MCVs that are assumed to match against random members of
2485  * relation 2's non-MCV population, plus non-MCV values that are
2486  * assumed to match against random members of relation 2's unmatched
2487  * MCVs plus non-MCV values.
2488  */
2489  totalsel1 = matchprodfreq;
2490  if (nd2 > sslot2.nvalues)
2491  totalsel1 += unmatchfreq1 * otherfreq2 / (nd2 - sslot2.nvalues);
2492  if (nd2 > nmatches)
2493  totalsel1 += otherfreq1 * (otherfreq2 + unmatchfreq2) /
2494  (nd2 - nmatches);
2495  /* Same estimate from the point of view of relation 2. */
2496  totalsel2 = matchprodfreq;
2497  if (nd1 > sslot1.nvalues)
2498  totalsel2 += unmatchfreq2 * otherfreq1 / (nd1 - sslot1.nvalues);
2499  if (nd1 > nmatches)
2500  totalsel2 += otherfreq2 * (otherfreq1 + unmatchfreq1) /
2501  (nd1 - nmatches);
2502 
2503  /*
2504  * Use the smaller of the two estimates. This can be justified in
2505  * essentially the same terms as given below for the no-stats case: to
2506  * a first approximation, we are estimating from the point of view of
2507  * the relation with smaller nd.
2508  */
2509  selec = (totalsel1 < totalsel2) ? totalsel1 : totalsel2;
2510  }
2511  else
2512  {
2513  /*
2514  * We do not have MCV lists for both sides. Estimate the join
2515  * selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). This
2516  * is plausible if we assume that the join operator is strict and the
2517  * non-null values are about equally distributed: a given non-null
2518  * tuple of rel1 will join to either zero or N2*(1-nullfrac2)/nd2 rows
2519  * of rel2, so total join rows are at most
2520  * N1*(1-nullfrac1)*N2*(1-nullfrac2)/nd2 giving a join selectivity of
2521  * not more than (1-nullfrac1)*(1-nullfrac2)/nd2. By the same logic it
2522  * is not more than (1-nullfrac1)*(1-nullfrac2)/nd1, so the expression
2523  * with MIN() is an upper bound. Using the MIN() means we estimate
2524  * from the point of view of the relation with smaller nd (since the
2525  * larger nd is determining the MIN). It is reasonable to assume that
2526  * most tuples in this rel will have join partners, so the bound is
2527  * probably reasonably tight and should be taken as-is.
2528  *
2529  * XXX Can we be smarter if we have an MCV list for just one side? It
2530  * seems that if we assume equal distribution for the other side, we
2531  * end up with the same answer anyway.
2532  */
2533  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2534  double nullfrac2 = stats2 ? stats2->stanullfrac : 0.0;
2535 
2536  selec = (1.0 - nullfrac1) * (1.0 - nullfrac2);
2537  if (nd1 > nd2)
2538  selec /= nd1;
2539  else
2540  selec /= nd2;
2541  }
2542 
2543  free_attstatsslot(&sslot1);
2544  free_attstatsslot(&sslot2);
2545 
2546  return selec;
2547 }
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:5041
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1042
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:949
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5070
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:122
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:877
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
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 2557 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, 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().

2560 {
2561  double selec;
2562  double nd1;
2563  double nd2;
2564  bool isdefault1;
2565  bool isdefault2;
2566  Oid opfuncoid;
2567  Form_pg_statistic stats1 = NULL;
2568  bool have_mcvs1 = false;
2569  bool have_mcvs2 = false;
2570  AttStatsSlot sslot1;
2571  AttStatsSlot sslot2;
2572 
2573  nd1 = get_variable_numdistinct(vardata1, &isdefault1);
2574  nd2 = get_variable_numdistinct(vardata2, &isdefault2);
2575 
2576  opfuncoid = OidIsValid(operator) ? get_opcode(operator) : InvalidOid;
2577 
2578  memset(&sslot1, 0, sizeof(sslot1));
2579  memset(&sslot2, 0, sizeof(sslot2));
2580 
2581  /*
2582  * We clamp nd2 to be not more than what we estimate the inner relation's
2583  * size to be. This is intuitively somewhat reasonable since obviously
2584  * there can't be more than that many distinct values coming from the
2585  * inner rel. The reason for the asymmetry (ie, that we don't clamp nd1
2586  * likewise) is that this is the only pathway by which restriction clauses
2587  * applied to the inner rel will affect the join result size estimate,
2588  * since set_joinrel_size_estimates will multiply SEMI/ANTI selectivity by
2589  * only the outer rel's size. If we clamped nd1 we'd be double-counting
2590  * the selectivity of outer-rel restrictions.
2591  *
2592  * We can apply this clamping both with respect to the base relation from
2593  * which the join variable comes (if there is just one), and to the
2594  * immediate inner input relation of the current join.
2595  *
2596  * If we clamp, we can treat nd2 as being a non-default estimate; it's not
2597  * great, maybe, but it didn't come out of nowhere either. This is most
2598  * helpful when the inner relation is empty and consequently has no stats.
2599  */
2600  if (vardata2->rel)
2601  {
2602  if (nd2 >= vardata2->rel->rows)
2603  {
2604  nd2 = vardata2->rel->rows;
2605  isdefault2 = false;
2606  }
2607  }
2608  if (nd2 >= inner_rel->rows)
2609  {
2610  nd2 = inner_rel->rows;
2611  isdefault2 = false;
2612  }
2613 
2614  if (HeapTupleIsValid(vardata1->statsTuple))
2615  {
2616  /* note we allow use of nullfrac regardless of security check */
2617  stats1 = (Form_pg_statistic) GETSTRUCT(vardata1->statsTuple);
2618  if (statistic_proc_security_check(vardata1, opfuncoid))
2619  have_mcvs1 = get_attstatsslot(&sslot1, vardata1->statsTuple,
2622  }
2623 
2624  if (HeapTupleIsValid(vardata2->statsTuple) &&
2625  statistic_proc_security_check(vardata2, opfuncoid))
2626  {
2627  have_mcvs2 = get_attstatsslot(&sslot2, vardata2->statsTuple,
2630  /* note: currently don't need stanumbers from RHS */
2631  }
2632 
2633  if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
2634  {
2635  /*
2636  * We have most-common-value lists for both relations. Run through
2637  * the lists to see which MCVs actually join to each other with the
2638  * given operator. This allows us to determine the exact join
2639  * selectivity for the portion of the relations represented by the MCV
2640  * lists. We still have to estimate for the remaining population, but
2641  * in a skewed distribution this gives us a big leg up in accuracy.
2642  */
2643  FmgrInfo eqproc;
2644  bool *hasmatch1;
2645  bool *hasmatch2;
2646  double nullfrac1 = stats1->stanullfrac;
2647  double matchfreq1,
2648  uncertainfrac,
2649  uncertain;
2650  int i,
2651  nmatches,
2652  clamped_nvalues2;
2653 
2654  /*
2655  * The clamping above could have resulted in nd2 being less than
2656  * sslot2.nvalues; in which case, we assume that precisely the nd2
2657  * most common values in the relation will appear in the join input,
2658  * and so compare to only the first nd2 members of the MCV list. Of
2659  * course this is frequently wrong, but it's the best bet we can make.
2660  */
2661  clamped_nvalues2 = Min(sslot2.nvalues, nd2);
2662 
2663  fmgr_info(opfuncoid, &eqproc);
2664  hasmatch1 = (bool *) palloc0(sslot1.nvalues * sizeof(bool));
2665  hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
2666 
2667  /*
2668  * Note we assume that each MCV will match at most one member of the
2669  * other MCV list. If the operator isn't really equality, there could
2670  * be multiple matches --- but we don't look for them, both for speed
2671  * and because the math wouldn't add up...
2672  */
2673  nmatches = 0;
2674  for (i = 0; i < sslot1.nvalues; i++)
2675  {
2676  int j;
2677 
2678  for (j = 0; j < clamped_nvalues2; j++)
2679  {
2680  if (hasmatch2[j])
2681  continue;
2682  if (DatumGetBool(FunctionCall2Coll(&eqproc,
2684  sslot1.values[i],
2685  sslot2.values[j])))
2686  {
2687  hasmatch1[i] = hasmatch2[j] = true;
2688  nmatches++;
2689  break;
2690  }
2691  }
2692  }
2693  /* Sum up frequencies of matched MCVs */
2694  matchfreq1 = 0.0;
2695  for (i = 0; i < sslot1.nvalues; i++)
2696  {
2697  if (hasmatch1[i])
2698  matchfreq1 += sslot1.numbers[i];
2699  }
2700  CLAMP_PROBABILITY(matchfreq1);
2701  pfree(hasmatch1);
2702  pfree(hasmatch2);
2703 
2704  /*
2705  * Now we need to estimate the fraction of relation 1 that has at
2706  * least one join partner. We know for certain that the matched MCVs
2707  * do, so that gives us a lower bound, but we're really in the dark
2708  * about everything else. Our crude approach is: if nd1 <= nd2 then
2709  * assume all non-null rel1 rows have join partners, else assume for
2710  * the uncertain rows that a fraction nd2/nd1 have join partners. We
2711  * can discount the known-matched MCVs from the distinct-values counts
2712  * before doing the division.
2713  *
2714  * Crude as the above is, it's completely useless if we don't have
2715  * reliable ndistinct values for both sides. Hence, if either nd1 or
2716  * nd2 is default, punt and assume half of the uncertain rows have
2717  * join partners.
2718  */
2719  if (!isdefault1 && !isdefault2)
2720  {
2721  nd1 -= nmatches;
2722  nd2 -= nmatches;
2723  if (nd1 <= nd2 || nd2 < 0)
2724  uncertainfrac = 1.0;
2725  else
2726  uncertainfrac = nd2 / nd1;
2727  }
2728  else
2729  uncertainfrac = 0.5;
2730  uncertain = 1.0 - matchfreq1 - nullfrac1;
2731  CLAMP_PROBABILITY(uncertain);
2732  selec = matchfreq1 + uncertainfrac * uncertain;
2733  }
2734  else
2735  {
2736  /*
2737  * Without MCV lists for both sides, we can only use the heuristic
2738  * about nd1 vs nd2.
2739  */
2740  double nullfrac1 = stats1 ? stats1->stanullfrac : 0.0;
2741 
2742  if (!isdefault1 && !isdefault2)
2743  {
2744  if (nd1 <= nd2 || nd2 < 0)
2745  selec = 1.0 - nullfrac1;
2746  else
2747  selec = (nd2 / nd1) * (1.0 - nullfrac1);
2748  }
2749  else
2750  selec = 0.5 * (1.0 - nullfrac1);
2751  }
2752 
2753  free_attstatsslot(&sslot1);
2754  free_attstatsslot(&sslot2);
2755 
2756  return selec;
2757 }
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:5041
RelOptInfo * rel
Definition: selfuncs.h:70
#define Min(x, y)
Definition: c.h:812
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1042
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:532
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:57
void pfree(void *pointer)
Definition: mcxt.c:949
#define ATTSTATSSLOT_NUMBERS
Definition: lsyscache.h:40
double get_variable_numdistinct(VariableStatData *vardata, bool *isdefault)
Definition: selfuncs.c:5070
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:122
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:877
double rows
Definition: relation.h:588
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
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 230 of file selfuncs.c.

References eqsel_internal(), and PG_RETURN_FLOAT8.

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

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

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

2168 {
2169  /* look through any binary-compatible relabeling of arrayexpr */
2170  arrayexpr = strip_array_coercion(arrayexpr);
2171 
2172  if (arrayexpr && IsA(arrayexpr, Const))
2173  {
2174  Datum arraydatum = ((Const *) arrayexpr)->constvalue;
2175  bool arrayisnull = ((Const *) arrayexpr)->constisnull;
2176  ArrayType *arrayval;
2177 
2178  if (arrayisnull)
2179  return 0;
2180  arrayval = DatumGetArrayTypeP(arraydatum);
2181  return ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2182  }
2183  else if (arrayexpr && IsA(arrayexpr, ArrayExpr) &&
2184  !((ArrayExpr *) arrayexpr)->multidims)
2185  {
2186  return list_length(((ArrayExpr *) arrayexpr)->elements);
2187  }
2188  else
2189  {
2190  /* default guess --- see also scalararraysel */
2191  return 10;
2192  }
2193 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:75
#define ARR_DIMS(a)
Definition: array.h:279
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:275
static Node * strip_array_coercion(Node *node)
Definition: selfuncs.c:1815
#define DatumGetArrayTypeP(X)
Definition: array.h:246
void estimate_hash_bucket_stats ( PlannerInfo root,
Node hashkey,
double  nbuckets,
Selectivity mcv_freq,
Selectivity bucketsize_frac 
)

Definition at line 3696 of file selfuncs.c.

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

Referenced by final_cost_hashjoin().

3699 {
3700  VariableStatData vardata;
3701  double estfract,
3702  ndistinct,
3703  stanullfrac,
3704  avgfreq;
3705  bool isdefault;
3706  AttStatsSlot sslot;
3707 
3708  examine_variable(root, hashkey, 0, &vardata);
3709 
3710  /* Look up the frequency of the most common value, if available */
3711  *mcv_freq = 0.0;
3712 
3713  if (HeapTupleIsValid(vardata.statsTuple))
3714  {
3715  if (get_attstatsslot(&sslot, vardata.statsTuple,
3718  {
3719  /*
3720  * The first MCV stat is for the most common value.
3721  */
3722  if (sslot.nnumbers > 0)
3723  *mcv_freq = sslot.numbers[0];
3724  free_attstatsslot(&sslot);
3725  }
3726  }
3727 
3728  /* Get number of distinct values */
3729  ndistinct = get_variable_numdistinct(&vardata, &isdefault);
3730 
3731  /*
3732  * If ndistinct isn't real, punt. We normally return 0.1, but if the
3733  * mcv_freq is known to be even higher than that, use it instead.
3734  */
3735  if (isdefault)
3736  {
3737  *bucketsize_frac = (Selectivity) Max(0.1, *mcv_freq);
3738  ReleaseVariableStats(vardata);
3739  return;
3740  }
3741 
3742  /* Get fraction that are null */
3743  if (HeapTupleIsValid(vardata.statsTuple))
3744  {
3745  Form_pg_statistic stats;
3746 
3747  stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
3748  stanullfrac = stats->stanullfrac;
3749  }
3750  else
3751  stanullfrac = 0.0;
3752 
3753  /* Compute avg freq of all distinct data values in raw relation */
3754  avgfreq = (1.0 - stanullfrac) / ndistinct;
3755 
3756  /*
3757  * Adjust ndistinct to account for restriction clauses. Observe we are
3758  * assuming that the data distribution is affected uniformly by the
3759  * restriction clauses!
3760  *
3761  * XXX Possibly better way, but much more expensive: multiply by
3762  * selectivity of rel's restriction clauses that mention the target Var.
3763  */
3764  if (vardata.rel && vardata.rel->tuples > 0)
3765  {
3766  ndistinct *= vardata.rel->rows / vardata.rel->tuples;
3767  ndistinct = clamp_row_est(ndistinct);
3768  }
3769 
3770  /*
3771  * Initial estimate of bucketsize fraction is 1/nbuckets as long as the
3772  * number of buckets is less than the expected number of distinct values;
3773  * otherwise it is 1/ndistinct.
3774  */
3775  if (ndistinct > nbuckets)
3776  estfract = 1.0 / nbuckets;
3777  else
3778  estfract = 1.0 / ndistinct;
3779 
3780  /*
3781  * Adjust estimated bucketsize upward to account for skewed distribution.
3782  */
3783  if (avgfreq > 0.0 && *mcv_freq > avgfreq)
3784  estfract *= *mcv_freq / avgfreq;
3785 
3786  /*
3787  * Clamp bucketsize to sane range (the above adjustment could easily
3788  * produce an out-of-range result). We set the lower bound a little above
3789  * zero, since zero isn't a very sane result.
3790  */
3791  if (estfract < 1.0e-6)
3792  estfract = 1.0e-6;
3793  else if (estfract > 1.0)
3794  estfract = 1.0;
3795 
3796  *bucketsize_frac = (Selectivity) estfract;
3797 
3798  ReleaseVariableStats(vardata);
3799 }
#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:625
RelOptInfo * rel
Definition: selfuncs.h:70
double Selectivity
Definition: nodes.h:640
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:5070
float4 * numbers
Definition: lsyscache.h:52
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
double rows
Definition: relation.h:588
#define InvalidOid
Definition: postgres_ext.h:36
#define Max(x, y)
Definition: c.h:806
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void examine_variable(PlannerInfo *root, Node *node, int varRelid, VariableStatData *vardata)
Definition: selfuncs.c:4663
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:174
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 3820 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, GroupVarInfo::rel, statext_ndistinct_load(), RelOptInfo::statlist, StatisticExtInfo::statOid, STATS_EXT_NDISTINCT, and GroupVarInfo::var.

Referenced by estimate_num_groups().

3822 {
3823  ListCell *lc;
3824  Bitmapset *attnums = NULL;
3825  int nmatches;
3826  Oid statOid = InvalidOid;
3827  MVNDistinct *stats;
3828  Bitmapset *matched = NULL;
3829 
3830  /* bail out immediately if the table has no extended statistics */
3831  if (!rel->statlist)
3832  return false;
3833 
3834  /* Determine the attnums we're looking for */
3835  foreach(lc, *varinfos)
3836  {
3837  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3838 
3839  Assert(varinfo->rel == rel);
3840 
3841  if (IsA(varinfo->var, Var))
3842  {
3843  attnums = bms_add_member(attnums,
3844  ((Var *) varinfo->var)->varattno);
3845  }
3846  }
3847 
3848  /* look for the ndistinct statistics matching the most vars */
3849  nmatches = 1; /* we require at least two matches */
3850  foreach(lc, rel->statlist)
3851  {
3852  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
3853  Bitmapset *shared;
3854  int nshared;
3855 
3856  /* skip statistics of other kinds */
3857  if (info->kind != STATS_EXT_NDISTINCT)
3858  continue;
3859 
3860  /* compute attnums shared by the vars and the statistics object */
3861  shared = bms_intersect(info->keys, attnums);
3862  nshared = bms_num_members(shared);
3863 
3864  /*
3865  * Does this statistics object match more columns than the currently
3866  * best object? If so, use this one instead.
3867  *
3868  * XXX This should break ties using name of the object, or something
3869  * like that, to make the outcome stable.
3870  */
3871  if (nshared > nmatches)
3872  {
3873  statOid = info->statOid;
3874  nmatches = nshared;
3875  matched = shared;
3876  }
3877  }
3878 
3879  /* No match? */
3880  if (statOid == InvalidOid)
3881  return false;
3882  Assert(nmatches > 1 && matched != NULL);
3883 
3884  stats = statext_ndistinct_load(statOid);
3885 
3886  /*
3887  * If we have a match, search it for the specific item that matches (there
3888  * must be one), and construct the output values.
3889  */
3890  if (stats)
3891  {
3892  int i;
3893  List *newlist = NIL;
3894  MVNDistinctItem *item = NULL;
3895 
3896  /* Find the specific item that exactly matches the combination */
3897  for (i = 0; i < stats->nitems; i++)
3898  {
3899  MVNDistinctItem *tmpitem = &stats->items[i];
3900 
3901  if (bms_subset_compare(tmpitem->attrs, matched) == BMS_EQUAL)
3902  {
3903  item = tmpitem;
3904  break;
3905  }
3906  }
3907 
3908  /* make sure we found an item */
3909  if (!item)
3910  elog(ERROR, "corrupt MVNDistinct entry");
3911 
3912  /* Form the output varinfo list, keeping only unmatched ones */
3913  foreach(lc, *varinfos)
3914  {
3915  GroupVarInfo *varinfo = (GroupVarInfo *) lfirst(lc);
3916  AttrNumber attnum;
3917 
3918  if (!IsA(varinfo->var, Var))
3919  {
3920  newlist = lappend(newlist, varinfo);
3921  continue;
3922  }
3923 
3924  attnum = ((Var *) varinfo->var)->varattno;
3925  if (!bms_is_member(attnum, matched))
3926  newlist = lappend(newlist, varinfo);
3927  }
3928 
3929  *varinfos = newlist;
3930  *ndistinct = item->ndistinct;
3931  return true;
3932  }
3933 
3934  return false;
3935 }
#define NIL
Definition: pg_list.h:69
#define STATS_EXT_NDISTINCT
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
List * statlist
Definition: relation.h:623
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:3236
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 Assert(condition)
Definition: c.h:681
#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:813
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:3237
double estimate_num_groups ( PlannerInfo root,
List groupExprs,
double  input_rows,
List **  pgset 
)

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

3362 {
3363  List *varinfos = NIL;
3364  double numdistinct;
3365  ListCell *l;
3366  int i;
3367 
3368  /*
3369  * We don't ever want to return an estimate of zero groups, as that tends
3370  * to lead to division-by-zero and other unpleasantness. The input_rows
3371  * estimate is usually already at least 1, but clamp it just in case it
3372  * isn't.
3373  */
3374  input_rows = clamp_row_est(input_rows);
3375 
3376  /*
3377  * If no grouping columns, there's exactly one group. (This can't happen
3378  * for normal cases with GROUP BY or DISTINCT, but it is possible for
3379  * corner cases with set operations.)
3380  */
3381  if (groupExprs == NIL || (pgset && list_length(*pgset) < 1))
3382  return 1.0;
3383 
3384  /*
3385  * Count groups derived from boolean grouping expressions. For other
3386  * expressions, find the unique Vars used, treating an expression as a Var
3387  * if we can find stats for it. For each one, record the statistical
3388  * estimate of number of distinct values (total in its table, without
3389  * regard for filtering).
3390  */
3391  numdistinct = 1.0;
3392 
3393  i = 0;
3394  foreach(l, groupExprs)
3395  {
3396  Node *groupexpr = (Node *) lfirst(l);
3397  VariableStatData vardata;
3398  List *varshere;
3399  ListCell *l2;
3400 
3401  /* is expression in this grouping set? */
3402  if (pgset && !list_member_int(*pgset, i++))
3403  continue;
3404 
3405  /* Short-circuit for expressions returning boolean */
3406  if (exprType(groupexpr) == BOOLOID)
3407  {
3408  numdistinct *= 2.0;
3409  continue;
3410  }
3411 
3412  /*
3413  * If examine_variable is able to deduce anything about the GROUP BY
3414  * expression, treat it as a single variable even if it's really more
3415  * complicated.
3416  */
3417  examine_variable(root, groupexpr, 0, &vardata);
3418  if (HeapTupleIsValid(vardata.statsTuple) || vardata.isunique)
3419  {
3420  varinfos = add_unique_group_var(root, varinfos,
3421  groupexpr, &vardata);
3422  ReleaseVariableStats(vardata);
3423  continue;
3424  }
3425  ReleaseVariableStats(vardata);
3426 
3427  /*
3428  * Else pull out the component Vars. Handle PlaceHolderVars by
3429  * recursing into their arguments (effectively assuming that the
3430  * PlaceHolderVar doesn't change the number of groups, which boils
3431  * down to ignoring the possible addition of nulls to the result set).
3432  */
3433  varshere = pull_var_clause(groupexpr,
3437 
3438  /*
3439  * If we find any variable-free GROUP BY item, then either it is a
3440  * constant (and we can ignore it) or it contains a volatile function;
3441  * in the latter case we punt and assume that each input row will
3442  * yield a distinct group.
3443  */
3444  if (varshere == NIL)
3445  {
3446  if (contain_volatile_functions(groupexpr))
3447  return input_rows;
3448  continue;
3449  }
3450 
3451  /*
3452  * Else add variables to varinfos list
3453  */
3454  foreach(l2, varshere)
3455  {
3456  Node *var = (Node *) lfirst(l2);
3457 
3458  examine_variable(root, var, 0, &vardata);
3459  varinfos = add_unique_group_var(root, varinfos, var, &vardata);
3460  ReleaseVariableStats(vardata);
3461  }
3462  }
3463 
3464  /*
3465  * If now no Vars, we must have an all-constant or all-boolean GROUP BY
3466  * list.
3467  */
3468  if (varinfos == NIL)
3469  {
3470  /* Guard against out-of-range answers */
3471  if (numdistinct > input_rows)
3472  numdistinct = input_rows;
3473  return numdistinct;
3474  }
3475 
3476  /*
3477  * Group Vars by relation and estimate total numdistinct.
3478  *
3479  * For each iteration of the outer loop, we process the frontmost Var in
3480  * varinfos, plus all other Vars in the same relation. We remove these
3481  * Vars from the newvarinfos list for the next iteration. This is the
3482  * easiest way to group Vars of same rel together.
3483  */
3484  do
3485  {
3486  GroupVarInfo *varinfo1 = (GroupVarInfo *) linitial(varinfos);
3487  RelOptInfo *rel = varinfo1->rel;
3488  double reldistinct = 1;
3489  double relmaxndistinct = reldistinct;
3490  int relvarcount = 0;
3491  List *newvarinfos = NIL;
3492  List *relvarinfos = NIL;
3493 
3494  /*
3495  * Split the list of varinfos in two - one for the current rel, one
3496  * for remaining Vars on other rels.
3497  */
3498  relvarinfos = lcons(varinfo1, relvarinfos);
3499  for_each_cell(l, lnext(list_head(varinfos)))
3500  {
3501  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3502 
3503  if (varinfo2->rel == varinfo1->rel)
3504  {
3505  /* varinfos on current rel */
3506  relvarinfos = lcons(varinfo2, relvarinfos);
3507  }
3508  else
3509  {
3510  /* not time to process varinfo2 yet */
3511  newvarinfos = lcons(varinfo2, newvarinfos);
3512  }
3513  }
3514 
3515  /*
3516  * Get the numdistinct estimate for the Vars of this rel. We
3517  * iteratively search for multivariate n-distinct with maximum number
3518  * of vars; assuming that each var group is independent of the others,
3519  * we multiply them together. Any remaining relvarinfos after no more
3520  * multivariate matches are found are assumed independent too, so
3521  * their individual ndistinct estimates are multiplied also.
3522  *
3523  * While iterating, count how many separate numdistinct values we
3524  * apply. We apply a fudge factor below, but only if we multiplied
3525  * more than one such values.
3526  */
3527  while (relvarinfos)
3528  {
3529  double mvndistinct;
3530 
3531  if (estimate_multivariate_ndistinct(root, rel, &relvarinfos,
3532  &mvndistinct))
3533  {
3534  reldistinct *= mvndistinct;
3535  if (relmaxndistinct < mvndistinct)
3536  relmaxndistinct = mvndistinct;
3537  relvarcount++;
3538  }
3539  else
3540  {
3541  foreach(l, relvarinfos)
3542  {
3543  GroupVarInfo *varinfo2 = (GroupVarInfo *) lfirst(l);
3544 
3545  reldistinct *= varinfo2->ndistinct;
3546  if (relmaxndistinct < varinfo2->ndistinct)
3547  relmaxndistinct = varinfo2->ndistinct;
3548  relvarcount++;
3549  }
3550 
3551  /* we're done with this relation */
3552  relvarinfos = NIL;
3553  }
3554  }
3555 
3556  /*
3557  * Sanity check --- don't divide by zero if empty relation.
3558  */
3559  Assert(IS_SIMPLE_REL(rel));
3560  if (rel->tuples > 0)
3561  {
3562  /*
3563  * Clamp to size of rel, or size of rel / 10 if multiple Vars. The
3564  * fudge factor is because the Vars are probably correlated but we
3565  * don't know by how much. We should never clamp to less than the
3566  * largest ndistinct value for any of the Vars, though, since
3567  * there will surely be at least that many groups.
3568  */
3569  double clamp = rel->tuples;
3570 
3571  if (relvarcount > 1)
3572  {
3573  clamp *= 0.1;
3574  if (clamp < relmaxndistinct)
3575  {
3576  clamp = relmaxndistinct;
3577  /* for sanity in case some ndistinct is too large: */
3578  if (clamp > rel->tuples)
3579  clamp = rel->tuples;
3580  }
3581  }
3582  if (reldistinct > clamp)
3583  reldistinct = clamp;
3584 
3585  /*
3586  * Update the estimate based on the restriction selectivity,
3587  * guarding against division by zero when reldistinct is zero.
3588  * Also skip this if we know that we are returning all rows.
3589  */
3590  if (reldistinct > 0 && rel->rows < rel->tuples)
3591  {
3592  /*
3593  * Given a table containing N rows with n distinct values in a
3594  * uniform distribution, if we select p rows at random then
3595  * the expected number of distinct values selected is
3596  *
3597  * n * (1 - product((N-N/n-i)/(N-i), i=0..p-1))
3598  *
3599  * = n * (1 - (N-N/n)! / (N-N/n-p)! * (N-p)! / N!)
3600  *
3601  * See "Approximating block accesses in database
3602  * organizations", S. B. Yao, Communications of the ACM,
3603  * Volume 20 Issue 4, April 1977 Pages 260-261.
3604  *
3605  * Alternatively, re-arranging the terms from the factorials,
3606  * this may be written as
3607  *
3608  * n * (1 - product((N-p-i)/(N-i), i=0..N/n-1))
3609  *
3610  * This form of the formula is more efficient to compute in
3611  * the common case where p is larger than N/n. Additionally,
3612  * as pointed out by Dell'Era, if i << N for all terms in the
3613  * product, it can be approximated by
3614  *
3615  * n * (1 - ((N-p)/N)^(N/n))
3616  *
3617  * See "Expected distinct values when selecting from a bag
3618  * without replacement", Alberto Dell'Era,
3619  * http://www.adellera.it/investigations/distinct_balls/.
3620  *
3621  * The condition i << N is equivalent to n >> 1, so this is a
3622  * good approximation when the number of distinct values in
3623  * the table is large. It turns out that this formula also
3624  * works well even when n is small.
3625  */
3626  reldistinct *=
3627  (1 - pow((rel->tuples - rel->rows) / rel->tuples,
3628  rel->tuples / reldistinct));
3629  }
3630  reldistinct = clamp_row_est(reldistinct);
3631 
3632  /*
3633  * Update estimate of total distinct groups.
3634  */
3635  numdistinct *= reldistinct;
3636  }
3637 
3638  varinfos = newvarinfos;
3639  } while (varinfos != NIL);
3640 
3641  numdistinct = ceil(numdistinct);
3642 
3643  /* Guard against out-of-range answers */
3644  if (numdistinct > input_rows)
3645  numdistinct = input_rows;
3646  if (numdistinct < 1.0)
3647  numdistinct = 1.0;
3648 
3649  return numdistinct;
3650 }
#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:625
Definition: nodes.h:510
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
double ndistinct
Definition: selfuncs.c:3238
#define PVC_RECURSE_PLACEHOLDERS
Definition: var.h:26
#define IS_SIMPLE_REL(rel)
Definition: relation.h:561
#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:3820
#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:3242
double rows
Definition: relation.h:588
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:4663
#define Assert(condition)
Definition: c.h:681
#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:174
Definition: pg_list.h:45
RelOptInfo * rel
Definition: selfuncs.c:3237
static void examine_simple_variable ( PlannerInfo root,
Var var,
VariableStatData vardata 
)
static

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

4876 {
4877  RangeTblEntry *rte = root->simple_rte_array[var->varno];
4878 
4879  Assert(IsA(rte, RangeTblEntry));
4880 
4882  (*get_relation_stats_hook) (root, rte, var->varattno, vardata))
4883  {
4884  /*
4885  * The hook took control of acquiring a stats tuple. If it did supply
4886  * a tuple, it'd better have supplied a freefunc.
4887  */
4888  if (HeapTupleIsValid(vardata->statsTuple) &&
4889  !vardata->freefunc)
4890  elog(ERROR, "no function provided to release variable stats with");
4891  }
4892  else if (rte->rtekind == RTE_RELATION)
4893  {
4894  /*
4895  * Plain table or parent of an inheritance appendrel, so look up the
4896  * column in pg_statistic
4897  */
4899  ObjectIdGetDatum(rte->relid),
4900  Int16GetDatum(var->varattno),
4901  BoolGetDatum(rte->inh));
4902  vardata->freefunc = ReleaseSysCache;
4903 
4904  if (HeapTupleIsValid(vardata->statsTuple))
4905  {
4906  /* check if user has permission to read this column */
4907  vardata->acl_ok =
4909  ACL_SELECT) == ACLCHECK_OK) ||
4911  ACL_SELECT) == ACLCHECK_OK);
4912  }
4913  else
4914  {
4915  /* suppress any possible leakproofness checks later */
4916  vardata->acl_ok = true;
4917  }
4918  }
4919  else if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
4920  {
4921  /*
4922  * Plain subquery (not one that was converted to an appendrel).
4923  */
4924  Query *subquery = rte->subquery;
4925  RelOptInfo *rel;
4926  TargetEntry *ste;
4927 
4928  /*
4929  * Punt if it's a whole-row var rather than a plain column reference.
4930  */
4931  if (var->varattno == InvalidAttrNumber)
4932  return;
4933 
4934  /*
4935  * Punt if subquery uses set operations or GROUP BY, as these will
4936  * mash underlying columns' stats beyond recognition. (Set ops are
4937  * particularly nasty; if we forged ahead, we would return stats
4938  * relevant to only the leftmost subselect...) DISTINCT is also
4939  * problematic, but we check that later because there is a possibility
4940  * of learning something even with it.
4941  */
4942  if (subquery->setOperations ||
4943  subquery->groupClause)
4944  return;
4945 
4946  /*
4947  * OK, fetch RelOptInfo for subquery. Note that we don't change the
4948  * rel returned in vardata, since caller expects it to be a rel of the
4949  * caller's query level. Because we might already be recursing, we
4950  * can't use that rel pointer either, but have to look up the Var's
4951  * rel afresh.
4952  */
4953  rel = find_base_rel(root, var->varno);
4954 
4955  /* If the subquery hasn't been planned yet, we have to punt */
4956  if (rel->subroot == NULL)
4957  return;
4958  Assert(IsA(rel->subroot, PlannerInfo));
4959 
4960  /*
4961  * Switch our attention to the subquery as mangled by the planner. It
4962  * was okay to look at the pre-planning version for the tests above,
4963  * but now we need a Var that will refer to the subroot's live
4964  * RelOptInfos. For instance, if any subquery pullup happened during
4965  * planning, Vars in the targetlist might have gotten replaced, and we
4966  * need to see the replacement expressions.
4967  */
4968  subquery = rel->subroot->parse;
4969  Assert(IsA(subquery, Query));
4970 
4971  /* Get the subquery output expression referenced by the upper Var */
4972  ste = get_tle_by_resno(subquery->targetList, var->varattno);
4973  if (ste == NULL || ste->resjunk)
4974  elog(ERROR, "subquery %s does not have attribute %d",
4975  rte->eref->aliasname, var->varattno);
4976  var = (Var *) ste->expr;
4977 
4978  /*
4979  * If subquery uses DISTINCT, we can't make use of any stats for the
4980  * variable ... but, if it's the only DISTINCT column, we are entitled
4981  * to consider it unique. We do the test this way so that it works
4982  * for cases involving DISTINCT ON.
4983  */
4984  if (subquery->distinctClause)
4985  {
4986  if (list_length(subquery->distinctClause) == 1 &&
4987  targetIsInSortList(ste, InvalidOid, subquery->distinctClause))
4988  vardata->isunique = true;
4989  /* cannot go further */
4990  return;
4991  }
4992 
4993  /*
4994  * If the sub-query originated from a view with the security_barrier
4995  * attribute, we must not look at the variable's statistics, though it
4996  * seems all right to notice the existence of a DISTINCT clause. So
4997  * stop here.
4998  *
4999  * This is probably a harsher restriction than necessary; it's
5000  * certainly OK for the selectivity estimator (which is a C function,
5001  * and therefore omnipotent anyway) to look at the statistics. But
5002  * many selectivity estimators will happily *invoke the operator
5003  * function* to try to work out a good estimate - and that's not OK.
5004  * So for now, don't dig down for stats.
5005  */
5006  if (rte->security_barrier)
5007  return;
5008 
5009  /* Can only handle a simple Var of subquery's query level */
5010  if (var && IsA(var, Var) &&
5011  var->varlevelsup == 0)
5012  {
5013  /*
5014  * OK, recurse into the subquery. Note that the original setting
5015  * of vardata->isunique (which will surely be false) is left
5016  * unchanged in this situation. That's what we want, since even
5017  * if the underlying column is unique, the subquery may have
5018  * joined to other tables in a way that creates duplicates.
5019  */
5020  examine_simple_variable(rel->subroot, var, vardata);
5021  }
5022  }
5023  else
5024  {
5025  /*
5026  * Otherwise, the Var comes from a FUNCTION, VALUES, or CTE RTE. (We
5027  * won't see RTE_JOIN here because join alias Vars have already been
5028  * flattened.) There's not much we can do with function outputs, but
5029  * maybe someday try to be smarter about VALUES and/or CTEs.
5030  */
5031  }
5032 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Query * parse
Definition: relation.h:155
Index varlevelsup
Definition: primnodes.h:173
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4308
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
#define Int16GetDatum(X)
Definition: postgres.h:457
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4874
List * targetList
Definition: parsenodes.h:138
PlannerInfo * subroot
Definition: relation.h:627
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
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
get_relation_stats_hook_type get_relation_stats_hook
Definition: selfuncs.c:155
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
Index varno
Definition: primnodes.h:166
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:73
bool security_barrier
Definition: parsenodes.h:969
#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 Assert(condition)
Definition: c.h:681
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:945
Node * setOperations
Definition: parsenodes.h:163
Query * subquery
Definition: parsenodes.h:968
List * groupClause
Definition: parsenodes.h:146
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define elog
Definition: elog.h:219
Alias * eref
Definition: parsenodes.h:1049
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
void examine_variable ( PlannerInfo root,
Node node,
int  varRelid,
VariableStatData vardata 
)

Definition at line 4663 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, ObjectIdGetDatum, pg_class_aclcheck(), planner_rt_fetch, IndexOptInfo::predOK, pull_varnos(), VariableStatData::rel, IndexOptInfo::rel, ReleaseSysCache(), RelOptInfo::relid, RangeTblEntry::relid, RTE_RELATION, RangeTblEntry::rtekind, SearchSysCache3(), STATRELATTINH, VariableStatData::statsTuple, IndexOptInfo::unique, VariableStatData::var, Var::varattno, Var::varno, VariableStatData::vartype, Var::vartype, and Var::vartypmod.

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

4665 {
4666  Node *basenode;
4667  Relids varnos;
4668  RelOptInfo *onerel;
4669 
4670  /* Make sure we don't return dangling pointers in vardata */
4671  MemSet(vardata, 0, sizeof(VariableStatData));
4672 
4673  /* Save the exposed type of the expression */
4674  vardata->vartype = exprType(node);
4675 
4676  /* Look inside any binary-compatible relabeling */
4677 
4678  if (IsA(node, RelabelType))
4679  basenode = (Node *) ((RelabelType *) node)->arg;
4680  else
4681  basenode = node;
4682 
4683  /* Fast path for a simple Var */
4684 
4685  if (IsA(basenode, Var) &&
4686  (varRelid == 0 || varRelid == ((Var *) basenode)->varno))
4687  {
4688  Var *var = (Var *) basenode;
4689 
4690  /* Set up result fields other than the stats tuple */
4691  vardata->var = basenode; /* return Var without relabeling */
4692  vardata->rel = find_base_rel(root, var->varno);
4693  vardata->atttype = var->vartype;
4694  vardata->atttypmod = var->vartypmod;
4695  vardata->isunique = has_unique_index(vardata->rel, var->varattno);
4696 
4697  /* Try to locate some stats */
4698  examine_simple_variable(root, var, vardata);
4699 
4700  return;
4701  }
4702 
4703  /*
4704  * Okay, it's a more complicated expression. Determine variable
4705  * membership. Note that when varRelid isn't zero, only vars of that
4706  * relation are considered "real" vars.
4707  */
4708  varnos = pull_varnos(basenode);
4709 
4710  onerel = NULL;
4711 
4712  switch (bms_membership(varnos))
4713  {
4714  case BMS_EMPTY_SET:
4715  /* No Vars at all ... must be pseudo-constant clause */
4716  break;
4717  case BMS_SINGLETON:
4718  if (varRelid == 0 || bms_is_member(varRelid, varnos))
4719  {
4720  onerel = find_base_rel(root,
4721  (varRelid ? varRelid : bms_singleton_member(varnos)));
4722  vardata->rel = onerel;
4723  node = basenode; /* strip any relabeling */
4724  }
4725  /* else treat it as a constant */
4726  break;
4727  case BMS_MULTIPLE:
4728  if (varRelid == 0)
4729  {
4730  /* treat it as a variable of a join relation */
4731  vardata->rel = find_join_rel(root, varnos);
4732  node = basenode; /* strip any relabeling */
4733  }
4734  else if (bms_is_member(varRelid, varnos))
4735  {
4736  /* ignore the vars belonging to other relations */
4737  vardata->rel = find_base_rel(root, varRelid);
4738  node = basenode; /* strip any relabeling */
4739  /* note: no point in expressional-index search here */
4740  }
4741  /* else treat it as a constant */
4742  break;
4743  }
4744 
4745  bms_free(varnos);
4746 
4747  vardata->var = node;
4748  vardata->atttype = exprType(node);
4749  vardata->atttypmod = exprTypmod(node);
4750 
4751  if (onerel)
4752  {
4753  /*
4754  * We have an expression in vars of a single relation. Try to match
4755  * it to expressional index columns, in hopes of finding some
4756  * statistics.
4757  *
4758  * XXX it's conceivable that there are multiple matches with different
4759  * index opfamilies; if so, we need to pick one that matches the
4760  * operator we are estimating for. FIXME later.
4761  */
4762  ListCell *ilist;
4763 
4764  foreach(ilist, onerel->indexlist)
4765  {
4766  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
4767  ListCell *indexpr_item;
4768  int pos;
4769 
4770  indexpr_item = list_head(index->indexprs);
4771  if (indexpr_item == NULL)
4772  continue; /* no expressions here... */
4773 
4774  for (pos = 0; pos < index->ncolumns; pos++)
4775  {
4776  if (index->indexkeys[pos] == 0)
4777  {
4778  Node *indexkey;
4779 
4780  if (indexpr_item == NULL)
4781  elog(ERROR, "too few entries in indexprs list");
4782  indexkey = (Node *) lfirst(indexpr_item);
4783  if (indexkey && IsA(indexkey, RelabelType))
4784  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4785  if (equal(node, indexkey))
4786  {
4787  /*
4788  * Found a match ... is it a unique index? Tests here
4789  * should match has_unique_index().
4790  */
4791  if (index->unique &&
4792  index->ncolumns == 1 &&
4793  (index->indpred == NIL || index->predOK))
4794  vardata->isunique = true;
4795 
4796  /*
4797  * Has it got stats? We only consider stats for
4798  * non-partial indexes, since partial indexes probably
4799  * don't reflect whole-relation statistics; the above
4800  * check for uniqueness is the only info we take from
4801  * a partial index.
4802  *
4803  * An index stats hook, however, must make its own
4804  * decisions about what to do with partial indexes.
4805  */
4806  if (get_index_stats_hook &&
4807  (*get_index_stats_hook) (root, index->indexoid,
4808  pos + 1, vardata))
4809  {
4810  /*
4811  * The hook took control of acquiring a stats
4812  * tuple. If it did supply a tuple, it'd better
4813  * have supplied a freefunc.
4814  */
4815  if (HeapTupleIsValid(vardata->statsTuple) &&
4816  !vardata->freefunc)
4817  elog(ERROR, "no function provided to release variable stats with");
4818  }
4819  else if (index->indpred == NIL)
4820  {
4821  vardata->statsTuple =
4823  ObjectIdGetDatum(index->indexoid),
4824  Int16GetDatum(pos + 1),
4825  BoolGetDatum(false));
4826  vardata->freefunc = ReleaseSysCache;
4827 
4828  if (HeapTupleIsValid(vardata->statsTuple))
4829  {
4830  /* Get index's table for permission check */
4831  RangeTblEntry *rte;
4832 
4833  rte = planner_rt_fetch(index->rel->relid, root);
4834  Assert(rte->rtekind == RTE_RELATION);
4835 
4836  /*
4837  * For simplicity, we insist on the whole
4838  * table being selectable, rather than trying
4839  * to identify which column(s) the index
4840  * depends on.
4841  */
4842  vardata->acl_ok =
4844  ACL_SELECT) == ACLCHECK_OK);
4845  }
4846  else
4847  {
4848  /* suppress leakproofness checks later */
4849  vardata->acl_ok = true;
4850  }
4851  }
4852  if (vardata->statsTuple)
4853  break;
4854  }
4855  indexpr_item = lnext(indexpr_item);
4856  }
4857  }
4858  if (vardata->statsTuple)
4859  break;
4860  }
4861  }
4862 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
bool predOK
Definition: relation.h:752
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:342
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2972
HeapTuple statsTuple
Definition: selfuncs.h:71
Oid GetUserId(void)
Definition: miscinit.c:284
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
RelOptInfo * rel
Definition: selfuncs.h:70
#define Int16GetDatum(X)
Definition: postgres.h:457
Definition: nodes.h:510
#define MemSet(start, val, len)
Definition: c.h:863
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
static void examine_simple_variable(PlannerInfo *root, Var *var, VariableStatData *vardata)
Definition: selfuncs.c:4874
int32 atttypmod
Definition: selfuncs.h:76
bool unique
Definition: relation.h:753
Definition: type.h:89
RelOptInfo * rel
Definition: relation.h:721
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1746
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid vartype
Definition: primnodes.h:170
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
int ncolumns
Definition: relation.h:729
#define lnext(lc)
Definition: pg_list.h:105
Relids pull_varnos(Node *node)
Definition: var.c:95
Index relid
Definition: relation.h:613
Index varno
Definition: primnodes.h:166
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:634
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define ACL_SELECT
Definition: parsenodes.h:73
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:526
List * indexlist
Definition: relation.h:622
#define BoolGetDatum(X)
Definition: postgres.h:408
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Assert(condition)
Definition: c.h:681
#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:156
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
RTEKind rtekind
Definition: parsenodes.h:945
void * arg
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
void(* freefunc)(HeapTuple tuple)
Definition: selfuncs.h:73
List * indpred
Definition: relation.h:742
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
List * indexprs
Definition: relation.h:741
int32 vartypmod
Definition: primnodes.h:171
static RelOptInfo * find_join_input_rel ( PlannerInfo root,
Relids  relids 
)
static

Definition at line 5576 of file selfuncs.c.

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

Referenced by eqjoinsel().

5577 {
5578  RelOptInfo *rel = NULL;
5579 
5580  switch (bms_membership(relids))
5581  {
5582  case BMS_EMPTY_SET:
5583  /* should not happen */
5584  break;
5585  case BMS_SINGLETON:
5586  rel = find_base_rel(root, bms_singleton_member(relids));
5587  break;
5588  case BMS_MULTIPLE:
5589  rel = find_join_rel(root, relids);
5590  break;
5591  }
5592 
5593  if (rel == NULL)
5594  elog(ERROR, "could not find RelOptInfo for given relids");
5595 
5596  return rel;
5597 }
RelOptInfo * find_join_rel(PlannerInfo *root, Relids relids)
Definition: relnode.c:342
#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 elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
void genericcostestimate ( PlannerInfo root,
IndexPath path,
double  loop_count,
List qinfos,
GenericCosts costs 
)

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

6579 {
6580  IndexOptInfo *index = path->indexinfo;
6581  List *indexQuals = path->indexquals;
6582  List *indexOrderBys = path->indexorderbys;
6583  Cost indexStartupCost;
6584  Cost indexTotalCost;
6585  Selectivity indexSelectivity;
6586  double indexCorrelation;
6587  double numIndexPages;
6588  double numIndexTuples;
6589  double spc_random_page_cost;
6590  double num_sa_scans;
6591  double num_outer_scans;
6592  double num_scans;
6593  double qual_op_cost;
6594  double qual_arg_cost;
6595  List *selectivityQuals;
6596  ListCell *l;
6597 
6598  /*
6599  * If the index is partial, AND the index predicate with the explicitly
6600  * given indexquals to produce a more accurate idea of the index
6601  * selectivity.
6602  */
6603  selectivityQuals = add_predicate_to_quals(index, indexQuals);
6604 
6605  /*
6606  * Check for ScalarArrayOpExpr index quals, and estimate the number of
6607  * index scans that will be performed.
6608  */
6609  num_sa_scans = 1;
6610  foreach(l, indexQuals)
6611  {
6612  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
6613 
6614  if (IsA(rinfo->clause, ScalarArrayOpExpr))
6615  {
6616  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
6617  int alength = estimate_array_length(lsecond(saop->args));
6618 
6619  if (alength > 1)
6620  num_sa_scans *= alength;
6621  }
6622  }
6623 
6624  /* Estimate the fraction of main-table tuples that will be visited */
6625  indexSelectivity = clauselist_selectivity(root, selectivityQuals,
6626  index->rel->relid,
6627  JOIN_INNER,
6628  NULL);
6629 
6630  /*
6631  * If caller didn't give us an estimate, estimate the number of index
6632  * tuples that will be visited. We do it in this rather peculiar-looking
6633  * way in order to get the right answer for partial indexes.
6634  */
6635  numIndexTuples = costs->numIndexTuples;
6636  if (numIndexTuples <= 0.0)
6637  {
6638  numIndexTuples = indexSelectivity * index->rel->tuples;
6639 
6640  /*
6641  * The above calculation counts all the tuples visited across all
6642  * scans induced by ScalarArrayOpExpr nodes. We want to consider the
6643  * average per-indexscan number, so adjust. This is a handy place to
6644  * round to integer, too. (If caller supplied tuple estimate, it's
6645  * responsible for handling these considerations.)
6646  */
6647  numIndexTuples = rint(numIndexTuples / num_sa_scans);
6648  }
6649 
6650  /*
6651  * We can bound the number of tuples by the index size in any case. Also,
6652  * always estimate at least one tuple is touched, even when
6653  * indexSelectivity estimate is tiny.
6654  */
6655  if (numIndexTuples > index->tuples)
6656  numIndexTuples = index->tuples;
6657  if (numIndexTuples < 1.0)
6658  numIndexTuples = 1.0;
6659 
6660  /*
6661  * Estimate the number of index pages that will be retrieved.
6662  *
6663  * We use the simplistic method of taking a pro-rata fraction of the total
6664  * number of index pages. In effect, this counts only leaf pages and not
6665  * any overhead such as index metapage or upper tree levels.
6666  *
6667  * In practice access to upper index levels is often nearly free because
6668  * those tend to stay in cache under load; moreover, the cost involved is
6669  * highly dependent on index type. We therefore ignore such costs here
6670  * and leave it to the caller to add a suitable charge if needed.
6671  */
6672  if (index->pages > 1 && index->tuples > 1)
6673  numIndexPages = ceil(numIndexTuples * index->pages / index->tuples);
6674  else
6675  numIndexPages = 1.0;
6676 
6677  /* fetch estimated page cost for tablespace containing index */
6679  &spc_random_page_cost,
6680  NULL);
6681 
6682  /*
6683  * Now compute the disk access costs.
6684  *
6685  * The above calculations are all per-index-scan. However, if we are in a
6686  * nestloop inner scan, we can expect the scan to be repeated (with
6687  * different search keys) for each row of the outer relation. Likewise,
6688  * ScalarArrayOpExpr quals result in multiple index scans. This creates
6689  * the potential for cache effects to reduce the number of disk page
6690  * fetches needed. We want to estimate the average per-scan I/O cost in
6691  * the presence of caching.
6692  *
6693  * We use the Mackert-Lohman formula (see costsize.c for details) to
6694  * estimate the total number of page fetches that occur. While this
6695  * wasn't what it was designed for, it seems a reasonable model anyway.
6696  * Note that we are counting pages not tuples anymore, so we take N = T =
6697  * index size, as if there were one "tuple" per page.
6698  */
6699  num_outer_scans = loop_count;
6700  num_scans = num_sa_scans * num_outer_scans;
6701 
6702  if (num_scans > 1)
6703  {
6704  double pages_fetched;
6705 
6706  /* total page fetches ignoring cache effects */
6707  pages_fetched = numIndexPages * num_scans;
6708 
6709  /* use Mackert and Lohman formula to adjust for cache effects */
6710  pages_fetched = index_pages_fetched(pages_fetched,
6711  index->pages,
6712  (double) index->pages,
6713  root);
6714 
6715  /*
6716  * Now compute the total disk access cost, and then report a pro-rated
6717  * share for each outer scan. (Don't pro-rate for ScalarArrayOpExpr,
6718  * since that's internal to the indexscan.)
6719  */
6720  indexTotalCost = (pages_fetched * spc_random_page_cost)
6721  / num_outer_scans;
6722  }
6723  else
6724  {
6725  /*
6726  * For a single index scan, we just charge spc_random_page_cost per
6727  * page touched.
6728  */
6729  indexTotalCost = numIndexPages * spc_random_page_cost;
6730  }
6731 
6732  /*
6733  * CPU cost: any complex expressions in the indexquals will need to be
6734  * evaluated once at the start of the scan to reduce them to runtime keys
6735  * to pass to the index AM (see nodeIndexscan.c). We model the per-tuple
6736  * CPU costs as cpu_index_tuple_cost plus one cpu_operator_cost per
6737  * indexqual operator. Because we have numIndexTuples as a per-scan
6738  * number, we have to multiply by num_sa_scans to get the correct result
6739  * for ScalarArrayOpExpr cases. Similarly add in costs for any index
6740  * ORDER BY expressions.
6741  *
6742  * Note: this neglects the possible costs of rechecking lossy operators.
6743  * Detecting that that might be needed seems more expensive than it's
6744  * worth, though, considering all the other inaccuracies here ...
6745  */
6746  qual_arg_cost = other_operands_eval_cost(root, qinfos) +
6747  orderby_operands_eval_cost(root, path);
6748  qual_op_cost = cpu_operator_cost *
6749  (list_length(indexQuals) + list_length(indexOrderBys));
6750 
6751  indexStartupCost = qual_arg_cost;
6752  indexTotalCost += qual_arg_cost;
6753  indexTotalCost += numIndexTuples * num_sa_scans * (cpu_index_tuple_cost + qual_op_cost);
6754 
6755  /*
6756  * Generic assumption about index correlation: there isn't any.
6757  */
6758  indexCorrelation = 0.0;
6759 
6760  /*
6761  * Return everything to caller.
6762  */
6763  costs->indexStartupCost = indexStartupCost;
6764  costs->indexTotalCost = indexTotalCost;
6765  costs->indexSelectivity = indexSelectivity;
6766  costs->indexCorrelation = indexCorrelation;
6767  costs->numIndexPages = numIndexPages;
6768  costs->numIndexTuples = numIndexTuples;
6769  costs->spc_random_page_cost = spc_random_page_cost;
6770  costs->num_sa_scans = num_sa_scans;
6771 }
Selectivity indexSelectivity
Definition: selfuncs.h:131
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
IndexOptInfo * indexinfo
Definition: relation.h:1119
double tuples
Definition: relation.h:625
static List * add_predicate_to_quals(IndexOptInfo *index, List *indexQuals)
Definition: selfuncs.c:6793
Oid reltablespace
Definition: relation.h:720
static Cost other_operands_eval_cost(PlannerInfo *root, List *qinfos)
Definition: selfuncs.c:6520
double Selectivity
Definition: nodes.h:640
double tuples
Definition: relation.h:725
#define lsecond(l)
Definition: pg_list.h:116
static Cost orderby_operands_eval_cost(PlannerInfo *root, IndexPath *path)
Definition: selfuncs.c:6545
Definition: type.h:89
BlockNumber pages
Definition: relation.h:724
List * indexquals
Definition: relation.h:1121
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2167
RelOptInfo * rel
Definition: relation.h:721
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:613
Expr * clause
Definition: relation.h:1835
double indexCorrelation
Definition: selfuncs.h:132
List * indexorderbys
Definition: relation.h:1123
double spc_random_page_cost
Definition: selfuncs.h:137
double numIndexTuples
Definition: selfuncs.h:136
#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:814
double Cost
Definition: nodes.h:641
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 5337 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, InitNonVacuumableSnapshot, InvalidBuffer, InvalidOid, InvalidStrategy, lfirst, MakeSingleTupleTableSlot(), match_index_to_operand(), MemoryContextSwitchTo(), NIL, NoLock, RecentGlobalXmin, 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().

5340 {
5341  bool have_data = false;
5342  RelOptInfo *rel = vardata->rel;
5343  RangeTblEntry *rte;
5344  ListCell *lc;
5345 
5346  /* No hope if no relation or it doesn't have indexes */
5347  if (rel == NULL || rel->indexlist == NIL)
5348  return false;
5349  /* If it has indexes it must be a plain relation */
5350  rte = root->simple_rte_array[rel->relid];
5351  Assert(rte->rtekind == RTE_RELATION);
5352 
5353  /* Search through the indexes to see if any match our problem */
5354  foreach(lc, rel->indexlist)
5355  {
5357  ScanDirection indexscandir;
5358 
5359  /* Ignore non-btree indexes */
5360  if (index->relam != BTREE_AM_OID)
5361  continue;
5362 
5363  /*
5364  * Ignore partial indexes --- we only want stats that cover the entire
5365  * relation.
5366  */
5367  if (index->indpred != NIL)
5368  continue;
5369 
5370  /*
5371  * The index list might include hypothetical indexes inserted by a
5372  * get_relation_info hook --- don't try to access them.
5373  */
5374  if (index->hypothetical)
5375  continue;
5376 
5377  /*
5378  * The first index column must match the desired variable and sort
5379  * operator --- but we can use a descending-order index.
5380  */
5381  if (!match_index_to_operand(vardata->var, 0, index))
5382  continue;
5383  switch (get_op_opfamily_strategy(sortop, index->sortopfamily[0]))
5384  {
5385  case BTLessStrategyNumber:
5386  if (index->reverse_sort[0])
5387  indexscandir = BackwardScanDirection;
5388  else
5389  indexscandir = ForwardScanDirection;
5390  break;
5392  if (index->reverse_sort[0])
5393  indexscandir = ForwardScanDirection;
5394  else
5395  indexscandir = BackwardScanDirection;
5396  break;
5397  default:
5398  /* index doesn't match the sortop */
5399  continue;
5400  }
5401 
5402  /*
5403  * Found a suitable index to extract data from. We'll need an EState
5404  * and a bunch of other infrastructure.
5405  */
5406  {
5407  EState *estate;
5408  ExprContext *econtext;
5409  MemoryContext tmpcontext;
5410  MemoryContext oldcontext;
5411  Relation heapRel;
5412  Relation indexRel;
5413  IndexInfo *indexInfo;
5414  TupleTableSlot *slot;
5415  int16 typLen;
5416  bool typByVal;
5417  ScanKeyData scankeys[1];
5418  IndexScanDesc index_scan;
5419  HeapTuple tup;
5421  bool isnull[INDEX_MAX_KEYS];
5422  SnapshotData SnapshotNonVacuumable;
5423 
5424  estate = CreateExecutorState();
5425  econtext = GetPerTupleExprContext(estate);
5426  /* Make sure any cruft is generated in the econtext's memory */
5427  tmpcontext = econtext->ecxt_per_tuple_memory;
5428  oldcontext = MemoryContextSwitchTo(tmpcontext);
5429 
5430  /*
5431  * Open the table and index so we can read from them. We should
5432  * already have at least AccessShareLock on the table, but not
5433  * necessarily on the index.
5434  */
5435  heapRel = heap_open(rte->relid, NoLock);
5436  indexRel = index_open(index->indexoid, AccessShareLock);
5437 
5438  /* extract index key information from the index's pg_index info */
5439  indexInfo = BuildIndexInfo(indexRel);
5440 
5441  /* some other stuff */
5442  slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRel));
5443  econtext->ecxt_scantuple = slot;
5444  get_typlenbyval(vardata->atttype, &typLen, &typByVal);
5445  InitNonVacuumableSnapshot(SnapshotNonVacuumable, RecentGlobalXmin);
5446 
5447  /* set up an IS NOT NULL scan key so that we ignore nulls */
5448  ScanKeyEntryInitialize(&scankeys[0],
5450  1, /* index col to scan */
5451  InvalidStrategy, /* no strategy */
5452  InvalidOid, /* no strategy subtype */
5453  InvalidOid, /* no collation */
5454  InvalidOid, /* no reg proc for this */
5455  (Datum) 0); /* constant */
5456 
5457  have_data = true;
5458 
5459  /* If min is requested ... */
5460  if (min)
5461  {
5462  /*
5463  * In principle, we should scan the index with our current
5464  * active snapshot, which is the best approximation we've got
5465  * to what the query will see when executed. But that won't
5466  * be exact if a new snap is taken before running the query,
5467  * and it can be very expensive if a lot of recently-dead or
5468  * uncommitted rows exist at the beginning or end of the index
5469  * (because we'll laboriously fetch each one and reject it).
5470  * Instead, we use SnapshotNonVacuumable. That will accept
5471  * recently-dead and uncommitted rows as well as normal
5472  * visible rows. On the other hand, it will reject known-dead
5473  * rows, and thus not give a bogus answer when the extreme
5474  * value has been deleted (unless the deletion was quite
5475  * recent); that case motivates not using SnapshotAny here.
5476  *
5477  * A crucial point here is that SnapshotNonVacuumable, with
5478  * RecentGlobalXmin as horizon, yields the inverse of the
5479  * condition that the indexscan will use to decide that index
5480  * entries are killable (see heap_hot_search_buffer()).
5481  * Therefore, if the snapshot rejects a tuple and we have to
5482  * continue scanning past it, we know that the indexscan will
5483  * mark that index entry killed. That means that the next
5484  * get_actual_variable_range() call will not have to visit
5485  * that heap entry. In this way we avoid repetitive work when
5486  * this function is used a lot during planning.
5487  */
5488  index_scan = index_beginscan(heapRel, indexRel,
5489  &SnapshotNonVacuumable,
5490  1, 0);
5491  index_rescan(index_scan, scankeys, 1, NULL, 0);
5492 
5493  /* Fetch first tuple in sortop's direction */
5494  if ((tup = index_getnext(index_scan,
5495  indexscandir)) != NULL)
5496  {
5497  /* Extract the index column values from the heap tuple */
5498  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5499  FormIndexDatum(indexInfo, slot, estate,
5500  values, isnull);
5501 
5502  /* Shouldn't have got a null, but be careful */
5503  if (isnull[0])
5504  elog(ERROR, "found unexpected null value in index \"%s\"",
5505  RelationGetRelationName(indexRel));
5506 
5507  /* Copy the index column value out to caller's context */
5508  MemoryContextSwitchTo(oldcontext);
5509  *min = datumCopy(values[0], typByVal, typLen);
5510  MemoryContextSwitchTo(tmpcontext);
5511  }
5512  else
5513  have_data = false;
5514 
5515  index_endscan(index_scan);
5516  }
5517 
5518  /* If max is requested, and we didn't find the index is empty */
5519  if (max && have_data)
5520  {
5521  index_scan = index_beginscan(heapRel, indexRel,
5522  &SnapshotNonVacuumable,
5523  1, 0);
5524  index_rescan(index_scan, scankeys, 1, NULL, 0);
5525 
5526  /* Fetch first tuple in reverse direction */
5527  if ((tup = index_getnext(index_scan,
5528  -indexscandir)) != NULL)
5529  {
5530  /* Extract the index column values from the heap tuple */
5531  ExecStoreTuple(tup, slot, InvalidBuffer, false);
5532  FormIndexDatum(indexInfo, slot, estate,
5533  values, isnull);
5534 
5535  /* Shouldn't have got a null, but be careful */
5536  if (isnull[0])
5537  elog(ERROR, "found unexpected null value in index \"%s\"",
5538  RelationGetRelationName(indexRel));
5539 
5540  /* Copy the index column value out to caller's context */
5541  MemoryContextSwitchTo(oldcontext);
5542  *max = datumCopy(values[0], typByVal, typLen);
5543  MemoryContextSwitchTo(tmpcontext);
5544  }
5545  else
5546  have_data = false;
5547 
5548  index_endscan(index_scan);
5549  }
5550 
5551  /* Clean everything up */
5553 
5554  index_close(indexRel, AccessShareLock);
5555  heap_close(heapRel, NoLock);
5556 
5557  MemoryContextSwitchTo(oldcontext);
5558  FreeExecutorState(estate);
5559 
5560  /* And we're done */
5561  break;
5562  }
5563  }
5564 
5565  return have_data;
5566 }
signed short int16
Definition: c.h:245
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1771
#define InvalidStrategy
Definition: stratnum.h:24
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
#define InitNonVacuumableSnapshot(snapshotdata, xmin_horizon)
Definition: tqual.h:110
#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:734
bool hypothetical
Definition: relation.h:755
#define heap_close(r, l)
Definition: heapam.h:97
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1642
Definition: type.h:89
void FreeExecutorState(EState *estate)
Definition: execUtils.c:183
#define GetPerTupleExprContext(estate)
Definition: executor.h:477
#define ERROR
Definition: elog.h:43
#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
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
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:613
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
List * indexlist
Definition: relation.h:622
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:681
#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:945
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int get_op_opfamily_strategy(Oid opno, Oid opfamily)
Definition: lsyscache.c:80
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:719
bool * reverse_sort
Definition: relation.h:735
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:742
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 4601 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().

4604 {
4605  Node *left,
4606  *right;
4607 
4608  if (list_length(args) != 2)
4609  elog(ERROR, "join operator should take two arguments");
4610 
4611  left = (Node *) linitial(args);
4612  right = (Node *) lsecond(args);
4613 
4614  examine_variable(root, left, 0, vardata1);
4615  examine_variable(root, right, 0, vardata2);
4616 
4617  if (vardata1->rel &&
4618  bms_is_subset(vardata1->rel->relids, sjinfo->syn_righthand))
4619  *join_is_reversed = true; /* var1 is on RHS */
4620  else if (vardata2->rel &&
4621  bms_is_subset(vardata2->rel->relids, sjinfo->syn_lefthand))
4622  *join_is_reversed = true; /* var2 is on LHS */
4623  else
4624  *join_is_reversed = false;
4625 }