PostgreSQL Source Code  git master
analyze.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/multixact.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "access/tupconvert.h"
#include "access/tuptoaster.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_statistic_ext.h"
#include "commands/dbcommands.h"
#include "commands/tablecmds.h"
#include "commands/vacuum.h"
#include "executor/executor.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/attoptcache.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/sampling.h"
#include "utils/sortsupport.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
#include "utils/tqual.h"
Include dependency graph for analyze.c:

Go to the source code of this file.

Data Structures

struct  AnlIndexData
 
struct  ScalarMCVItem
 
struct  CompareScalarsContext
 

Macros

#define WIDTH_THRESHOLD   1024
 
#define swapInt(a, b)   do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
 
#define swapDatum(a, b)   do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
 

Typedefs

typedef struct AnlIndexData AnlIndexData
 

Functions

static void do_analyze_rel (Relation onerel, int options, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
 
static void compute_index_stats (Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
 
static VacAttrStatsexamine_attribute (Relation onerel, int attnum, Node *index_expr)
 
static int acquire_sample_rows (Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
 
static int compare_rows (const void *a, const void *b)
 
static int acquire_inherited_sample_rows (Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
 
static void update_attstats (Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
 
static Datum std_fetch_func (VacAttrStatsP stats, int rownum, bool *isNull)
 
static Datum ind_fetch_func (VacAttrStatsP stats, int rownum, bool *isNull)
 
void analyze_rel (Oid relid, RangeVar *relation, int options, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
 
static void compute_trivial_stats (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static void compute_distinct_stats (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static void compute_scalar_stats (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static int compare_scalars (const void *a, const void *b, void *arg)
 
static int compare_mcvs (const void *a, const void *b)
 
static int analyze_mcv_list (int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
 
bool std_typanalyze (VacAttrStats *stats)
 

Variables

int default_statistics_target = 100
 
static MemoryContext anl_context = NULL
 
static BufferAccessStrategy vac_strategy
 

Macro Definition Documentation

◆ swapDatum

#define swapDatum (   a,
 
)    do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)

Definition at line 1687 of file analyze.c.

Referenced by compute_distinct_stats().

◆ swapInt

#define swapInt (   a,
 
)    do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)

Definition at line 1686 of file analyze.c.

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1684 of file analyze.c.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

Typedef Documentation

◆ AnlIndexData

Function Documentation

◆ acquire_inherited_sample_rows()

static int acquire_inherited_sample_rows ( Relation  onerel,
int  elevel,
HeapTuple rows,
int  targrows,
double *  totalrows,
double *  totaldeadrows 
)
static

Definition at line 1265 of file analyze.c.

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert, CommandCounterIncrement(), convert_tuples_by_name(), elevel, equalTupleDescs(), ereport, errmsg(), execute_attr_map_tuple(), find_all_inheritors(), free_conversion_map(), get_namespace_name(), GetFdwRoutineForRelation(), gettext_noop, heap_close, heap_freetuple(), heap_open(), i, lfirst_oid, list_length(), Min, NoLock, palloc(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, relpages, rint(), and SetRelationHasSubclass().

Referenced by do_analyze_rel().

1268 {
1269  List *tableOIDs;
1270  Relation *rels;
1271  AcquireSampleRowsFunc *acquirefuncs;
1272  double *relblocks;
1273  double totalblocks;
1274  int numrows,
1275  nrels,
1276  i;
1277  ListCell *lc;
1278  bool has_child;
1279 
1280  /*
1281  * Find all members of inheritance set. We only need AccessShareLock on
1282  * the children.
1283  */
1284  tableOIDs =
1286 
1287  /*
1288  * Check that there's at least one descendant, else fail. This could
1289  * happen despite analyze_rel's relhassubclass check, if table once had a
1290  * child but no longer does. In that case, we can clear the
1291  * relhassubclass field so as not to make the same mistake again later.
1292  * (This is safe because we hold ShareUpdateExclusiveLock.)
1293  */
1294  if (list_length(tableOIDs) < 2)
1295  {
1296  /* CCI because we already updated the pg_class row in this command */
1298  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1299  ereport(elevel,
1300  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1302  RelationGetRelationName(onerel))));
1303  return 0;
1304  }
1305 
1306  /*
1307  * Identify acquirefuncs to use, and count blocks in all the relations.
1308  * The result could overflow BlockNumber, so we use double arithmetic.
1309  */
1310  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1311  acquirefuncs = (AcquireSampleRowsFunc *)
1312  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1313  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1314  totalblocks = 0;
1315  nrels = 0;
1316  has_child = false;
1317  foreach(lc, tableOIDs)
1318  {
1319  Oid childOID = lfirst_oid(lc);
1320  Relation childrel;
1321  AcquireSampleRowsFunc acquirefunc = NULL;
1322  BlockNumber relpages = 0;
1323 
1324  /* We already got the needed lock */
1325  childrel = heap_open(childOID, NoLock);
1326 
1327  /* Ignore if temp table of another backend */
1328  if (RELATION_IS_OTHER_TEMP(childrel))
1329  {
1330  /* ... but release the lock on it */
1331  Assert(childrel != onerel);
1332  heap_close(childrel, AccessShareLock);
1333  continue;
1334  }
1335 
1336  /* Check table type (MATVIEW can't happen, but might as well allow) */
1337  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1338  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1339  {
1340  /* Regular table, so use the regular row acquisition function */
1341  acquirefunc = acquire_sample_rows;
1342  relpages = RelationGetNumberOfBlocks(childrel);
1343  }
1344  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1345  {
1346  /*
1347  * For a foreign table, call the FDW's hook function to see
1348  * whether it supports analysis.
1349  */
1350  FdwRoutine *fdwroutine;
1351  bool ok = false;
1352 
1353  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1354 
1355  if (fdwroutine->AnalyzeForeignTable != NULL)
1356  ok = fdwroutine->AnalyzeForeignTable(childrel,
1357  &acquirefunc,
1358  &relpages);
1359 
1360  if (!ok)
1361  {
1362  /* ignore, but release the lock on it */
1363  Assert(childrel != onerel);
1364  heap_close(childrel, AccessShareLock);
1365  continue;
1366  }
1367  }
1368  else
1369  {
1370  /*
1371  * ignore, but release the lock on it. don't try to unlock the
1372  * passed-in relation
1373  */
1374  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1375  if (childrel != onerel)
1376  heap_close(childrel, AccessShareLock);
1377  else
1378  heap_close(childrel, NoLock);
1379  continue;
1380  }
1381 
1382  /* OK, we'll process this child */
1383  has_child = true;
1384  rels[nrels] = childrel;
1385  acquirefuncs[nrels] = acquirefunc;
1386  relblocks[nrels] = (double) relpages;
1387  totalblocks += (double) relpages;
1388  nrels++;
1389  }
1390 
1391  /*
1392  * If we don't have at least one child table to consider, fail. If the
1393  * relation is a partitioned table, it's not counted as a child table.
1394  */
1395  if (!has_child)
1396  {
1397  ereport(elevel,
1398  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1400  RelationGetRelationName(onerel))));
1401  return 0;
1402  }
1403 
1404  /*
1405  * Now sample rows from each relation, proportionally to its fraction of
1406  * the total block count. (This might be less than desirable if the child
1407  * rels have radically different free-space percentages, but it's not
1408  * clear that it's worth working harder.)
1409  */
1410  numrows = 0;
1411  *totalrows = 0;
1412  *totaldeadrows = 0;
1413  for (i = 0; i < nrels; i++)
1414  {
1415  Relation childrel = rels[i];
1416  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1417  double childblocks = relblocks[i];
1418 
1419  if (childblocks > 0)
1420  {
1421  int childtargrows;
1422 
1423  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1424  /* Make sure we don't overrun due to roundoff error */
1425  childtargrows = Min(childtargrows, targrows - numrows);
1426  if (childtargrows > 0)
1427  {
1428  int childrows;
1429  double trows,
1430  tdrows;
1431 
1432  /* Fetch a random sample of the child's rows */
1433  childrows = (*acquirefunc) (childrel, elevel,
1434  rows + numrows, childtargrows,
1435  &trows, &tdrows);
1436 
1437  /* We may need to convert from child's rowtype to parent's */
1438  if (childrows > 0 &&
1439  !equalTupleDescs(RelationGetDescr(childrel),
1440  RelationGetDescr(onerel)))
1441  {
1442  TupleConversionMap *map;
1443 
1444  map = convert_tuples_by_name(RelationGetDescr(childrel),
1445  RelationGetDescr(onerel),
1446  gettext_noop("could not convert row type"));
1447  if (map != NULL)
1448  {
1449  int j;
1450 
1451  for (j = 0; j < childrows; j++)
1452  {
1453  HeapTuple newtup;
1454 
1455  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1456  heap_freetuple(rows[numrows + j]);
1457  rows[numrows + j] = newtup;
1458  }
1459  free_conversion_map(map);
1460  }
1461  }
1462 
1463  /* And add to counts */
1464  numrows += childrows;
1465  *totalrows += trows;
1466  *totaldeadrows += tdrows;
1467  }
1468  }
1469 
1470  /*
1471  * Note: we cannot release the child-table locks, since we may have
1472  * pointers to their TOAST tables in the sampled rows.
1473  */
1474  heap_close(childrel, NoLock);
1475  }
1476 
1477  return numrows;
1478 }
#define RelationGetDescr(relation)
Definition: rel.h:434
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:233
#define Min(x, y)
Definition: c.h:890
#define AccessShareLock
Definition: lockdefs.h:36
#define gettext_noop(x)
Definition: c.h:1103
uint32 BlockNumber
Definition: block.h:31
#define heap_close(r, l)
Definition: heapam.h:98
Form_pg_class rd_rel
Definition: rel.h:84
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1537
unsigned int Oid
Definition: postgres_ext.h:31
int32 relpages
Definition: pg_class.h:43
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:2676
struct RelationData * Relation
Definition: relcache.h:26
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3101
#define NoLock
Definition: lockdefs.h:34
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:492
#define RelationGetRelationName(relation)
Definition: rel.h:442
double rint(double x)
Definition: rint.c:21
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:398
#define ereport(elevel, rest)
Definition: elog.h:141
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:209
static int elevel
Definition: vacuumlazy.c:144
void CommandCounterIncrement(void)
Definition: xact.c:918
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1306
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define Assert(condition)
Definition: c.h:732
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:539
static int list_length(const List *l)
Definition: pg_list.h:89
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:141
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:166
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:786
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
int i
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:409
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:408
#define lfirst_oid(lc)
Definition: pg_list.h:108
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:989
#define RelationGetNamespace(relation)
Definition: rel.h:449

◆ acquire_sample_rows()

static int acquire_sample_rows ( Relation  onerel,
int  elevel,
HeapTuple rows,
int  targrows,
double *  totalrows,
double *  totaldeadrows 
)
static

Definition at line 989 of file analyze.c.

References Assert, BlockSampler_HasMore(), BlockSampler_Init(), BlockSampler_Next(), BUFFER_LOCK_SHARE, BufferGetPage, compare_rows(), elog, ereport, errmsg(), ERROR, FirstOffsetNumber, GetOldestXmin(), heap_copytuple(), heap_freetuple(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleSatisfiesVacuum(), ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemPointerSet, LockBuffer(), BlockSamplerData::m, MAIN_FORKNUM, OldestXmin, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PROCARRAY_FLAGS_VACUUM, qsort, random(), ReservoirStateData::randstate, RBM_NORMAL, ReadBufferExtended(), RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, reservoir_get_next_S(), reservoir_init_selection_state(), sampler_random_fract(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdIsCurrentTransactionId(), UnlockReleaseBuffer(), and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

992 {
993  int numrows = 0; /* # rows now in reservoir */
994  double samplerows = 0; /* total # rows collected */
995  double liverows = 0; /* # live rows seen */
996  double deadrows = 0; /* # dead rows seen */
997  double rowstoskip = -1; /* -1 means not set yet */
998  BlockNumber totalblocks;
1000  BlockSamplerData bs;
1001  ReservoirStateData rstate;
1002 
1003  Assert(targrows > 0);
1004 
1005  totalblocks = RelationGetNumberOfBlocks(onerel);
1006 
1007  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1008  OldestXmin = GetOldestXmin(onerel, PROCARRAY_FLAGS_VACUUM);
1009 
1010  /* Prepare for sampling block numbers */
1011  BlockSampler_Init(&bs, totalblocks, targrows, random());
1012  /* Prepare for sampling rows */
1013  reservoir_init_selection_state(&rstate, targrows);
1014 
1015  /* Outer loop over blocks to sample */
1016  while (BlockSampler_HasMore(&bs))
1017  {
1018  BlockNumber targblock = BlockSampler_Next(&bs);
1019  Buffer targbuffer;
1020  Page targpage;
1021  OffsetNumber targoffset,
1022  maxoffset;
1023 
1025 
1026  /*
1027  * We must maintain a pin on the target page's buffer to ensure that
1028  * the maxoffset value stays good (else concurrent VACUUM might delete
1029  * tuples out from under us). Hence, pin the page until we are done
1030  * looking at it. We also choose to hold sharelock on the buffer
1031  * throughout --- we could release and re-acquire sharelock for each
1032  * tuple, but since we aren't doing much work per tuple, the extra
1033  * lock traffic is probably better avoided.
1034  */
1035  targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1037  LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1038  targpage = BufferGetPage(targbuffer);
1039  maxoffset = PageGetMaxOffsetNumber(targpage);
1040 
1041  /* Inner loop over all tuples on the selected page */
1042  for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1043  {
1044  ItemId itemid;
1045  HeapTupleData targtuple;
1046  bool sample_it = false;
1047 
1048  itemid = PageGetItemId(targpage, targoffset);
1049 
1050  /*
1051  * We ignore unused and redirect line pointers. DEAD line
1052  * pointers should be counted as dead, because we need vacuum to
1053  * run to get rid of them. Note that this rule agrees with the
1054  * way that heap_page_prune() counts things.
1055  */
1056  if (!ItemIdIsNormal(itemid))
1057  {
1058  if (ItemIdIsDead(itemid))
1059  deadrows += 1;
1060  continue;
1061  }
1062 
1063  ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1064 
1065  targtuple.t_tableOid = RelationGetRelid(onerel);
1066  targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1067  targtuple.t_len = ItemIdGetLength(itemid);
1068 
1069  switch (HeapTupleSatisfiesVacuum(&targtuple,
1070  OldestXmin,
1071  targbuffer))
1072  {
1073  case HEAPTUPLE_LIVE:
1074  sample_it = true;
1075  liverows += 1;
1076  break;
1077 
1078  case HEAPTUPLE_DEAD:
1080  /* Count dead and recently-dead rows */
1081  deadrows += 1;
1082  break;
1083 
1085 
1086  /*
1087  * Insert-in-progress rows are not counted. We assume
1088  * that when the inserting transaction commits or aborts,
1089  * it will send a stats message to increment the proper
1090  * count. This works right only if that transaction ends
1091  * after we finish analyzing the table; if things happen
1092  * in the other order, its stats update will be
1093  * overwritten by ours. However, the error will be large
1094  * only if the other transaction runs long enough to
1095  * insert many tuples, so assuming it will finish after us
1096  * is the safer option.
1097  *
1098  * A special case is that the inserting transaction might
1099  * be our own. In this case we should count and sample
1100  * the row, to accommodate users who load a table and
1101  * analyze it in one transaction. (pgstat_report_analyze
1102  * has to adjust the numbers we send to the stats
1103  * collector to make this come out right.)
1104  */
1106  {
1107  sample_it = true;
1108  liverows += 1;
1109  }
1110  break;
1111 
1113 
1114  /*
1115  * We count delete-in-progress rows as still live, using
1116  * the same reasoning given above; but we don't bother to
1117  * include them in the sample.
1118  *
1119  * If the delete was done by our own transaction, however,
1120  * we must count the row as dead to make
1121  * pgstat_report_analyze's stats adjustments come out
1122  * right. (Note: this works out properly when the row was
1123  * both inserted and deleted in our xact.)
1124  */
1126  deadrows += 1;
1127  else
1128  liverows += 1;
1129  break;
1130 
1131  default:
1132  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1133  break;
1134  }
1135 
1136  if (sample_it)
1137  {
1138  /*
1139  * The first targrows sample rows are simply copied into the
1140  * reservoir. Then we start replacing tuples in the sample
1141  * until we reach the end of the relation. This algorithm is
1142  * from Jeff Vitter's paper (see full citation below). It
1143  * works by repeatedly computing the number of tuples to skip
1144  * before selecting a tuple, which replaces a randomly chosen
1145  * element of the reservoir (current set of tuples). At all
1146  * times the reservoir is a true random sample of the tuples
1147  * we've passed over so far, so when we fall off the end of
1148  * the relation we're done.
1149  */
1150  if (numrows < targrows)
1151  rows[numrows++] = heap_copytuple(&targtuple);
1152  else
1153  {
1154  /*
1155  * t in Vitter's paper is the number of records already
1156  * processed. If we need to compute a new S value, we
1157  * must use the not-yet-incremented value of samplerows as
1158  * t.
1159  */
1160  if (rowstoskip < 0)
1161  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1162 
1163  if (rowstoskip <= 0)
1164  {
1165  /*
1166  * Found a suitable tuple, so save it, replacing one
1167  * old tuple at random
1168  */
1169  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1170 
1171  Assert(k >= 0 && k < targrows);
1172  heap_freetuple(rows[k]);
1173  rows[k] = heap_copytuple(&targtuple);
1174  }
1175 
1176  rowstoskip -= 1;
1177  }
1178 
1179  samplerows += 1;
1180  }
1181  }
1182 
1183  /* Now release the lock and pin on the page */
1184  UnlockReleaseBuffer(targbuffer);
1185  }
1186 
1187  /*
1188  * If we didn't find as many tuples as we wanted then we're done. No sort
1189  * is needed, since they're already in order.
1190  *
1191  * Otherwise we need to sort the collected tuples by position
1192  * (itempointer). It's not worth worrying about corner cases where the
1193  * tuples are already sorted.
1194  */
1195  if (numrows == targrows)
1196  qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1197 
1198  /*
1199  * Estimate total numbers of live and dead rows in relation, extrapolating
1200  * on the assumption that the average tuple density in pages we didn't
1201  * scan is the same as in the pages we did scan. Since what we scanned is
1202  * a random sample of the pages in the relation, this should be a good
1203  * assumption.
1204  */
1205  if (bs.m > 0)
1206  {
1207  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1208  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1209  }
1210  else
1211  {
1212  *totalrows = 0.0;
1213  *totaldeadrows = 0.0;
1214  }
1215 
1216  /*
1217  * Emit some interesting relation info
1218  */
1219  ereport(elevel,
1220  (errmsg("\"%s\": scanned %d of %u pages, "
1221  "containing %.0f live rows and %.0f dead rows; "
1222  "%d rows in sample, %.0f estimated total rows",
1223  RelationGetRelationName(onerel),
1224  bs.m, totalblocks,
1225  liverows, deadrows,
1226  numrows, *totalrows)));
1227 
1228  return numrows;
1229 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:364
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:54
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:684
uint32 TransactionId
Definition: c.h:507
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:769
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:60
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
long random(void)
Definition: random.c:22
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
Definition: tqual.c:1164
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
uint32 BlockNumber
Definition: block.h:31
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:129
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:52
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1537
#define ItemIdIsDead(itemId)
Definition: itemid.h:112
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, long randseed)
Definition: sampling.c:37
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
#define FirstOffsetNumber
Definition: off.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:442
static TransactionId OldestXmin
Definition: vacuumlazy.c:146
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:141
static int compare_rows(const void *a, const void *b)
Definition: analyze.c:1235
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
static int elevel
Definition: vacuumlazy.c:144
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1317
#define Assert(condition)
Definition: c.h:732
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:312
int errmsg(const char *fmt,...)
Definition: elog.c:786
#define elog(elevel,...)
Definition: elog.h:226
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define qsort(a, b, c, d)
Definition: port.h:462
void vacuum_delay_point(void)
Definition: vacuum.c:1829
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:408
#define PageGetItem(page, itemId)
Definition: bufpage.h:336
Pointer Page
Definition: bufpage.h:74
SamplerRandomState randstate
Definition: sampling.h:50
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142

◆ analyze_mcv_list()

static int analyze_mcv_list ( int *  mcv_counts,
int  num_mcv,
double  stadistinct,
double  stanullfrac,
int  samplerows,
double  totalrows 
)
static

Definition at line 2820 of file analyze.c.

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

2826 {
2827  double ndistinct_table;
2828  double sumcount;
2829  int i;
2830 
2831  /*
2832  * If the entire table was sampled, keep the whole list. This also
2833  * protects us against division by zero in the code below.
2834  */
2835  if (samplerows == totalrows || totalrows <= 1.0)
2836  return num_mcv;
2837 
2838  /* Re-extract the estimated number of distinct nonnull values in table */
2839  ndistinct_table = stadistinct;
2840  if (ndistinct_table < 0)
2841  ndistinct_table = -ndistinct_table * totalrows;
2842 
2843  /*
2844  * Exclude the least common values from the MCV list, if they are not
2845  * significantly more common than the estimated selectivity they would
2846  * have if they weren't in the list. All non-MCV values are assumed to be
2847  * equally common, after taking into account the frequencies of all the
2848  * values in the MCV list and the number of nulls (c.f. eqsel()).
2849  *
2850  * Here sumcount tracks the total count of all but the last (least common)
2851  * value in the MCV list, allowing us to determine the effect of excluding
2852  * that value from the list.
2853  *
2854  * Note that we deliberately do this by removing values from the full
2855  * list, rather than starting with an empty list and adding values,
2856  * because the latter approach can fail to add any values if all the most
2857  * common values have around the same frequency and make up the majority
2858  * of the table, so that the overall average frequency of all values is
2859  * roughly the same as that of the common values. This would lead to any
2860  * uncommon values being significantly overestimated.
2861  */
2862  sumcount = 0.0;
2863  for (i = 0; i < num_mcv - 1; i++)
2864  sumcount += mcv_counts[i];
2865 
2866  while (num_mcv > 0)
2867  {
2868  double selec,
2869  otherdistinct,
2870  N,
2871  n,
2872  K,
2873  variance,
2874  stddev;
2875 
2876  /*
2877  * Estimated selectivity the least common value would have if it
2878  * wasn't in the MCV list (c.f. eqsel()).
2879  */
2880  selec = 1.0 - sumcount / samplerows - stanullfrac;
2881  if (selec < 0.0)
2882  selec = 0.0;
2883  if (selec > 1.0)
2884  selec = 1.0;
2885  otherdistinct = ndistinct_table - (num_mcv - 1);
2886  if (otherdistinct > 1)
2887  selec /= otherdistinct;
2888 
2889  /*
2890  * If the value is kept in the MCV list, its population frequency is
2891  * assumed to equal its sample frequency. We use the lower end of a
2892  * textbook continuity-corrected Wald-type confidence interval to
2893  * determine if that is significantly more common than the non-MCV
2894  * frequency --- specifically we assume the population frequency is
2895  * highly likely to be within around 2 standard errors of the sample
2896  * frequency, which equates to an interval of 2 standard deviations
2897  * either side of the sample count, plus an additional 0.5 for the
2898  * continuity correction. Since we are sampling without replacement,
2899  * this is a hypergeometric distribution.
2900  *
2901  * XXX: Empirically, this approach seems to work quite well, but it
2902  * may be worth considering more advanced techniques for estimating
2903  * the confidence interval of the hypergeometric distribution.
2904  */
2905  N = totalrows;
2906  n = samplerows;
2907  K = N * mcv_counts[num_mcv - 1] / n;
2908  variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
2909  stddev = sqrt(variance);
2910 
2911  if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
2912  {
2913  /*
2914  * The value is significantly more common than the non-MCV
2915  * selectivity would suggest. Keep it, and all the other more
2916  * common values in the list.
2917  */
2918  break;
2919  }
2920  else
2921  {
2922  /* Discard this value and consider the next least common value */
2923  num_mcv--;
2924  if (num_mcv == 0)
2925  break;
2926  sumcount -= mcv_counts[num_mcv - 1];
2927  }
2928  }
2929  return num_mcv;
2930 }
#define K(t)
Definition: sha1.c:48
int i

◆ analyze_rel()

void analyze_rel ( Oid  relid,
RangeVar relation,
int  options,
VacuumParams params,
List va_cols,
bool  in_outer_xact,
BufferAccessStrategy  bstrategy 
)

Definition at line 115 of file analyze.c.

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), elevel, ereport, errmsg(), GetFdwRoutineForRelation(), INFO, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyPgXact, NoLock, PROC_IN_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, relpages, ShareUpdateExclusiveLock, VACOPT_ANALYZE, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_relation_owner(), vacuum_open_relation(), PGXACT::vacuumFlags, and WARNING.

Referenced by vacuum().

118 {
119  Relation onerel;
120  int elevel;
121  AcquireSampleRowsFunc acquirefunc = NULL;
122  BlockNumber relpages = 0;
123 
124  /* Select logging level */
125  if (options & VACOPT_VERBOSE)
126  elevel = INFO;
127  else
128  elevel = DEBUG2;
129 
130  /* Set up static variables */
131  vac_strategy = bstrategy;
132 
133  /*
134  * Check for user-requested abort.
135  */
137 
138  /*
139  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
140  * ANALYZEs don't run on it concurrently. (This also locks out a
141  * concurrent VACUUM, which doesn't matter much at the moment but might
142  * matter if we ever try to accumulate stats on dead tuples.) If the rel
143  * has been dropped since we last saw it, we don't need to process it.
144  *
145  * Make sure to generate only logs for ANALYZE in this case.
146  */
147  onerel = vacuum_open_relation(relid, relation, params,
148  options & ~(VACOPT_VACUUM),
150 
151  /* leave if relation could not be opened or locked */
152  if (!onerel)
153  return;
154 
155  /*
156  * Check if relation needs to be skipped based on ownership. This check
157  * happens also when building the relation list to analyze for a manual
158  * operation, and needs to be done additionally here as ANALYZE could
159  * happen across multiple transactions where relation ownership could have
160  * changed in-between. Make sure to generate only logs for ANALYZE in
161  * this case.
162  */
164  onerel->rd_rel,
166  {
168  return;
169  }
170 
171  /*
172  * Silently ignore tables that are temp tables of other backends ---
173  * trying to analyze these is rather pointless, since their contents are
174  * probably not up-to-date on disk. (We don't throw a warning here; it
175  * would just lead to chatter during a database-wide ANALYZE.)
176  */
177  if (RELATION_IS_OTHER_TEMP(onerel))
178  {
180  return;
181  }
182 
183  /*
184  * We can ANALYZE any table except pg_statistic. See update_attstats
185  */
186  if (RelationGetRelid(onerel) == StatisticRelationId)
187  {
189  return;
190  }
191 
192  /*
193  * Check that it's of an analyzable relkind, and set up appropriately.
194  */
195  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
196  onerel->rd_rel->relkind == RELKIND_MATVIEW)
197  {
198  /* Regular table, so we'll use the regular row acquisition function */
199  acquirefunc = acquire_sample_rows;
200  /* Also get regular table's size */
201  relpages = RelationGetNumberOfBlocks(onerel);
202  }
203  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
204  {
205  /*
206  * For a foreign table, call the FDW's hook function to see whether it
207  * supports analysis.
208  */
209  FdwRoutine *fdwroutine;
210  bool ok = false;
211 
212  fdwroutine = GetFdwRoutineForRelation(onerel, false);
213 
214  if (fdwroutine->AnalyzeForeignTable != NULL)
215  ok = fdwroutine->AnalyzeForeignTable(onerel,
216  &acquirefunc,
217  &relpages);
218 
219  if (!ok)
220  {
222  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
223  RelationGetRelationName(onerel))));
225  return;
226  }
227  }
228  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
229  {
230  /*
231  * For partitioned tables, we want to do the recursive ANALYZE below.
232  */
233  }
234  else
235  {
236  /* No need for a WARNING if we already complained during VACUUM */
237  if (!(options & VACOPT_VACUUM))
239  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
240  RelationGetRelationName(onerel))));
242  return;
243  }
244 
245  /*
246  * OK, let's do it. First let other backends know I'm in ANALYZE.
247  */
248  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
250  LWLockRelease(ProcArrayLock);
251 
252  /*
253  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
254  * tables, which don't contain any rows.
255  */
256  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
257  do_analyze_rel(onerel, options, params, va_cols, acquirefunc,
258  relpages, false, in_outer_xact, elevel);
259 
260  /*
261  * If there are child tables, do recursive ANALYZE.
262  */
263  if (onerel->rd_rel->relhassubclass)
264  do_analyze_rel(onerel, options, params, va_cols, acquirefunc, relpages,
265  true, in_outer_xact, elevel);
266 
267  /*
268  * Close source relation now, but keep lock so that no one deletes it
269  * before we commit. (If someone did, they'd fail to clean up the entries
270  * we made in pg_statistic. Also, releasing the lock before commit would
271  * expose us to concurrent-update failures in update_attstats.)
272  */
273  relation_close(onerel, NoLock);
274 
275  /*
276  * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
277  * because the vacuum flag is cleared by the end-of-xact code.
278  */
279  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
281  LWLockRelease(ProcArrayLock);
282 }
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:233
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1282
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:84
int32 relpages
Definition: pg_class.h:43
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:233
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, int options)
Definition: vacuum.c:419
#define DEBUG2
Definition: elog.h:24
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:442
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
static void do_analyze_rel(Relation onerel, int options, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:292
static int elevel
Definition: vacuumlazy.c:144
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:539
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:786
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define PROC_IN_ANALYZE
Definition: proc.h:55
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
Relation vacuum_open_relation(Oid relid, RangeVar *relation, VacuumParams *params, int options, LOCKMODE lmode)
Definition: vacuum.c:493
#define RelationGetRelid(relation)
Definition: rel.h:408
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:989

◆ compare_mcvs()

static int compare_mcvs ( const void *  a,
const void *  b 
)
static

Definition at line 2802 of file analyze.c.

Referenced by compute_scalar_stats().

2803 {
2804  int da = ((const ScalarMCVItem *) a)->first;
2805  int db = ((const ScalarMCVItem *) b)->first;
2806 
2807  return da - db;
2808 }

◆ compare_rows()

static int compare_rows ( const void *  a,
const void *  b 
)
static

Definition at line 1235 of file analyze.c.

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1236 {
1237  HeapTuple ha = *(const HeapTuple *) a;
1238  HeapTuple hb = *(const HeapTuple *) b;
1243 
1244  if (ba < bb)
1245  return -1;
1246  if (ba > bb)
1247  return 1;
1248  if (oa < ob)
1249  return -1;
1250  if (oa > ob)
1251  return 1;
1252  return 0;
1253 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ compare_scalars()

static int compare_scalars ( const void *  a,
const void *  b,
void *  arg 
)
static

Definition at line 2771 of file analyze.c.

References ApplySortComparator(), compare(), CompareScalarsContext::ssup, and CompareScalarsContext::tupnoLink.

Referenced by compute_scalar_stats().

2772 {
2773  Datum da = ((const ScalarItem *) a)->value;
2774  int ta = ((const ScalarItem *) a)->tupno;
2775  Datum db = ((const ScalarItem *) b)->value;
2776  int tb = ((const ScalarItem *) b)->tupno;
2778  int compare;
2779 
2780  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2781  if (compare != 0)
2782  return compare;
2783 
2784  /*
2785  * The two datums are equal, so update cxt->tupnoLink[].
2786  */
2787  if (cxt->tupnoLink[ta] < tb)
2788  cxt->tupnoLink[ta] = tb;
2789  if (cxt->tupnoLink[tb] < ta)
2790  cxt->tupnoLink[tb] = ta;
2791 
2792  /*
2793  * For equal datums, sort by tupno
2794  */
2795  return ta - tb;
2796 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
SortSupport ssup
Definition: analyze.c:1700
uintptr_t Datum
Definition: postgres.h:367
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

◆ compute_distinct_stats()

static void compute_distinct_stats ( VacAttrStatsP  stats,
AnalyzeAttrFetchFunc  fetchfunc,
int  samplerows,
double  totalrows 
)
static

Definition at line 1901 of file analyze.c.

References analyze_mcv_list(), VacAttrStats::anl_context, VacAttrStats::attr, VacAttrStats::attrtype, datumCopy(), DatumGetBool, DatumGetCString, DatumGetPointer, StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, fmgr_info(), FunctionCall2Coll(), i, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, VacAttrStats::stats_valid, VacAttrStats::stavalues, VacAttrStats::stawidth, swapDatum, swapInt, toast_raw_datum_size(), vacuum_delay_point(), value, VARSIZE_ANY, and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

1905 {
1906  int i;
1907  int null_cnt = 0;
1908  int nonnull_cnt = 0;
1909  int toowide_cnt = 0;
1910  double total_width = 0;
1911  bool is_varlena = (!stats->attrtype->typbyval &&
1912  stats->attrtype->typlen == -1);
1913  bool is_varwidth = (!stats->attrtype->typbyval &&
1914  stats->attrtype->typlen < 0);
1915  FmgrInfo f_cmpeq;
1916  typedef struct
1917  {
1918  Datum value;
1919  int count;
1920  } TrackItem;
1921  TrackItem *track;
1922  int track_cnt,
1923  track_max;
1924  int num_mcv = stats->attr->attstattarget;
1925  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1926 
1927  /*
1928  * We track up to 2*n values for an n-element MCV list; but at least 10
1929  */
1930  track_max = 2 * num_mcv;
1931  if (track_max < 10)
1932  track_max = 10;
1933  track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1934  track_cnt = 0;
1935 
1936  fmgr_info(mystats->eqfunc, &f_cmpeq);
1937 
1938  for (i = 0; i < samplerows; i++)
1939  {
1940  Datum value;
1941  bool isnull;
1942  bool match;
1943  int firstcount1,
1944  j;
1945 
1947 
1948  value = fetchfunc(stats, i, &isnull);
1949 
1950  /* Check for null/nonnull */
1951  if (isnull)
1952  {
1953  null_cnt++;
1954  continue;
1955  }
1956  nonnull_cnt++;
1957 
1958  /*
1959  * If it's a variable-width field, add up widths for average width
1960  * calculation. Note that if the value is toasted, we use the toasted
1961  * width. We don't bother with this calculation if it's a fixed-width
1962  * type.
1963  */
1964  if (is_varlena)
1965  {
1966  total_width += VARSIZE_ANY(DatumGetPointer(value));
1967 
1968  /*
1969  * If the value is toasted, we want to detoast it just once to
1970  * avoid repeated detoastings and resultant excess memory usage
1971  * during the comparisons. Also, check to see if the value is
1972  * excessively wide, and if so don't detoast at all --- just
1973  * ignore the value.
1974  */
1976  {
1977  toowide_cnt++;
1978  continue;
1979  }
1980  value = PointerGetDatum(PG_DETOAST_DATUM(value));
1981  }
1982  else if (is_varwidth)
1983  {
1984  /* must be cstring */
1985  total_width += strlen(DatumGetCString(value)) + 1;
1986  }
1987 
1988  /*
1989  * See if the value matches anything we're already tracking.
1990  */
1991  match = false;
1992  firstcount1 = track_cnt;
1993  for (j = 0; j < track_cnt; j++)
1994  {
1995  /* We always use the default collation for statistics */
1996  if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
1997  DEFAULT_COLLATION_OID,
1998  value, track[j].value)))
1999  {
2000  match = true;
2001  break;
2002  }
2003  if (j < firstcount1 && track[j].count == 1)
2004  firstcount1 = j;
2005  }
2006 
2007  if (match)
2008  {
2009  /* Found a match */
2010  track[j].count++;
2011  /* This value may now need to "bubble up" in the track list */
2012  while (j > 0 && track[j].count > track[j - 1].count)
2013  {
2014  swapDatum(track[j].value, track[j - 1].value);
2015  swapInt(track[j].count, track[j - 1].count);
2016  j--;
2017  }
2018  }
2019  else
2020  {
2021  /* No match. Insert at head of count-1 list */
2022  if (track_cnt < track_max)
2023  track_cnt++;
2024  for (j = track_cnt - 1; j > firstcount1; j--)
2025  {
2026  track[j].value = track[j - 1].value;
2027  track[j].count = track[j - 1].count;
2028  }
2029  if (firstcount1 < track_cnt)
2030  {
2031  track[firstcount1].value = value;
2032  track[firstcount1].count = 1;
2033  }
2034  }
2035  }
2036 
2037  /* We can only compute real stats if we found some non-null values. */
2038  if (nonnull_cnt > 0)
2039  {
2040  int nmultiple,
2041  summultiple;
2042 
2043  stats->stats_valid = true;
2044  /* Do the simple null-frac and width stats */
2045  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2046  if (is_varwidth)
2047  stats->stawidth = total_width / (double) nonnull_cnt;
2048  else
2049  stats->stawidth = stats->attrtype->typlen;
2050 
2051  /* Count the number of values we found multiple times */
2052  summultiple = 0;
2053  for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2054  {
2055  if (track[nmultiple].count == 1)
2056  break;
2057  summultiple += track[nmultiple].count;
2058  }
2059 
2060  if (nmultiple == 0)
2061  {
2062  /*
2063  * If we found no repeated non-null values, assume it's a unique
2064  * column; but be sure to discount for any nulls we found.
2065  */
2066  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2067  }
2068  else if (track_cnt < track_max && toowide_cnt == 0 &&
2069  nmultiple == track_cnt)
2070  {
2071  /*
2072  * Our track list includes every value in the sample, and every
2073  * value appeared more than once. Assume the column has just
2074  * these values. (This case is meant to address columns with
2075  * small, fixed sets of possible values, such as boolean or enum
2076  * columns. If there are any values that appear just once in the
2077  * sample, including too-wide values, we should assume that that's
2078  * not what we're dealing with.)
2079  */
2080  stats->stadistinct = track_cnt;
2081  }
2082  else
2083  {
2084  /*----------
2085  * Estimate the number of distinct values using the estimator
2086  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2087  * n*d / (n - f1 + f1*n/N)
2088  * where f1 is the number of distinct values that occurred
2089  * exactly once in our sample of n rows (from a total of N),
2090  * and d is the total number of distinct values in the sample.
2091  * This is their Duj1 estimator; the other estimators they
2092  * recommend are considerably more complex, and are numerically
2093  * very unstable when n is much smaller than N.
2094  *
2095  * In this calculation, we consider only non-nulls. We used to
2096  * include rows with null values in the n and N counts, but that
2097  * leads to inaccurate answers in columns with many nulls, and
2098  * it's intuitively bogus anyway considering the desired result is
2099  * the number of distinct non-null values.
2100  *
2101  * We assume (not very reliably!) that all the multiply-occurring
2102  * values are reflected in the final track[] list, and the other
2103  * nonnull values all appeared but once. (XXX this usually
2104  * results in a drastic overestimate of ndistinct. Can we do
2105  * any better?)
2106  *----------
2107  */
2108  int f1 = nonnull_cnt - summultiple;
2109  int d = f1 + nmultiple;
2110  double n = samplerows - null_cnt;
2111  double N = totalrows * (1.0 - stats->stanullfrac);
2112  double stadistinct;
2113 
2114  /* N == 0 shouldn't happen, but just in case ... */
2115  if (N > 0)
2116  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2117  else
2118  stadistinct = 0;
2119 
2120  /* Clamp to sane range in case of roundoff error */
2121  if (stadistinct < d)
2122  stadistinct = d;
2123  if (stadistinct > N)
2124  stadistinct = N;
2125  /* And round to integer */
2126  stats->stadistinct = floor(stadistinct + 0.5);
2127  }
2128 
2129  /*
2130  * If we estimated the number of distinct values at more than 10% of
2131  * the total row count (a very arbitrary limit), then assume that
2132  * stadistinct should scale with the row count rather than be a fixed
2133  * value.
2134  */
2135  if (stats->stadistinct > 0.1 * totalrows)
2136  stats->stadistinct = -(stats->stadistinct / totalrows);
2137 
2138  /*
2139  * Decide how many values are worth storing as most-common values. If
2140  * we are able to generate a complete MCV list (all the values in the
2141  * sample will fit, and we think these are all the ones in the table),
2142  * then do so. Otherwise, store only those values that are
2143  * significantly more common than the values not in the list.
2144  *
2145  * Note: the first of these cases is meant to address columns with
2146  * small, fixed sets of possible values, such as boolean or enum
2147  * columns. If we can *completely* represent the column population by
2148  * an MCV list that will fit into the stats target, then we should do
2149  * so and thus provide the planner with complete information. But if
2150  * the MCV list is not complete, it's generally worth being more
2151  * selective, and not just filling it all the way up to the stats
2152  * target.
2153  */
2154  if (track_cnt < track_max && toowide_cnt == 0 &&
2155  stats->stadistinct > 0 &&
2156  track_cnt <= num_mcv)
2157  {
2158  /* Track list includes all values seen, and all will fit */
2159  num_mcv = track_cnt;
2160  }
2161  else
2162  {
2163  int *mcv_counts;
2164 
2165  /* Incomplete list; decide how many values are worth keeping */
2166  if (num_mcv > track_cnt)
2167  num_mcv = track_cnt;
2168 
2169  if (num_mcv > 0)
2170  {
2171  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2172  for (i = 0; i < num_mcv; i++)
2173  mcv_counts[i] = track[i].count;
2174 
2175  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2176  stats->stadistinct,
2177  stats->stanullfrac,
2178  samplerows, totalrows);
2179  }
2180  }
2181 
2182  /* Generate MCV slot entry */
2183  if (num_mcv > 0)
2184  {
2185  MemoryContext old_context;
2186  Datum *mcv_values;
2187  float4 *mcv_freqs;
2188 
2189  /* Must copy the target values into anl_context */
2190  old_context = MemoryContextSwitchTo(stats->anl_context);
2191  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2192  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2193  for (i = 0; i < num_mcv; i++)
2194  {
2195  mcv_values[i] = datumCopy(track[i].value,
2196  stats->attrtype->typbyval,
2197  stats->attrtype->typlen);
2198  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2199  }
2200  MemoryContextSwitchTo(old_context);
2201 
2202  stats->stakind[0] = STATISTIC_KIND_MCV;
2203  stats->staop[0] = mystats->eqopr;
2204  stats->stanumbers[0] = mcv_freqs;
2205  stats->numnumbers[0] = num_mcv;
2206  stats->stavalues[0] = mcv_values;
2207  stats->numvalues[0] = num_mcv;
2208 
2209  /*
2210  * Accept the defaults for stats->statypid and others. They have
2211  * been set before we were called (see vacuum.h)
2212  */
2213  }
2214  }
2215  else if (null_cnt > 0)
2216  {
2217  /* We found only nulls; assume the column is entirely null */
2218  stats->stats_valid = true;
2219  stats->stanullfrac = 1.0;
2220  if (is_varwidth)
2221  stats->stawidth = 0; /* "unknown" */
2222  else
2223  stats->stawidth = stats->attrtype->typlen;
2224  stats->stadistinct = 0.0; /* "unknown" */
2225  }
2226 
2227  /* We don't need to bother cleaning up any of our temporary palloc's */
2228 }
Definition: fmgr.h:56
static struct @130 value
#define PointerGetDatum(X)
Definition: postgres.h:541
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition: analyze.c:2820
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1133
Form_pg_attribute attr
Definition: vacuum.h:82
#define swapDatum(a, b)
Definition: analyze.c:1687
Size toast_raw_datum_size(Datum value)
Definition: tuptoaster.c:353
#define DatumGetCString(X)
Definition: postgres.h:551
int32 stawidth
Definition: vacuum.h:102
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
#define DatumGetBool(X)
Definition: postgres.h:378
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
float4 stanullfrac
Definition: vacuum.h:101
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
bool stats_valid
Definition: vacuum.h:100
float float4
Definition: c.h:490
#define WIDTH_THRESHOLD
Definition: analyze.c:1684
uintptr_t Datum
Definition: postgres.h:367
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
MemoryContext anl_context
Definition: vacuum.h:86
#define swapInt(a, b)
Definition: analyze.c:1686
#define DatumGetPointer(X)
Definition: postgres.h:534
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
Form_pg_type attrtype
Definition: vacuum.h:85
void * palloc(Size size)
Definition: mcxt.c:924
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:210
void * extra_data
Definition: vacuum.h:94
void vacuum_delay_point(void)
Definition: vacuum.c:1829
float4 stadistinct
Definition: vacuum.h:103

◆ compute_index_stats()

static void compute_index_stats ( Relation  onerel,
double  totalrows,
AnlIndexData indexdata,
int  nindexes,
HeapTuple rows,
int  numrows,
MemoryContext  col_context 
)
static

Definition at line 688 of file analyze.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, attnum, VacAttrStats::attr, AnlIndexData::attr_cnt, VacAttrStats::attrtype, VacAttrStats::compute_stats, CreateExecutorState(), datumCopy(), ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreHeapTuple(), VacAttrStats::exprnulls, VacAttrStats::exprvals, FormIndexDatum(), FreeExecutorState(), get_attribute_options(), GetPerTupleExprContext, i, IndexInfo::ii_Predicate, ind_fetch_func(), INDEX_MAX_KEYS, AnlIndexData::indexInfo, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), AttributeOpts::n_distinct, NIL, palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, VacAttrStats::stadistinct, AnlIndexData::tupleFract, AnlIndexData::vacattrstats, vacuum_delay_point(), and values.

Referenced by do_analyze_rel().

692 {
693  MemoryContext ind_context,
694  old_context;
696  bool isnull[INDEX_MAX_KEYS];
697  int ind,
698  i;
699 
700  ind_context = AllocSetContextCreate(anl_context,
701  "Analyze Index",
703  old_context = MemoryContextSwitchTo(ind_context);
704 
705  for (ind = 0; ind < nindexes; ind++)
706  {
707  AnlIndexData *thisdata = &indexdata[ind];
708  IndexInfo *indexInfo = thisdata->indexInfo;
709  int attr_cnt = thisdata->attr_cnt;
710  TupleTableSlot *slot;
711  EState *estate;
712  ExprContext *econtext;
713  ExprState *predicate;
714  Datum *exprvals;
715  bool *exprnulls;
716  int numindexrows,
717  tcnt,
718  rowno;
719  double totalindexrows;
720 
721  /* Ignore index if no columns to analyze and not partial */
722  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
723  continue;
724 
725  /*
726  * Need an EState for evaluation of index expressions and
727  * partial-index predicates. Create it in the per-index context to be
728  * sure it gets cleaned up at the bottom of the loop.
729  */
730  estate = CreateExecutorState();
731  econtext = GetPerTupleExprContext(estate);
732  /* Need a slot to hold the current heap tuple, too */
734 
735  /* Arrange for econtext's scan tuple to be the tuple under test */
736  econtext->ecxt_scantuple = slot;
737 
738  /* Set up execution state for predicate. */
739  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
740 
741  /* Compute and save index expression values */
742  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
743  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
744  numindexrows = 0;
745  tcnt = 0;
746  for (rowno = 0; rowno < numrows; rowno++)
747  {
748  HeapTuple heapTuple = rows[rowno];
749 
751 
752  /*
753  * Reset the per-tuple context each time, to reclaim any cruft
754  * left behind by evaluating the predicate or index expressions.
755  */
756  ResetExprContext(econtext);
757 
758  /* Set up for predicate or expression evaluation */
759  ExecStoreHeapTuple(heapTuple, slot, false);
760 
761  /* If index is partial, check predicate */
762  if (predicate != NULL)
763  {
764  if (!ExecQual(predicate, econtext))
765  continue;
766  }
767  numindexrows++;
768 
769  if (attr_cnt > 0)
770  {
771  /*
772  * Evaluate the index row to compute expression values. We
773  * could do this by hand, but FormIndexDatum is convenient.
774  */
775  FormIndexDatum(indexInfo,
776  slot,
777  estate,
778  values,
779  isnull);
780 
781  /*
782  * Save just the columns we care about. We copy the values
783  * into ind_context from the estate's per-tuple context.
784  */
785  for (i = 0; i < attr_cnt; i++)
786  {
787  VacAttrStats *stats = thisdata->vacattrstats[i];
788  int attnum = stats->attr->attnum;
789 
790  if (isnull[attnum - 1])
791  {
792  exprvals[tcnt] = (Datum) 0;
793  exprnulls[tcnt] = true;
794  }
795  else
796  {
797  exprvals[tcnt] = datumCopy(values[attnum - 1],
798  stats->attrtype->typbyval,
799  stats->attrtype->typlen);
800  exprnulls[tcnt] = false;
801  }
802  tcnt++;
803  }
804  }
805  }
806 
807  /*
808  * Having counted the number of rows that pass the predicate in the
809  * sample, we can estimate the total number of rows in the index.
810  */
811  thisdata->tupleFract = (double) numindexrows / (double) numrows;
812  totalindexrows = ceil(thisdata->tupleFract * totalrows);
813 
814  /*
815  * Now we can compute the statistics for the expression columns.
816  */
817  if (numindexrows > 0)
818  {
819  MemoryContextSwitchTo(col_context);
820  for (i = 0; i < attr_cnt; i++)
821  {
822  VacAttrStats *stats = thisdata->vacattrstats[i];
823  AttributeOpts *aopt =
824  get_attribute_options(stats->attr->attrelid,
825  stats->attr->attnum);
826 
827  stats->exprvals = exprvals + i;
828  stats->exprnulls = exprnulls + i;
829  stats->rowstride = attr_cnt;
830  stats->compute_stats(stats,
832  numindexrows,
833  totalindexrows);
834 
835  /*
836  * If the n_distinct option is specified, it overrides the
837  * above computation. For indices, we always use just
838  * n_distinct, not n_distinct_inherited.
839  */
840  if (aopt != NULL && aopt->n_distinct != 0.0)
841  stats->stadistinct = aopt->n_distinct;
842 
844  }
845  }
846 
847  /* And clean up */
848  MemoryContextSwitchTo(ind_context);
849 
851  FreeExecutorState(estate);
853  }
854 
855  MemoryContextSwitchTo(old_context);
856  MemoryContextDelete(ind_context);
857 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
int rowstride
Definition: vacuum.h:131
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2016
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
List * ii_Predicate
Definition: execnodes.h:159
#define RelationGetDescr(relation)
Definition: rel.h:434
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:360
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:82
int attr_cnt
Definition: analyze.c:72
void FreeExecutorState(EState *estate)
Definition: execUtils.c:195
#define GetPerTupleExprContext(estate)
Definition: executor.h:488
bool * exprnulls
Definition: vacuum.h:130
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
static MemoryContext anl_context
Definition: analyze.c:80
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:219
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:516
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:204
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:85
Datum * exprvals
Definition: vacuum.h:129
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
uintptr_t Datum
Definition: postgres.h:367
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1654
int16 attnum
Definition: pg_attribute.h:79
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:221
double tupleFract
Definition: analyze.c:70
static Datum values[MAXATTR]
Definition: bootstrap.c:165
Form_pg_type attrtype
Definition: vacuum.h:85
void * palloc(Size size)
Definition: mcxt.c:924
VacAttrStats ** vacattrstats
Definition: analyze.c:71
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:92
void vacuum_delay_point(void)
Definition: vacuum.c:1829
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:313
#define ResetExprContext(econtext)
Definition: executor.h:482
float4 stadistinct
Definition: vacuum.h:103
IndexInfo * indexInfo
Definition: analyze.c:69

◆ compute_scalar_stats()

static void compute_scalar_stats ( VacAttrStatsP  stats,
AnalyzeAttrFetchFunc  fetchfunc,
int  samplerows,
double  totalrows 
)
static

Definition at line 2244 of file analyze.c.

References SortSupportData::abbreviate, analyze_mcv_list(), VacAttrStats::anl_context, Assert, VacAttrStats::attr, VacAttrStats::attrtype, compare_mcvs(), compare_scalars(), ScalarMCVItem::count, CurrentMemoryContext, datumCopy(), DatumGetCString, DatumGetPointer, generate_unaccent_rules::dest, StdAnalyzeData::eqopr, VacAttrStats::extra_data, ScalarMCVItem::first, i, StdAnalyzeData::ltopr, memmove, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum, PrepareSortSupportFromOrderingOp(), qsort, qsort_arg(), CompareScalarsContext::ssup, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, VacAttrStats::stats_valid, VacAttrStats::stavalues, VacAttrStats::stawidth, toast_raw_datum_size(), ScalarItem::tupno, CompareScalarsContext::tupnoLink, vacuum_delay_point(), ScalarItem::value, value, values, VARSIZE_ANY, and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

2248 {
2249  int i;
2250  int null_cnt = 0;
2251  int nonnull_cnt = 0;
2252  int toowide_cnt = 0;
2253  double total_width = 0;
2254  bool is_varlena = (!stats->attrtype->typbyval &&
2255  stats->attrtype->typlen == -1);
2256  bool is_varwidth = (!stats->attrtype->typbyval &&
2257  stats->attrtype->typlen < 0);
2258  double corr_xysum;
2259  SortSupportData ssup;
2260  ScalarItem *values;
2261  int values_cnt = 0;
2262  int *tupnoLink;
2263  ScalarMCVItem *track;
2264  int track_cnt = 0;
2265  int num_mcv = stats->attr->attstattarget;
2266  int num_bins = stats->attr->attstattarget;
2267  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2268 
2269  values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2270  tupnoLink = (int *) palloc(samplerows * sizeof(int));
2271  track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2272 
2273  memset(&ssup, 0, sizeof(ssup));
2275  /* We always use the default collation for statistics */
2276  ssup.ssup_collation = DEFAULT_COLLATION_OID;
2277  ssup.ssup_nulls_first = false;
2278 
2279  /*
2280  * For now, don't perform abbreviated key conversion, because full values
2281  * are required for MCV slot generation. Supporting that optimization
2282  * would necessitate teaching compare_scalars() to call a tie-breaker.
2283  */
2284  ssup.abbreviate = false;
2285 
2286  PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2287 
2288  /* Initial scan to find sortable values */
2289  for (i = 0; i < samplerows; i++)
2290  {
2291  Datum value;
2292  bool isnull;
2293 
2295 
2296  value = fetchfunc(stats, i, &isnull);
2297 
2298  /* Check for null/nonnull */
2299  if (isnull)
2300  {
2301  null_cnt++;
2302  continue;
2303  }
2304  nonnull_cnt++;
2305 
2306  /*
2307  * If it's a variable-width field, add up widths for average width
2308  * calculation. Note that if the value is toasted, we use the toasted
2309  * width. We don't bother with this calculation if it's a fixed-width
2310  * type.
2311  */
2312  if (is_varlena)
2313  {
2314  total_width += VARSIZE_ANY(DatumGetPointer(value));
2315 
2316  /*
2317  * If the value is toasted, we want to detoast it just once to
2318  * avoid repeated detoastings and resultant excess memory usage
2319  * during the comparisons. Also, check to see if the value is
2320  * excessively wide, and if so don't detoast at all --- just
2321  * ignore the value.
2322  */
2324  {
2325  toowide_cnt++;
2326  continue;
2327  }
2328  value = PointerGetDatum(PG_DETOAST_DATUM(value));
2329  }
2330  else if (is_varwidth)
2331  {
2332  /* must be cstring */
2333  total_width += strlen(DatumGetCString(value)) + 1;
2334  }
2335 
2336  /* Add it to the list to be sorted */
2337  values[values_cnt].value = value;
2338  values[values_cnt].tupno = values_cnt;
2339  tupnoLink[values_cnt] = values_cnt;
2340  values_cnt++;
2341  }
2342 
2343  /* We can only compute real stats if we found some sortable values. */
2344  if (values_cnt > 0)
2345  {
2346  int ndistinct, /* # distinct values in sample */
2347  nmultiple, /* # that appear multiple times */
2348  num_hist,
2349  dups_cnt;
2350  int slot_idx = 0;
2352 
2353  /* Sort the collected values */
2354  cxt.ssup = &ssup;
2355  cxt.tupnoLink = tupnoLink;
2356  qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2357  compare_scalars, (void *) &cxt);
2358 
2359  /*
2360  * Now scan the values in order, find the most common ones, and also
2361  * accumulate ordering-correlation statistics.
2362  *
2363  * To determine which are most common, we first have to count the
2364  * number of duplicates of each value. The duplicates are adjacent in
2365  * the sorted list, so a brute-force approach is to compare successive
2366  * datum values until we find two that are not equal. However, that
2367  * requires N-1 invocations of the datum comparison routine, which are
2368  * completely redundant with work that was done during the sort. (The
2369  * sort algorithm must at some point have compared each pair of items
2370  * that are adjacent in the sorted order; otherwise it could not know
2371  * that it's ordered the pair correctly.) We exploit this by having
2372  * compare_scalars remember the highest tupno index that each
2373  * ScalarItem has been found equal to. At the end of the sort, a
2374  * ScalarItem's tupnoLink will still point to itself if and only if it
2375  * is the last item of its group of duplicates (since the group will
2376  * be ordered by tupno).
2377  */
2378  corr_xysum = 0;
2379  ndistinct = 0;
2380  nmultiple = 0;
2381  dups_cnt = 0;
2382  for (i = 0; i < values_cnt; i++)
2383  {
2384  int tupno = values[i].tupno;
2385 
2386  corr_xysum += ((double) i) * ((double) tupno);
2387  dups_cnt++;
2388  if (tupnoLink[tupno] == tupno)
2389  {
2390  /* Reached end of duplicates of this value */
2391  ndistinct++;
2392  if (dups_cnt > 1)
2393  {
2394  nmultiple++;
2395  if (track_cnt < num_mcv ||
2396  dups_cnt > track[track_cnt - 1].count)
2397  {
2398  /*
2399  * Found a new item for the mcv list; find its
2400  * position, bubbling down old items if needed. Loop
2401  * invariant is that j points at an empty/ replaceable
2402  * slot.
2403  */
2404  int j;
2405 
2406  if (track_cnt < num_mcv)
2407  track_cnt++;
2408  for (j = track_cnt - 1; j > 0; j--)
2409  {
2410  if (dups_cnt <= track[j - 1].count)
2411  break;
2412  track[j].count = track[j - 1].count;
2413  track[j].first = track[j - 1].first;
2414  }
2415  track[j].count = dups_cnt;
2416  track[j].first = i + 1 - dups_cnt;
2417  }
2418  }
2419  dups_cnt = 0;
2420  }
2421  }
2422 
2423  stats->stats_valid = true;
2424  /* Do the simple null-frac and width stats */
2425  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2426  if (is_varwidth)
2427  stats->stawidth = total_width / (double) nonnull_cnt;
2428  else
2429  stats->stawidth = stats->attrtype->typlen;
2430 
2431  if (nmultiple == 0)
2432  {
2433  /*
2434  * If we found no repeated non-null values, assume it's a unique
2435  * column; but be sure to discount for any nulls we found.
2436  */
2437  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2438  }
2439  else if (toowide_cnt == 0 && nmultiple == ndistinct)
2440  {
2441  /*
2442  * Every value in the sample appeared more than once. Assume the
2443  * column has just these values. (This case is meant to address
2444  * columns with small, fixed sets of possible values, such as
2445  * boolean or enum columns. If there are any values that appear
2446  * just once in the sample, including too-wide values, we should
2447  * assume that that's not what we're dealing with.)
2448  */
2449  stats->stadistinct = ndistinct;
2450  }
2451  else
2452  {
2453  /*----------
2454  * Estimate the number of distinct values using the estimator
2455  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2456  * n*d / (n - f1 + f1*n/N)
2457  * where f1 is the number of distinct values that occurred
2458  * exactly once in our sample of n rows (from a total of N),
2459  * and d is the total number of distinct values in the sample.
2460  * This is their Duj1 estimator; the other estimators they
2461  * recommend are considerably more complex, and are numerically
2462  * very unstable when n is much smaller than N.
2463  *
2464  * In this calculation, we consider only non-nulls. We used to
2465  * include rows with null values in the n and N counts, but that
2466  * leads to inaccurate answers in columns with many nulls, and
2467  * it's intuitively bogus anyway considering the desired result is
2468  * the number of distinct non-null values.
2469  *
2470  * Overwidth values are assumed to have been distinct.
2471  *----------
2472  */
2473  int f1 = ndistinct - nmultiple + toowide_cnt;
2474  int d = f1 + nmultiple;
2475  double n = samplerows - null_cnt;
2476  double N = totalrows * (1.0 - stats->stanullfrac);
2477  double stadistinct;
2478 
2479  /* N == 0 shouldn't happen, but just in case ... */
2480  if (N > 0)
2481  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2482  else
2483  stadistinct = 0;
2484 
2485  /* Clamp to sane range in case of roundoff error */
2486  if (stadistinct < d)
2487  stadistinct = d;
2488  if (stadistinct > N)
2489  stadistinct = N;
2490  /* And round to integer */
2491  stats->stadistinct = floor(stadistinct + 0.5);
2492  }
2493 
2494  /*
2495  * If we estimated the number of distinct values at more than 10% of
2496  * the total row count (a very arbitrary limit), then assume that
2497  * stadistinct should scale with the row count rather than be a fixed
2498  * value.
2499  */
2500  if (stats->stadistinct > 0.1 * totalrows)
2501  stats->stadistinct = -(stats->stadistinct / totalrows);
2502 
2503  /*
2504  * Decide how many values are worth storing as most-common values. If
2505  * we are able to generate a complete MCV list (all the values in the
2506  * sample will fit, and we think these are all the ones in the table),
2507  * then do so. Otherwise, store only those values that are
2508  * significantly more common than the values not in the list.
2509  *
2510  * Note: the first of these cases is meant to address columns with
2511  * small, fixed sets of possible values, such as boolean or enum
2512  * columns. If we can *completely* represent the column population by
2513  * an MCV list that will fit into the stats target, then we should do
2514  * so and thus provide the planner with complete information. But if
2515  * the MCV list is not complete, it's generally worth being more
2516  * selective, and not just filling it all the way up to the stats
2517  * target.
2518  */
2519  if (track_cnt == ndistinct && toowide_cnt == 0 &&
2520  stats->stadistinct > 0 &&
2521  track_cnt <= num_mcv)
2522  {
2523  /* Track list includes all values seen, and all will fit */
2524  num_mcv = track_cnt;
2525  }
2526  else
2527  {
2528  int *mcv_counts;
2529 
2530  /* Incomplete list; decide how many values are worth keeping */
2531  if (num_mcv > track_cnt)
2532  num_mcv = track_cnt;
2533 
2534  if (num_mcv > 0)
2535  {
2536  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2537  for (i = 0; i < num_mcv; i++)
2538  mcv_counts[i] = track[i].count;
2539 
2540  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2541  stats->stadistinct,
2542  stats->stanullfrac,
2543  samplerows, totalrows);
2544  }
2545  }
2546 
2547  /* Generate MCV slot entry */
2548  if (num_mcv > 0)
2549  {
2550  MemoryContext old_context;
2551  Datum *mcv_values;
2552  float4 *mcv_freqs;
2553 
2554  /* Must copy the target values into anl_context */
2555  old_context = MemoryContextSwitchTo(stats->anl_context);
2556  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2557  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2558  for (i = 0; i < num_mcv; i++)
2559  {
2560  mcv_values[i] = datumCopy(values[track[i].first].value,
2561  stats->attrtype->typbyval,
2562  stats->attrtype->typlen);
2563  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2564  }
2565  MemoryContextSwitchTo(old_context);
2566 
2567  stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2568  stats->staop[slot_idx] = mystats->eqopr;
2569  stats->stanumbers[slot_idx] = mcv_freqs;
2570  stats->numnumbers[slot_idx] = num_mcv;
2571  stats->stavalues[slot_idx] = mcv_values;
2572  stats->numvalues[slot_idx] = num_mcv;
2573 
2574  /*
2575  * Accept the defaults for stats->statypid and others. They have
2576  * been set before we were called (see vacuum.h)
2577  */
2578  slot_idx++;
2579  }
2580 
2581  /*
2582  * Generate a histogram slot entry if there are at least two distinct
2583  * values not accounted for in the MCV list. (This ensures the
2584  * histogram won't collapse to empty or a singleton.)
2585  */
2586  num_hist = ndistinct - num_mcv;
2587  if (num_hist > num_bins)
2588  num_hist = num_bins + 1;
2589  if (num_hist >= 2)
2590  {
2591  MemoryContext old_context;
2592  Datum *hist_values;
2593  int nvals;
2594  int pos,
2595  posfrac,
2596  delta,
2597  deltafrac;
2598 
2599  /* Sort the MCV items into position order to speed next loop */
2600  qsort((void *) track, num_mcv,
2601  sizeof(ScalarMCVItem), compare_mcvs);
2602 
2603  /*
2604  * Collapse out the MCV items from the values[] array.
2605  *
2606  * Note we destroy the values[] array here... but we don't need it
2607  * for anything more. We do, however, still need values_cnt.
2608  * nvals will be the number of remaining entries in values[].
2609  */
2610  if (num_mcv > 0)
2611  {
2612  int src,
2613  dest;
2614  int j;
2615 
2616  src = dest = 0;
2617  j = 0; /* index of next interesting MCV item */
2618  while (src < values_cnt)
2619  {
2620  int ncopy;
2621 
2622  if (j < num_mcv)
2623  {
2624  int first = track[j].first;
2625 
2626  if (src >= first)
2627  {
2628  /* advance past this MCV item */
2629  src = first + track[j].count;
2630  j++;
2631  continue;
2632  }
2633  ncopy = first - src;
2634  }
2635  else
2636  ncopy = values_cnt - src;
2637  memmove(&values[dest], &values[src],
2638  ncopy * sizeof(ScalarItem));
2639  src += ncopy;
2640  dest += ncopy;
2641  }
2642  nvals = dest;
2643  }
2644  else
2645  nvals = values_cnt;
2646  Assert(nvals >= num_hist);
2647 
2648  /* Must copy the target values into anl_context */
2649  old_context = MemoryContextSwitchTo(stats->anl_context);
2650  hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2651 
2652  /*
2653  * The object of this loop is to copy the first and last values[]
2654  * entries along with evenly-spaced values in between. So the
2655  * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2656  * computing that subscript directly risks integer overflow when
2657  * the stats target is more than a couple thousand. Instead we
2658  * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2659  * the integral and fractional parts of the sum separately.
2660  */
2661  delta = (nvals - 1) / (num_hist - 1);
2662  deltafrac = (nvals - 1) % (num_hist - 1);
2663  pos = posfrac = 0;
2664 
2665  for (i = 0; i < num_hist; i++)
2666  {
2667  hist_values[i] = datumCopy(values[pos].value,
2668  stats->attrtype->typbyval,
2669  stats->attrtype->typlen);
2670  pos += delta;
2671  posfrac += deltafrac;
2672  if (posfrac >= (num_hist - 1))
2673  {
2674  /* fractional part exceeds 1, carry to integer part */
2675  pos++;
2676  posfrac -= (num_hist - 1);
2677  }
2678  }
2679 
2680  MemoryContextSwitchTo(old_context);
2681 
2682  stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2683  stats->staop[slot_idx] = mystats->ltopr;
2684  stats->stavalues[slot_idx] = hist_values;
2685  stats->numvalues[slot_idx] = num_hist;
2686 
2687  /*
2688  * Accept the defaults for stats->statypid and others. They have
2689  * been set before we were called (see vacuum.h)
2690  */
2691  slot_idx++;
2692  }
2693 
2694  /* Generate a correlation entry if there are multiple values */
2695  if (values_cnt > 1)
2696  {
2697  MemoryContext old_context;
2698  float4 *corrs;
2699  double corr_xsum,
2700  corr_x2sum;
2701 
2702  /* Must copy the target values into anl_context */
2703  old_context = MemoryContextSwitchTo(stats->anl_context);
2704  corrs = (float4 *) palloc(sizeof(float4));
2705  MemoryContextSwitchTo(old_context);
2706 
2707  /*----------
2708  * Since we know the x and y value sets are both
2709  * 0, 1, ..., values_cnt-1
2710  * we have sum(x) = sum(y) =
2711  * (values_cnt-1)*values_cnt / 2
2712  * and sum(x^2) = sum(y^2) =
2713  * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2714  *----------
2715  */
2716  corr_xsum = ((double) (values_cnt - 1)) *
2717  ((double) values_cnt) / 2.0;
2718  corr_x2sum = ((double) (values_cnt - 1)) *
2719  ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2720 
2721  /* And the correlation coefficient reduces to */
2722  corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2723  (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2724 
2725  stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2726  stats->staop[slot_idx] = mystats->ltopr;
2727  stats->stanumbers[slot_idx] = corrs;
2728  stats->numnumbers[slot_idx] = 1;
2729  slot_idx++;
2730  }
2731  }
2732  else if (nonnull_cnt > 0)
2733  {
2734  /* We found some non-null values, but they were all too wide */
2735  Assert(nonnull_cnt == toowide_cnt);
2736  stats->stats_valid = true;
2737  /* Do the simple null-frac and width stats */
2738  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2739  if (is_varwidth)
2740  stats->stawidth = total_width / (double) nonnull_cnt;
2741  else
2742  stats->stawidth = stats->attrtype->typlen;
2743  /* Assume all too-wide values are distinct, so it's a unique column */
2744  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2745  }
2746  else if (null_cnt > 0)
2747  {
2748  /* We found only nulls; assume the column is entirely null */
2749  stats->stats_valid = true;
2750  stats->stanullfrac = 1.0;
2751  if (is_varwidth)
2752  stats->stawidth = 0; /* "unknown" */
2753  else
2754  stats->stawidth = stats->attrtype->typlen;
2755  stats->stadistinct = 0.0; /* "unknown" */
2756  }
2757 
2758  /* We don't need to bother cleaning up any of our temporary palloc's */
2759 }
bool ssup_nulls_first
Definition: sortsupport.h:75
static struct @130 value
static int compare_mcvs(const void *a, const void *b)
Definition: analyze.c:2802
#define PointerGetDatum(X)
Definition: postgres.h:541
static int compare_scalars(const void *a, const void *b, void *arg)
Definition: analyze.c:2771
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition: analyze.c:2820
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:133
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Form_pg_attribute attr
Definition: vacuum.h:82
Size toast_raw_datum_size(Datum value)
Definition: tuptoaster.c:353
#define DatumGetCString(X)
Definition: postgres.h:551
int32 stawidth
Definition: vacuum.h:102
MemoryContext ssup_cxt
Definition: sortsupport.h:66
SortSupport ssup
Definition: analyze.c:1700
#define memmove(d, s, c)
Definition: c.h:1194
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
float4 stanullfrac
Definition: vacuum.h:101
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:113
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
bool stats_valid
Definition: vacuum.h:100
float float4
Definition: c.h:490
#define WIDTH_THRESHOLD
Definition: analyze.c:1684
uintptr_t Datum
Definition: postgres.h:367
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
#define Assert(condition)
Definition: c.h:732
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
MemoryContext anl_context
Definition: vacuum.h:86
#define DatumGetPointer(X)
Definition: postgres.h:534
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
Form_pg_type attrtype
Definition: vacuum.h:85
void * palloc(Size size)
Definition: mcxt.c:924
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:210
void * extra_data
Definition: vacuum.h:94
#define qsort(a, b, c, d)
Definition: port.h:462
void vacuum_delay_point(void)
Definition: vacuum.c:1829
float4 stadistinct
Definition: vacuum.h:103

◆ compute_trivial_stats()

static void compute_trivial_stats ( VacAttrStatsP  stats,
AnalyzeAttrFetchFunc  fetchfunc,
int  samplerows,
double  totalrows 
)
static

Definition at line 1811 of file analyze.c.

References VacAttrStats::attrtype, DatumGetCString, DatumGetPointer, i, VacAttrStats::stadistinct, VacAttrStats::stanullfrac, VacAttrStats::stats_valid, VacAttrStats::stawidth, vacuum_delay_point(), value, and VARSIZE_ANY.

Referenced by std_typanalyze().

1815 {
1816  int i;
1817  int null_cnt = 0;
1818  int nonnull_cnt = 0;
1819  double total_width = 0;
1820  bool is_varlena = (!stats->attrtype->typbyval &&
1821  stats->attrtype->typlen == -1);
1822  bool is_varwidth = (!stats->attrtype->typbyval &&
1823  stats->attrtype->typlen < 0);
1824 
1825  for (i = 0; i < samplerows; i++)
1826  {
1827  Datum value;
1828  bool isnull;
1829 
1831 
1832  value = fetchfunc(stats, i, &isnull);
1833 
1834  /* Check for null/nonnull */
1835  if (isnull)
1836  {
1837  null_cnt++;
1838  continue;
1839  }
1840  nonnull_cnt++;
1841 
1842  /*
1843  * If it's a variable-width field, add up widths for average width
1844  * calculation. Note that if the value is toasted, we use the toasted
1845  * width. We don't bother with this calculation if it's a fixed-width
1846  * type.
1847  */
1848  if (is_varlena)
1849  {
1850  total_width += VARSIZE_ANY(DatumGetPointer(value));
1851  }
1852  else if (is_varwidth)
1853  {
1854  /* must be cstring */
1855  total_width += strlen(DatumGetCString(value)) + 1;
1856  }
1857  }
1858 
1859  /* We can only compute average width if we found some non-null values. */
1860  if (nonnull_cnt > 0)
1861  {
1862  stats->stats_valid = true;
1863  /* Do the simple null-frac and width stats */
1864  stats->stanullfrac = (double) null_cnt / (double) samplerows;
1865  if (is_varwidth)
1866  stats->stawidth = total_width / (double) nonnull_cnt;
1867  else
1868  stats->stawidth = stats->attrtype->typlen;
1869  stats->stadistinct = 0.0; /* "unknown" */
1870  }
1871  else if (null_cnt > 0)
1872  {
1873  /* We found only nulls; assume the column is entirely null */
1874  stats->stats_valid = true;
1875  stats->stanullfrac = 1.0;
1876  if (is_varwidth)
1877  stats->stawidth = 0; /* "unknown" */
1878  else
1879  stats->stawidth = stats->attrtype->typlen;
1880  stats->stadistinct = 0.0; /* "unknown" */
1881  }
1882 }
static struct @130 value
#define DatumGetCString(X)
Definition: postgres.h:551
int32 stawidth
Definition: vacuum.h:102
float4 stanullfrac
Definition: vacuum.h:101
bool stats_valid
Definition: vacuum.h:100
uintptr_t Datum
Definition: postgres.h:367
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
#define DatumGetPointer(X)
Definition: postgres.h:534
Form_pg_type attrtype
Definition: vacuum.h:85
int i
void vacuum_delay_point(void)
Definition: vacuum.c:1829
float4 stadistinct
Definition: vacuum.h:103

◆ do_analyze_rel()

static void do_analyze_rel ( Relation  onerel,
int  options,
VacuumParams params,
List va_cols,
AcquireSampleRowsFunc  acquirefunc,
BlockNumber  relpages,
bool  inh,
bool  in_outer_xact,
int  elevel 
)
static

Definition at line 292 of file analyze.c.

References AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, IndexVacuumInfo::analyze_only, AtEOXact_GUC(), attnameAttNum(), VacAttrStats::attr, AnlIndexData::attr_cnt, bms_add_member(), bms_is_member(), BuildIndexInfo(), BuildRelationExtStatistics(), compute_index_stats(), VacAttrStats::compute_stats, CurrentMemoryContext, elevel, elog, ereport, errcode(), errmsg(), ERROR, IndexVacuumInfo::estimated_count, examine_attribute(), get_attribute_options(), get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GetUserIdAndSecContext(), i, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexVacuumInfo::index, index_vacuum_cleanup(), AnlIndexData::indexInfo, InvalidAttrNumber, InvalidMultiXactId, InvalidTransactionId, IsAutoVacuumWorkerProcess(), lfirst, list_head(), list_length(), lnext, LOG, VacuumParams::log_min_duration, MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), IndexVacuumInfo::message_level, VacAttrStats::minrows, MyDatabaseId, AttributeOpts::n_distinct, AttributeOpts::n_distinct_inherited, tupleDesc::natts, NewGUCNestLevel(), NIL, NoLock, IndexVacuumInfo::num_heap_tuples, palloc(), palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_report_analyze(), RelationData::rd_att, RelationData::rd_rel, relallvisible, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, VacAttrStats::rows, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), VacAttrStats::stadistinct, std_fetch_func(), IndexVacuumInfo::strategy, strVal, TimestampDifferenceExceeds(), VacAttrStats::tupDesc, AnlIndexData::tupleFract, update_attstats(), vac_close_indexes(), vac_open_indexes(), vac_strategy, vac_update_relstats(), AnlIndexData::vacattrstats, VACOPT_VACUUM, and visibilitymap_count().

Referenced by analyze_rel().

296 {
297  int attr_cnt,
298  tcnt,
299  i,
300  ind;
301  Relation *Irel;
302  int nindexes;
303  bool hasindex;
304  VacAttrStats **vacattrstats;
305  AnlIndexData *indexdata;
306  int targrows,
307  numrows;
308  double totalrows,
309  totaldeadrows;
310  HeapTuple *rows;
311  PGRUsage ru0;
312  TimestampTz starttime = 0;
313  MemoryContext caller_context;
314  Oid save_userid;
315  int save_sec_context;
316  int save_nestlevel;
317 
318  if (inh)
319  ereport(elevel,
320  (errmsg("analyzing \"%s.%s\" inheritance tree",
322  RelationGetRelationName(onerel))));
323  else
324  ereport(elevel,
325  (errmsg("analyzing \"%s.%s\"",
327  RelationGetRelationName(onerel))));
328 
329  /*
330  * Set up a working context so that we can easily free whatever junk gets
331  * created.
332  */
334  "Analyze",
336  caller_context = MemoryContextSwitchTo(anl_context);
337 
338  /*
339  * Switch to the table owner's userid, so that any index functions are run
340  * as that user. Also lock down security-restricted operations and
341  * arrange to make GUC variable changes local to this command.
342  */
343  GetUserIdAndSecContext(&save_userid, &save_sec_context);
344  SetUserIdAndSecContext(onerel->rd_rel->relowner,
345  save_sec_context | SECURITY_RESTRICTED_OPERATION);
346  save_nestlevel = NewGUCNestLevel();
347 
348  /* measure elapsed time iff autovacuum logging requires it */
349  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
350  {
351  pg_rusage_init(&ru0);
352  if (params->log_min_duration > 0)
353  starttime = GetCurrentTimestamp();
354  }
355 
356  /*
357  * Determine which columns to analyze
358  *
359  * Note that system attributes are never analyzed, so we just reject them
360  * at the lookup stage. We also reject duplicate column mentions. (We
361  * could alternatively ignore duplicates, but analyzing a column twice
362  * won't work; we'd end up making a conflicting update in pg_statistic.)
363  */
364  if (va_cols != NIL)
365  {
366  Bitmapset *unique_cols = NULL;
367  ListCell *le;
368 
369  vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
370  sizeof(VacAttrStats *));
371  tcnt = 0;
372  foreach(le, va_cols)
373  {
374  char *col = strVal(lfirst(le));
375 
376  i = attnameAttNum(onerel, col, false);
377  if (i == InvalidAttrNumber)
378  ereport(ERROR,
379  (errcode(ERRCODE_UNDEFINED_COLUMN),
380  errmsg("column \"%s\" of relation \"%s\" does not exist",
381  col, RelationGetRelationName(onerel))));
382  if (bms_is_member(i, unique_cols))
383  ereport(ERROR,
384  (errcode(ERRCODE_DUPLICATE_COLUMN),
385  errmsg("column \"%s\" of relation \"%s\" appears more than once",
386  col, RelationGetRelationName(onerel))));
387  unique_cols = bms_add_member(unique_cols, i);
388 
389  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
390  if (vacattrstats[tcnt] != NULL)
391  tcnt++;
392  }
393  attr_cnt = tcnt;
394  }
395  else
396  {
397  attr_cnt = onerel->rd_att->natts;
398  vacattrstats = (VacAttrStats **)
399  palloc(attr_cnt * sizeof(VacAttrStats *));
400  tcnt = 0;
401  for (i = 1; i <= attr_cnt; i++)
402  {
403  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
404  if (vacattrstats[tcnt] != NULL)
405  tcnt++;
406  }
407  attr_cnt = tcnt;
408  }
409 
410  /*
411  * Open all indexes of the relation, and see if there are any analyzable
412  * columns in the indexes. We do not analyze index columns if there was
413  * an explicit column list in the ANALYZE command, however. If we are
414  * doing a recursive scan, we don't want to touch the parent's indexes at
415  * all.
416  */
417  if (!inh)
418  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
419  else
420  {
421  Irel = NULL;
422  nindexes = 0;
423  }
424  hasindex = (nindexes > 0);
425  indexdata = NULL;
426  if (hasindex)
427  {
428  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
429  for (ind = 0; ind < nindexes; ind++)
430  {
431  AnlIndexData *thisdata = &indexdata[ind];
432  IndexInfo *indexInfo;
433 
434  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
435  thisdata->tupleFract = 1.0; /* fix later if partial */
436  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
437  {
438  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
439 
440  thisdata->vacattrstats = (VacAttrStats **)
441  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
442  tcnt = 0;
443  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
444  {
445  int keycol = indexInfo->ii_IndexAttrNumbers[i];
446 
447  if (keycol == 0)
448  {
449  /* Found an index expression */
450  Node *indexkey;
451 
452  if (indexpr_item == NULL) /* shouldn't happen */
453  elog(ERROR, "too few entries in indexprs list");
454  indexkey = (Node *) lfirst(indexpr_item);
455  indexpr_item = lnext(indexpr_item);
456  thisdata->vacattrstats[tcnt] =
457  examine_attribute(Irel[ind], i + 1, indexkey);
458  if (thisdata->vacattrstats[tcnt] != NULL)
459  tcnt++;
460  }
461  }
462  thisdata->attr_cnt = tcnt;
463  }
464  }
465  }
466 
467  /*
468  * Determine how many rows we need to sample, using the worst case from
469  * all analyzable columns. We use a lower bound of 100 rows to avoid
470  * possible overflow in Vitter's algorithm. (Note: that will also be the
471  * target in the corner case where there are no analyzable columns.)
472  */
473  targrows = 100;
474  for (i = 0; i < attr_cnt; i++)
475  {
476  if (targrows < vacattrstats[i]->minrows)
477  targrows = vacattrstats[i]->minrows;
478  }
479  for (ind = 0; ind < nindexes; ind++)
480  {
481  AnlIndexData *thisdata = &indexdata[ind];
482 
483  for (i = 0; i < thisdata->attr_cnt; i++)
484  {
485  if (targrows < thisdata->vacattrstats[i]->minrows)
486  targrows = thisdata->vacattrstats[i]->minrows;
487  }
488  }
489 
490  /*
491  * Acquire the sample rows
492  */
493  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
494  if (inh)
495  numrows = acquire_inherited_sample_rows(onerel, elevel,
496  rows, targrows,
497  &totalrows, &totaldeadrows);
498  else
499  numrows = (*acquirefunc) (onerel, elevel,
500  rows, targrows,
501  &totalrows, &totaldeadrows);
502 
503  /*
504  * Compute the statistics. Temporary results during the calculations for
505  * each column are stored in a child context. The calc routines are
506  * responsible to make sure that whatever they store into the VacAttrStats
507  * structure is allocated in anl_context.
508  */
509  if (numrows > 0)
510  {
511  MemoryContext col_context,
512  old_context;
513 
514  col_context = AllocSetContextCreate(anl_context,
515  "Analyze Column",
517  old_context = MemoryContextSwitchTo(col_context);
518 
519  for (i = 0; i < attr_cnt; i++)
520  {
521  VacAttrStats *stats = vacattrstats[i];
522  AttributeOpts *aopt;
523 
524  stats->rows = rows;
525  stats->tupDesc = onerel->rd_att;
526  stats->compute_stats(stats,
528  numrows,
529  totalrows);
530 
531  /*
532  * If the appropriate flavor of the n_distinct option is
533  * specified, override with the corresponding value.
534  */
535  aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
536  if (aopt != NULL)
537  {
538  float8 n_distinct;
539 
540  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
541  if (n_distinct != 0.0)
542  stats->stadistinct = n_distinct;
543  }
544 
546  }
547 
548  if (hasindex)
549  compute_index_stats(onerel, totalrows,
550  indexdata, nindexes,
551  rows, numrows,
552  col_context);
553 
554  MemoryContextSwitchTo(old_context);
555  MemoryContextDelete(col_context);
556 
557  /*
558  * Emit the completed stats rows into pg_statistic, replacing any
559  * previous statistics for the target columns. (If there are stats in
560  * pg_statistic for columns we didn't process, we leave them alone.)
561  */
562  update_attstats(RelationGetRelid(onerel), inh,
563  attr_cnt, vacattrstats);
564 
565  for (ind = 0; ind < nindexes; ind++)
566  {
567  AnlIndexData *thisdata = &indexdata[ind];
568 
569  update_attstats(RelationGetRelid(Irel[ind]), false,
570  thisdata->attr_cnt, thisdata->vacattrstats);
571  }
572 
573  /* Build extended statistics (if there are any). */
574  BuildRelationExtStatistics(onerel, totalrows, numrows, rows, attr_cnt,
575  vacattrstats);
576  }
577 
578  /*
579  * Update pages/tuples stats in pg_class ... but not if we're doing
580  * inherited stats.
581  */
582  if (!inh)
583  {
585 
586  visibilitymap_count(onerel, &relallvisible, NULL);
587 
588  vac_update_relstats(onerel,
589  relpages,
590  totalrows,
591  relallvisible,
592  hasindex,
595  in_outer_xact);
596  }
597 
598  /*
599  * Same for indexes. Vacuum always scans all indexes, so if we're part of
600  * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
601  * VACUUM.
602  */
603  if (!inh && !(options & VACOPT_VACUUM))
604  {
605  for (ind = 0; ind < nindexes; ind++)
606  {
607  AnlIndexData *thisdata = &indexdata[ind];
608  double totalindexrows;
609 
610  totalindexrows = ceil(thisdata->tupleFract * totalrows);
611  vac_update_relstats(Irel[ind],
612  RelationGetNumberOfBlocks(Irel[ind]),
613  totalindexrows,
614  0,
615  false,
618  in_outer_xact);
619  }
620  }
621 
622  /*
623  * Report ANALYZE to the stats collector, too. However, if doing
624  * inherited stats we shouldn't report, because the stats collector only
625  * tracks per-table stats. Reset the changes_since_analyze counter only
626  * if we analyzed all columns; otherwise, there is still work for
627  * auto-analyze to do.
628  */
629  if (!inh)
630  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
631  (va_cols == NIL));
632 
633  /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
634  if (!(options & VACOPT_VACUUM))
635  {
636  for (ind = 0; ind < nindexes; ind++)
637  {
638  IndexBulkDeleteResult *stats;
639  IndexVacuumInfo ivinfo;
640 
641  ivinfo.index = Irel[ind];
642  ivinfo.analyze_only = true;
643  ivinfo.estimated_count = true;
644  ivinfo.message_level = elevel;
645  ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
646  ivinfo.strategy = vac_strategy;
647 
648  stats = index_vacuum_cleanup(&ivinfo, NULL);
649 
650  if (stats)
651  pfree(stats);
652  }
653  }
654 
655  /* Done with indexes */
656  vac_close_indexes(nindexes, Irel, NoLock);
657 
658  /* Log the action if appropriate */
659  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
660  {
661  if (params->log_min_duration == 0 ||
663  params->log_min_duration))
664  ereport(LOG,
665  (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
668  RelationGetRelationName(onerel),
669  pg_rusage_show(&ru0))));
670  }
671 
672  /* Roll back any GUC changes executed by index functions */
673  AtEOXact_GUC(false, save_nestlevel);
674 
675  /* Restore userid and security context */
676  SetUserIdAndSecContext(save_userid, save_sec_context);
677 
678  /* Restore current context and release memory */
679  MemoryContextSwitchTo(caller_context);
681  anl_context = NULL;
682 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
#define NIL
Definition: pg_list.h:69
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1808
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1265
int minrows
Definition: vacuum.h:93
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:504
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
HeapTuple * rows
Definition: vacuum.h:127
bool analyze_only
Definition: genam.h:47
void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
Definition: pgstat.c:1433
BufferAccessStrategy strategy
Definition: genam.h:51
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:572
Relation index
Definition: genam.h:46
int32 relallvisible
Definition: pg_class.h:45
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
TupleDesc tupDesc
Definition: vacuum.h:128
uint32 BlockNumber
Definition: block.h:31
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1504
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1761
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1669
int natts
Definition: tupdesc.h:82
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:82
int32 relpages
Definition: pg_class.h:43
int attr_cnt
Definition: analyze.c:72
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:491
void BuildRelationExtStatistics(Relation onerel, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
static MemoryContext anl_context
Definition: analyze.c:80
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3101
#define NoLock
Definition: lockdefs.h:34
float8 n_distinct_inherited
Definition: attoptcache.h:23
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:497
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5358
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:442
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3285
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:141
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1765
static int elevel
Definition: vacuumlazy.c:144
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
void * palloc0(Size size)
Definition: mcxt.c:955
int ii_NumIndexAttrs
Definition: execnodes.h:154
Oid MyDatabaseId
Definition: globals.c:84
#define InvalidMultiXactId
Definition: multixact.h:23
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
TupleDesc rd_att
Definition: rel.h:85
int message_level
Definition: genam.h:49
double num_heap_tuples
Definition: genam.h:50
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
static void compute_index_stats(Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
Definition: analyze.c:688
List * ii_Expressions
Definition: execnodes.h:157
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int log_min_duration
Definition: vacuum.h:146
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:765
double tupleFract
Definition: analyze.c:70
#define InvalidAttrNumber
Definition: attnum.h:23
int NewGUCNestLevel(void)
Definition: guc.c:5344
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:786
VacAttrStats ** vacattrstats
Definition: analyze.c:71
#define elog(elevel,...)
Definition: elog.h:226
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:92
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:156
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:1087
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition: analyze.c:869
#define RelationGetRelid(relation)
Definition: rel.h:408
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1638
bool estimated_count
Definition: genam.h:48
float4 stadistinct
Definition: vacuum.h:103
IndexInfo * indexInfo
Definition: analyze.c:69
#define RelationGetNamespace(relation)
Definition: rel.h:449

◆ examine_attribute()

static VacAttrStats * examine_attribute ( Relation  onerel,
int  attnum,
Node index_expr 
)
static

Definition at line 869 of file analyze.c.

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

Referenced by do_analyze_rel().

870 {
871  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
872  HeapTuple typtuple;
873  VacAttrStats *stats;
874  int i;
875  bool ok;
876 
877  /* Never analyze dropped columns */
878  if (attr->attisdropped)
879  return NULL;
880 
881  /* Don't analyze column if user has specified not to */
882  if (attr->attstattarget == 0)
883  return NULL;
884 
885  /*
886  * Create the VacAttrStats struct. Note that we only have a copy of the
887  * fixed fields of the pg_attribute tuple.
888  */
889  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
891  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
892 
893  /*
894  * When analyzing an expression index, believe the expression tree's type
895  * not the column datatype --- the latter might be the opckeytype storage
896  * type of the opclass, which is not interesting for our purposes. (Note:
897  * if we did anything with non-expression index columns, we'd need to
898  * figure out where to get the correct type info from, but for now that's
899  * not a problem.) It's not clear whether anyone will care about the
900  * typmod, but we store that too just in case.
901  */
902  if (index_expr)
903  {
904  stats->attrtypid = exprType(index_expr);
905  stats->attrtypmod = exprTypmod(index_expr);
906  }
907  else
908  {
909  stats->attrtypid = attr->atttypid;
910  stats->attrtypmod = attr->atttypmod;
911  }
912 
913  typtuple = SearchSysCacheCopy1(TYPEOID,
914  ObjectIdGetDatum(stats->attrtypid));
915  if (!HeapTupleIsValid(typtuple))
916  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
917  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
918  stats->anl_context = anl_context;
919  stats->tupattnum = attnum;
920 
921  /*
922  * The fields describing the stats->stavalues[n] element types default to
923  * the type of the data being analyzed, but the type-specific typanalyze
924  * function can change them if it wants to store something else.
925  */
926  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
927  {
928  stats->statypid[i] = stats->attrtypid;
929  stats->statyplen[i] = stats->attrtype->typlen;
930  stats->statypbyval[i] = stats->attrtype->typbyval;
931  stats->statypalign[i] = stats->attrtype->typalign;
932  }
933 
934  /*
935  * Call the type-specific typanalyze function. If none is specified, use
936  * std_typanalyze().
937  */
938  if (OidIsValid(stats->attrtype->typanalyze))
939  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
940  PointerGetDatum(stats)));
941  else
942  ok = std_typanalyze(stats);
943 
944  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
945  {
946  heap_freetuple(typtuple);
947  pfree(stats->attr);
948  pfree(stats);
949  return NULL;
950  }
951 
952  return stats;
953 }
int minrows
Definition: vacuum.h:93
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
#define PointerGetDatum(X)
Definition: postgres.h:541
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
int tupattnum
Definition: vacuum.h:126
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1731
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1537
int32 attrtypmod
Definition: vacuum.h:84
#define OidIsValid(objectId)
Definition: c.h:638
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:120
Form_pg_attribute attr
Definition: vacuum.h:82
void pfree(void *pointer)
Definition: mcxt.c:1031
Oid attrtypid
Definition: vacuum.h:83
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:628
static MemoryContext anl_context
Definition: analyze.c:80
#define DatumGetBool(X)
Definition: postgres.h:378
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:189
void * palloc0(Size size)
Definition: mcxt.c:955
TupleDesc rd_att
Definition: rel.h:85
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
int16 attnum
Definition: pg_attribute.h:79
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:119
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
FormData_pg_type * Form_pg_type
Definition: pg_type.h:248
MemoryContext anl_context
Definition: vacuum.h:86
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
Form_pg_type attrtype
Definition: vacuum.h:85
void * palloc(Size size)
Definition: mcxt.c:924
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
#define elog(elevel,...)
Definition: elog.h:226
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:92

◆ ind_fetch_func()

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

Definition at line 1654 of file analyze.c.

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

Referenced by compute_index_stats().

1655 {
1656  int i;
1657 
1658  /* exprvals and exprnulls are already offset for proper column */
1659  i = rownum * stats->rowstride;
1660  *isNull = stats->exprnulls[i];
1661  return stats->exprvals[i];
1662 }
int rowstride
Definition: vacuum.h:131
bool * exprnulls
Definition: vacuum.h:130
Datum * exprvals
Definition: vacuum.h:129
int i

◆ std_fetch_func()

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

Definition at line 1638 of file analyze.c.

References attnum, heap_getattr, VacAttrStats::rows, VacAttrStats::tupattnum, and VacAttrStats::tupDesc.

Referenced by do_analyze_rel().

1639 {
1640  int attnum = stats->tupattnum;
1641  HeapTuple tuple = stats->rows[rownum];
1642  TupleDesc tupDesc = stats->tupDesc;
1643 
1644  return heap_getattr(tuple, attnum, tupDesc, isNull);
1645 }
HeapTuple * rows
Definition: vacuum.h:127
int tupattnum
Definition: vacuum.h:126
TupleDesc tupDesc
Definition: vacuum.h:128
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:781
int16 attnum
Definition: pg_attribute.h:79

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

Definition at line 1731 of file analyze.c.

References VacAttrStats::attr, VacAttrStats::attrtypid, compute_distinct_stats(), compute_scalar_stats(), VacAttrStats::compute_stats, compute_trivial_stats(), default_statistics_target, StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, get_opcode(), get_sort_group_operators(), InvalidOid, StdAnalyzeData::ltopr, VacAttrStats::minrows, OidIsValid, and palloc().

Referenced by array_typanalyze(), and examine_attribute().

1732 {
1733  Form_pg_attribute attr = stats->attr;
1734  Oid ltopr;
1735  Oid eqopr;
1736  StdAnalyzeData *mystats;
1737 
1738  /* If the attstattarget column is negative, use the default value */
1739  /* NB: it is okay to scribble on stats->attr since it's a copy */
1740  if (attr->attstattarget < 0)
1741  attr->attstattarget = default_statistics_target;
1742 
1743  /* Look for default "<" and "=" operators for column's type */
1745  false, false, false,
1746  &ltopr, &eqopr, NULL,
1747  NULL);
1748 
1749  /* Save the operator info for compute_stats routines */
1750  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1751  mystats->eqopr = eqopr;
1752  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1753  mystats->ltopr = ltopr;
1754  stats->extra_data = mystats;
1755 
1756  /*
1757  * Determine which standard statistics algorithm to use
1758  */
1759  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1760  {
1761  /* Seems to be a scalar datatype */
1763  /*--------------------
1764  * The following choice of minrows is based on the paper
1765  * "Random sampling for histogram construction: how much is enough?"
1766  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1767  * Proceedings of ACM SIGMOD International Conference on Management
1768  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1769  * says that for table size n, histogram size k, maximum relative
1770  * error in bin size f, and error probability gamma, the minimum
1771  * random sample size is
1772  * r = 4 * k * ln(2*n/gamma) / f^2
1773  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1774  * r = 305.82 * k
1775  * Note that because of the log function, the dependence on n is
1776  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1777  * bin size error with probability 0.99. So there's no real need to
1778  * scale for n, which is a good thing because we don't necessarily
1779  * know it at this point.
1780  *--------------------
1781  */
1782  stats->minrows = 300 * attr->attstattarget;
1783  }
1784  else if (OidIsValid(eqopr))
1785  {
1786  /* We can still recognize distinct values */
1788  /* Might as well use the same minrows as above */
1789  stats->minrows = 300 * attr->attstattarget;
1790  }
1791  else
1792  {
1793  /* Can't do much but the trivial stuff */
1795  /* Might as well use the same minrows as above */
1796  stats->minrows = 300 * attr->attstattarget;
1797  }
1798 
1799  return true;
1800 }
int minrows
Definition: vacuum.h:93
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2244
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
Form_pg_attribute attr
Definition: vacuum.h:82
Oid attrtypid
Definition: vacuum.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1901
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1105
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1811
void * palloc(Size size)
Definition: mcxt.c:924
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:92
void * extra_data
Definition: vacuum.h:94
int default_statistics_target
Definition: analyze.c:77

◆ update_attstats()

static void update_attstats ( Oid  relid,
bool  inh,
int  natts,
VacAttrStats **  vacattrstats 
)
static

Definition at line 1504 of file analyze.c.

References VacAttrStats::attr, BoolGetDatum, CatalogTupleInsert(), CatalogTupleUpdate(), construct_array(), Float4GetDatum(), heap_close, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, i, Int16GetDatum, Int32GetDatum, VacAttrStats::numnumbers, VacAttrStats::numvalues, ObjectIdGetDatum, palloc(), PointerGetDatum, RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3(), VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_NUM_SLOTS, STATRELATTINH, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, HeapTupleData::t_self, and values.

Referenced by do_analyze_rel().

1505 {
1506  Relation sd;
1507  int attno;
1508 
1509  if (natts <= 0)
1510  return; /* nothing to do */
1511 
1512  sd = heap_open(StatisticRelationId, RowExclusiveLock);
1513 
1514  for (attno = 0; attno < natts; attno++)
1515  {
1516  VacAttrStats *stats = vacattrstats[attno];
1517  HeapTuple stup,
1518  oldtup;
1519  int i,
1520  k,
1521  n;
1522  Datum values[Natts_pg_statistic];
1523  bool nulls[Natts_pg_statistic];
1524  bool replaces[Natts_pg_statistic];
1525 
1526  /* Ignore attr if we weren't able to collect stats */
1527  if (!stats->stats_valid)
1528  continue;
1529 
1530  /*
1531  * Construct a new pg_statistic tuple
1532  */
1533  for (i = 0; i < Natts_pg_statistic; ++i)
1534  {
1535  nulls[i] = false;
1536  replaces[i] = true;
1537  }
1538 
1539  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1540  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1541  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1542  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1543  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1544  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1545  i = Anum_pg_statistic_stakind1 - 1;
1546  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1547  {
1548  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1549  }
1550  i = Anum_pg_statistic_staop1 - 1;
1551  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1552  {
1553  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1554  }
1555  i = Anum_pg_statistic_stanumbers1 - 1;
1556  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1557  {
1558  int nnum = stats->numnumbers[k];
1559 
1560  if (nnum > 0)
1561  {
1562  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1563  ArrayType *arry;
1564 
1565  for (n = 0; n < nnum; n++)
1566  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1567  /* XXX knows more than it should about type float4: */
1568  arry = construct_array(numdatums, nnum,
1569  FLOAT4OID,
1570  sizeof(float4), FLOAT4PASSBYVAL, 'i');
1571  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1572  }
1573  else
1574  {
1575  nulls[i] = true;
1576  values[i++] = (Datum) 0;
1577  }
1578  }
1579  i = Anum_pg_statistic_stavalues1 - 1;
1580  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1581  {
1582  if (stats->numvalues[k] > 0)
1583  {
1584  ArrayType *arry;
1585 
1586  arry = construct_array(stats->stavalues[k],
1587  stats->numvalues[k],
1588  stats->statypid[k],
1589  stats->statyplen[k],
1590  stats->statypbyval[k],
1591  stats->statypalign[k]);
1592  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1593  }
1594  else
1595  {
1596  nulls[i] = true;
1597  values[i++] = (Datum) 0;
1598  }
1599  }
1600 
1601  /* Is there already a pg_statistic tuple for this attribute? */
1602  oldtup = SearchSysCache3(STATRELATTINH,
1603  ObjectIdGetDatum(relid),
1604  Int16GetDatum(stats->attr->attnum),
1605  BoolGetDatum(inh));
1606 
1607  if (HeapTupleIsValid(oldtup))
1608  {
1609  /* Yes, replace it */
1610  stup = heap_modify_tuple(oldtup,
1611  RelationGetDescr(sd),
1612  values,
1613  nulls,
1614  replaces);
1615  ReleaseSysCache(oldtup);
1616  CatalogTupleUpdate(sd, &stup->t_self, stup);
1617  }
1618  else
1619  {
1620  /* No, insert new tuple */
1621  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1622  CatalogTupleInsert(sd, stup);
1623  }
1624 
1625  heap_freetuple(stup);
1626  }
1627 
1629 }
#define RelationGetDescr(relation)
Definition: rel.h:434
#define PointerGetDatum(X)
Definition: postgres.h:541
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
#define Int16GetDatum(X)
Definition: postgres.h:436
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3288
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1027
#define heap_close(r, l)
Definition: heapam.h:98
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1537
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:120
Form_pg_attribute attr
Definition: vacuum.h:82
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:163
int32 stawidth
Definition: vacuum.h:102
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
Datum Float4GetDatum(float4 X)
Definition: fmgr.c:1889
ItemPointerData t_self
Definition: htup.h:65
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
#define RowExclusiveLock
Definition: lockdefs.h:38
float4 stanullfrac
Definition: vacuum.h:101
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
bool stats_valid
Definition: vacuum.h:100
float float4
Definition: c.h:490
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1306
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
#define BoolGetDatum(X)
Definition: postgres.h:387
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:119
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define Int32GetDatum(X)
Definition: postgres.h:464
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
void * palloc(Size size)
Definition: mcxt.c:924
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
int i
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1126
float4 stadistinct
Definition: vacuum.h:103

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 80 of file analyze.c.

Referenced by examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

Definition at line 77 of file analyze.c.

Referenced by range_typanalyze(), std_typanalyze(), and ts_typanalyze().

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 81 of file analyze.c.

Referenced by do_analyze_rel().