PostgreSQL Source Code  git master
extended_stats.c File Reference
#include "postgres.h"
#include "access/detoast.h"
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "catalog/indexing.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "executor/executor.h"
#include "commands/defrem.h"
#include "commands/progress.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "parser/parsetree.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/attoptcache.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for extended_stats.c:

Go to the source code of this file.

Data Structures

struct  StatExtEntry
 
struct  AnlExprData
 

Macros

#define WIDTH_THRESHOLD   1024
 

Typedefs

typedef struct StatExtEntry StatExtEntry
 
typedef struct AnlExprData AnlExprData
 

Functions

static Listfetch_statentries_for_relation (Relation pg_statext, Oid relid)
 
static VacAttrStats ** lookup_var_attr_stats (Relation rel, Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
 
static void statext_store (Oid statOid, bool inh, MVNDistinct *ndistinct, MVDependencies *dependencies, MCVList *mcv, Datum exprs, VacAttrStats **stats)
 
static int statext_compute_stattarget (int stattarget, int nattrs, VacAttrStats **stats)
 
static void compute_expr_stats (Relation onerel, double totalrows, AnlExprData *exprdata, int nexprs, HeapTuple *rows, int numrows)
 
static Datum serialize_expr_stats (AnlExprData *exprdata, int nexprs)
 
static Datum expr_fetch_func (VacAttrStatsP stats, int rownum, bool *isNull)
 
static AnlExprDatabuild_expr_data (List *exprs, int stattarget)
 
static StatsBuildDatamake_build_data (Relation rel, StatExtEntry *stat, int numrows, HeapTuple *rows, VacAttrStats **stats, int stattarget)
 
void BuildRelationExtStatistics (Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
 
int ComputeExtStatisticsRows (Relation onerel, int natts, VacAttrStats **vacattrstats)
 
bool statext_is_kind_built (HeapTuple htup, char type)
 
static VacAttrStatsexamine_attribute (Node *expr)
 
static VacAttrStatsexamine_expression (Node *expr, int stattarget)
 
MultiSortSupport multi_sort_init (int ndims)
 
void multi_sort_add_dimension (MultiSortSupport mss, int sortdim, Oid oper, Oid collation)
 
int multi_sort_compare (const void *a, const void *b, void *arg)
 
int multi_sort_compare_dim (int dim, const SortItem *a, const SortItem *b, MultiSortSupport mss)
 
int multi_sort_compare_dims (int start, int end, const SortItem *a, const SortItem *b, MultiSortSupport mss)
 
int compare_scalars_simple (const void *a, const void *b, void *arg)
 
int compare_datums_simple (Datum a, Datum b, SortSupport ssup)
 
AttrNumberbuild_attnums_array (Bitmapset *attrs, int nexprs, int *numattrs)
 
SortItembuild_sorted_items (StatsBuildData *data, int *nitems, MultiSortSupport mss, int numattrs, AttrNumber *attnums)
 
bool has_stats_of_kind (List *stats, char requiredkind)
 
static int stat_find_expression (StatisticExtInfo *stat, Node *expr)
 
static bool stat_covers_expressions (StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
 
StatisticExtInfochoose_best_statistics (List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
 
static bool statext_is_compatible_clause_internal (PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
 
static bool statext_is_compatible_clause (PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
 
static Selectivity statext_mcv_clauselist_selectivity (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
 
Selectivity statext_clauselist_selectivity (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
 
bool examine_opclause_args (List *args, Node **exprp, Const **cstp, bool *expronleftp)
 
HeapTuple statext_expressions_load (Oid stxoid, bool inh, int idx)
 

Macro Definition Documentation

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 61 of file extended_stats.c.

Typedef Documentation

◆ AnlExprData

typedef struct AnlExprData AnlExprData

◆ StatExtEntry

typedef struct StatExtEntry StatExtEntry

Function Documentation

◆ build_attnums_array()

AttrNumber* build_attnums_array ( Bitmapset attrs,
int  nexprs,
int *  numattrs 
)

Definition at line 966 of file extended_stats.c.

967 {
968  int i,
969  j;
970  AttrNumber *attnums;
971  int num = bms_num_members(attrs);
972 
973  if (numattrs)
974  *numattrs = num;
975 
976  /* build attnums from the bitmapset */
977  attnums = (AttrNumber *) palloc(sizeof(AttrNumber) * num);
978  i = 0;
979  j = -1;
980  while ((j = bms_next_member(attrs, j)) >= 0)
981  {
982  int attnum = (j - nexprs);
983 
984  /*
985  * Make sure the bitmap contains only user-defined attributes. As
986  * bitmaps can't contain negative values, this can be violated in two
987  * ways. Firstly, the bitmap might contain 0 as a member, and secondly
988  * the integer value might be larger than MaxAttrNumber.
989  */
992  Assert(attnum >= (-nexprs));
993 
994  attnums[i++] = (AttrNumber) attnum;
995 
996  /* protect against overflows */
997  Assert(i <= num);
998  }
999 
1000  return attnums;
1001 }
int16 AttrNumber
Definition: attnum.h:21
#define AttributeNumberIsValid(attributeNumber)
Definition: attnum.h:34
#define MaxAttrNumber
Definition: attnum.h:24
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1047
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:649
int j
Definition: isn.c:74
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void * palloc(Size size)
Definition: mcxt.c:1199
int16 attnum
Definition: pg_attribute.h:83

References Assert(), attnum, AttributeNumberIsValid, bms_next_member(), bms_num_members(), i, j, MaxAttrNumber, and palloc().

◆ build_expr_data()

static AnlExprData * build_expr_data ( List exprs,
int  stattarget 
)
static

Definition at line 2296 of file extended_stats.c.

2297 {
2298  int idx;
2299  int nexprs = list_length(exprs);
2300  AnlExprData *exprdata;
2301  ListCell *lc;
2302 
2303  exprdata = (AnlExprData *) palloc0(nexprs * sizeof(AnlExprData));
2304 
2305  idx = 0;
2306  foreach(lc, exprs)
2307  {
2308  Node *expr = (Node *) lfirst(lc);
2309  AnlExprData *thisdata = &exprdata[idx];
2310 
2311  thisdata->expr = expr;
2312  thisdata->vacattrstat = examine_expression(expr, stattarget);
2313  idx++;
2314  }
2315 
2316  return exprdata;
2317 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
static VacAttrStats * examine_expression(Node *expr, int stattarget)
void * palloc0(Size size)
Definition: mcxt.c:1230
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
VacAttrStats * vacattrstat
Definition: nodes.h:118

References examine_expression(), AnlExprData::expr, idx(), lfirst, list_length(), palloc0(), and AnlExprData::vacattrstat.

Referenced by BuildRelationExtStatistics().

◆ build_sorted_items()

SortItem* build_sorted_items ( StatsBuildData data,
int *  nitems,
MultiSortSupport  mss,
int  numattrs,
AttrNumber attnums 
)

Definition at line 1011 of file extended_stats.c.

1014 {
1015  int i,
1016  j,
1017  len,
1018  nrows;
1019  int nvalues = data->numrows * numattrs;
1020 
1021  SortItem *items;
1022  Datum *values;
1023  bool *isnull;
1024  char *ptr;
1025  int *typlen;
1026 
1027  /* Compute the total amount of memory we need (both items and values). */
1028  len = data->numrows * sizeof(SortItem) + nvalues * (sizeof(Datum) + sizeof(bool));
1029 
1030  /* Allocate the memory and split it into the pieces. */
1031  ptr = palloc0(len);
1032 
1033  /* items to sort */
1034  items = (SortItem *) ptr;
1035  ptr += data->numrows * sizeof(SortItem);
1036 
1037  /* values and null flags */
1038  values = (Datum *) ptr;
1039  ptr += nvalues * sizeof(Datum);
1040 
1041  isnull = (bool *) ptr;
1042  ptr += nvalues * sizeof(bool);
1043 
1044  /* make sure we consumed the whole buffer exactly */
1045  Assert((ptr - (char *) items) == len);
1046 
1047  /* fix the pointers to Datum and bool arrays */
1048  nrows = 0;
1049  for (i = 0; i < data->numrows; i++)
1050  {
1051  items[nrows].values = &values[nrows * numattrs];
1052  items[nrows].isnull = &isnull[nrows * numattrs];
1053 
1054  nrows++;
1055  }
1056 
1057  /* build a local cache of typlen for all attributes */
1058  typlen = (int *) palloc(sizeof(int) * data->nattnums);
1059  for (i = 0; i < data->nattnums; i++)
1060  typlen[i] = get_typlen(data->stats[i]->attrtypid);
1061 
1062  nrows = 0;
1063  for (i = 0; i < data->numrows; i++)
1064  {
1065  bool toowide = false;
1066 
1067  /* load the values/null flags from sample rows */
1068  for (j = 0; j < numattrs; j++)
1069  {
1070  Datum value;
1071  bool isnull;
1072  int attlen;
1073  AttrNumber attnum = attnums[j];
1074 
1075  int idx;
1076 
1077  /* match attnum to the pre-calculated data */
1078  for (idx = 0; idx < data->nattnums; idx++)
1079  {
1080  if (attnum == data->attnums[idx])
1081  break;
1082  }
1083 
1084  Assert(idx < data->nattnums);
1085 
1086  value = data->values[idx][i];
1087  isnull = data->nulls[idx][i];
1088  attlen = typlen[idx];
1089 
1090  /*
1091  * If this is a varlena value, check if it's too wide and if yes
1092  * then skip the whole item. Otherwise detoast the value.
1093  *
1094  * XXX It may happen that we've already detoasted some preceding
1095  * values for the current item. We don't bother to cleanup those
1096  * on the assumption that those are small (below WIDTH_THRESHOLD)
1097  * and will be discarded at the end of analyze.
1098  */
1099  if ((!isnull) && (attlen == -1))
1100  {
1102  {
1103  toowide = true;
1104  break;
1105  }
1106 
1108  }
1109 
1110  items[nrows].values[j] = value;
1111  items[nrows].isnull[j] = isnull;
1112  }
1113 
1114  if (toowide)
1115  continue;
1116 
1117  nrows++;
1118  }
1119 
1120  /* store the actual number of items (ignoring the too-wide ones) */
1121  *nitems = nrows;
1122 
1123  /* all items were too wide */
1124  if (nrows == 0)
1125  {
1126  /* everything is allocated as a single chunk */
1127  pfree(items);
1128  return NULL;
1129  }
1130 
1131  /* do the sort, using the multi-sort */
1132  qsort_interruptible((void *) items, nrows, sizeof(SortItem),
1133  multi_sort_compare, mss);
1134 
1135  return items;
1136 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
unsigned char bool
Definition: c.h:392
Size toast_raw_datum_size(Datum value)
Definition: detoast.c:545
#define WIDTH_THRESHOLD
int multi_sort_compare(const void *a, const void *b, void *arg)
struct SortItem SortItem
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
static struct @143 value
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2155
void pfree(void *pointer)
Definition: mcxt.c:1306
int16 attlen
Definition: pg_attribute.h:68
const void size_t len
const void * data
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
uintptr_t Datum
Definition: postgres.h:412

References Assert(), attlen, attnum, data, get_typlen(), i, idx(), SortItem::isnull, j, len, multi_sort_compare(), palloc(), palloc0(), pfree(), PG_DETOAST_DATUM, PointerGetDatum(), qsort_interruptible(), toast_raw_datum_size(), value, values, SortItem::values, and WIDTH_THRESHOLD.

Referenced by dependency_degree(), and statext_mcv_build().

◆ BuildRelationExtStatistics()

void BuildRelationExtStatistics ( Relation  onerel,
bool  inh,
double  totalrows,
int  numrows,
HeapTuple rows,
int  natts,
VacAttrStats **  vacattrstats 
)

Definition at line 115 of file extended_stats.c.

118 {
119  Relation pg_stext;
120  ListCell *lc;
121  List *statslist;
122  MemoryContext cxt;
123  MemoryContext oldcxt;
124  int64 ext_cnt;
125 
126  /* Do nothing if there are no columns to analyze. */
127  if (!natts)
128  return;
129 
130  /* the list of stats has to be allocated outside the memory context */
131  pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
132  statslist = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel));
133 
134  /* memory context for building each statistics object */
136  "BuildRelationExtStatistics",
138  oldcxt = MemoryContextSwitchTo(cxt);
139 
140  /* report this phase */
141  if (statslist != NIL)
142  {
143  const int index[] = {
146  };
147  const int64 val[] = {
149  list_length(statslist)
150  };
151 
153  }
154 
155  ext_cnt = 0;
156  foreach(lc, statslist)
157  {
159  MVNDistinct *ndistinct = NULL;
160  MVDependencies *dependencies = NULL;
161  MCVList *mcv = NULL;
162  Datum exprstats = (Datum) 0;
163  VacAttrStats **stats;
164  ListCell *lc2;
165  int stattarget;
167 
168  /*
169  * Check if we can build these stats based on the column analyzed. If
170  * not, report this fact (except in autovacuum) and move on.
171  */
172  stats = lookup_var_attr_stats(onerel, stat->columns, stat->exprs,
173  natts, vacattrstats);
174  if (!stats)
175  {
178  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
179  errmsg("statistics object \"%s.%s\" could not be computed for relation \"%s.%s\"",
180  stat->schema, stat->name,
181  get_namespace_name(onerel->rd_rel->relnamespace),
182  RelationGetRelationName(onerel)),
183  errtable(onerel)));
184  continue;
185  }
186 
187  /* compute statistics target for this statistics object */
188  stattarget = statext_compute_stattarget(stat->stattarget,
189  bms_num_members(stat->columns),
190  stats);
191 
192  /*
193  * Don't rebuild statistics objects with statistics target set to 0
194  * (we just leave the existing values around, just like we do for
195  * regular per-column statistics).
196  */
197  if (stattarget == 0)
198  continue;
199 
200  /* evaluate expressions (if the statistics object has any) */
201  data = make_build_data(onerel, stat, numrows, rows, stats, stattarget);
202 
203  /* compute statistic of each requested type */
204  foreach(lc2, stat->types)
205  {
206  char t = (char) lfirst_int(lc2);
207 
208  if (t == STATS_EXT_NDISTINCT)
209  ndistinct = statext_ndistinct_build(totalrows, data);
210  else if (t == STATS_EXT_DEPENDENCIES)
211  dependencies = statext_dependencies_build(data);
212  else if (t == STATS_EXT_MCV)
213  mcv = statext_mcv_build(data, totalrows, stattarget);
214  else if (t == STATS_EXT_EXPRESSIONS)
215  {
216  AnlExprData *exprdata;
217  int nexprs;
218 
219  /* should not happen, thanks to checks when defining stats */
220  if (!stat->exprs)
221  elog(ERROR, "requested expression stats, but there are no expressions");
222 
223  exprdata = build_expr_data(stat->exprs, stattarget);
224  nexprs = list_length(stat->exprs);
225 
226  compute_expr_stats(onerel, totalrows,
227  exprdata, nexprs,
228  rows, numrows);
229 
230  exprstats = serialize_expr_stats(exprdata, nexprs);
231  }
232  }
233 
234  /* store the statistics in the catalog */
235  statext_store(stat->statOid, inh,
236  ndistinct, dependencies, mcv, exprstats, stats);
237 
238  /* for reporting progress */
240  ++ext_cnt);
241 
242  /* free the data used for building this statistics object */
243  MemoryContextReset(cxt);
244  }
245 
246  MemoryContextSwitchTo(oldcxt);
247  MemoryContextDelete(cxt);
248 
249  list_free(statslist);
250 
251  table_close(pg_stext, RowExclusiveLock);
252 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3314
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
MVDependencies * statext_dependencies_build(StatsBuildData *data)
Definition: dependencies.c:350
int errcode(int sqlerrcode)
Definition: elog.c:735
int errmsg(const char *fmt,...)
Definition: elog.c:946
#define WARNING
Definition: elog.h:32
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
static AnlExprData * build_expr_data(List *exprs, int stattarget)
static StatsBuildData * make_build_data(Relation rel, StatExtEntry *stat, int numrows, HeapTuple *rows, VacAttrStats **stats, int stattarget)
static VacAttrStats ** lookup_var_attr_stats(Relation rel, Bitmapset *attrs, List *exprs, int nvacatts, VacAttrStats **vacatts)
static List * fetch_statentries_for_relation(Relation pg_statext, Oid relid)
static void statext_store(Oid statOid, bool inh, MVNDistinct *ndistinct, MVDependencies *dependencies, MCVList *mcv, Datum exprs, VacAttrStats **stats)
static void compute_expr_stats(Relation onerel, double totalrows, AnlExprData *exprdata, int nexprs, HeapTuple *rows, int numrows)
static int statext_compute_stattarget(int stattarget, int nattrs, VacAttrStats **stats)
static Datum serialize_expr_stats(AnlExprData *exprdata, int nexprs)
long val
Definition: informix.c:664
void list_free(List *list)
Definition: list.c:1545
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
MCVList * statext_mcv_build(StatsBuildData *data, double totalrows, int stattarget)
Definition: mcv.c:184
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:303
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
MVNDistinct * statext_ndistinct_build(double totalrows, StatsBuildData *data)
Definition: mvdistinct.c:89
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
#define NIL
Definition: pg_list.h:66
#define lfirst_int(lc)
Definition: pg_list.h:171
#define PROGRESS_ANALYZE_EXT_STATS_COMPUTED
Definition: progress.h:42
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:38
#define PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS
Definition: progress.h:51
#define PROGRESS_ANALYZE_EXT_STATS_TOTAL
Definition: progress.h:41
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationGetRelationName(relation)
Definition: rel.h:535
int errtable(Relation rel)
Definition: relcache.c:5876
Definition: pg_list.h:52
Form_pg_class rd_rel
Definition: rel.h:110
Definition: type.h:95
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, bms_num_members(), build_expr_data(), compute_expr_stats(), CurrentMemoryContext, data, elog(), ereport, errcode(), errmsg(), ERROR, errtable(), fetch_statentries_for_relation(), get_namespace_name(), IsAutoVacuumWorkerProcess(), lfirst, lfirst_int, list_free(), list_length(), lookup_var_attr_stats(), make_build_data(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), NIL, pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_ANALYZE_EXT_STATS_COMPUTED, PROGRESS_ANALYZE_EXT_STATS_TOTAL, PROGRESS_ANALYZE_PHASE, PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS, RelationData::rd_rel, RelationGetRelationName, RelationGetRelid, RowExclusiveLock, serialize_expr_stats(), statext_compute_stattarget(), statext_dependencies_build(), statext_mcv_build(), statext_ndistinct_build(), statext_store(), table_close(), table_open(), val, and WARNING.

Referenced by do_analyze_rel().

◆ choose_best_statistics()

StatisticExtInfo* choose_best_statistics ( List stats,
char  requiredkind,
bool  inh,
Bitmapset **  clause_attnums,
List **  clause_exprs,
int  nclauses 
)

Definition at line 1234 of file extended_stats.c.

1237 {
1238  ListCell *lc;
1239  StatisticExtInfo *best_match = NULL;
1240  int best_num_matched = 2; /* goal #1: maximize */
1241  int best_match_keys = (STATS_MAX_DIMENSIONS + 1); /* goal #2: minimize */
1242 
1243  foreach(lc, stats)
1244  {
1245  int i;
1246  StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
1247  Bitmapset *matched_attnums = NULL;
1248  Bitmapset *matched_exprs = NULL;
1249  int num_matched;
1250  int numkeys;
1251 
1252  /* skip statistics that are not of the correct type */
1253  if (info->kind != requiredkind)
1254  continue;
1255 
1256  /* skip statistics with mismatching inheritance flag */
1257  if (info->inherit != inh)
1258  continue;
1259 
1260  /*
1261  * Collect attributes and expressions in remaining (unestimated)
1262  * clauses fully covered by this statistic object.
1263  *
1264  * We know already estimated clauses have both clause_attnums and
1265  * clause_exprs set to NULL. We leave the pointers NULL if already
1266  * estimated, or we reset them to NULL after estimating the clause.
1267  */
1268  for (i = 0; i < nclauses; i++)
1269  {
1270  Bitmapset *expr_idxs = NULL;
1271 
1272  /* ignore incompatible/estimated clauses */
1273  if (!clause_attnums[i] && !clause_exprs[i])
1274  continue;
1275 
1276  /* ignore clauses that are not covered by this object */
1277  if (!bms_is_subset(clause_attnums[i], info->keys) ||
1278  !stat_covers_expressions(info, clause_exprs[i], &expr_idxs))
1279  continue;
1280 
1281  /* record attnums and indexes of expressions covered */
1282  matched_attnums = bms_add_members(matched_attnums, clause_attnums[i]);
1283  matched_exprs = bms_add_members(matched_exprs, expr_idxs);
1284  }
1285 
1286  num_matched = bms_num_members(matched_attnums) + bms_num_members(matched_exprs);
1287 
1288  bms_free(matched_attnums);
1289  bms_free(matched_exprs);
1290 
1291  /*
1292  * save the actual number of keys in the stats so that we can choose
1293  * the narrowest stats with the most matching keys.
1294  */
1295  numkeys = bms_num_members(info->keys) + list_length(info->exprs);
1296 
1297  /*
1298  * Use this object when it increases the number of matched attributes
1299  * and expressions or when it matches the same number of attributes
1300  * and expressions but these stats have fewer keys than any previous
1301  * match.
1302  */
1303  if (num_matched > best_num_matched ||
1304  (num_matched == best_num_matched && numkeys < best_match_keys))
1305  {
1306  best_match = info;
1307  best_num_matched = num_matched;
1308  best_match_keys = numkeys;
1309  }
1310  }
1311 
1312  return best_match;
1313 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:316
void bms_free(Bitmapset *a)
Definition: bitmapset.c:209
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:796
static bool stat_covers_expressions(StatisticExtInfo *stat, List *exprs, Bitmapset **expr_idxs)
#define STATS_MAX_DIMENSIONS
Definition: statistics.h:19
Bitmapset * keys
Definition: pathnodes.h:1237

References bms_add_members(), bms_free(), bms_is_subset(), bms_num_members(), StatisticExtInfo::exprs, i, StatisticExtInfo::inherit, StatisticExtInfo::keys, StatisticExtInfo::kind, lfirst, list_length(), stat_covers_expressions(), and STATS_MAX_DIMENSIONS.

Referenced by statext_mcv_clauselist_selectivity().

◆ compare_datums_simple()

int compare_datums_simple ( Datum  a,
Datum  b,
SortSupport  ssup 
)

Definition at line 952 of file extended_stats.c.

953 {
954  return ApplySortComparator(a, false, b, false, ssup);
955 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

References a, ApplySortComparator(), and b.

Referenced by compare_scalars_simple(), and statext_mcv_serialize().

◆ compare_scalars_simple()

int compare_scalars_simple ( const void *  a,
const void *  b,
void *  arg 
)

Definition at line 944 of file extended_stats.c.

945 {
946  return compare_datums_simple(*(Datum *) a,
947  *(Datum *) b,
948  (SortSupport) arg);
949 }
int compare_datums_simple(Datum a, Datum b, SortSupport ssup)
void * arg

References a, arg, b, and compare_datums_simple().

Referenced by statext_mcv_serialize().

◆ compute_expr_stats()

static void compute_expr_stats ( Relation  onerel,
double  totalrows,
AnlExprData exprdata,
int  nexprs,
HeapTuple rows,
int  numrows 
)
static

Definition at line 2135 of file extended_stats.c.

2138 {
2139  MemoryContext expr_context,
2140  old_context;
2141  int ind,
2142  i;
2143 
2145  "Analyze Expression",
2147  old_context = MemoryContextSwitchTo(expr_context);
2148 
2149  for (ind = 0; ind < nexprs; ind++)
2150  {
2151  AnlExprData *thisdata = &exprdata[ind];
2152  VacAttrStats *stats = thisdata->vacattrstat;
2153  Node *expr = thisdata->expr;
2154  TupleTableSlot *slot;
2155  EState *estate;
2156  ExprContext *econtext;
2157  Datum *exprvals;
2158  bool *exprnulls;
2159  ExprState *exprstate;
2160  int tcnt;
2161 
2162  /* Are we still in the main context? */
2163  Assert(CurrentMemoryContext == expr_context);
2164 
2165  /*
2166  * Need an EState for evaluation of expressions. Create it in the
2167  * per-expression context to be sure it gets cleaned up at the bottom
2168  * of the loop.
2169  */
2170  estate = CreateExecutorState();
2171  econtext = GetPerTupleExprContext(estate);
2172 
2173  /* Set up expression evaluation state */
2174  exprstate = ExecPrepareExpr((Expr *) expr, estate);
2175 
2176  /* Need a slot to hold the current heap tuple, too */
2178  &TTSOpsHeapTuple);
2179 
2180  /* Arrange for econtext's scan tuple to be the tuple under test */
2181  econtext->ecxt_scantuple = slot;
2182 
2183  /* Compute and save expression values */
2184  exprvals = (Datum *) palloc(numrows * sizeof(Datum));
2185  exprnulls = (bool *) palloc(numrows * sizeof(bool));
2186 
2187  tcnt = 0;
2188  for (i = 0; i < numrows; i++)
2189  {
2190  Datum datum;
2191  bool isnull;
2192 
2193  /*
2194  * Reset the per-tuple context each time, to reclaim any cruft
2195  * left behind by evaluating the statistics expressions.
2196  */
2197  ResetExprContext(econtext);
2198 
2199  /* Set up for expression evaluation */
2200  ExecStoreHeapTuple(rows[i], slot, false);
2201 
2202  /*
2203  * Evaluate the expression. We do this in the per-tuple context so
2204  * as not to leak memory, and then copy the result into the
2205  * context created at the beginning of this function.
2206  */
2207  datum = ExecEvalExprSwitchContext(exprstate,
2208  GetPerTupleExprContext(estate),
2209  &isnull);
2210  if (isnull)
2211  {
2212  exprvals[tcnt] = (Datum) 0;
2213  exprnulls[tcnt] = true;
2214  }
2215  else
2216  {
2217  /* Make sure we copy the data into the context. */
2218  Assert(CurrentMemoryContext == expr_context);
2219 
2220  exprvals[tcnt] = datumCopy(datum,
2221  stats->attrtype->typbyval,
2222  stats->attrtype->typlen);
2223  exprnulls[tcnt] = false;
2224  }
2225 
2226  tcnt++;
2227  }
2228 
2229  /*
2230  * Now we can compute the statistics for the expression columns.
2231  *
2232  * XXX Unlike compute_index_stats we don't need to switch and reset
2233  * memory contexts here, because we're only computing stats for a
2234  * single expression (and not iterating over many indexes), so we just
2235  * do it in expr_context. Note that compute_stats copies the result
2236  * into stats->anl_context, so it does not disappear.
2237  */
2238  if (tcnt > 0)
2239  {
2240  AttributeOpts *aopt =
2241  get_attribute_options(stats->attr->attrelid,
2242  stats->attr->attnum);
2243 
2244  stats->exprvals = exprvals;
2245  stats->exprnulls = exprnulls;
2246  stats->rowstride = 1;
2247  stats->compute_stats(stats,
2249  tcnt,
2250  tcnt);
2251 
2252  /*
2253  * If the n_distinct option is specified, it overrides the above
2254  * computation.
2255  */
2256  if (aopt != NULL && aopt->n_distinct != 0.0)
2257  stats->stadistinct = aopt->n_distinct;
2258  }
2259 
2260  /* And clean up */
2261  MemoryContextSwitchTo(expr_context);
2262 
2264  FreeExecutorState(estate);
2266  }
2267 
2268  MemoryContextSwitchTo(old_context);
2269  MemoryContextDelete(expr_context);
2270 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:103
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition: execExpr.c:747
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
EState * CreateExecutorState(void)
Definition: execUtils.c:92
void FreeExecutorState(EState *estate)
Definition: execUtils.c:190
#define GetPerTupleExprContext(estate)
Definition: executor.h:538
#define ResetExprContext(econtext)
Definition: executor.h:532
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:336
static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:70
#define RelationGetDescr(relation)
Definition: rel.h:527
float8 n_distinct
Definition: attoptcache.h:22
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:247
Form_pg_type attrtype
Definition: vacuum.h:131
int rowstride
Definition: vacuum.h:179
Form_pg_attribute attr
Definition: vacuum.h:128
bool * exprnulls
Definition: vacuum.h:178
Datum * exprvals
Definition: vacuum.h:177
float4 stadistinct
Definition: vacuum.h:150
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:139

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), VacAttrStats::attr, VacAttrStats::attrtype, VacAttrStats::compute_stats, CreateExecutorState(), CurrentMemoryContext, datumCopy(), ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecEvalExprSwitchContext(), ExecPrepareExpr(), ExecStoreHeapTuple(), AnlExprData::expr, expr_fetch_func(), VacAttrStats::exprnulls, VacAttrStats::exprvals, FreeExecutorState(), get_attribute_options(), GetPerTupleExprContext, i, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), AttributeOpts::n_distinct, palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, VacAttrStats::stadistinct, TTSOpsHeapTuple, and AnlExprData::vacattrstat.

Referenced by BuildRelationExtStatistics().

◆ ComputeExtStatisticsRows()

int ComputeExtStatisticsRows ( Relation  onerel,
int  natts,
VacAttrStats **  vacattrstats 
)

Definition at line 268 of file extended_stats.c.

270 {
271  Relation pg_stext;
272  ListCell *lc;
273  List *lstats;
274  MemoryContext cxt;
275  MemoryContext oldcxt;
276  int result = 0;
277 
278  /* If there are no columns to analyze, just return 0. */
279  if (!natts)
280  return 0;
281 
283  "ComputeExtStatisticsRows",
285  oldcxt = MemoryContextSwitchTo(cxt);
286 
287  pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
288  lstats = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel));
289 
290  foreach(lc, lstats)
291  {
293  int stattarget;
294  VacAttrStats **stats;
295  int nattrs = bms_num_members(stat->columns);
296 
297  /*
298  * Check if we can build this statistics object based on the columns
299  * analyzed. If not, ignore it (don't report anything, we'll do that
300  * during the actual build BuildRelationExtStatistics).
301  */
302  stats = lookup_var_attr_stats(onerel, stat->columns, stat->exprs,
303  natts, vacattrstats);
304 
305  if (!stats)
306  continue;
307 
308  /*
309  * Compute statistics target, based on what's set for the statistic
310  * object itself, and for its attributes.
311  */
312  stattarget = statext_compute_stattarget(stat->stattarget,
313  nattrs, stats);
314 
315  /* Use the largest value for all statistics objects. */
316  if (stattarget > result)
317  result = stattarget;
318  }
319 
320  table_close(pg_stext, RowExclusiveLock);
321 
322  MemoryContextSwitchTo(oldcxt);
323  MemoryContextDelete(cxt);
324 
325  /* compute sample size based on the statistics target */
326  return (300 * result);
327 }

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, bms_num_members(), CurrentMemoryContext, fetch_statentries_for_relation(), lfirst, lookup_var_attr_stats(), MemoryContextDelete(), MemoryContextSwitchTo(), RelationGetRelid, RowExclusiveLock, statext_compute_stattarget(), table_close(), and table_open().

Referenced by do_analyze_rel().

◆ examine_attribute()

static VacAttrStats* examine_attribute ( Node expr)
static

Definition at line 530 of file extended_stats.c.

531 {
532  HeapTuple typtuple;
533  VacAttrStats *stats;
534  int i;
535  bool ok;
536 
537  /*
538  * Create the VacAttrStats struct. Note that we only have a copy of the
539  * fixed fields of the pg_attribute tuple.
540  */
541  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
542 
543  /* fake the attribute */
545  stats->attr->attstattarget = -1;
546 
547  /*
548  * When analyzing an expression, believe the expression tree's type not
549  * the column datatype --- the latter might be the opckeytype storage type
550  * of the opclass, which is not interesting for our purposes. (Note: if
551  * we did anything with non-expression statistics columns, we'd need to
552  * figure out where to get the correct type info from, but for now that's
553  * not a problem.) It's not clear whether anyone will care about the
554  * typmod, but we store that too just in case.
555  */
556  stats->attrtypid = exprType(expr);
557  stats->attrtypmod = exprTypmod(expr);
558  stats->attrcollid = exprCollation(expr);
559 
560  typtuple = SearchSysCacheCopy1(TYPEOID,
561  ObjectIdGetDatum(stats->attrtypid));
562  if (!HeapTupleIsValid(typtuple))
563  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
564  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
565 
566  /*
567  * We don't actually analyze individual attributes, so no need to set the
568  * memory context.
569  */
570  stats->anl_context = NULL;
571  stats->tupattnum = InvalidAttrNumber;
572 
573  /*
574  * The fields describing the stats->stavalues[n] element types default to
575  * the type of the data being analyzed, but the type-specific typanalyze
576  * function can change them if it wants to store something else.
577  */
578  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
579  {
580  stats->statypid[i] = stats->attrtypid;
581  stats->statyplen[i] = stats->attrtype->typlen;
582  stats->statypbyval[i] = stats->attrtype->typbyval;
583  stats->statypalign[i] = stats->attrtype->typalign;
584  }
585 
586  /*
587  * Call the type-specific typanalyze function. If none is specified, use
588  * std_typanalyze().
589  */
590  if (OidIsValid(stats->attrtype->typanalyze))
591  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
592  PointerGetDatum(stats)));
593  else
594  ok = std_typanalyze(stats);
595 
596  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
597  {
598  heap_freetuple(typtuple);
599  pfree(stats->attr);
600  pfree(stats);
601  return NULL;
602  }
603 
604  return stats;
605 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define OidIsValid(objectId)
Definition: c.h:711
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1858
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:266
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:199
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static bool DatumGetBool(Datum X)
Definition: postgres.h:438
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
int32 attrtypmod
Definition: vacuum.h:130
int tupattnum
Definition: vacuum.h:174
MemoryContext anl_context
Definition: vacuum.h:133
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:165
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:168
Oid attrtypid
Definition: vacuum.h:129
int minrows
Definition: vacuum.h:140
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:167
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:166
Oid attrcollid
Definition: vacuum.h:132
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ TYPEOID
Definition: syscache.h:114

References VacAttrStats::anl_context, VacAttrStats::attr, VacAttrStats::attrcollid, ATTRIBUTE_FIXED_PART_SIZE, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::compute_stats, DatumGetBool(), elog(), ERROR, exprCollation(), exprType(), exprTypmod(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, i, InvalidAttrNumber, VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0(), pfree(), PointerGetDatum(), SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), VacAttrStats::tupattnum, and TYPEOID.

Referenced by lookup_var_attr_stats().

◆ examine_expression()

static VacAttrStats* examine_expression ( Node expr,
int  stattarget 
)
static

Definition at line 614 of file extended_stats.c.

615 {
616  HeapTuple typtuple;
617  VacAttrStats *stats;
618  int i;
619  bool ok;
620 
621  Assert(expr != NULL);
622 
623  /*
624  * Create the VacAttrStats struct.
625  */
626  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
627 
628  /*
629  * When analyzing an expression, believe the expression tree's type.
630  */
631  stats->attrtypid = exprType(expr);
632  stats->attrtypmod = exprTypmod(expr);
633 
634  /*
635  * We don't allow collation to be specified in CREATE STATISTICS, so we
636  * have to use the collation specified for the expression. It's possible
637  * to specify the collation in the expression "(col COLLATE "en_US")" in
638  * which case exprCollation() does the right thing.
639  */
640  stats->attrcollid = exprCollation(expr);
641 
642  /*
643  * We don't have any pg_attribute for expressions, so let's fake something
644  * reasonable into attstattarget, which is the only thing std_typanalyze
645  * needs.
646  */
648 
649  /*
650  * We can't have statistics target specified for the expression, so we
651  * could use either the default_statistics_target, or the target computed
652  * for the extended statistics. The second option seems more reasonable.
653  */
654  stats->attr->attstattarget = stattarget;
655 
656  /* initialize some basic fields */
657  stats->attr->attrelid = InvalidOid;
658  stats->attr->attnum = InvalidAttrNumber;
659  stats->attr->atttypid = stats->attrtypid;
660 
661  typtuple = SearchSysCacheCopy1(TYPEOID,
662  ObjectIdGetDatum(stats->attrtypid));
663  if (!HeapTupleIsValid(typtuple))
664  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
665 
666  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
667  stats->anl_context = CurrentMemoryContext; /* XXX should be using
668  * something else? */
669  stats->tupattnum = InvalidAttrNumber;
670 
671  /*
672  * The fields describing the stats->stavalues[n] element types default to
673  * the type of the data being analyzed, but the type-specific typanalyze
674  * function can change them if it wants to store something else.
675  */
676  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
677  {
678  stats->statypid[i] = stats->attrtypid;
679  stats->statyplen[i] = stats->attrtype->typlen;
680  stats->statypbyval[i] = stats->attrtype->typbyval;
681  stats->statypalign[i] = stats->attrtype->typalign;
682  }
683 
684  /*
685  * Call the type-specific typanalyze function. If none is specified, use
686  * std_typanalyze().
687  */
688  if (OidIsValid(stats->attrtype->typanalyze))
689  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
690  PointerGetDatum(stats)));
691  else
692  ok = std_typanalyze(stats);
693 
694  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
695  {
696  heap_freetuple(typtuple);
697  pfree(stats);
698  return NULL;
699  }
700 
701  return stats;
702 }
#define InvalidOid
Definition: postgres_ext.h:36

References VacAttrStats::anl_context, Assert(), VacAttrStats::attr, VacAttrStats::attrcollid, ATTRIBUTE_FIXED_PART_SIZE, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::compute_stats, CurrentMemoryContext, DatumGetBool(), elog(), ERROR, exprCollation(), exprType(), exprTypmod(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, i, InvalidAttrNumber, InvalidOid, VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc(), palloc0(), pfree(), PointerGetDatum(), SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), VacAttrStats::tupattnum, and TYPEOID.

Referenced by build_expr_data(), and make_build_data().

◆ examine_opclause_args()

bool examine_opclause_args ( List args,
Node **  exprp,
Const **  cstp,
bool expronleftp 
)

Definition at line 2080 of file extended_stats.c.

2082 {
2083  Node *expr;
2084  Const *cst;
2085  bool expronleft;
2086  Node *leftop,
2087  *rightop;
2088 
2089  /* enforced by statext_is_compatible_clause_internal */
2090  Assert(list_length(args) == 2);
2091 
2092  leftop = linitial(args);
2093  rightop = lsecond(args);
2094 
2095  /* strip RelabelType from either side of the expression */
2096  if (IsA(leftop, RelabelType))
2097  leftop = (Node *) ((RelabelType *) leftop)->arg;
2098 
2099  if (IsA(rightop, RelabelType))
2100  rightop = (Node *) ((RelabelType *) rightop)->arg;
2101 
2102  if (IsA(rightop, Const))
2103  {
2104  expr = (Node *) leftop;
2105  cst = (Const *) rightop;
2106  expronleft = true;
2107  }
2108  else if (IsA(leftop, Const))
2109  {
2110  expr = (Node *) rightop;
2111  cst = (Const *) leftop;
2112  expronleft = false;
2113  }
2114  else
2115  return false;
2116 
2117  /* return pointers to the extracted parts if requested */
2118  if (exprp)
2119  *exprp = expr;
2120 
2121  if (cstp)
2122  *cstp = cst;
2123 
2124  if (expronleftp)
2125  *expronleftp = expronleft;
2126 
2127  return true;
2128 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define linitial(l)
Definition: pg_list.h:176
#define lsecond(l)
Definition: pg_list.h:181

References arg, generate_unaccent_rules::args, Assert(), IsA, linitial, list_length(), and lsecond.

Referenced by mcv_get_match_bitmap(), and statext_is_compatible_clause_internal().

◆ expr_fetch_func()

static Datum expr_fetch_func ( VacAttrStatsP  stats,
int  rownum,
bool isNull 
)
static

Definition at line 2280 of file extended_stats.c.

2281 {
2282  int i;
2283 
2284  /* exprvals and exprnulls are already offset for proper column */
2285  i = rownum * stats->rowstride;
2286  *isNull = stats->exprnulls[i];
2287  return stats->exprvals[i];
2288 }

References VacAttrStats::exprnulls, VacAttrStats::exprvals, i, and VacAttrStats::rowstride.

Referenced by compute_expr_stats().

◆ fetch_statentries_for_relation()

static List * fetch_statentries_for_relation ( Relation  pg_statext,
Oid  relid 
)
static

Definition at line 425 of file extended_stats.c.

426 {
427  SysScanDesc scan;
428  ScanKeyData skey;
429  HeapTuple htup;
430  List *result = NIL;
431 
432  /*
433  * Prepare to scan pg_statistic_ext for entries having stxrelid = this
434  * rel.
435  */
436  ScanKeyInit(&skey,
437  Anum_pg_statistic_ext_stxrelid,
438  BTEqualStrategyNumber, F_OIDEQ,
439  ObjectIdGetDatum(relid));
440 
441  scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
442  NULL, 1, &skey);
443 
444  while (HeapTupleIsValid(htup = systable_getnext(scan)))
445  {
446  StatExtEntry *entry;
447  Datum datum;
448  bool isnull;
449  int i;
450  ArrayType *arr;
451  char *enabled;
452  Form_pg_statistic_ext staForm;
453  List *exprs = NIL;
454 
455  entry = palloc0(sizeof(StatExtEntry));
456  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
457  entry->statOid = staForm->oid;
458  entry->schema = get_namespace_name(staForm->stxnamespace);
459  entry->name = pstrdup(NameStr(staForm->stxname));
460  entry->stattarget = staForm->stxstattarget;
461  for (i = 0; i < staForm->stxkeys.dim1; i++)
462  {
463  entry->columns = bms_add_member(entry->columns,
464  staForm->stxkeys.values[i]);
465  }
466 
467  /* decode the stxkind char array into a list of chars */
468  datum = SysCacheGetAttr(STATEXTOID, htup,
469  Anum_pg_statistic_ext_stxkind, &isnull);
470  Assert(!isnull);
471  arr = DatumGetArrayTypeP(datum);
472  if (ARR_NDIM(arr) != 1 ||
473  ARR_HASNULL(arr) ||
474  ARR_ELEMTYPE(arr) != CHAROID)
475  elog(ERROR, "stxkind is not a 1-D char array");
476  enabled = (char *) ARR_DATA_PTR(arr);
477  for (i = 0; i < ARR_DIMS(arr)[0]; i++)
478  {
479  Assert((enabled[i] == STATS_EXT_NDISTINCT) ||
480  (enabled[i] == STATS_EXT_DEPENDENCIES) ||
481  (enabled[i] == STATS_EXT_MCV) ||
482  (enabled[i] == STATS_EXT_EXPRESSIONS));
483  entry->types = lappend_int(entry->types, (int) enabled[i]);
484  }
485 
486  /* decode expression (if any) */
487  datum = SysCacheGetAttr(STATEXTOID, htup,
488  Anum_pg_statistic_ext_stxexprs, &isnull);
489 
490  if (!isnull)
491  {
492  char *exprsString;
493 
494  exprsString = TextDatumGetCString(datum);
495  exprs = (List *) stringToNode(exprsString);
496 
497  pfree(exprsString);
498 
499  /*
500  * Run the expressions through eval_const_expressions. This is not
501  * just an optimization, but is necessary, because the planner
502  * will be comparing them to similarly-processed qual clauses, and
503  * may fail to detect valid matches without this. We must not use
504  * canonicalize_qual, however, since these aren't qual
505  * expressions.
506  */
507  exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
508 
509  /* May as well fix opfuncids too */
510  fix_opfuncids((Node *) exprs);
511  }
512 
513  entry->exprs = exprs;
514 
515  result = lappend(result, entry);
516  }
517 
518  systable_endscan(scan);
519 
520  return result;
521 }
#define ARR_NDIM(a)
Definition: array.h:283
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_ELEMTYPE(a)
Definition: array.h:285
#define ARR_DIMS(a)
Definition: array.h:287
#define ARR_HASNULL(a)
Definition: array.h:284
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NameStr(name)
Definition: c.h:682
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2132
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
List * lappend(List *list, void *datum)
Definition: list.c:338
List * lappend_int(List *list, int datum)
Definition: list.c:356
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1641
FormData_pg_statistic_ext * Form_pg_statistic_ext
void * stringToNode(const char *str)
Definition: read.c:90
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Bitmapset * columns
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ STATEXTOID
Definition: syscache.h:96

References ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert(), bms_add_member(), BTEqualStrategyNumber, StatExtEntry::columns, DatumGetArrayTypeP, elog(), ERROR, eval_const_expressions(), StatExtEntry::exprs, fix_opfuncids(), get_namespace_name(), GETSTRUCT, HeapTupleIsValid, i, lappend(), lappend_int(), StatExtEntry::name, NameStr, NIL, ObjectIdGetDatum(), palloc0(), pfree(), pstrdup(), ScanKeyInit(), StatExtEntry::schema, STATEXTOID, StatExtEntry::statOid, StatExtEntry::stattarget, stringToNode(), SysCacheGetAttr(), systable_beginscan(), systable_endscan(), systable_getnext(), TextDatumGetCString, and StatExtEntry::types.

Referenced by BuildRelationExtStatistics(), and ComputeExtStatisticsRows().

◆ has_stats_of_kind()

bool has_stats_of_kind ( List stats,
char  requiredkind 
)

Definition at line 1143 of file extended_stats.c.

1144 {
1145  ListCell *l;
1146 
1147  foreach(l, stats)
1148  {
1150 
1151  if (stat->kind == requiredkind)
1152  return true;
1153  }
1154 
1155  return false;
1156 }

References lfirst.

Referenced by dependencies_clauselist_selectivity(), and statext_mcv_clauselist_selectivity().

◆ lookup_var_attr_stats()

static VacAttrStats ** lookup_var_attr_stats ( Relation  rel,
Bitmapset attrs,
List exprs,
int  nvacatts,
VacAttrStats **  vacatts 
)
static

Definition at line 712 of file extended_stats.c.

714 {
715  int i = 0;
716  int x = -1;
717  int natts;
718  VacAttrStats **stats;
719  ListCell *lc;
720 
721  natts = bms_num_members(attrs) + list_length(exprs);
722 
723  stats = (VacAttrStats **) palloc(natts * sizeof(VacAttrStats *));
724 
725  /* lookup VacAttrStats info for the requested columns (same attnum) */
726  while ((x = bms_next_member(attrs, x)) >= 0)
727  {
728  int j;
729 
730  stats[i] = NULL;
731  for (j = 0; j < nvacatts; j++)
732  {
733  if (x == vacatts[j]->tupattnum)
734  {
735  stats[i] = vacatts[j];
736  break;
737  }
738  }
739 
740  if (!stats[i])
741  {
742  /*
743  * Looks like stats were not gathered for one of the columns
744  * required. We'll be unable to build the extended stats without
745  * this column.
746  */
747  pfree(stats);
748  return NULL;
749  }
750 
751  /*
752  * Sanity check that the column is not dropped - stats should have
753  * been removed in this case.
754  */
755  Assert(!stats[i]->attr->attisdropped);
756 
757  i++;
758  }
759 
760  /* also add info for expressions */
761  foreach(lc, exprs)
762  {
763  Node *expr = (Node *) lfirst(lc);
764 
765  stats[i] = examine_attribute(expr);
766 
767  /*
768  * XXX We need tuple descriptor later, and we just grab it from
769  * stats[0]->tupDesc (see e.g. statext_mcv_build). But as coded
770  * examine_attribute does not set that, so just grab it from the first
771  * vacatts element.
772  */
773  stats[i]->tupDesc = vacatts[0]->tupDesc;
774 
775  i++;
776  }
777 
778  return stats;
779 }
static VacAttrStats * examine_attribute(Node *expr)
int x
Definition: isn.c:71
TupleDesc tupDesc
Definition: vacuum.h:176

References Assert(), bms_next_member(), bms_num_members(), examine_attribute(), i, j, lfirst, list_length(), palloc(), pfree(), VacAttrStats::tupDesc, and x.

Referenced by BuildRelationExtStatistics(), and ComputeExtStatisticsRows().

◆ make_build_data()

static StatsBuildData * make_build_data ( Relation  rel,
StatExtEntry stat,
int  numrows,
HeapTuple rows,
VacAttrStats **  stats,
int  stattarget 
)
static

Definition at line 2498 of file extended_stats.c.

2500 {
2501  /* evaluated expressions */
2502  StatsBuildData *result;
2503  char *ptr;
2504  Size len;
2505 
2506  int i;
2507  int k;
2508  int idx;
2509  TupleTableSlot *slot;
2510  EState *estate;
2511  ExprContext *econtext;
2512  List *exprstates = NIL;
2513  int nkeys = bms_num_members(stat->columns) + list_length(stat->exprs);
2514  ListCell *lc;
2515 
2516  /* allocate everything as a single chunk, so we can free it easily */
2517  len = MAXALIGN(sizeof(StatsBuildData));
2518  len += MAXALIGN(sizeof(AttrNumber) * nkeys); /* attnums */
2519  len += MAXALIGN(sizeof(VacAttrStats *) * nkeys); /* stats */
2520 
2521  /* values */
2522  len += MAXALIGN(sizeof(Datum *) * nkeys);
2523  len += nkeys * MAXALIGN(sizeof(Datum) * numrows);
2524 
2525  /* nulls */
2526  len += MAXALIGN(sizeof(bool *) * nkeys);
2527  len += nkeys * MAXALIGN(sizeof(bool) * numrows);
2528 
2529  ptr = palloc(len);
2530 
2531  /* set the pointers */
2532  result = (StatsBuildData *) ptr;
2533  ptr += MAXALIGN(sizeof(StatsBuildData));
2534 
2535  /* attnums */
2536  result->attnums = (AttrNumber *) ptr;
2537  ptr += MAXALIGN(sizeof(AttrNumber) * nkeys);
2538 
2539  /* stats */
2540  result->stats = (VacAttrStats **) ptr;
2541  ptr += MAXALIGN(sizeof(VacAttrStats *) * nkeys);
2542 
2543  /* values */
2544  result->values = (Datum **) ptr;
2545  ptr += MAXALIGN(sizeof(Datum *) * nkeys);
2546 
2547  /* nulls */
2548  result->nulls = (bool **) ptr;
2549  ptr += MAXALIGN(sizeof(bool *) * nkeys);
2550 
2551  for (i = 0; i < nkeys; i++)
2552  {
2553  result->values[i] = (Datum *) ptr;
2554  ptr += MAXALIGN(sizeof(Datum) * numrows);
2555 
2556  result->nulls[i] = (bool *) ptr;
2557  ptr += MAXALIGN(sizeof(bool) * numrows);
2558  }
2559 
2560  Assert((ptr - (char *) result) == len);
2561 
2562  /* we have it allocated, so let's fill the values */
2563  result->nattnums = nkeys;
2564  result->numrows = numrows;
2565 
2566  /* fill the attribute info - first attributes, then expressions */
2567  idx = 0;
2568  k = -1;
2569  while ((k = bms_next_member(stat->columns, k)) >= 0)
2570  {
2571  result->attnums[idx] = k;
2572  result->stats[idx] = stats[idx];
2573 
2574  idx++;
2575  }
2576 
2577  k = -1;
2578  foreach(lc, stat->exprs)
2579  {
2580  Node *expr = (Node *) lfirst(lc);
2581 
2582  result->attnums[idx] = k;
2583  result->stats[idx] = examine_expression(expr, stattarget);
2584 
2585  idx++;
2586  k--;
2587  }
2588 
2589  /* first extract values for all the regular attributes */
2590  for (i = 0; i < numrows; i++)
2591  {
2592  idx = 0;
2593  k = -1;
2594  while ((k = bms_next_member(stat->columns, k)) >= 0)
2595  {
2596  result->values[idx][i] = heap_getattr(rows[i], k,
2597  result->stats[idx]->tupDesc,
2598  &result->nulls[idx][i]);
2599 
2600  idx++;
2601  }
2602  }
2603 
2604  /* Need an EState for evaluation expressions. */
2605  estate = CreateExecutorState();
2606  econtext = GetPerTupleExprContext(estate);
2607 
2608  /* Need a slot to hold the current heap tuple, too */
2610  &TTSOpsHeapTuple);
2611 
2612  /* Arrange for econtext's scan tuple to be the tuple under test */
2613  econtext->ecxt_scantuple = slot;
2614 
2615  /* Set up expression evaluation state */
2616  exprstates = ExecPrepareExprList(stat->exprs, estate);
2617 
2618  for (i = 0; i < numrows; i++)
2619  {
2620  /*
2621  * Reset the per-tuple context each time, to reclaim any cruft left
2622  * behind by evaluating the statistics object expressions.
2623  */
2624  ResetExprContext(econtext);
2625 
2626  /* Set up for expression evaluation */
2627  ExecStoreHeapTuple(rows[i], slot, false);
2628 
2629  idx = bms_num_members(stat->columns);
2630  foreach(lc, exprstates)
2631  {
2632  Datum datum;
2633  bool isnull;
2634  ExprState *exprstate = (ExprState *) lfirst(lc);
2635 
2636  /*
2637  * XXX This probably leaks memory. Maybe we should use
2638  * ExecEvalExprSwitchContext but then we need to copy the result
2639  * somewhere else.
2640  */
2641  datum = ExecEvalExpr(exprstate,
2642  GetPerTupleExprContext(estate),
2643  &isnull);
2644  if (isnull)
2645  {
2646  result->values[idx][i] = (Datum) 0;
2647  result->nulls[idx][i] = true;
2648  }
2649  else
2650  {
2651  result->values[idx][i] = (Datum) datum;
2652  result->nulls[idx][i] = false;
2653  }
2654 
2655  idx++;
2656  }
2657  }
2658 
2660  FreeExecutorState(estate);
2661 
2662  return result;
2663 }
#define MAXALIGN(LEN)
Definition: c.h:747
size_t Size
Definition: c.h:541
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:821
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:321
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:788
VacAttrStats ** stats

References Assert(), StatsBuildData::attnums, bms_next_member(), bms_num_members(), CreateExecutorState(), ExprContext::ecxt_scantuple, examine_expression(), ExecDropSingleTupleTableSlot(), ExecEvalExpr(), ExecPrepareExprList(), ExecStoreHeapTuple(), FreeExecutorState(), GetPerTupleExprContext, heap_getattr(), i, idx(), len, lfirst, list_length(), MakeSingleTupleTableSlot(), MAXALIGN, StatsBuildData::nattnums, NIL, StatsBuildData::nulls, StatsBuildData::numrows, palloc(), RelationGetDescr, ResetExprContext, StatsBuildData::stats, TTSOpsHeapTuple, VacAttrStats::tupDesc, and StatsBuildData::values.

Referenced by BuildRelationExtStatistics().

◆ multi_sort_add_dimension()

void multi_sort_add_dimension ( MultiSortSupport  mss,
int  sortdim,
Oid  oper,
Oid  collation 
)

Definition at line 876 of file extended_stats.c.

878 {
879  SortSupport ssup = &mss->ssup[sortdim];
880 
882  ssup->ssup_collation = collation;
883  ssup->ssup_nulls_first = false;
884 
886 }
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:382
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:135
SortSupportData ssup[FLEXIBLE_ARRAY_MEMBER]
bool ssup_nulls_first
Definition: sortsupport.h:75
MemoryContext ssup_cxt
Definition: sortsupport.h:66

References CurrentMemoryContext, oper(), PrepareSortSupportFromOrderingOp(), MultiSortSupportData::ssup, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, and SortSupportData::ssup_nulls_first.

Referenced by build_mss(), dependency_degree(), and ndistinct_for_combination().

◆ multi_sort_compare()

int multi_sort_compare ( const void *  a,
const void *  b,
void *  arg 
)

Definition at line 890 of file extended_stats.c.

891 {
893  SortItem *ia = (SortItem *) a;
894  SortItem *ib = (SortItem *) b;
895  int i;
896 
897  for (i = 0; i < mss->ndims; i++)
898  {
899  int compare;
900 
902  ib->values[i], ib->isnull[i],
903  &mss->ssup[i]);
904 
905  if (compare != 0)
906  return compare;
907  }
908 
909  /* equal by default */
910  return 0;
911 }
MultiSortSupportData * MultiSortSupport
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145

References a, ApplySortComparator(), arg, b, compare(), i, SortItem::isnull, MultiSortSupportData::ndims, MultiSortSupportData::ssup, and SortItem::values.

Referenced by build_distinct_groups(), build_sorted_items(), count_distinct_groups(), ndistinct_for_combination(), and statext_mcv_build().

◆ multi_sort_compare_dim()

int multi_sort_compare_dim ( int  dim,
const SortItem a,
const SortItem b,
MultiSortSupport  mss 
)

Definition at line 915 of file extended_stats.c.

917 {
918  return ApplySortComparator(a->values[dim], a->isnull[dim],
919  b->values[dim], b->isnull[dim],
920  &mss->ssup[dim]);
921 }

References a, ApplySortComparator(), b, and MultiSortSupportData::ssup.

Referenced by dependency_degree().

◆ multi_sort_compare_dims()

int multi_sort_compare_dims ( int  start,
int  end,
const SortItem a,
const SortItem b,
MultiSortSupport  mss 
)

Definition at line 924 of file extended_stats.c.

927 {
928  int dim;
929 
930  for (dim = start; dim <= end; dim++)
931  {
932  int r = ApplySortComparator(a->values[dim], a->isnull[dim],
933  b->values[dim], b->isnull[dim],
934  &mss->ssup[dim]);
935 
936  if (r != 0)
937  return r;
938  }
939 
940  return 0;
941 }

References a, ApplySortComparator(), b, and MultiSortSupportData::ssup.

Referenced by dependency_degree().

◆ multi_sort_init()

MultiSortSupport multi_sort_init ( int  ndims)

Definition at line 857 of file extended_stats.c.

858 {
859  MultiSortSupport mss;
860 
861  Assert(ndims >= 2);
862 
863  mss = (MultiSortSupport) palloc0(offsetof(MultiSortSupportData, ssup)
864  + sizeof(SortSupportData) * ndims);
865 
866  mss->ndims = ndims;
867 
868  return mss;
869 }
struct SortSupportData SortSupportData

References Assert(), MultiSortSupportData::ndims, and palloc0().

Referenced by build_mss(), dependency_degree(), and ndistinct_for_combination().

◆ serialize_expr_stats()

static Datum serialize_expr_stats ( AnlExprData exprdata,
int  nexprs 
)
static

Definition at line 2321 of file extended_stats.c.

2322 {
2323  int exprno;
2324  Oid typOid;
2325  Relation sd;
2326 
2327  ArrayBuildState *astate = NULL;
2328 
2329  sd = table_open(StatisticRelationId, RowExclusiveLock);
2330 
2331  /* lookup OID of composite type for pg_statistic */
2332  typOid = get_rel_type_id(StatisticRelationId);
2333  if (!OidIsValid(typOid))
2334  ereport(ERROR,
2335  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2336  errmsg("relation \"%s\" does not have a composite type",
2337  "pg_statistic")));
2338 
2339  for (exprno = 0; exprno < nexprs; exprno++)
2340  {
2341  int i,
2342  k;
2343  VacAttrStats *stats = exprdata[exprno].vacattrstat;
2344 
2345  Datum values[Natts_pg_statistic];
2346  bool nulls[Natts_pg_statistic];
2347  HeapTuple stup;
2348 
2349  if (!stats->stats_valid)
2350  {
2351  astate = accumArrayResult(astate,
2352  (Datum) 0,
2353  true,
2354  typOid,
2356  continue;
2357  }
2358 
2359  /*
2360  * Construct a new pg_statistic tuple
2361  */
2362  for (i = 0; i < Natts_pg_statistic; ++i)
2363  {
2364  nulls[i] = false;
2365  }
2366 
2367  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(InvalidOid);
2368  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(InvalidAttrNumber);
2369  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(false);
2370  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
2371  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
2372  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
2373  i = Anum_pg_statistic_stakind1 - 1;
2374  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2375  {
2376  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
2377  }
2378  i = Anum_pg_statistic_staop1 - 1;
2379  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2380  {
2381  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
2382  }
2383  i = Anum_pg_statistic_stacoll1 - 1;
2384  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2385  {
2386  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
2387  }
2388  i = Anum_pg_statistic_stanumbers1 - 1;
2389  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2390  {
2391  int nnum = stats->numnumbers[k];
2392 
2393  if (nnum > 0)
2394  {
2395  int n;
2396  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
2397  ArrayType *arry;
2398 
2399  for (n = 0; n < nnum; n++)
2400  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
2401  arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
2402  values[i++] = PointerGetDatum(arry); /* stanumbersN */
2403  }
2404  else
2405  {
2406  nulls[i] = true;
2407  values[i++] = (Datum) 0;
2408  }
2409  }
2410  i = Anum_pg_statistic_stavalues1 - 1;
2411  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2412  {
2413  if (stats->numvalues[k] > 0)
2414  {
2415  ArrayType *arry;
2416 
2417  arry = construct_array(stats->stavalues[k],
2418  stats->numvalues[k],
2419  stats->statypid[k],
2420  stats->statyplen[k],
2421  stats->statypbyval[k],
2422  stats->statypalign[k]);
2423  values[i++] = PointerGetDatum(arry); /* stavaluesN */
2424  }
2425  else
2426  {
2427  nulls[i] = true;
2428  values[i++] = (Datum) 0;
2429  }
2430  }
2431 
2432  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
2433 
2434  astate = accumArrayResult(astate,
2436  false,
2437  typOid,
2439  }
2440 
2442 
2443  return makeArrayResult(astate, CurrentMemoryContext);
2444 }
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5277
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3338
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5341
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition: heaptuple.c:984
Oid get_rel_type_id(Oid relid)
Definition: lsyscache.c:1961
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:823
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:520
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
unsigned int Oid
Definition: postgres_ext.h:31
bool stats_valid
Definition: vacuum.h:147
float4 stanullfrac
Definition: vacuum.h:148
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:151
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:152
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:153
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:155
int32 stawidth
Definition: vacuum.h:149
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:156
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:157
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:154

References accumArrayResult(), BoolGetDatum(), construct_array(), construct_array_builtin(), CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, Float4GetDatum(), get_rel_type_id(), heap_copy_tuple_as_datum(), heap_form_tuple(), i, Int16GetDatum(), Int32GetDatum(), InvalidAttrNumber, InvalidOid, makeArrayResult(), VacAttrStats::numnumbers, VacAttrStats::numvalues, ObjectIdGetDatum(), OidIsValid, palloc(), PointerGetDatum(), RelationGetDescr, RowExclusiveLock, VacAttrStats::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_NUM_SLOTS, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, table_close(), table_open(), AnlExprData::vacattrstat, and values.

Referenced by BuildRelationExtStatistics().

◆ stat_covers_expressions()

static bool stat_covers_expressions ( StatisticExtInfo stat,
List exprs,
Bitmapset **  expr_idxs 
)
static

Definition at line 1193 of file extended_stats.c.

1195 {
1196  ListCell *lc;
1197 
1198  foreach(lc, exprs)
1199  {
1200  Node *expr = (Node *) lfirst(lc);
1201  int expr_idx;
1202 
1203  expr_idx = stat_find_expression(stat, expr);
1204  if (expr_idx == -1)
1205  return false;
1206 
1207  if (expr_idxs != NULL)
1208  *expr_idxs = bms_add_member(*expr_idxs, expr_idx);
1209  }
1210 
1211  /* If we reach here, all expressions are covered */
1212  return true;
1213 }
static int stat_find_expression(StatisticExtInfo *stat, Node *expr)

References bms_add_member(), lfirst, and stat_find_expression().

Referenced by choose_best_statistics(), and statext_mcv_clauselist_selectivity().

◆ stat_find_expression()

static int stat_find_expression ( StatisticExtInfo stat,
Node expr 
)
static

Definition at line 1166 of file extended_stats.c.

1167 {
1168  ListCell *lc;
1169  int idx;
1170 
1171  idx = 0;
1172  foreach(lc, stat->exprs)
1173  {
1174  Node *stat_expr = (Node *) lfirst(lc);
1175 
1176  if (equal(stat_expr, expr))
1177  return idx;
1178  idx++;
1179  }
1180 
1181  /* Expression not found */
1182  return -1;
1183 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225

References equal(), idx(), and lfirst.

Referenced by stat_covers_expressions().

◆ statext_clauselist_selectivity()

Selectivity statext_clauselist_selectivity ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
RelOptInfo rel,
Bitmapset **  estimatedclauses,
bool  is_or 
)

Definition at line 2029 of file extended_stats.c.

2033 {
2034  Selectivity sel;
2035 
2036  /* First, try estimating clauses using a multivariate MCV list. */
2037  sel = statext_mcv_clauselist_selectivity(root, clauses, varRelid, jointype,
2038  sjinfo, rel, estimatedclauses, is_or);
2039 
2040  /*
2041  * Functional dependencies only work for clauses connected by AND, so for
2042  * OR clauses we're done.
2043  */
2044  if (is_or)
2045  return sel;
2046 
2047  /*
2048  * Then, apply functional dependencies on the remaining clauses by calling
2049  * dependencies_clauselist_selectivity. Pass 'estimatedclauses' so the
2050  * function can properly skip clauses already estimated above.
2051  *
2052  * The reasoning for applying dependencies last is that the more complex
2053  * stats can track more complex correlations between the attributes, and
2054  * so may be considered more reliable.
2055  *
2056  * For example, MCV list can give us an exact selectivity for values in
2057  * two columns, while functional dependencies can only provide information
2058  * about the overall strength of the dependency.
2059  */
2060  sel *= dependencies_clauselist_selectivity(root, clauses, varRelid,
2061  jointype, sjinfo, rel,
2062  estimatedclauses);
2063 
2064  return sel;
2065 }
Selectivity dependencies_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses)
static Selectivity statext_mcv_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
double Selectivity
Definition: nodes.h:250

References dependencies_clauselist_selectivity(), and statext_mcv_clauselist_selectivity().

Referenced by clauselist_selectivity_ext(), and clauselist_selectivity_or().

◆ statext_compute_stattarget()

static int statext_compute_stattarget ( int  stattarget,
int  nattrs,
VacAttrStats **  stats 
)
static

Definition at line 350 of file extended_stats.c.

351 {
352  int i;
353 
354  /*
355  * If there's statistics target set for the statistics object, use it. It
356  * may be set to 0 which disables building of that statistic.
357  */
358  if (stattarget >= 0)
359  return stattarget;
360 
361  /*
362  * The target for the statistics object is set to -1, in which case we
363  * look at the maximum target set for any of the attributes the object is
364  * defined on.
365  */
366  for (i = 0; i < nattrs; i++)
367  {
368  /* keep the maximum statistics target */
369  if (stats[i]->attr->attstattarget > stattarget)
370  stattarget = stats[i]->attr->attstattarget;
371  }
372 
373  /*
374  * If the value is still negative (so neither the statistics object nor
375  * any of the columns have custom statistics target set), use the global
376  * default target.
377  */
378  if (stattarget < 0)
379  stattarget = default_statistics_target;
380 
381  /* As this point we should have a valid statistics target. */
382  Assert((stattarget >= 0) && (stattarget <= 10000));
383 
384  return stattarget;
385 }
int default_statistics_target
Definition: analyze.c:83

References Assert(), VacAttrStats::attr, default_statistics_target, and i.

Referenced by BuildRelationExtStatistics(), and ComputeExtStatisticsRows().

◆ statext_expressions_load()

HeapTuple statext_expressions_load ( Oid  stxoid,
bool  inh,
int  idx 
)

Definition at line 2451 of file extended_stats.c.

2452 {
2453  bool isnull;
2454  Datum value;
2455  HeapTuple htup;
2456  ExpandedArrayHeader *eah;
2457  HeapTupleHeader td;
2458  HeapTupleData tmptup;
2459  HeapTuple tup;
2460 
2462  ObjectIdGetDatum(stxoid), BoolGetDatum(inh));
2463  if (!HeapTupleIsValid(htup))
2464  elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
2465 
2467  Anum_pg_statistic_ext_data_stxdexpr, &isnull);
2468  if (isnull)
2469  elog(ERROR,
2470  "requested statistics kind \"%c\" is not yet built for statistics object %u",
2471  STATS_EXT_DEPENDENCIES, stxoid);
2472 
2474 
2476 
2477  td = DatumGetHeapTupleHeader(eah->dvalues[idx]);
2478 
2479  /* Build a temporary HeapTuple control structure */
2480  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2481  ItemPointerSetInvalid(&(tmptup.t_self));
2482  tmptup.t_tableOid = InvalidOid;
2483  tmptup.t_data = td;
2484 
2485  tup = heap_copytuple(&tmptup);
2486 
2487  ReleaseSysCache(htup);
2488 
2489  return tup;
2490 }
ExpandedArrayHeader * DatumGetExpandedArray(Datum d)
void deconstruct_expanded_array(ExpandedArrayHeader *eah)
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:446
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
Datum * dvalues
Definition: array.h:139
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1184
@ STATEXTDATASTXOID
Definition: syscache.h:94

References BoolGetDatum(), DatumGetExpandedArray(), DatumGetHeapTupleHeader, deconstruct_expanded_array(), ExpandedArrayHeader::dvalues, elog(), ERROR, heap_copytuple(), HeapTupleHeaderGetDatumLength, HeapTupleIsValid, idx(), InvalidOid, ItemPointerSetInvalid(), ObjectIdGetDatum(), ReleaseSysCache(), SearchSysCache2(), STATEXTDATASTXOID, SysCacheGetAttr(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, and value.

Referenced by examine_variable().

◆ statext_is_compatible_clause()

static bool statext_is_compatible_clause ( PlannerInfo root,
Node clause,
Index  relid,
Bitmapset **  attnums,
List **  exprs 
)
static

Definition at line 1597 of file extended_stats.c.

1599 {
1600  RangeTblEntry *rte = root->simple_rte_array[relid];
1601  RelOptInfo *rel = root->simple_rel_array[relid];
1602  RestrictInfo *rinfo;
1603  int clause_relid;
1604  Oid userid;
1605 
1606  /*
1607  * Special-case handling for bare BoolExpr AND clauses, because the
1608  * restrictinfo machinery doesn't build RestrictInfos on top of AND
1609  * clauses.
1610  */
1611  if (is_andclause(clause))
1612  {
1613  BoolExpr *expr = (BoolExpr *) clause;
1614  ListCell *lc;
1615 
1616  /*
1617  * Check that each sub-clause is compatible. We expect these to be
1618  * RestrictInfos.
1619  */
1620  foreach(lc, expr->args)
1621  {
1622  if (!statext_is_compatible_clause(root, (Node *) lfirst(lc),
1623  relid, attnums, exprs))
1624  return false;
1625  }
1626 
1627  return true;
1628  }
1629 
1630  /* Otherwise it must be a RestrictInfo. */
1631  if (!IsA(clause, RestrictInfo))
1632  return false;
1633  rinfo = (RestrictInfo *) clause;
1634 
1635  /* Pseudoconstants are not really interesting here. */
1636  if (rinfo->pseudoconstant)
1637  return false;
1638 
1639  /* Clauses referencing other varnos are incompatible. */
1640  if (!bms_get_singleton_member(rinfo->clause_relids, &clause_relid) ||
1641  clause_relid != relid)
1642  return false;
1643 
1644  /* Check the clause and determine what attributes it references. */
1645  if (!statext_is_compatible_clause_internal(root, (Node *) rinfo->clause,
1646  relid, attnums, exprs))
1647  return false;
1648 
1649  /*
1650  * Check that the user has permission to read all required attributes.
1651  */
1652  userid = OidIsValid(rel->userid) ? rel->userid : GetUserId();
1653 
1654  /* Table-level SELECT privilege is sufficient for all columns */
1655  if (pg_class_aclcheck(rte->relid, userid, ACL_SELECT) != ACLCHECK_OK)
1656  {
1657  Bitmapset *clause_attnums = NULL;
1658  int attnum = -1;
1659 
1660  /*
1661  * We have to check per-column privileges. *attnums has the attnums
1662  * for individual Vars we saw, but there may also be Vars within
1663  * subexpressions in *exprs. We can use pull_varattnos() to extract
1664  * those, but there's an impedance mismatch: attnums returned by
1665  * pull_varattnos() are offset by FirstLowInvalidHeapAttributeNumber,
1666  * while attnums within *attnums aren't. Convert *attnums to the
1667  * offset style so we can combine the results.
1668  */
1669  while ((attnum = bms_next_member(*attnums, attnum)) >= 0)
1670  {
1671  clause_attnums =
1672  bms_add_member(clause_attnums,
1674  }
1675 
1676  /* Now merge attnums from *exprs into clause_attnums */
1677  if (*exprs != NIL)
1678  pull_varattnos((Node *) *exprs, relid, &clause_attnums);
1679 
1680  attnum = -1;
1681  while ((attnum = bms_next_member(clause_attnums, attnum)) >= 0)
1682  {
1683  /* Undo the offset */
1685 
1686  if (attno == InvalidAttrNumber)
1687  {
1688  /* Whole-row reference, so must have access to all columns */
1689  if (pg_attribute_aclcheck_all(rte->relid, userid, ACL_SELECT,
1691  return false;
1692  }
1693  else
1694  {
1695  if (pg_attribute_aclcheck(rte->relid, attno, userid,
1696  ACL_SELECT) != ACLCHECK_OK)
1697  return false;
1698  }
1699  }
1700  }
1701 
1702  /* If we reach here, the clause is OK */
1703  return true;
1704 }
@ ACLCHECK_OK
Definition: acl.h:184
@ ACLMASK_ALL
Definition: acl.h:177
AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode, AclMaskHow how)
Definition: aclchk.c:4661
AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum, Oid roleid, AclMode mode)
Definition: aclchk.c:4617
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4746
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:618
static bool statext_is_compatible_clause_internal(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
static bool statext_is_compatible_clause(PlannerInfo *root, Node *clause, Index relid, Bitmapset **attnums, List **exprs)
Oid GetUserId(void)
Definition: miscinit.c:497
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:105
#define ACL_SELECT
Definition: parsenodes.h:84
List * args
Definition: primnodes.h:767
Oid userid
Definition: pathnodes.h:914
Expr * clause
Definition: pathnodes.h:2435
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:281

References ACL_SELECT, ACLCHECK_OK, ACLMASK_ALL, BoolExpr::args, attnum, bms_add_member(), bms_get_singleton_member(), bms_next_member(), RestrictInfo::clause, FirstLowInvalidHeapAttributeNumber, GetUserId(), InvalidAttrNumber, is_andclause(), IsA, lfirst, NIL, OidIsValid, pg_attribute_aclcheck(), pg_attribute_aclcheck_all(), pg_class_aclcheck(), pull_varattnos(), RangeTblEntry::relid, statext_is_compatible_clause_internal(), and RelOptInfo::userid.

Referenced by statext_mcv_clauselist_selectivity().

◆ statext_is_compatible_clause_internal()

static bool statext_is_compatible_clause_internal ( PlannerInfo root,
Node clause,
Index  relid,
Bitmapset **  attnums,
List **  exprs 
)
static

Definition at line 1353 of file extended_stats.c.

1356 {
1357  /* Look inside any binary-compatible relabeling (as in examine_variable) */
1358  if (IsA(clause, RelabelType))
1359  clause = (Node *) ((RelabelType *) clause)->arg;
1360 
1361  /* plain Var references (boolean Vars or recursive checks) */
1362  if (IsA(clause, Var))
1363  {
1364  Var *var = (Var *) clause;
1365 
1366  /* Ensure var is from the correct relation */
1367  if (var->varno != relid)
1368  return false;
1369 
1370  /* we also better ensure the Var is from the current level */
1371  if (var->varlevelsup > 0)
1372  return false;
1373 
1374  /*
1375  * Also reject system attributes and whole-row Vars (we don't allow
1376  * stats on those).
1377  */
1379  return false;
1380 
1381  /* OK, record the attnum for later permissions checks. */
1382  *attnums = bms_add_member(*attnums, var->varattno);
1383 
1384  return true;
1385  }
1386 
1387  /* (Var/Expr op Const) or (Const op Var/Expr) */
1388  if (is_opclause(clause))
1389  {
1390  RangeTblEntry *rte = root->simple_rte_array[relid];
1391  OpExpr *expr = (OpExpr *) clause;
1392  Node *clause_expr;
1393 
1394  /* Only expressions with two arguments are considered compatible. */
1395  if (list_length(expr->args) != 2)
1396  return false;
1397 
1398  /* Check if the expression has the right shape */
1399  if (!examine_opclause_args(expr->args, &clause_expr, NULL, NULL))
1400  return false;
1401 
1402  /*
1403  * If it's not one of the supported operators ("=", "<", ">", etc.),
1404  * just ignore the clause, as it's not compatible with MCV lists.
1405  *
1406  * This uses the function for estimating selectivity, not the operator
1407  * directly (a bit awkward, but well ...).
1408  */
1409  switch (get_oprrest(expr->opno))
1410  {
1411  case F_EQSEL:
1412  case F_NEQSEL:
1413  case F_SCALARLTSEL:
1414  case F_SCALARLESEL:
1415  case F_SCALARGTSEL:
1416  case F_SCALARGESEL:
1417  /* supported, will continue with inspection of the Var/Expr */
1418  break;
1419 
1420  default:
1421  /* other estimators are considered unknown/unsupported */
1422  return false;
1423  }
1424 
1425  /*
1426  * If there are any securityQuals on the RTE from security barrier
1427  * views or RLS policies, then the user may not have access to all the
1428  * table's data, and we must check that the operator is leak-proof.
1429  *
1430  * If the operator is leaky, then we must ignore this clause for the
1431  * purposes of estimating with MCV lists, otherwise the operator might
1432  * reveal values from the MCV list that the user doesn't have
1433  * permission to see.
1434  */
1435  if (rte->securityQuals != NIL &&
1437  return false;
1438 
1439  /* Check (Var op Const) or (Const op Var) clauses by recursing. */
1440  if (IsA(clause_expr, Var))
1441  return statext_is_compatible_clause_internal(root, clause_expr,
1442  relid, attnums, exprs);
1443 
1444  /* Otherwise we have (Expr op Const) or (Const op Expr). */
1445  *exprs = lappend(*exprs, clause_expr);
1446  return true;
1447  }
1448 
1449  /* Var/Expr IN Array */
1450  if (IsA(clause, ScalarArrayOpExpr))
1451  {
1452  RangeTblEntry *rte = root->simple_rte_array[relid];
1453  ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
1454  Node *clause_expr;
1455  bool expronleft;
1456 
1457  /* Only expressions with two arguments are considered compatible. */
1458  if (list_length(expr->args) != 2)
1459  return false;
1460 
1461  /* Check if the expression has the right shape (one Var, one Const) */
1462  if (!examine_opclause_args(expr->args, &clause_expr, NULL, &expronleft))
1463  return false;
1464 
1465  /* We only support Var on left, Const on right */
1466  if (!expronleft)
1467  return false;
1468 
1469  /*
1470  * If it's not one of the supported operators ("=", "<", ">", etc.),
1471  * just ignore the clause, as it's not compatible with MCV lists.
1472  *
1473  * This uses the function for estimating selectivity, not the operator
1474  * directly (a bit awkward, but well ...).
1475  */
1476  switch (get_oprrest(expr->opno))
1477  {
1478  case F_EQSEL:
1479  case F_NEQSEL:
1480  case F_SCALARLTSEL:
1481  case F_SCALARLESEL:
1482  case F_SCALARGTSEL:
1483  case F_SCALARGESEL:
1484  /* supported, will continue with inspection of the Var/Expr */
1485  break;
1486 
1487  default:
1488  /* other estimators are considered unknown/unsupported */
1489  return false;
1490  }
1491 
1492  /*
1493  * If there are any securityQuals on the RTE from security barrier
1494  * views or RLS policies, then the user may not have access to all the
1495  * table's data, and we must check that the operator is leak-proof.
1496  *
1497  * If the operator is leaky, then we must ignore this clause for the
1498  * purposes of estimating with MCV lists, otherwise the operator might
1499  * reveal values from the MCV list that the user doesn't have
1500  * permission to see.
1501  */
1502  if (rte->securityQuals != NIL &&
1504  return false;
1505 
1506  /* Check Var IN Array clauses by recursing. */
1507  if (IsA(clause_expr, Var))
1508  return statext_is_compatible_clause_internal(root, clause_expr,
1509  relid, attnums, exprs);
1510 
1511  /* Otherwise we have Expr IN Array. */
1512  *exprs = lappend(*exprs, clause_expr);
1513  return true;
1514  }
1515 
1516  /* AND/OR/NOT clause */
1517  if (is_andclause(clause) ||
1518  is_orclause(clause) ||
1519  is_notclause(clause))
1520  {
1521  /*
1522  * AND/OR/NOT-clauses are supported if all sub-clauses are supported
1523  *
1524  * Perhaps we could improve this by handling mixed cases, when some of
1525  * the clauses are supported and some are not. Selectivity for the
1526  * supported subclauses would be computed using extended statistics,
1527  * and the remaining clauses would be estimated using the traditional
1528  * algorithm (product of selectivities).
1529  *
1530  * It however seems overly complex, and in a way we already do that
1531  * because if we reject the whole clause as unsupported here, it will
1532  * be eventually passed to clauselist_selectivity() which does exactly
1533  * this (split into supported/unsupported clauses etc).
1534  */
1535  BoolExpr *expr = (BoolExpr *) clause;
1536  ListCell *lc;
1537 
1538  foreach(lc, expr->args)
1539  {
1540  /*
1541  * If we find an incompatible clause in the arguments, treat the
1542  * whole clause as incompatible.
1543  */
1545  (Node *) lfirst(lc),
1546  relid, attnums, exprs))
1547  return false;
1548  }
1549 
1550  return true;
1551  }
1552 
1553  /* Var/Expr IS NULL */
1554  if (IsA(clause, NullTest))
1555  {
1556  NullTest *nt = (NullTest *) clause;
1557 
1558  /* Check Var IS NULL clauses by recursing. */
1559  if (IsA(nt->arg, Var))
1560  return statext_is_compatible_clause_internal(root, (Node *) (nt->arg),
1561  relid, attnums, exprs);
1562 
1563  /* Otherwise we have Expr IS NULL. */
1564  *exprs = lappend(*exprs, nt->arg);
1565  return true;
1566  }
1567 
1568  /*
1569  * Treat any other expressions as bare expressions to be matched against
1570  * expressions in statistics objects.
1571  */
1572  *exprs = lappend(*exprs, clause);
1573  return true;
1574 }
#define AttrNumberIsForUserDefinedAttr(attributeNumber)
Definition: attnum.h:41
bool examine_opclause_args(List *args, Node **exprp, Const **cstp, bool *expronleftp)
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1539
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
bool get_func_leakproof(Oid funcid)
Definition: lsyscache.c:1819
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:114
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:74
static bool is_notclause(const void *clause)
Definition: nodeFuncs.h:123
Expr * arg
Definition: primnodes.h:1365
Oid opno
Definition: primnodes.h:648
List * args
Definition: primnodes.h:666
List * securityQuals
Definition: parsenodes.h:1157
Definition: primnodes.h:205
AttrNumber varattno
Definition: primnodes.h:217
int varno
Definition: primnodes.h:212
Index varlevelsup
Definition: primnodes.h:230

References arg, NullTest::arg, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, AttrNumberIsForUserDefinedAttr, bms_add_member(), examine_opclause_args(), get_func_leakproof(), get_opcode(), get_oprrest(), is_andclause(), is_notclause(), is_opclause(), is_orclause(), IsA, lappend(), lfirst, list_length(), NIL, OpExpr::opno, ScalarArrayOpExpr::opno, RangeTblEntry::securityQuals, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by statext_is_compatible_clause().

◆ statext_is_kind_built()

bool statext_is_kind_built ( HeapTuple  htup,
char  type 
)

Definition at line 392 of file extended_stats.c.

393 {
395 
396  switch (type)
397  {
398  case STATS_EXT_NDISTINCT:
399  attnum = Anum_pg_statistic_ext_data_stxdndistinct;
400  break;
401 
402  case STATS_EXT_DEPENDENCIES:
403  attnum = Anum_pg_statistic_ext_data_stxddependencies;
404  break;
405 
406  case STATS_EXT_MCV:
407  attnum = Anum_pg_statistic_ext_data_stxdmcv;
408  break;
409 
410  case STATS_EXT_EXPRESSIONS:
411  attnum = Anum_pg_statistic_ext_data_stxdexpr;
412  break;
413 
414  default:
415  elog(ERROR, "unexpected statistics type requested: %d", type);
416  }
417 
418  return !heap_attisnull(htup, attnum, NULL);
419 }
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition: heaptuple.c:359

References attnum, elog(), ERROR, heap_attisnull(), and generate_unaccent_rules::type.

Referenced by get_relation_statistics_worker().

◆ statext_mcv_clauselist_selectivity()

static Selectivity statext_mcv_clauselist_selectivity ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
RelOptInfo rel,
Bitmapset **  estimatedclauses,
bool  is_or 
)
static

Definition at line 1741 of file extended_stats.c.

1745 {
1746  ListCell *l;
1747  Bitmapset **list_attnums; /* attnums extracted from the clause */
1748  List **list_exprs; /* expressions matched to any statistic */
1749  int listidx;
1750  Selectivity sel = (is_or) ? 0.0 : 1.0;
1751  RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1752 
1753  /* check if there's any stats that might be useful for us. */
1754  if (!has_stats_of_kind(rel->statlist, STATS_EXT_MCV))
1755  return sel;
1756 
1757  list_attnums = (Bitmapset **) palloc(sizeof(Bitmapset *) *
1758  list_length(clauses));
1759 
1760  /* expressions extracted from complex expressions */
1761  list_exprs = (List **) palloc(sizeof(Node *) * list_length(clauses));
1762 
1763  /*
1764  * Pre-process the clauses list to extract the attnums and expressions
1765  * seen in each item. We need to determine if there are any clauses which
1766  * will be useful for selectivity estimations with extended stats. Along
1767  * the way we'll record all of the attnums and expressions for each clause
1768  * in lists which we'll reference later so we don't need to repeat the
1769  * same work again.
1770  *
1771  * We also skip clauses that we already estimated using different types of
1772  * statistics (we treat them as incompatible).
1773  */
1774  listidx = 0;
1775  foreach(l, clauses)
1776  {
1777  Node *clause = (Node *) lfirst(l);
1778  Bitmapset *attnums = NULL;
1779  List *exprs = NIL;
1780 
1781  if (!bms_is_member(listidx, *estimatedclauses) &&
1782  statext_is_compatible_clause(root, clause, rel->relid, &attnums, &exprs))
1783  {
1784  list_attnums[listidx] = attnums;
1785  list_exprs[listidx] = exprs;
1786  }
1787  else
1788  {
1789  list_attnums[listidx] = NULL;
1790  list_exprs[listidx] = NIL;
1791  }
1792 
1793  listidx++;
1794  }
1795 
1796  /* apply as many extended statistics as possible */
1797  while (true)
1798  {
1800  List *stat_clauses;
1801  Bitmapset *simple_clauses;
1802 
1803  /* find the best suited statistics object for these attnums */
1804  stat = choose_best_statistics(rel->statlist, STATS_EXT_MCV, rte->inh,
1805  list_attnums, list_exprs,
1806  list_length(clauses));
1807 
1808  /*
1809  * if no (additional) matching stats could be found then we've nothing
1810  * to do
1811  */
1812  if (!stat)
1813  break;
1814 
1815  /* Ensure choose_best_statistics produced an expected stats type. */
1816  Assert(stat->kind == STATS_EXT_MCV);
1817 
1818  /* now filter the clauses to be estimated using the selected MCV */
1819  stat_clauses = NIL;
1820 
1821  /* record which clauses are simple (single column or expression) */
1822  simple_clauses = NULL;
1823 
1824  listidx = -1;
1825  foreach(l, clauses)
1826  {
1827  /* Increment the index before we decide if to skip the clause. */
1828  listidx++;
1829 
1830  /*
1831  * Ignore clauses from which we did not extract any attnums or
1832  * expressions (this needs to be consistent with what we do in
1833  * choose_best_statistics).
1834  *
1835  * This also eliminates already estimated clauses - both those
1836  * estimated before and during applying extended statistics.
1837  *
1838  * XXX This check is needed because both bms_is_subset and
1839  * stat_covers_expressions return true for empty attnums and
1840  * expressions.
1841  */
1842  if (!list_attnums[listidx] && !list_exprs[listidx])
1843  continue;
1844 
1845  /*
1846  * The clause was not estimated yet, and we've extracted either
1847  * attnums or expressions from it. Ignore it if it's not fully
1848  * covered by the chosen statistics object.
1849  *
1850  * We need to check both attributes and expressions, and reject if
1851  * either is not covered.
1852  */
1853  if (!bms_is_subset(list_attnums[listidx], stat->keys) ||
1854  !stat_covers_expressions(stat, list_exprs[listidx], NULL))
1855  continue;
1856 
1857  /*
1858  * Now we know the clause is compatible (we have either attnums or
1859  * expressions extracted from it), and was not estimated yet.
1860  */
1861 
1862  /* record simple clauses (single column or expression) */
1863  if ((list_attnums[listidx] == NULL &&
1864  list_length(list_exprs[listidx]) == 1) ||
1865  (list_exprs[listidx] == NIL &&
1866  bms_membership(list_attnums[listidx]) == BMS_SINGLETON))
1867  simple_clauses = bms_add_member(simple_clauses,
1868  list_length(stat_clauses));
1869 
1870  /* add clause to list and mark it as estimated */
1871  stat_clauses = lappend(stat_clauses, (Node *) lfirst(l));
1872  *estimatedclauses = bms_add_member(*estimatedclauses, listidx);
1873 
1874  /*
1875  * Reset the pointers, so that choose_best_statistics knows this
1876  * clause was estimated and does not consider it again.
1877  */
1878  bms_free(list_attnums[listidx]);
1879  list_attnums[listidx] = NULL;
1880 
1881  list_free(list_exprs[listidx]);
1882  list_exprs[listidx] = NULL;
1883  }
1884 
1885  if (is_or)
1886  {
1887  bool *or_matches = NULL;
1888  Selectivity simple_or_sel = 0.0,
1889  stat_sel = 0.0;
1890  MCVList *mcv_list;
1891 
1892  /* Load the MCV list stored in the statistics object */
1893  mcv_list = statext_mcv_load(stat->statOid, rte->inh);
1894 
1895  /*
1896  * Compute the selectivity of the ORed list of clauses covered by
1897  * this statistics object by estimating each in turn and combining
1898  * them using the formula P(A OR B) = P(A) + P(B) - P(A AND B).
1899  * This allows us to use the multivariate MCV stats to better
1900  * estimate the individual terms and their overlap.
1901  *
1902  * Each time we iterate this formula, the clause "A" above is
1903  * equal to all the clauses processed so far, combined with "OR".
1904  */
1905  listidx = 0;
1906  foreach(l, stat_clauses)
1907  {
1908  Node *clause = (Node *) lfirst(l);
1909  Selectivity simple_sel,
1910  overlap_simple_sel,
1911  mcv_sel,
1912  mcv_basesel,
1913  overlap_mcvsel,
1914  overlap_basesel,
1915  mcv_totalsel,
1916  clause_sel,
1917  overlap_sel;
1918 
1919  /*
1920  * "Simple" selectivity of the next clause and its overlap
1921  * with any of the previous clauses. These are our initial
1922  * estimates of P(B) and P(A AND B), assuming independence of
1923  * columns/clauses.
1924  */
1925  simple_sel = clause_selectivity_ext(root, clause, varRelid,
1926  jointype, sjinfo, false);
1927 
1928  overlap_simple_sel = simple_or_sel * simple_sel;
1929 
1930  /*
1931  * New "simple" selectivity of all clauses seen so far,
1932  * assuming independence.
1933  */
1934  simple_or_sel += simple_sel - overlap_simple_sel;
1935  CLAMP_PROBABILITY(simple_or_sel);
1936 
1937  /*
1938  * Multi-column estimate of this clause using MCV statistics,
1939  * along with base and total selectivities, and corresponding
1940  * selectivities for the overlap term P(A AND B).
1941  */
1942  mcv_sel = mcv_clause_selectivity_or(root, stat, mcv_list,
1943  clause, &or_matches,
1944  &mcv_basesel,
1945  &overlap_mcvsel,
1946  &overlap_basesel,
1947  &mcv_totalsel);
1948 
1949  /*
1950  * Combine the simple and multi-column estimates.
1951  *
1952  * If this clause is a simple single-column clause, then we
1953  * just use the simple selectivity estimate for it, since the
1954  * multi-column statistics are unlikely to improve on that
1955  * (and in fact could make it worse). For the overlap, we
1956  * always make use of the multi-column statistics.
1957  */
1958  if (bms_is_member(listidx, simple_clauses))
1959  clause_sel = simple_sel;
1960  else
1961  clause_sel = mcv_combine_selectivities(simple_sel,
1962  mcv_sel,
1963  mcv_basesel,
1964  mcv_totalsel);
1965 
1966  overlap_sel = mcv_combine_selectivities(overlap_simple_sel,
1967  overlap_mcvsel,
1968  overlap_basesel,
1969  mcv_totalsel);
1970 
1971  /* Factor these into the result for this statistics object */
1972  stat_sel += clause_sel - overlap_sel;
1973  CLAMP_PROBABILITY(stat_sel);
1974 
1975  listidx++;
1976  }
1977 
1978  /*
1979  * Factor the result for this statistics object into the overall
1980  * result. We treat the results from each separate statistics
1981  * object as independent of one another.
1982  */
1983  sel = sel + stat_sel - sel * stat_sel;
1984  }
1985  else /* Implicitly-ANDed list of clauses */
1986  {
1987  Selectivity simple_sel,
1988  mcv_sel,
1989  mcv_basesel,
1990  mcv_totalsel,
1991  stat_sel;
1992 
1993  /*
1994  * "Simple" selectivity, i.e. without any extended statistics,
1995  * essentially assuming independence of the columns/clauses.
1996  */
1997  simple_sel = clauselist_selectivity_ext(root, stat_clauses,
1998  varRelid, jointype,
1999  sjinfo, false);
2000 
2001  /*
2002  * Multi-column estimate using MCV statistics, along with base and
2003  * total selectivities.
2004  */
2005  mcv_sel = mcv_clauselist_selectivity(root, stat, stat_clauses,
2006  varRelid, jointype, sjinfo,
2007  rel, &mcv_basesel,
2008  &mcv_totalsel);
2009 
2010  /* Combine the simple and multi-column estimates. */
2011  stat_sel = mcv_combine_selectivities(simple_sel,
2012  mcv_sel,
2013  mcv_basesel,
2014  mcv_totalsel);
2015 
2016  /* Factor this into the overall result */
2017  sel *= stat_sel;
2018  }
2019  }
2020 
2021  return sel;
2022 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:675
@ BMS_SINGLETON
Definition: bitmapset.h:74
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:707
Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:119
bool has_stats_of_kind(List *stats, char requiredkind)
StatisticExtInfo * choose_best_statistics(List *stats, char requiredkind, bool inh, Bitmapset **clause_attnums, List **clause_exprs, int nclauses)
Selectivity mcv_clauselist_selectivity(PlannerInfo *root, StatisticExtInfo *stat, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Selectivity *basesel, Selectivity *totalsel)
Definition: mcv.c:2052
Selectivity mcv_combine_selectivities(Selectivity simple_sel, Selectivity mcv_sel, Selectivity mcv_basesel, Selectivity mcv_totalsel)
Definition: mcv.c:2010
Selectivity mcv_clause_selectivity_or(PlannerInfo *root, StatisticExtInfo *stat, MCVList *mcv, Node *clause, bool **or_matches, Selectivity *basesel, Selectivity *overlap_mcvsel, Selectivity *overlap_basesel, Selectivity *totalsel)
Definition: mcv.c:2130
MCVList * statext_mcv_load(Oid mvoid, bool inh)
Definition: mcv.c:562
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:523
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
Index relid
Definition: pathnodes.h:871
List * statlist
Definition: pathnodes.h:891
#define stat
Definition: win32_port.h:286

References Assert(), bms_add_member(), bms_free(), bms_is_member(), bms_is_subset(), bms_membership(), BMS_SINGLETON, choose_best_statistics(), CLAMP_PROBABILITY, clause_selectivity_ext(), clauselist_selectivity_ext(), has_stats_of_kind(), RangeTblEntry::inh, lappend(), lfirst, list_free(), list_length(), mcv_clause_selectivity_or(), mcv_clauselist_selectivity(), mcv_combine_selectivities(), NIL, palloc(), planner_rt_fetch, RelOptInfo::relid, stat, stat_covers_expressions(), statext_is_compatible_clause(), statext_mcv_load(), and RelOptInfo::statlist.

Referenced by statext_clauselist_selectivity().

◆ statext_store()

static void statext_store ( Oid  statOid,
bool  inh,
MVNDistinct ndistinct,
MVDependencies dependencies,
MCVList mcv,
Datum  exprs,
VacAttrStats **  stats 
)
static

Definition at line 787 of file extended_stats.c.

790 {
791  Relation pg_stextdata;
792  HeapTuple stup;
793  Datum values[Natts_pg_statistic_ext_data];
794  bool nulls[Natts_pg_statistic_ext_data];
795 
796  pg_stextdata = table_open(StatisticExtDataRelationId, RowExclusiveLock);
797 
798  memset(nulls, true, sizeof(nulls));
799  memset(values, 0, sizeof(values));
800 
801  /* basic info */
802  values[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statOid);
803  nulls[Anum_pg_statistic_ext_data_stxoid - 1] = false;
804 
805  values[Anum_pg_statistic_ext_data_stxdinherit - 1] = BoolGetDatum(inh);
806  nulls[Anum_pg_statistic_ext_data_stxdinherit - 1] = false;
807 
808  /*
809  * Construct a new pg_statistic_ext_data tuple, replacing the calculated
810  * stats.
811  */
812  if (ndistinct != NULL)
813  {
814  bytea *data = statext_ndistinct_serialize(ndistinct);
815 
816  nulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = (data == NULL);
817  values[Anum_pg_statistic_ext_data_stxdndistinct - 1] = PointerGetDatum(data);
818  }
819 
820  if (dependencies != NULL)
821  {
822  bytea *data = statext_dependencies_serialize(dependencies);
823 
824  nulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = (data == NULL);
825  values[Anum_pg_statistic_ext_data_stxddependencies - 1] = PointerGetDatum(data);
826  }
827  if (mcv != NULL)
828  {
829  bytea *data = statext_mcv_serialize(mcv, stats);
830 
831  nulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = (data == NULL);
832  values[Anum_pg_statistic_ext_data_stxdmcv - 1] = PointerGetDatum(data);
833  }
834  if (exprs != (Datum) 0)
835  {
836  nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = false;
837  values[Anum_pg_statistic_ext_data_stxdexpr - 1] = exprs;
838  }
839 
840  /*
841  * Delete the old tuple if it exists, and insert a new one. It's easier
842  * than trying to update or insert, based on various conditions.
843  */
844  RemoveStatisticsDataById(statOid, inh);
845 
846  /* form and insert a new tuple */
847  stup = heap_form_tuple(RelationGetDescr(pg_stextdata), values, nulls);
848  CatalogTupleInsert(pg_stextdata, stup);
849 
850  heap_freetuple(stup);
851 
852  table_close(pg_stextdata, RowExclusiveLock);
853 }
bytea * statext_dependencies_serialize(MVDependencies *dependencies)
Definition: dependencies.c:446
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
bytea * statext_mcv_serialize(MCVList *mcvlist, VacAttrStats **stats)
Definition: mcv.c:625
bytea * statext_ndistinct_serialize(MVNDistinct *ndistinct)
Definition: mvdistinct.c:180
void RemoveStatisticsDataById(Oid statsOid, bool inh)
Definition: statscmds.c:709
Definition: c.h:623

References BoolGetDatum(), CatalogTupleInsert(), data, heap_form_tuple(), heap_freetuple(), ObjectIdGetDatum(), PointerGetDatum(), RelationGetDescr, RemoveStatisticsDataById(), RowExclusiveLock, statext_dependencies_serialize(), statext_mcv_serialize(), statext_ndistinct_serialize(), table_close(), table_open(), and values.

Referenced by BuildRelationExtStatistics().