PostgreSQL Source Code  git master
analyze.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/detoast.h"
#include "access/genam.h"
#include "access/multixact.h"
#include "access/relation.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/tupconvert.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_inherits.h"
#include "commands/dbcommands.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/vacuum.h"
#include "common/pg_prng.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 "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "storage/procarray.h"
#include "utils/attoptcache.h"
#include "utils/datum.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 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, 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, void *arg)
 
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, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
 
static BlockNumber block_sampling_read_stream_next (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
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, void *arg)
 
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,
  b 
)    do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)

Definition at line 1826 of file analyze.c.

◆ swapInt

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

Definition at line 1825 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1823 of file analyze.c.

Typedef Documentation

◆ AnlIndexData

typedef struct AnlIndexData 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 1370 of file analyze.c.

1373 {
1374  List *tableOIDs;
1375  Relation *rels;
1376  AcquireSampleRowsFunc *acquirefuncs;
1377  double *relblocks;
1378  double totalblocks;
1379  int numrows,
1380  nrels,
1381  i;
1382  ListCell *lc;
1383  bool has_child;
1384 
1385  /* Initialize output parameters to zero now, in case we exit early */
1386  *totalrows = 0;
1387  *totaldeadrows = 0;
1388 
1389  /*
1390  * Find all members of inheritance set. We only need AccessShareLock on
1391  * the children.
1392  */
1393  tableOIDs =
1395 
1396  /*
1397  * Check that there's at least one descendant, else fail. This could
1398  * happen despite analyze_rel's relhassubclass check, if table once had a
1399  * child but no longer does. In that case, we can clear the
1400  * relhassubclass field so as not to make the same mistake again later.
1401  * (This is safe because we hold ShareUpdateExclusiveLock.)
1402  */
1403  if (list_length(tableOIDs) < 2)
1404  {
1405  /* CCI because we already updated the pg_class row in this command */
1407  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1408  ereport(elevel,
1409  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1411  RelationGetRelationName(onerel))));
1412  return 0;
1413  }
1414 
1415  /*
1416  * Identify acquirefuncs to use, and count blocks in all the relations.
1417  * The result could overflow BlockNumber, so we use double arithmetic.
1418  */
1419  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1420  acquirefuncs = (AcquireSampleRowsFunc *)
1421  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1422  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1423  totalblocks = 0;
1424  nrels = 0;
1425  has_child = false;
1426  foreach(lc, tableOIDs)
1427  {
1428  Oid childOID = lfirst_oid(lc);
1429  Relation childrel;
1430  AcquireSampleRowsFunc acquirefunc = NULL;
1431  BlockNumber relpages = 0;
1432 
1433  /* We already got the needed lock */
1434  childrel = table_open(childOID, NoLock);
1435 
1436  /* Ignore if temp table of another backend */
1437  if (RELATION_IS_OTHER_TEMP(childrel))
1438  {
1439  /* ... but release the lock on it */
1440  Assert(childrel != onerel);
1441  table_close(childrel, AccessShareLock);
1442  continue;
1443  }
1444 
1445  /* Check table type (MATVIEW can't happen, but might as well allow) */
1446  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1447  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1448  {
1449  /* Regular table, so use the regular row acquisition function */
1450  acquirefunc = acquire_sample_rows;
1451  relpages = RelationGetNumberOfBlocks(childrel);
1452  }
1453  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1454  {
1455  /*
1456  * For a foreign table, call the FDW's hook function to see
1457  * whether it supports analysis.
1458  */
1459  FdwRoutine *fdwroutine;
1460  bool ok = false;
1461 
1462  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1463 
1464  if (fdwroutine->AnalyzeForeignTable != NULL)
1465  ok = fdwroutine->AnalyzeForeignTable(childrel,
1466  &acquirefunc,
1467  &relpages);
1468 
1469  if (!ok)
1470  {
1471  /* ignore, but release the lock on it */
1472  Assert(childrel != onerel);
1473  table_close(childrel, AccessShareLock);
1474  continue;
1475  }
1476  }
1477  else
1478  {
1479  /*
1480  * ignore, but release the lock on it. don't try to unlock the
1481  * passed-in relation
1482  */
1483  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1484  if (childrel != onerel)
1485  table_close(childrel, AccessShareLock);
1486  else
1487  table_close(childrel, NoLock);
1488  continue;
1489  }
1490 
1491  /* OK, we'll process this child */
1492  has_child = true;
1493  rels[nrels] = childrel;
1494  acquirefuncs[nrels] = acquirefunc;
1495  relblocks[nrels] = (double) relpages;
1496  totalblocks += (double) relpages;
1497  nrels++;
1498  }
1499 
1500  /*
1501  * If we don't have at least one child table to consider, fail. If the
1502  * relation is a partitioned table, it's not counted as a child table.
1503  */
1504  if (!has_child)
1505  {
1506  ereport(elevel,
1507  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1509  RelationGetRelationName(onerel))));
1510  return 0;
1511  }
1512 
1513  /*
1514  * Now sample rows from each relation, proportionally to its fraction of
1515  * the total block count. (This might be less than desirable if the child
1516  * rels have radically different free-space percentages, but it's not
1517  * clear that it's worth working harder.)
1518  */
1520  nrels);
1521  numrows = 0;
1522  for (i = 0; i < nrels; i++)
1523  {
1524  Relation childrel = rels[i];
1525  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1526  double childblocks = relblocks[i];
1527 
1528  /*
1529  * Report progress. The sampling function will normally report blocks
1530  * done/total, but we need to reset them to 0 here, so that they don't
1531  * show an old value until that.
1532  */
1533  {
1534  const int progress_index[] = {
1538  };
1539  const int64 progress_vals[] = {
1540  RelationGetRelid(childrel),
1541  0,
1542  0,
1543  };
1544 
1545  pgstat_progress_update_multi_param(3, progress_index, progress_vals);
1546  }
1547 
1548  if (childblocks > 0)
1549  {
1550  int childtargrows;
1551 
1552  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1553  /* Make sure we don't overrun due to roundoff error */
1554  childtargrows = Min(childtargrows, targrows - numrows);
1555  if (childtargrows > 0)
1556  {
1557  int childrows;
1558  double trows,
1559  tdrows;
1560 
1561  /* Fetch a random sample of the child's rows */
1562  childrows = (*acquirefunc) (childrel, elevel,
1563  rows + numrows, childtargrows,
1564  &trows, &tdrows);
1565 
1566  /* We may need to convert from child's rowtype to parent's */
1567  if (childrows > 0 &&
1568  !equalRowTypes(RelationGetDescr(childrel),
1569  RelationGetDescr(onerel)))
1570  {
1571  TupleConversionMap *map;
1572 
1573  map = convert_tuples_by_name(RelationGetDescr(childrel),
1574  RelationGetDescr(onerel));
1575  if (map != NULL)
1576  {
1577  int j;
1578 
1579  for (j = 0; j < childrows; j++)
1580  {
1581  HeapTuple newtup;
1582 
1583  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1584  heap_freetuple(rows[numrows + j]);
1585  rows[numrows + j] = newtup;
1586  }
1587  free_conversion_map(map);
1588  }
1589  }
1590 
1591  /* And add to counts */
1592  numrows += childrows;
1593  *totalrows += trows;
1594  *totaldeadrows += tdrows;
1595  }
1596  }
1597 
1598  /*
1599  * Note: we cannot release the child-table locks, since we may have
1600  * pointers to their TOAST tables in the sampled rows.
1601  */
1602  table_close(childrel, NoLock);
1604  i + 1);
1605  }
1606 
1607  return numrows;
1608 }
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:273
#define Min(x, y)
Definition: c.h:958
#define Assert(condition)
Definition: c.h:812
int64_t int64
Definition: c.h:482
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1183
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:151
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:442
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
int j
Definition: isn.c:73
int i
Definition: isn.c:72
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
void * palloc(Size size)
Definition: mcxt.c:1317
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:255
static int list_length(const List *l)
Definition: pg_list.h:152
#define lfirst_oid(lc)
Definition: pg_list.h:174
unsigned int Oid
Definition: postgres_ext.h:31
#define PROGRESS_ANALYZE_BLOCKS_DONE
Definition: progress.h:43
#define PROGRESS_ANALYZE_CHILD_TABLES_TOTAL
Definition: progress.h:46
#define PROGRESS_ANALYZE_BLOCKS_TOTAL
Definition: progress.h:42
#define PROGRESS_ANALYZE_CHILD_TABLES_DONE
Definition: progress.h:47
#define PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID
Definition: progress.h:48
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetDescr(relation)
Definition: rel.h:531
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:658
#define RelationGetNamespace(relation)
Definition: rel.h:546
struct RelationData * Relation
Definition: relcache.h:27
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:257
Definition: pg_list.h:54
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3560
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:299
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:102
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:154
bool equalRowTypes(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:586
void CommandCounterIncrement(void)
Definition: xact.c:1099

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert, CommandCounterIncrement(), convert_tuples_by_name(), equalRowTypes(), ereport, errmsg(), execute_attr_map_tuple(), find_all_inheritors(), free_conversion_map(), get_namespace_name(), GetFdwRoutineForRelation(), heap_freetuple(), i, j, lfirst_oid, list_length(), Min, NoLock, palloc(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, PROGRESS_ANALYZE_CHILD_TABLES_DONE, PROGRESS_ANALYZE_CHILD_TABLES_TOTAL, PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, SetRelationHasSubclass(), table_close(), and table_open().

Referenced by do_analyze_rel().

◆ acquire_sample_rows()

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

Definition at line 1183 of file analyze.c.

1186 {
1187  int numrows = 0; /* # rows now in reservoir */
1188  double samplerows = 0; /* total # rows collected */
1189  double liverows = 0; /* # live rows seen */
1190  double deadrows = 0; /* # dead rows seen */
1191  double rowstoskip = -1; /* -1 means not set yet */
1192  uint32 randseed; /* Seed for block sampler(s) */
1193  BlockNumber totalblocks;
1194  TransactionId OldestXmin;
1195  BlockSamplerData bs;
1196  ReservoirStateData rstate;
1197  TupleTableSlot *slot;
1198  TableScanDesc scan;
1199  BlockNumber nblocks;
1200  BlockNumber blksdone = 0;
1201  ReadStream *stream;
1202 
1203  Assert(targrows > 0);
1204 
1205  totalblocks = RelationGetNumberOfBlocks(onerel);
1206 
1207  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1208  OldestXmin = GetOldestNonRemovableTransactionId(onerel);
1209 
1210  /* Prepare for sampling block numbers */
1211  randseed = pg_prng_uint32(&pg_global_prng_state);
1212  nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1213 
1214  /* Report sampling block numbers */
1216  nblocks);
1217 
1218  /* Prepare for sampling rows */
1219  reservoir_init_selection_state(&rstate, targrows);
1220 
1221  scan = table_beginscan_analyze(onerel);
1222  slot = table_slot_create(onerel, NULL);
1223 
1225  vac_strategy,
1226  scan->rs_rd,
1227  MAIN_FORKNUM,
1229  &bs,
1230  0);
1231 
1232  /* Outer loop over blocks to sample */
1233  while (table_scan_analyze_next_block(scan, stream))
1234  {
1236 
1237  while (table_scan_analyze_next_tuple(scan, OldestXmin, &liverows, &deadrows, slot))
1238  {
1239  /*
1240  * The first targrows sample rows are simply copied into the
1241  * reservoir. Then we start replacing tuples in the sample until
1242  * we reach the end of the relation. This algorithm is from Jeff
1243  * Vitter's paper (see full citation in utils/misc/sampling.c). It
1244  * works by repeatedly computing the number of tuples to skip
1245  * before selecting a tuple, which replaces a randomly chosen
1246  * element of the reservoir (current set of tuples). At all times
1247  * the reservoir is a true random sample of the tuples we've
1248  * passed over so far, so when we fall off the end of the relation
1249  * we're done.
1250  */
1251  if (numrows < targrows)
1252  rows[numrows++] = ExecCopySlotHeapTuple(slot);
1253  else
1254  {
1255  /*
1256  * t in Vitter's paper is the number of records already
1257  * processed. If we need to compute a new S value, we must
1258  * use the not-yet-incremented value of samplerows as t.
1259  */
1260  if (rowstoskip < 0)
1261  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1262 
1263  if (rowstoskip <= 0)
1264  {
1265  /*
1266  * Found a suitable tuple, so save it, replacing one old
1267  * tuple at random
1268  */
1269  int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1270 
1271  Assert(k >= 0 && k < targrows);
1272  heap_freetuple(rows[k]);
1273  rows[k] = ExecCopySlotHeapTuple(slot);
1274  }
1275 
1276  rowstoskip -= 1;
1277  }
1278 
1279  samplerows += 1;
1280  }
1281 
1283  ++blksdone);
1284  }
1285 
1286  read_stream_end(stream);
1287 
1289  table_endscan(scan);
1290 
1291  /*
1292  * If we didn't find as many tuples as we wanted then we're done. No sort
1293  * is needed, since they're already in order.
1294  *
1295  * Otherwise we need to sort the collected tuples by position
1296  * (itempointer). It's not worth worrying about corner cases where the
1297  * tuples are already sorted.
1298  */
1299  if (numrows == targrows)
1300  qsort_interruptible(rows, numrows, sizeof(HeapTuple),
1301  compare_rows, NULL);
1302 
1303  /*
1304  * Estimate total numbers of live and dead rows in relation, extrapolating
1305  * on the assumption that the average tuple density in pages we didn't
1306  * scan is the same as in the pages we did scan. Since what we scanned is
1307  * a random sample of the pages in the relation, this should be a good
1308  * assumption.
1309  */
1310  if (bs.m > 0)
1311  {
1312  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1313  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1314  }
1315  else
1316  {
1317  *totalrows = 0.0;
1318  *totaldeadrows = 0.0;
1319  }
1320 
1321  /*
1322  * Emit some interesting relation info
1323  */
1324  ereport(elevel,
1325  (errmsg("\"%s\": scanned %d of %u pages, "
1326  "containing %.0f live rows and %.0f dead rows; "
1327  "%d rows in sample, %.0f estimated total rows",
1328  RelationGetRelationName(onerel),
1329  bs.m, totalblocks,
1330  liverows, deadrows,
1331  numrows, *totalrows)));
1332 
1333  return numrows;
1334 }
uint32_t uint32
Definition: c.h:485
uint32 TransactionId
Definition: c.h:606
static BufferAccessStrategy vac_strategy
Definition: analyze.c:75
static BlockNumber block_sampling_read_stream_next(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: analyze.c:1140
static int compare_rows(const void *a, const void *b, void *arg)
Definition: analyze.c:1340
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1341
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:227
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:2005
ReadStream * read_stream_begin_relation(int flags, BufferAccessStrategy strategy, Relation rel, ForkNumber forknum, ReadStreamBlockNumberCB callback, void *callback_private_data, size_t per_buffer_data_size)
Definition: read_stream.c:551
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:846
#define READ_STREAM_MAINTENANCE
Definition: read_stream.h:28
@ MAIN_FORKNUM
Definition: relpath.h:58
BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, uint32 randseed)
Definition: sampling.c:39
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
double sampler_random_fract(pg_prng_state *randstate)
Definition: sampling.c:241
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:147
pg_prng_state randstate
Definition: sampling.h:49
Relation rs_rd
Definition: relscan.h:38
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1028
static bool table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition: tableam.h:1747
static bool table_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
Definition: tableam.h:1731
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition: tableam.h:1017
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:481
void vacuum_delay_point(void)
Definition: vacuum.c:2362

References Assert, block_sampling_read_stream_next(), BlockSampler_Init(), compare_rows(), ereport, errmsg(), ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), GetOldestNonRemovableTransactionId(), heap_freetuple(), BlockSamplerData::m, MAIN_FORKNUM, pg_global_prng_state, pg_prng_uint32(), pgstat_progress_update_param(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, qsort_interruptible(), ReservoirStateData::randstate, read_stream_begin_relation(), read_stream_end(), READ_STREAM_MAINTENANCE, RelationGetNumberOfBlocks, RelationGetRelationName, reservoir_get_next_S(), reservoir_init_selection_state(), TableScanDescData::rs_rd, sampler_random_fract(), table_beginscan_analyze(), table_endscan(), table_scan_analyze_next_block(), table_scan_analyze_next_tuple(), table_slot_create(), vac_strategy, and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

◆ 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 2959 of file analyze.c.

2965 {
2966  double ndistinct_table;
2967  double sumcount;
2968  int i;
2969 
2970  /*
2971  * If the entire table was sampled, keep the whole list. This also
2972  * protects us against division by zero in the code below.
2973  */
2974  if (samplerows == totalrows || totalrows <= 1.0)
2975  return num_mcv;
2976 
2977  /* Re-extract the estimated number of distinct nonnull values in table */
2978  ndistinct_table = stadistinct;
2979  if (ndistinct_table < 0)
2980  ndistinct_table = -ndistinct_table * totalrows;
2981 
2982  /*
2983  * Exclude the least common values from the MCV list, if they are not
2984  * significantly more common than the estimated selectivity they would
2985  * have if they weren't in the list. All non-MCV values are assumed to be
2986  * equally common, after taking into account the frequencies of all the
2987  * values in the MCV list and the number of nulls (c.f. eqsel()).
2988  *
2989  * Here sumcount tracks the total count of all but the last (least common)
2990  * value in the MCV list, allowing us to determine the effect of excluding
2991  * that value from the list.
2992  *
2993  * Note that we deliberately do this by removing values from the full
2994  * list, rather than starting with an empty list and adding values,
2995  * because the latter approach can fail to add any values if all the most
2996  * common values have around the same frequency and make up the majority
2997  * of the table, so that the overall average frequency of all values is
2998  * roughly the same as that of the common values. This would lead to any
2999  * uncommon values being significantly overestimated.
3000  */
3001  sumcount = 0.0;
3002  for (i = 0; i < num_mcv - 1; i++)
3003  sumcount += mcv_counts[i];
3004 
3005  while (num_mcv > 0)
3006  {
3007  double selec,
3008  otherdistinct,
3009  N,
3010  n,
3011  K,
3012  variance,
3013  stddev;
3014 
3015  /*
3016  * Estimated selectivity the least common value would have if it
3017  * wasn't in the MCV list (c.f. eqsel()).
3018  */
3019  selec = 1.0 - sumcount / samplerows - stanullfrac;
3020  if (selec < 0.0)
3021  selec = 0.0;
3022  if (selec > 1.0)
3023  selec = 1.0;
3024  otherdistinct = ndistinct_table - (num_mcv - 1);
3025  if (otherdistinct > 1)
3026  selec /= otherdistinct;
3027 
3028  /*
3029  * If the value is kept in the MCV list, its population frequency is
3030  * assumed to equal its sample frequency. We use the lower end of a
3031  * textbook continuity-corrected Wald-type confidence interval to
3032  * determine if that is significantly more common than the non-MCV
3033  * frequency --- specifically we assume the population frequency is
3034  * highly likely to be within around 2 standard errors of the sample
3035  * frequency, which equates to an interval of 2 standard deviations
3036  * either side of the sample count, plus an additional 0.5 for the
3037  * continuity correction. Since we are sampling without replacement,
3038  * this is a hypergeometric distribution.
3039  *
3040  * XXX: Empirically, this approach seems to work quite well, but it
3041  * may be worth considering more advanced techniques for estimating
3042  * the confidence interval of the hypergeometric distribution.
3043  */
3044  N = totalrows;
3045  n = samplerows;
3046  K = N * mcv_counts[num_mcv - 1] / n;
3047  variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
3048  stddev = sqrt(variance);
3049 
3050  if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
3051  {
3052  /*
3053  * The value is significantly more common than the non-MCV
3054  * selectivity would suggest. Keep it, and all the other more
3055  * common values in the list.
3056  */
3057  break;
3058  }
3059  else
3060  {
3061  /* Discard this value and consider the next least common value */
3062  num_mcv--;
3063  if (num_mcv == 0)
3064  break;
3065  sumcount -= mcv_counts[num_mcv - 1];
3066  }
3067  }
3068  return num_mcv;
3069 }
#define K(t)
Definition: sha1.c:66

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

◆ analyze_rel()

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

Definition at line 109 of file analyze.c.

112 {
113  Relation onerel;
114  int elevel;
115  AcquireSampleRowsFunc acquirefunc = NULL;
116  BlockNumber relpages = 0;
117 
118  /* Select logging level */
119  if (params->options & VACOPT_VERBOSE)
120  elevel = INFO;
121  else
122  elevel = DEBUG2;
123 
124  /* Set up static variables */
125  vac_strategy = bstrategy;
126 
127  /*
128  * Check for user-requested abort.
129  */
131 
132  /*
133  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
134  * ANALYZEs don't run on it concurrently. (This also locks out a
135  * concurrent VACUUM, which doesn't matter much at the moment but might
136  * matter if we ever try to accumulate stats on dead tuples.) If the rel
137  * has been dropped since we last saw it, we don't need to process it.
138  *
139  * Make sure to generate only logs for ANALYZE in this case.
140  */
141  onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
142  params->log_min_duration >= 0,
144 
145  /* leave if relation could not be opened or locked */
146  if (!onerel)
147  return;
148 
149  /*
150  * Check if relation needs to be skipped based on privileges. This check
151  * happens also when building the relation list to analyze for a manual
152  * operation, and needs to be done additionally here as ANALYZE could
153  * happen across multiple transactions where privileges could have changed
154  * in-between. Make sure to generate only logs for ANALYZE in this case.
155  */
157  onerel->rd_rel,
158  params->options & ~VACOPT_VACUUM))
159  {
161  return;
162  }
163 
164  /*
165  * Silently ignore tables that are temp tables of other backends ---
166  * trying to analyze these is rather pointless, since their contents are
167  * probably not up-to-date on disk. (We don't throw a warning here; it
168  * would just lead to chatter during a database-wide ANALYZE.)
169  */
170  if (RELATION_IS_OTHER_TEMP(onerel))
171  {
173  return;
174  }
175 
176  /*
177  * We can ANALYZE any table except pg_statistic. See update_attstats
178  */
179  if (RelationGetRelid(onerel) == StatisticRelationId)
180  {
182  return;
183  }
184 
185  /*
186  * Check that it's of an analyzable relkind, and set up appropriately.
187  */
188  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
189  onerel->rd_rel->relkind == RELKIND_MATVIEW)
190  {
191  /* Regular table, so we'll use the regular row acquisition function */
192  acquirefunc = acquire_sample_rows;
193  /* Also get regular table's size */
194  relpages = RelationGetNumberOfBlocks(onerel);
195  }
196  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
197  {
198  /*
199  * For a foreign table, call the FDW's hook function to see whether it
200  * supports analysis.
201  */
202  FdwRoutine *fdwroutine;
203  bool ok = false;
204 
205  fdwroutine = GetFdwRoutineForRelation(onerel, false);
206 
207  if (fdwroutine->AnalyzeForeignTable != NULL)
208  ok = fdwroutine->AnalyzeForeignTable(onerel,
209  &acquirefunc,
210  &relpages);
211 
212  if (!ok)
213  {
215  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
216  RelationGetRelationName(onerel))));
218  return;
219  }
220  }
221  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
222  {
223  /*
224  * For partitioned tables, we want to do the recursive ANALYZE below.
225  */
226  }
227  else
228  {
229  /* No need for a WARNING if we already complained during VACUUM */
230  if (!(params->options & VACOPT_VACUUM))
232  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
233  RelationGetRelationName(onerel))));
235  return;
236  }
237 
238  /*
239  * OK, let's do it. First, initialize progress reporting.
240  */
242  RelationGetRelid(onerel));
243 
244  /*
245  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
246  * tables, which don't contain any rows.
247  */
248  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
249  do_analyze_rel(onerel, params, va_cols, acquirefunc,
250  relpages, false, in_outer_xact, elevel);
251 
252  /*
253  * If there are child tables, do recursive ANALYZE.
254  */
255  if (onerel->rd_rel->relhassubclass)
256  do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
257  true, in_outer_xact, elevel);
258 
259  /*
260  * Close source relation now, but keep lock so that no one deletes it
261  * before we commit. (If someone did, they'd fail to clean up the entries
262  * we made in pg_statistic. Also, releasing the lock before commit would
263  * expose us to concurrent-update failures in update_attstats.)
264  */
265  relation_close(onerel, NoLock);
266 
268 }
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_ANALYZE
static void do_analyze_rel(Relation onerel, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:278
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
#define INFO
Definition: elog.h:34
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
bits32 options
Definition: vacuum.h:219
int log_min_duration
Definition: vacuum.h:227
Relation vacuum_open_relation(Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:755
bool vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple, bits32 options)
Definition: vacuum.c:703
#define VACOPT_VACUUM
Definition: vacuum.h:180
#define VACOPT_VERBOSE
Definition: vacuum.h:182

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), ereport, errmsg(), GetFdwRoutineForRelation(), INFO, VacuumParams::log_min_duration, NoLock, VacuumParams::options, pgstat_progress_end_command(), pgstat_progress_start_command(), PROGRESS_COMMAND_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, ShareUpdateExclusiveLock, vac_strategy, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_permitted_for_relation(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

◆ block_sampling_read_stream_next()

static BlockNumber block_sampling_read_stream_next ( ReadStream stream,
void *  callback_private_data,
void *  per_buffer_data 
)
static

Definition at line 1140 of file analyze.c.

1143 {
1144  BlockSamplerData *bs = callback_private_data;
1145 
1147 }
#define InvalidBlockNumber
Definition: block.h:33
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:58
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:64

References BlockSampler_HasMore(), BlockSampler_Next(), and InvalidBlockNumber.

Referenced by acquire_sample_rows().

◆ compare_mcvs()

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

Definition at line 2941 of file analyze.c.

2942 {
2943  int da = ((const ScalarMCVItem *) a)->first;
2944  int db = ((const ScalarMCVItem *) b)->first;
2945 
2946  return da - db;
2947 }
int b
Definition: isn.c:69
int a
Definition: isn.c:68

References a, and b.

Referenced by compute_scalar_stats().

◆ compare_rows()

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

Definition at line 1340 of file analyze.c.

1341 {
1342  HeapTuple ha = *(const HeapTuple *) a;
1343  HeapTuple hb = *(const HeapTuple *) b;
1348 
1349  if (ba < bb)
1350  return -1;
1351  if (ba > bb)
1352  return 1;
1353  if (oa < ob)
1354  return -1;
1355  if (oa > ob)
1356  return 1;
1357  return 0;
1358 }
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65

References a, b, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

◆ compare_scalars()

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

Definition at line 2910 of file analyze.c.

2911 {
2912  Datum da = ((const ScalarItem *) a)->value;
2913  int ta = ((const ScalarItem *) a)->tupno;
2914  Datum db = ((const ScalarItem *) b)->value;
2915  int tb = ((const ScalarItem *) b)->tupno;
2917  int compare;
2918 
2919  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2920  if (compare != 0)
2921  return compare;
2922 
2923  /*
2924  * The two datums are equal, so update cxt->tupnoLink[].
2925  */
2926  if (cxt->tupnoLink[ta] < tb)
2927  cxt->tupnoLink[ta] = tb;
2928  if (cxt->tupnoLink[tb] < ta)
2929  cxt->tupnoLink[tb] = ta;
2930 
2931  /*
2932  * For equal datums, sort by tupno
2933  */
2934  return ta - tb;
2935 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
void * arg
uintptr_t Datum
Definition: postgres.h:64
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
SortSupport ssup
Definition: analyze.c:1839

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

Referenced by compute_scalar_stats().

◆ compute_distinct_stats()

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

Definition at line 2038 of file analyze.c.

2042 {
2043  int i;
2044  int null_cnt = 0;
2045  int nonnull_cnt = 0;
2046  int toowide_cnt = 0;
2047  double total_width = 0;
2048  bool is_varlena = (!stats->attrtype->typbyval &&
2049  stats->attrtype->typlen == -1);
2050  bool is_varwidth = (!stats->attrtype->typbyval &&
2051  stats->attrtype->typlen < 0);
2052  FmgrInfo f_cmpeq;
2053  typedef struct
2054  {
2055  Datum value;
2056  int count;
2057  } TrackItem;
2058  TrackItem *track;
2059  int track_cnt,
2060  track_max;
2061  int num_mcv = stats->attstattarget;
2062  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2063 
2064  /*
2065  * We track up to 2*n values for an n-element MCV list; but at least 10
2066  */
2067  track_max = 2 * num_mcv;
2068  if (track_max < 10)
2069  track_max = 10;
2070  track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
2071  track_cnt = 0;
2072 
2073  fmgr_info(mystats->eqfunc, &f_cmpeq);
2074 
2075  for (i = 0; i < samplerows; i++)
2076  {
2077  Datum value;
2078  bool isnull;
2079  bool match;
2080  int firstcount1,
2081  j;
2082 
2084 
2085  value = fetchfunc(stats, i, &isnull);
2086 
2087  /* Check for null/nonnull */
2088  if (isnull)
2089  {
2090  null_cnt++;
2091  continue;
2092  }
2093  nonnull_cnt++;
2094 
2095  /*
2096  * If it's a variable-width field, add up widths for average width
2097  * calculation. Note that if the value is toasted, we use the toasted
2098  * width. We don't bother with this calculation if it's a fixed-width
2099  * type.
2100  */
2101  if (is_varlena)
2102  {
2103  total_width += VARSIZE_ANY(DatumGetPointer(value));
2104 
2105  /*
2106  * If the value is toasted, we want to detoast it just once to
2107  * avoid repeated detoastings and resultant excess memory usage
2108  * during the comparisons. Also, check to see if the value is
2109  * excessively wide, and if so don't detoast at all --- just
2110  * ignore the value.
2111  */
2113  {
2114  toowide_cnt++;
2115  continue;
2116  }
2118  }
2119  else if (is_varwidth)
2120  {
2121  /* must be cstring */
2122  total_width += strlen(DatumGetCString(value)) + 1;
2123  }
2124 
2125  /*
2126  * See if the value matches anything we're already tracking.
2127  */
2128  match = false;
2129  firstcount1 = track_cnt;
2130  for (j = 0; j < track_cnt; j++)
2131  {
2132  if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
2133  stats->attrcollid,
2134  value, track[j].value)))
2135  {
2136  match = true;
2137  break;
2138  }
2139  if (j < firstcount1 && track[j].count == 1)
2140  firstcount1 = j;
2141  }
2142 
2143  if (match)
2144  {
2145  /* Found a match */
2146  track[j].count++;
2147  /* This value may now need to "bubble up" in the track list */
2148  while (j > 0 && track[j].count > track[j - 1].count)
2149  {
2150  swapDatum(track[j].value, track[j - 1].value);
2151  swapInt(track[j].count, track[j - 1].count);
2152  j--;
2153  }
2154  }
2155  else
2156  {
2157  /* No match. Insert at head of count-1 list */
2158  if (track_cnt < track_max)
2159  track_cnt++;
2160  for (j = track_cnt - 1; j > firstcount1; j--)
2161  {
2162  track[j].value = track[j - 1].value;
2163  track[j].count = track[j - 1].count;
2164  }
2165  if (firstcount1 < track_cnt)
2166  {
2167  track[firstcount1].value = value;
2168  track[firstcount1].count = 1;
2169  }
2170  }
2171  }
2172 
2173  /* We can only compute real stats if we found some non-null values. */
2174  if (nonnull_cnt > 0)
2175  {
2176  int nmultiple,
2177  summultiple;
2178 
2179  stats->stats_valid = true;
2180  /* Do the simple null-frac and width stats */
2181  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2182  if (is_varwidth)
2183  stats->stawidth = total_width / (double) nonnull_cnt;
2184  else
2185  stats->stawidth = stats->attrtype->typlen;
2186 
2187  /* Count the number of values we found multiple times */
2188  summultiple = 0;
2189  for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2190  {
2191  if (track[nmultiple].count == 1)
2192  break;
2193  summultiple += track[nmultiple].count;
2194  }
2195 
2196  if (nmultiple == 0)
2197  {
2198  /*
2199  * If we found no repeated non-null values, assume it's a unique
2200  * column; but be sure to discount for any nulls we found.
2201  */
2202  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2203  }
2204  else if (track_cnt < track_max && toowide_cnt == 0 &&
2205  nmultiple == track_cnt)
2206  {
2207  /*
2208  * Our track list includes every value in the sample, and every
2209  * value appeared more than once. Assume the column has just
2210  * these values. (This case is meant to address columns with
2211  * small, fixed sets of possible values, such as boolean or enum
2212  * columns. If there are any values that appear just once in the
2213  * sample, including too-wide values, we should assume that that's
2214  * not what we're dealing with.)
2215  */
2216  stats->stadistinct = track_cnt;
2217  }
2218  else
2219  {
2220  /*----------
2221  * Estimate the number of distinct values using the estimator
2222  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2223  * n*d / (n - f1 + f1*n/N)
2224  * where f1 is the number of distinct values that occurred
2225  * exactly once in our sample of n rows (from a total of N),
2226  * and d is the total number of distinct values in the sample.
2227  * This is their Duj1 estimator; the other estimators they
2228  * recommend are considerably more complex, and are numerically
2229  * very unstable when n is much smaller than N.
2230  *
2231  * In this calculation, we consider only non-nulls. We used to
2232  * include rows with null values in the n and N counts, but that
2233  * leads to inaccurate answers in columns with many nulls, and
2234  * it's intuitively bogus anyway considering the desired result is
2235  * the number of distinct non-null values.
2236  *
2237  * We assume (not very reliably!) that all the multiply-occurring
2238  * values are reflected in the final track[] list, and the other
2239  * nonnull values all appeared but once. (XXX this usually
2240  * results in a drastic overestimate of ndistinct. Can we do
2241  * any better?)
2242  *----------
2243  */
2244  int f1 = nonnull_cnt - summultiple;
2245  int d = f1 + nmultiple;
2246  double n = samplerows - null_cnt;
2247  double N = totalrows * (1.0 - stats->stanullfrac);
2248  double stadistinct;
2249 
2250  /* N == 0 shouldn't happen, but just in case ... */
2251  if (N > 0)
2252  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2253  else
2254  stadistinct = 0;
2255 
2256  /* Clamp to sane range in case of roundoff error */
2257  if (stadistinct < d)
2258  stadistinct = d;
2259  if (stadistinct > N)
2260  stadistinct = N;
2261  /* And round to integer */
2262  stats->stadistinct = floor(stadistinct + 0.5);
2263  }
2264 
2265  /*
2266  * If we estimated the number of distinct values at more than 10% of
2267  * the total row count (a very arbitrary limit), then assume that
2268  * stadistinct should scale with the row count rather than be a fixed
2269  * value.
2270  */
2271  if (stats->stadistinct > 0.1 * totalrows)
2272  stats->stadistinct = -(stats->stadistinct / totalrows);
2273 
2274  /*
2275  * Decide how many values are worth storing as most-common values. If
2276  * we are able to generate a complete MCV list (all the values in the
2277  * sample will fit, and we think these are all the ones in the table),
2278  * then do so. Otherwise, store only those values that are
2279  * significantly more common than the values not in the list.
2280  *
2281  * Note: the first of these cases is meant to address columns with
2282  * small, fixed sets of possible values, such as boolean or enum
2283  * columns. If we can *completely* represent the column population by
2284  * an MCV list that will fit into the stats target, then we should do
2285  * so and thus provide the planner with complete information. But if
2286  * the MCV list is not complete, it's generally worth being more
2287  * selective, and not just filling it all the way up to the stats
2288  * target.
2289  */
2290  if (track_cnt < track_max && toowide_cnt == 0 &&
2291  stats->stadistinct > 0 &&
2292  track_cnt <= num_mcv)
2293  {
2294  /* Track list includes all values seen, and all will fit */
2295  num_mcv = track_cnt;
2296  }
2297  else
2298  {
2299  int *mcv_counts;
2300 
2301  /* Incomplete list; decide how many values are worth keeping */
2302  if (num_mcv > track_cnt)
2303  num_mcv = track_cnt;
2304 
2305  if (num_mcv > 0)
2306  {
2307  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2308  for (i = 0; i < num_mcv; i++)
2309  mcv_counts[i] = track[i].count;
2310 
2311  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2312  stats->stadistinct,
2313  stats->stanullfrac,
2314  samplerows, totalrows);
2315  }
2316  }
2317 
2318  /* Generate MCV slot entry */
2319  if (num_mcv > 0)
2320  {
2321  MemoryContext old_context;
2322  Datum *mcv_values;
2323  float4 *mcv_freqs;
2324 
2325  /* Must copy the target values into anl_context */
2326  old_context = MemoryContextSwitchTo(stats->anl_context);
2327  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2328  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2329  for (i = 0; i < num_mcv; i++)
2330  {
2331  mcv_values[i] = datumCopy(track[i].value,
2332  stats->attrtype->typbyval,
2333  stats->attrtype->typlen);
2334  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2335  }
2336  MemoryContextSwitchTo(old_context);
2337 
2338  stats->stakind[0] = STATISTIC_KIND_MCV;
2339  stats->staop[0] = mystats->eqopr;
2340  stats->stacoll[0] = stats->attrcollid;
2341  stats->stanumbers[0] = mcv_freqs;
2342  stats->numnumbers[0] = num_mcv;
2343  stats->stavalues[0] = mcv_values;
2344  stats->numvalues[0] = num_mcv;
2345 
2346  /*
2347  * Accept the defaults for stats->statypid and others. They have
2348  * been set before we were called (see vacuum.h)
2349  */
2350  }
2351  }
2352  else if (null_cnt > 0)
2353  {
2354  /* We found only nulls; assume the column is entirely null */
2355  stats->stats_valid = true;
2356  stats->stanullfrac = 1.0;
2357  if (is_varwidth)
2358  stats->stawidth = 0; /* "unknown" */
2359  else
2360  stats->stawidth = stats->attrtype->typlen;
2361  stats->stadistinct = 0.0; /* "unknown" */
2362  }
2363 
2364  /* We don't need to bother cleaning up any of our temporary palloc's */
2365 }
float float4
Definition: c.h:583
#define swapInt(a, b)
Definition: analyze.c:1825
#define swapDatum(a, b)
Definition: analyze.c:1826
#define WIDTH_THRESHOLD
Definition: analyze.c:1823
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition: analyze.c:2959
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
Size toast_raw_datum_size(Datum value)
Definition: detoast.c:545
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
static struct @160 value
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static char * DatumGetCString(Datum X)
Definition: postgres.h:335
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
MemoryContextSwitchTo(old_ctx)
int f1[ARRAY_SIZE]
Definition: sql-declare.c:113
Definition: fmgr.h:57
bool stats_valid
Definition: vacuum.h:144
float4 stanullfrac
Definition: vacuum.h:145
Form_pg_type attrtype
Definition: vacuum.h:128
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:148
MemoryContext anl_context
Definition: vacuum.h:130
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:149
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:150
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:152
int attstattarget
Definition: vacuum.h:125
int32 stawidth
Definition: vacuum.h:146
void * extra_data
Definition: vacuum.h:138
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:153
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:154
float4 stadistinct
Definition: vacuum.h:147
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:151
Oid attrcollid
Definition: vacuum.h:129
#define VARSIZE_ANY(PTR)
Definition: varatt.h:311

References analyze_mcv_list(), VacAttrStats::anl_context, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attstattarget, datumCopy(), DatumGetBool(), DatumGetCString(), DatumGetPointer(), StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, f1, fmgr_info(), FunctionCall2Coll(), i, if(), j, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum(), VacAttrStats::stacoll, 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().

◆ 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 853 of file analyze.c.

857 {
858  MemoryContext ind_context,
859  old_context;
861  bool isnull[INDEX_MAX_KEYS];
862  int ind,
863  i;
864 
865  ind_context = AllocSetContextCreate(anl_context,
866  "Analyze Index",
868  old_context = MemoryContextSwitchTo(ind_context);
869 
870  for (ind = 0; ind < nindexes; ind++)
871  {
872  AnlIndexData *thisdata = &indexdata[ind];
873  IndexInfo *indexInfo = thisdata->indexInfo;
874  int attr_cnt = thisdata->attr_cnt;
875  TupleTableSlot *slot;
876  EState *estate;
877  ExprContext *econtext;
878  ExprState *predicate;
879  Datum *exprvals;
880  bool *exprnulls;
881  int numindexrows,
882  tcnt,
883  rowno;
884  double totalindexrows;
885 
886  /* Ignore index if no columns to analyze and not partial */
887  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
888  continue;
889 
890  /*
891  * Need an EState for evaluation of index expressions and
892  * partial-index predicates. Create it in the per-index context to be
893  * sure it gets cleaned up at the bottom of the loop.
894  */
895  estate = CreateExecutorState();
896  econtext = GetPerTupleExprContext(estate);
897  /* Need a slot to hold the current heap tuple, too */
899  &TTSOpsHeapTuple);
900 
901  /* Arrange for econtext's scan tuple to be the tuple under test */
902  econtext->ecxt_scantuple = slot;
903 
904  /* Set up execution state for predicate. */
905  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
906 
907  /* Compute and save index expression values */
908  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
909  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
910  numindexrows = 0;
911  tcnt = 0;
912  for (rowno = 0; rowno < numrows; rowno++)
913  {
914  HeapTuple heapTuple = rows[rowno];
915 
917 
918  /*
919  * Reset the per-tuple context each time, to reclaim any cruft
920  * left behind by evaluating the predicate or index expressions.
921  */
922  ResetExprContext(econtext);
923 
924  /* Set up for predicate or expression evaluation */
925  ExecStoreHeapTuple(heapTuple, slot, false);
926 
927  /* If index is partial, check predicate */
928  if (predicate != NULL)
929  {
930  if (!ExecQual(predicate, econtext))
931  continue;
932  }
933  numindexrows++;
934 
935  if (attr_cnt > 0)
936  {
937  /*
938  * Evaluate the index row to compute expression values. We
939  * could do this by hand, but FormIndexDatum is convenient.
940  */
941  FormIndexDatum(indexInfo,
942  slot,
943  estate,
944  values,
945  isnull);
946 
947  /*
948  * Save just the columns we care about. We copy the values
949  * into ind_context from the estate's per-tuple context.
950  */
951  for (i = 0; i < attr_cnt; i++)
952  {
953  VacAttrStats *stats = thisdata->vacattrstats[i];
954  int attnum = stats->tupattnum;
955 
956  if (isnull[attnum - 1])
957  {
958  exprvals[tcnt] = (Datum) 0;
959  exprnulls[tcnt] = true;
960  }
961  else
962  {
963  exprvals[tcnt] = datumCopy(values[attnum - 1],
964  stats->attrtype->typbyval,
965  stats->attrtype->typlen);
966  exprnulls[tcnt] = false;
967  }
968  tcnt++;
969  }
970  }
971  }
972 
973  /*
974  * Having counted the number of rows that pass the predicate in the
975  * sample, we can estimate the total number of rows in the index.
976  */
977  thisdata->tupleFract = (double) numindexrows / (double) numrows;
978  totalindexrows = ceil(thisdata->tupleFract * totalrows);
979 
980  /*
981  * Now we can compute the statistics for the expression columns.
982  */
983  if (numindexrows > 0)
984  {
985  MemoryContextSwitchTo(col_context);
986  for (i = 0; i < attr_cnt; i++)
987  {
988  VacAttrStats *stats = thisdata->vacattrstats[i];
989 
990  stats->exprvals = exprvals + i;
991  stats->exprnulls = exprnulls + i;
992  stats->rowstride = attr_cnt;
993  stats->compute_stats(stats,
995  numindexrows,
996  totalindexrows);
997 
998  MemoryContextReset(col_context);
999  }
1000  }
1001 
1002  /* And clean up */
1003  MemoryContextSwitchTo(ind_context);
1004 
1006  FreeExecutorState(estate);
1007  MemoryContextReset(ind_context);
1008  }
1009 
1010  MemoryContextSwitchTo(old_context);
1011  MemoryContextDelete(ind_context);
1012 }
static Datum values[MAXATTR]
Definition: bootstrap.c:151
static MemoryContext anl_context
Definition: analyze.c:74
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1793
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:771
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1325
EState * CreateExecutorState(void)
Definition: execUtils.c:88
void FreeExecutorState(EState *estate)
Definition: execUtils.c:191
#define GetPerTupleExprContext(estate)
Definition: executor.h:560
#define ResetExprContext(econtext)
Definition: executor.h:554
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:423
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2726
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
int16 attnum
Definition: pg_attribute.h:74
#define INDEX_MAX_KEYS
#define NIL
Definition: pg_list.h:68
double tupleFract
Definition: analyze.c:64
int attr_cnt
Definition: analyze.c:66
IndexInfo * indexInfo
Definition: analyze.c:63
VacAttrStats ** vacattrstats
Definition: analyze.c:65
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:258
List * ii_Predicate
Definition: execnodes.h:191
int tupattnum
Definition: vacuum.h:171
int rowstride
Definition: vacuum.h:176
bool * exprnulls
Definition: vacuum.h:175
Datum * exprvals
Definition: vacuum.h:174
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:136

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

Referenced by do_analyze_rel().

◆ compute_scalar_stats()

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

Definition at line 2381 of file analyze.c.

2385 {
2386  int i;
2387  int null_cnt = 0;
2388  int nonnull_cnt = 0;
2389  int toowide_cnt = 0;
2390  double total_width = 0;
2391  bool is_varlena = (!stats->attrtype->typbyval &&
2392  stats->attrtype->typlen == -1);
2393  bool is_varwidth = (!stats->attrtype->typbyval &&
2394  stats->attrtype->typlen < 0);
2395  double corr_xysum;
2396  SortSupportData ssup;
2397  ScalarItem *values;
2398  int values_cnt = 0;
2399  int *tupnoLink;
2400  ScalarMCVItem *track;
2401  int track_cnt = 0;
2402  int num_mcv = stats->attstattarget;
2403  int num_bins = stats->attstattarget;
2404  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2405 
2406  values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2407  tupnoLink = (int *) palloc(samplerows * sizeof(int));
2408  track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2409 
2410  memset(&ssup, 0, sizeof(ssup));
2412  ssup.ssup_collation = stats->attrcollid;
2413  ssup.ssup_nulls_first = false;
2414 
2415  /*
2416  * For now, don't perform abbreviated key conversion, because full values
2417  * are required for MCV slot generation. Supporting that optimization
2418  * would necessitate teaching compare_scalars() to call a tie-breaker.
2419  */
2420  ssup.abbreviate = false;
2421 
2422  PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2423 
2424  /* Initial scan to find sortable values */
2425  for (i = 0; i < samplerows; i++)
2426  {
2427  Datum value;
2428  bool isnull;
2429 
2431 
2432  value = fetchfunc(stats, i, &isnull);
2433 
2434  /* Check for null/nonnull */
2435  if (isnull)
2436  {
2437  null_cnt++;
2438  continue;
2439  }
2440  nonnull_cnt++;
2441 
2442  /*
2443  * If it's a variable-width field, add up widths for average width
2444  * calculation. Note that if the value is toasted, we use the toasted
2445  * width. We don't bother with this calculation if it's a fixed-width
2446  * type.
2447  */
2448  if (is_varlena)
2449  {
2450  total_width += VARSIZE_ANY(DatumGetPointer(value));
2451 
2452  /*
2453  * If the value is toasted, we want to detoast it just once to
2454  * avoid repeated detoastings and resultant excess memory usage
2455  * during the comparisons. Also, check to see if the value is
2456  * excessively wide, and if so don't detoast at all --- just
2457  * ignore the value.
2458  */
2460  {
2461  toowide_cnt++;
2462  continue;
2463  }
2465  }
2466  else if (is_varwidth)
2467  {
2468  /* must be cstring */
2469  total_width += strlen(DatumGetCString(value)) + 1;
2470  }
2471 
2472  /* Add it to the list to be sorted */
2473  values[values_cnt].value = value;
2474  values[values_cnt].tupno = values_cnt;
2475  tupnoLink[values_cnt] = values_cnt;
2476  values_cnt++;
2477  }
2478 
2479  /* We can only compute real stats if we found some sortable values. */
2480  if (values_cnt > 0)
2481  {
2482  int ndistinct, /* # distinct values in sample */
2483  nmultiple, /* # that appear multiple times */
2484  num_hist,
2485  dups_cnt;
2486  int slot_idx = 0;
2488 
2489  /* Sort the collected values */
2490  cxt.ssup = &ssup;
2491  cxt.tupnoLink = tupnoLink;
2492  qsort_interruptible(values, values_cnt, sizeof(ScalarItem),
2493  compare_scalars, &cxt);
2494 
2495  /*
2496  * Now scan the values in order, find the most common ones, and also
2497  * accumulate ordering-correlation statistics.
2498  *
2499  * To determine which are most common, we first have to count the
2500  * number of duplicates of each value. The duplicates are adjacent in
2501  * the sorted list, so a brute-force approach is to compare successive
2502  * datum values until we find two that are not equal. However, that
2503  * requires N-1 invocations of the datum comparison routine, which are
2504  * completely redundant with work that was done during the sort. (The
2505  * sort algorithm must at some point have compared each pair of items
2506  * that are adjacent in the sorted order; otherwise it could not know
2507  * that it's ordered the pair correctly.) We exploit this by having
2508  * compare_scalars remember the highest tupno index that each
2509  * ScalarItem has been found equal to. At the end of the sort, a
2510  * ScalarItem's tupnoLink will still point to itself if and only if it
2511  * is the last item of its group of duplicates (since the group will
2512  * be ordered by tupno).
2513  */
2514  corr_xysum = 0;
2515  ndistinct = 0;
2516  nmultiple = 0;
2517  dups_cnt = 0;
2518  for (i = 0; i < values_cnt; i++)
2519  {
2520  int tupno = values[i].tupno;
2521 
2522  corr_xysum += ((double) i) * ((double) tupno);
2523  dups_cnt++;
2524  if (tupnoLink[tupno] == tupno)
2525  {
2526  /* Reached end of duplicates of this value */
2527  ndistinct++;
2528  if (dups_cnt > 1)
2529  {
2530  nmultiple++;
2531  if (track_cnt < num_mcv ||
2532  dups_cnt > track[track_cnt - 1].count)
2533  {
2534  /*
2535  * Found a new item for the mcv list; find its
2536  * position, bubbling down old items if needed. Loop
2537  * invariant is that j points at an empty/ replaceable
2538  * slot.
2539  */
2540  int j;
2541 
2542  if (track_cnt < num_mcv)
2543  track_cnt++;
2544  for (j = track_cnt - 1; j > 0; j--)
2545  {
2546  if (dups_cnt <= track[j - 1].count)
2547  break;
2548  track[j].count = track[j - 1].count;
2549  track[j].first = track[j - 1].first;
2550  }
2551  track[j].count = dups_cnt;
2552  track[j].first = i + 1 - dups_cnt;
2553  }
2554  }
2555  dups_cnt = 0;
2556  }
2557  }
2558 
2559  stats->stats_valid = true;
2560  /* Do the simple null-frac and width stats */
2561  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2562  if (is_varwidth)
2563  stats->stawidth = total_width / (double) nonnull_cnt;
2564  else
2565  stats->stawidth = stats->attrtype->typlen;
2566 
2567  if (nmultiple == 0)
2568  {
2569  /*
2570  * If we found no repeated non-null values, assume it's a unique
2571  * column; but be sure to discount for any nulls we found.
2572  */
2573  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2574  }
2575  else if (toowide_cnt == 0 && nmultiple == ndistinct)
2576  {
2577  /*
2578  * Every value in the sample appeared more than once. Assume the
2579  * column has just these values. (This case is meant to address
2580  * columns with small, fixed sets of possible values, such as
2581  * boolean or enum columns. If there are any values that appear
2582  * just once in the sample, including too-wide values, we should
2583  * assume that that's not what we're dealing with.)
2584  */
2585  stats->stadistinct = ndistinct;
2586  }
2587  else
2588  {
2589  /*----------
2590  * Estimate the number of distinct values using the estimator
2591  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2592  * n*d / (n - f1 + f1*n/N)
2593  * where f1 is the number of distinct values that occurred
2594  * exactly once in our sample of n rows (from a total of N),
2595  * and d is the total number of distinct values in the sample.
2596  * This is their Duj1 estimator; the other estimators they
2597  * recommend are considerably more complex, and are numerically
2598  * very unstable when n is much smaller than N.
2599  *
2600  * In this calculation, we consider only non-nulls. We used to
2601  * include rows with null values in the n and N counts, but that
2602  * leads to inaccurate answers in columns with many nulls, and
2603  * it's intuitively bogus anyway considering the desired result is
2604  * the number of distinct non-null values.
2605  *
2606  * Overwidth values are assumed to have been distinct.
2607  *----------
2608  */
2609  int f1 = ndistinct - nmultiple + toowide_cnt;
2610  int d = f1 + nmultiple;
2611  double n = samplerows - null_cnt;
2612  double N = totalrows * (1.0 - stats->stanullfrac);
2613  double stadistinct;
2614 
2615  /* N == 0 shouldn't happen, but just in case ... */
2616  if (N > 0)
2617  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2618  else
2619  stadistinct = 0;
2620 
2621  /* Clamp to sane range in case of roundoff error */
2622  if (stadistinct < d)
2623  stadistinct = d;
2624  if (stadistinct > N)
2625  stadistinct = N;
2626  /* And round to integer */
2627  stats->stadistinct = floor(stadistinct + 0.5);
2628  }
2629 
2630  /*
2631  * If we estimated the number of distinct values at more than 10% of
2632  * the total row count (a very arbitrary limit), then assume that
2633  * stadistinct should scale with the row count rather than be a fixed
2634  * value.
2635  */
2636  if (stats->stadistinct > 0.1 * totalrows)
2637  stats->stadistinct = -(stats->stadistinct / totalrows);
2638 
2639  /*
2640  * Decide how many values are worth storing as most-common values. If
2641  * we are able to generate a complete MCV list (all the values in the
2642  * sample will fit, and we think these are all the ones in the table),
2643  * then do so. Otherwise, store only those values that are
2644  * significantly more common than the values not in the list.
2645  *
2646  * Note: the first of these cases is meant to address columns with
2647  * small, fixed sets of possible values, such as boolean or enum
2648  * columns. If we can *completely* represent the column population by
2649  * an MCV list that will fit into the stats target, then we should do
2650  * so and thus provide the planner with complete information. But if
2651  * the MCV list is not complete, it's generally worth being more
2652  * selective, and not just filling it all the way up to the stats
2653  * target.
2654  */
2655  if (track_cnt == ndistinct && toowide_cnt == 0 &&
2656  stats->stadistinct > 0 &&
2657  track_cnt <= num_mcv)
2658  {
2659  /* Track list includes all values seen, and all will fit */
2660  num_mcv = track_cnt;
2661  }
2662  else
2663  {
2664  int *mcv_counts;
2665 
2666  /* Incomplete list; decide how many values are worth keeping */
2667  if (num_mcv > track_cnt)
2668  num_mcv = track_cnt;
2669 
2670  if (num_mcv > 0)
2671  {
2672  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2673  for (i = 0; i < num_mcv; i++)
2674  mcv_counts[i] = track[i].count;
2675 
2676  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2677  stats->stadistinct,
2678  stats->stanullfrac,
2679  samplerows, totalrows);
2680  }
2681  }
2682 
2683  /* Generate MCV slot entry */
2684  if (num_mcv > 0)
2685  {
2686  MemoryContext old_context;
2687  Datum *mcv_values;
2688  float4 *mcv_freqs;
2689 
2690  /* Must copy the target values into anl_context */
2691  old_context = MemoryContextSwitchTo(stats->anl_context);
2692  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2693  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2694  for (i = 0; i < num_mcv; i++)
2695  {
2696  mcv_values[i] = datumCopy(values[track[i].first].value,
2697  stats->attrtype->typbyval,
2698  stats->attrtype->typlen);
2699  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2700  }
2701  MemoryContextSwitchTo(old_context);
2702 
2703  stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2704  stats->staop[slot_idx] = mystats->eqopr;
2705  stats->stacoll[slot_idx] = stats->attrcollid;
2706  stats->stanumbers[slot_idx] = mcv_freqs;
2707  stats->numnumbers[slot_idx] = num_mcv;
2708  stats->stavalues[slot_idx] = mcv_values;
2709  stats->numvalues[slot_idx] = num_mcv;
2710 
2711  /*
2712  * Accept the defaults for stats->statypid and others. They have
2713  * been set before we were called (see vacuum.h)
2714  */
2715  slot_idx++;
2716  }
2717 
2718  /*
2719  * Generate a histogram slot entry if there are at least two distinct
2720  * values not accounted for in the MCV list. (This ensures the
2721  * histogram won't collapse to empty or a singleton.)
2722  */
2723  num_hist = ndistinct - num_mcv;
2724  if (num_hist > num_bins)
2725  num_hist = num_bins + 1;
2726  if (num_hist >= 2)
2727  {
2728  MemoryContext old_context;
2729  Datum *hist_values;
2730  int nvals;
2731  int pos,
2732  posfrac,
2733  delta,
2734  deltafrac;
2735 
2736  /* Sort the MCV items into position order to speed next loop */
2737  qsort_interruptible(track, num_mcv, sizeof(ScalarMCVItem),
2738  compare_mcvs, NULL);
2739 
2740  /*
2741  * Collapse out the MCV items from the values[] array.
2742  *
2743  * Note we destroy the values[] array here... but we don't need it
2744  * for anything more. We do, however, still need values_cnt.
2745  * nvals will be the number of remaining entries in values[].
2746  */
2747  if (num_mcv > 0)
2748  {
2749  int src,
2750  dest;
2751  int j;
2752 
2753  src = dest = 0;
2754  j = 0; /* index of next interesting MCV item */
2755  while (src < values_cnt)
2756  {
2757  int ncopy;
2758 
2759  if (j < num_mcv)
2760  {
2761  int first = track[j].first;
2762 
2763  if (src >= first)
2764  {
2765  /* advance past this MCV item */
2766  src = first + track[j].count;
2767  j++;
2768  continue;
2769  }
2770  ncopy = first - src;
2771  }
2772  else
2773  ncopy = values_cnt - src;
2774  memmove(&values[dest], &values[src],
2775  ncopy * sizeof(ScalarItem));
2776  src += ncopy;
2777  dest += ncopy;
2778  }
2779  nvals = dest;
2780  }
2781  else
2782  nvals = values_cnt;
2783  Assert(nvals >= num_hist);
2784 
2785  /* Must copy the target values into anl_context */
2786  old_context = MemoryContextSwitchTo(stats->anl_context);
2787  hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2788 
2789  /*
2790  * The object of this loop is to copy the first and last values[]
2791  * entries along with evenly-spaced values in between. So the
2792  * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2793  * computing that subscript directly risks integer overflow when
2794  * the stats target is more than a couple thousand. Instead we
2795  * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2796  * the integral and fractional parts of the sum separately.
2797  */
2798  delta = (nvals - 1) / (num_hist - 1);
2799  deltafrac = (nvals - 1) % (num_hist - 1);
2800  pos = posfrac = 0;
2801 
2802  for (i = 0; i < num_hist; i++)
2803  {
2804  hist_values[i] = datumCopy(values[pos].value,
2805  stats->attrtype->typbyval,
2806  stats->attrtype->typlen);
2807  pos += delta;
2808  posfrac += deltafrac;
2809  if (posfrac >= (num_hist - 1))
2810  {
2811  /* fractional part exceeds 1, carry to integer part */
2812  pos++;
2813  posfrac -= (num_hist - 1);
2814  }
2815  }
2816 
2817  MemoryContextSwitchTo(old_context);
2818 
2819  stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2820  stats->staop[slot_idx] = mystats->ltopr;
2821  stats->stacoll[slot_idx] = stats->attrcollid;
2822  stats->stavalues[slot_idx] = hist_values;
2823  stats->numvalues[slot_idx] = num_hist;
2824 
2825  /*
2826  * Accept the defaults for stats->statypid and others. They have
2827  * been set before we were called (see vacuum.h)
2828  */
2829  slot_idx++;
2830  }
2831 
2832  /* Generate a correlation entry if there are multiple values */
2833  if (values_cnt > 1)
2834  {
2835  MemoryContext old_context;
2836  float4 *corrs;
2837  double corr_xsum,
2838  corr_x2sum;
2839 
2840  /* Must copy the target values into anl_context */
2841  old_context = MemoryContextSwitchTo(stats->anl_context);
2842  corrs = (float4 *) palloc(sizeof(float4));
2843  MemoryContextSwitchTo(old_context);
2844 
2845  /*----------
2846  * Since we know the x and y value sets are both
2847  * 0, 1, ..., values_cnt-1
2848  * we have sum(x) = sum(y) =
2849  * (values_cnt-1)*values_cnt / 2
2850  * and sum(x^2) = sum(y^2) =
2851  * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2852  *----------
2853  */
2854  corr_xsum = ((double) (values_cnt - 1)) *
2855  ((double) values_cnt) / 2.0;
2856  corr_x2sum = ((double) (values_cnt - 1)) *
2857  ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2858 
2859  /* And the correlation coefficient reduces to */
2860  corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2861  (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2862 
2863  stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2864  stats->staop[slot_idx] = mystats->ltopr;
2865  stats->stacoll[slot_idx] = stats->attrcollid;
2866  stats->stanumbers[slot_idx] = corrs;
2867  stats->numnumbers[slot_idx] = 1;
2868  slot_idx++;
2869  }
2870  }
2871  else if (nonnull_cnt > 0)
2872  {
2873  /* We found some non-null values, but they were all too wide */
2874  Assert(nonnull_cnt == toowide_cnt);
2875  stats->stats_valid = true;
2876  /* Do the simple null-frac and width stats */
2877  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2878  if (is_varwidth)
2879  stats->stawidth = total_width / (double) nonnull_cnt;
2880  else
2881  stats->stawidth = stats->attrtype->typlen;
2882  /* Assume all too-wide values are distinct, so it's a unique column */
2883  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2884  }
2885  else if (null_cnt > 0)
2886  {
2887  /* We found only nulls; assume the column is entirely null */
2888  stats->stats_valid = true;
2889  stats->stanullfrac = 1.0;
2890  if (is_varwidth)
2891  stats->stawidth = 0; /* "unknown" */
2892  else
2893  stats->stawidth = stats->attrtype->typlen;
2894  stats->stadistinct = 0.0; /* "unknown" */
2895  }
2896 
2897  /* We don't need to bother cleaning up any of our temporary palloc's */
2898 }
static int compare_mcvs(const void *a, const void *b, void *arg)
Definition: analyze.c:2941
static int compare_scalars(const void *a, const void *b, void *arg)
Definition: analyze.c:2910
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:134
bool ssup_nulls_first
Definition: sortsupport.h:75
MemoryContext ssup_cxt
Definition: sortsupport.h:66

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

Referenced by std_typanalyze().

◆ compute_trivial_stats()

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

Definition at line 1948 of file analyze.c.

1952 {
1953  int i;
1954  int null_cnt = 0;
1955  int nonnull_cnt = 0;
1956  double total_width = 0;
1957  bool is_varlena = (!stats->attrtype->typbyval &&
1958  stats->attrtype->typlen == -1);
1959  bool is_varwidth = (!stats->attrtype->typbyval &&
1960  stats->attrtype->typlen < 0);
1961 
1962  for (i = 0; i < samplerows; i++)
1963  {
1964  Datum value;
1965  bool isnull;
1966 
1968 
1969  value = fetchfunc(stats, i, &isnull);
1970 
1971  /* Check for null/nonnull */
1972  if (isnull)
1973  {
1974  null_cnt++;
1975  continue;
1976  }
1977  nonnull_cnt++;
1978 
1979  /*
1980  * If it's a variable-width field, add up widths for average width
1981  * calculation. Note that if the value is toasted, we use the toasted
1982  * width. We don't bother with this calculation if it's a fixed-width
1983  * type.
1984  */
1985  if (is_varlena)
1986  {
1987  total_width += VARSIZE_ANY(DatumGetPointer(value));
1988  }
1989  else if (is_varwidth)
1990  {
1991  /* must be cstring */
1992  total_width += strlen(DatumGetCString(value)) + 1;
1993  }
1994  }
1995 
1996  /* We can only compute average width if we found some non-null values. */
1997  if (nonnull_cnt > 0)
1998  {
1999  stats->stats_valid = true;
2000  /* Do the simple null-frac and width stats */
2001  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2002  if (is_varwidth)
2003  stats->stawidth = total_width / (double) nonnull_cnt;
2004  else
2005  stats->stawidth = stats->attrtype->typlen;
2006  stats->stadistinct = 0.0; /* "unknown" */
2007  }
2008  else if (null_cnt > 0)
2009  {
2010  /* We found only nulls; assume the column is entirely null */
2011  stats->stats_valid = true;
2012  stats->stanullfrac = 1.0;
2013  if (is_varwidth)
2014  stats->stawidth = 0; /* "unknown" */
2015  else
2016  stats->stawidth = stats->attrtype->typlen;
2017  stats->stadistinct = 0.0; /* "unknown" */
2018  }
2019 }

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().

◆ do_analyze_rel()

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

Definition at line 278 of file analyze.c.

282 {
283  int attr_cnt,
284  tcnt,
285  i,
286  ind;
287  Relation *Irel;
288  int nindexes;
289  bool verbose,
290  instrument,
291  hasindex;
292  VacAttrStats **vacattrstats;
293  AnlIndexData *indexdata;
294  int targrows,
295  numrows,
296  minrows;
297  double totalrows,
298  totaldeadrows;
299  HeapTuple *rows;
300  PGRUsage ru0;
301  TimestampTz starttime = 0;
302  MemoryContext caller_context;
303  Oid save_userid;
304  int save_sec_context;
305  int save_nestlevel;
306  WalUsage startwalusage = pgWalUsage;
307  BufferUsage startbufferusage = pgBufferUsage;
308  BufferUsage bufferusage;
309  PgStat_Counter startreadtime = 0;
310  PgStat_Counter startwritetime = 0;
311 
312  verbose = (params->options & VACOPT_VERBOSE) != 0;
313  instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
314  params->log_min_duration >= 0));
315  if (inh)
316  ereport(elevel,
317  (errmsg("analyzing \"%s.%s\" inheritance tree",
319  RelationGetRelationName(onerel))));
320  else
321  ereport(elevel,
322  (errmsg("analyzing \"%s.%s\"",
324  RelationGetRelationName(onerel))));
325 
326  /*
327  * Set up a working context so that we can easily free whatever junk gets
328  * created.
329  */
331  "Analyze",
333  caller_context = MemoryContextSwitchTo(anl_context);
334 
335  /*
336  * Switch to the table owner's userid, so that any index functions are run
337  * as that user. Also lock down security-restricted operations and
338  * arrange to make GUC variable changes local to this command.
339  */
340  GetUserIdAndSecContext(&save_userid, &save_sec_context);
341  SetUserIdAndSecContext(onerel->rd_rel->relowner,
342  save_sec_context | SECURITY_RESTRICTED_OPERATION);
343  save_nestlevel = NewGUCNestLevel();
345 
346  /*
347  * measure elapsed time if called with verbose or if autovacuum logging
348  * requires it
349  */
350  if (instrument)
351  {
352  if (track_io_timing)
353  {
354  startreadtime = pgStatBlockReadTime;
355  startwritetime = pgStatBlockWriteTime;
356  }
357 
358  pg_rusage_init(&ru0);
359  starttime = GetCurrentTimestamp();
360  }
361 
362  /*
363  * Determine which columns to analyze
364  *
365  * Note that system attributes are never analyzed, so we just reject them
366  * at the lookup stage. We also reject duplicate column mentions. (We
367  * could alternatively ignore duplicates, but analyzing a column twice
368  * won't work; we'd end up making a conflicting update in pg_statistic.)
369  */
370  if (va_cols != NIL)
371  {
372  Bitmapset *unique_cols = NULL;
373  ListCell *le;
374 
375  vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
376  sizeof(VacAttrStats *));
377  tcnt = 0;
378  foreach(le, va_cols)
379  {
380  char *col = strVal(lfirst(le));
381 
382  i = attnameAttNum(onerel, col, false);
383  if (i == InvalidAttrNumber)
384  ereport(ERROR,
385  (errcode(ERRCODE_UNDEFINED_COLUMN),
386  errmsg("column \"%s\" of relation \"%s\" does not exist",
387  col, RelationGetRelationName(onerel))));
388  if (bms_is_member(i, unique_cols))
389  ereport(ERROR,
390  (errcode(ERRCODE_DUPLICATE_COLUMN),
391  errmsg("column \"%s\" of relation \"%s\" appears more than once",
392  col, RelationGetRelationName(onerel))));
393  unique_cols = bms_add_member(unique_cols, i);
394 
395  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
396  if (vacattrstats[tcnt] != NULL)
397  tcnt++;
398  }
399  attr_cnt = tcnt;
400  }
401  else
402  {
403  attr_cnt = onerel->rd_att->natts;
404  vacattrstats = (VacAttrStats **)
405  palloc(attr_cnt * sizeof(VacAttrStats *));
406  tcnt = 0;
407  for (i = 1; i <= attr_cnt; i++)
408  {
409  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
410  if (vacattrstats[tcnt] != NULL)
411  tcnt++;
412  }
413  attr_cnt = tcnt;
414  }
415 
416  /*
417  * Open all indexes of the relation, and see if there are any analyzable
418  * columns in the indexes. We do not analyze index columns if there was
419  * an explicit column list in the ANALYZE command, however.
420  *
421  * If we are doing a recursive scan, we don't want to touch the parent's
422  * indexes at all. If we're processing a partitioned table, we need to
423  * know if there are any indexes, but we don't want to process them.
424  */
425  if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
426  {
427  List *idxs = RelationGetIndexList(onerel);
428 
429  Irel = NULL;
430  nindexes = 0;
431  hasindex = idxs != NIL;
432  list_free(idxs);
433  }
434  else if (!inh)
435  {
436  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
437  hasindex = nindexes > 0;
438  }
439  else
440  {
441  Irel = NULL;
442  nindexes = 0;
443  hasindex = false;
444  }
445  indexdata = NULL;
446  if (nindexes > 0)
447  {
448  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
449  for (ind = 0; ind < nindexes; ind++)
450  {
451  AnlIndexData *thisdata = &indexdata[ind];
452  IndexInfo *indexInfo;
453 
454  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
455  thisdata->tupleFract = 1.0; /* fix later if partial */
456  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
457  {
458  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
459 
460  thisdata->vacattrstats = (VacAttrStats **)
461  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
462  tcnt = 0;
463  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
464  {
465  int keycol = indexInfo->ii_IndexAttrNumbers[i];
466 
467  if (keycol == 0)
468  {
469  /* Found an index expression */
470  Node *indexkey;
471 
472  if (indexpr_item == NULL) /* shouldn't happen */
473  elog(ERROR, "too few entries in indexprs list");
474  indexkey = (Node *) lfirst(indexpr_item);
475  indexpr_item = lnext(indexInfo->ii_Expressions,
476  indexpr_item);
477  thisdata->vacattrstats[tcnt] =
478  examine_attribute(Irel[ind], i + 1, indexkey);
479  if (thisdata->vacattrstats[tcnt] != NULL)
480  tcnt++;
481  }
482  }
483  thisdata->attr_cnt = tcnt;
484  }
485  }
486  }
487 
488  /*
489  * Determine how many rows we need to sample, using the worst case from
490  * all analyzable columns. We use a lower bound of 100 rows to avoid
491  * possible overflow in Vitter's algorithm. (Note: that will also be the
492  * target in the corner case where there are no analyzable columns.)
493  */
494  targrows = 100;
495  for (i = 0; i < attr_cnt; i++)
496  {
497  if (targrows < vacattrstats[i]->minrows)
498  targrows = vacattrstats[i]->minrows;
499  }
500  for (ind = 0; ind < nindexes; ind++)
501  {
502  AnlIndexData *thisdata = &indexdata[ind];
503 
504  for (i = 0; i < thisdata->attr_cnt; i++)
505  {
506  if (targrows < thisdata->vacattrstats[i]->minrows)
507  targrows = thisdata->vacattrstats[i]->minrows;
508  }
509  }
510 
511  /*
512  * Look at extended statistics objects too, as those may define custom
513  * statistics target. So we may need to sample more rows and then build
514  * the statistics with enough detail.
515  */
516  minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
517 
518  if (targrows < minrows)
519  targrows = minrows;
520 
521  /*
522  * Acquire the sample rows
523  */
524  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
528  if (inh)
529  numrows = acquire_inherited_sample_rows(onerel, elevel,
530  rows, targrows,
531  &totalrows, &totaldeadrows);
532  else
533  numrows = (*acquirefunc) (onerel, elevel,
534  rows, targrows,
535  &totalrows, &totaldeadrows);
536 
537  /*
538  * Compute the statistics. Temporary results during the calculations for
539  * each column are stored in a child context. The calc routines are
540  * responsible to make sure that whatever they store into the VacAttrStats
541  * structure is allocated in anl_context.
542  */
543  if (numrows > 0)
544  {
545  MemoryContext col_context,
546  old_context;
547 
550 
551  col_context = AllocSetContextCreate(anl_context,
552  "Analyze Column",
554  old_context = MemoryContextSwitchTo(col_context);
555 
556  for (i = 0; i < attr_cnt; i++)
557  {
558  VacAttrStats *stats = vacattrstats[i];
559  AttributeOpts *aopt;
560 
561  stats->rows = rows;
562  stats->tupDesc = onerel->rd_att;
563  stats->compute_stats(stats,
565  numrows,
566  totalrows);
567 
568  /*
569  * If the appropriate flavor of the n_distinct option is
570  * specified, override with the corresponding value.
571  */
572  aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
573  if (aopt != NULL)
574  {
575  float8 n_distinct;
576 
577  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
578  if (n_distinct != 0.0)
579  stats->stadistinct = n_distinct;
580  }
581 
582  MemoryContextReset(col_context);
583  }
584 
585  if (nindexes > 0)
586  compute_index_stats(onerel, totalrows,
587  indexdata, nindexes,
588  rows, numrows,
589  col_context);
590 
591  MemoryContextSwitchTo(old_context);
592  MemoryContextDelete(col_context);
593 
594  /*
595  * Emit the completed stats rows into pg_statistic, replacing any
596  * previous statistics for the target columns. (If there are stats in
597  * pg_statistic for columns we didn't process, we leave them alone.)
598  */
599  update_attstats(RelationGetRelid(onerel), inh,
600  attr_cnt, vacattrstats);
601 
602  for (ind = 0; ind < nindexes; ind++)
603  {
604  AnlIndexData *thisdata = &indexdata[ind];
605 
606  update_attstats(RelationGetRelid(Irel[ind]), false,
607  thisdata->attr_cnt, thisdata->vacattrstats);
608  }
609 
610  /* Build extended statistics (if there are any). */
611  BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
612  attr_cnt, vacattrstats);
613  }
614 
617 
618  /*
619  * Update pages/tuples stats in pg_class ... but not if we're doing
620  * inherited stats.
621  *
622  * We assume that VACUUM hasn't set pg_class.reltuples already, even
623  * during a VACUUM ANALYZE. Although VACUUM often updates pg_class,
624  * exceptions exist. A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command will
625  * never update pg_class entries for index relations. It's also possible
626  * that an individual index's pg_class entry won't be updated during
627  * VACUUM if the index AM returns NULL from its amvacuumcleanup() routine.
628  */
629  if (!inh)
630  {
631  BlockNumber relallvisible;
632 
633  if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
634  visibilitymap_count(onerel, &relallvisible, NULL);
635  else
636  relallvisible = 0;
637 
638  /*
639  * Update pg_class for table relation. CCI first, in case acquirefunc
640  * updated pg_class.
641  */
643  vac_update_relstats(onerel,
644  relpages,
645  totalrows,
646  relallvisible,
647  hasindex,
650  NULL, NULL,
651  in_outer_xact);
652 
653  /* Same for indexes */
654  for (ind = 0; ind < nindexes; ind++)
655  {
656  AnlIndexData *thisdata = &indexdata[ind];
657  double totalindexrows;
658 
659  totalindexrows = ceil(thisdata->tupleFract * totalrows);
660  vac_update_relstats(Irel[ind],
662  totalindexrows,
663  0,
664  false,
667  NULL, NULL,
668  in_outer_xact);
669  }
670  }
671  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
672  {
673  /*
674  * Partitioned tables don't have storage, so we don't set any fields
675  * in their pg_class entries except for reltuples and relhasindex.
676  */
678  vac_update_relstats(onerel, -1, totalrows,
679  0, hasindex, InvalidTransactionId,
681  NULL, NULL,
682  in_outer_xact);
683  }
684 
685  /*
686  * Now report ANALYZE to the cumulative stats system. For regular tables,
687  * we do it only if not doing inherited stats. For partitioned tables, we
688  * only do it for inherited stats. (We're never called for not-inherited
689  * stats on partitioned tables anyway.)
690  *
691  * Reset the changes_since_analyze counter only if we analyzed all
692  * columns; otherwise, there is still work for auto-analyze to do.
693  */
694  if (!inh)
695  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
696  (va_cols == NIL));
697  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
698  pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL));
699 
700  /*
701  * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
702  *
703  * Note that most index AMs perform a no-op as a matter of policy for
704  * amvacuumcleanup() when called in ANALYZE-only mode. The only exception
705  * among core index AMs is GIN/ginvacuumcleanup().
706  */
707  if (!(params->options & VACOPT_VACUUM))
708  {
709  for (ind = 0; ind < nindexes; ind++)
710  {
711  IndexBulkDeleteResult *stats;
712  IndexVacuumInfo ivinfo;
713 
714  ivinfo.index = Irel[ind];
715  ivinfo.heaprel = onerel;
716  ivinfo.analyze_only = true;
717  ivinfo.estimated_count = true;
718  ivinfo.message_level = elevel;
719  ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
720  ivinfo.strategy = vac_strategy;
721 
722  stats = index_vacuum_cleanup(&ivinfo, NULL);
723 
724  if (stats)
725  pfree(stats);
726  }
727  }
728 
729  /* Done with indexes */
730  vac_close_indexes(nindexes, Irel, NoLock);
731 
732  /* Log the action if appropriate */
733  if (instrument)
734  {
735  TimestampTz endtime = GetCurrentTimestamp();
736 
737  if (verbose || params->log_min_duration == 0 ||
738  TimestampDifferenceExceeds(starttime, endtime,
739  params->log_min_duration))
740  {
741  long delay_in_ms;
742  WalUsage walusage;
743  double read_rate = 0;
744  double write_rate = 0;
745  char *msgfmt;
747  int64 total_blks_hit;
748  int64 total_blks_read;
749  int64 total_blks_dirtied;
750 
751  memset(&bufferusage, 0, sizeof(BufferUsage));
752  BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
753  memset(&walusage, 0, sizeof(WalUsage));
754  WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
755 
756  total_blks_hit = bufferusage.shared_blks_hit +
757  bufferusage.local_blks_hit;
758  total_blks_read = bufferusage.shared_blks_read +
759  bufferusage.local_blks_read;
760  total_blks_dirtied = bufferusage.shared_blks_dirtied +
761  bufferusage.local_blks_dirtied;
762 
763  /*
764  * We do not expect an analyze to take > 25 days and it simplifies
765  * things a bit to use TimestampDifferenceMilliseconds.
766  */
767  delay_in_ms = TimestampDifferenceMilliseconds(starttime, endtime);
768 
769  /*
770  * Note that we are reporting these read/write rates in the same
771  * manner as VACUUM does, which means that while the 'average read
772  * rate' here actually corresponds to page misses and resulting
773  * reads which are also picked up by track_io_timing, if enabled,
774  * the 'average write rate' is actually talking about the rate of
775  * pages being dirtied, not being written out, so it's typical to
776  * have a non-zero 'avg write rate' while I/O timings only reports
777  * reads.
778  *
779  * It's not clear that an ANALYZE will ever result in
780  * FlushBuffer() being called, but we track and support reporting
781  * on I/O write time in case that changes as it's practically free
782  * to do so anyway.
783  */
784 
785  if (delay_in_ms > 0)
786  {
787  read_rate = (double) BLCKSZ * total_blks_read /
788  (1024 * 1024) / (delay_in_ms / 1000.0);
789  write_rate = (double) BLCKSZ * total_blks_dirtied /
790  (1024 * 1024) / (delay_in_ms / 1000.0);
791  }
792 
793  /*
794  * We split this up so we don't emit empty I/O timing values when
795  * track_io_timing isn't enabled.
796  */
797 
799 
801  msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
802  else
803  msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
804 
805  appendStringInfo(&buf, msgfmt,
808  RelationGetRelationName(onerel));
809  if (track_io_timing)
810  {
811  double read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
812  double write_ms = (double) (pgStatBlockWriteTime - startwritetime) / 1000;
813 
814  appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
815  read_ms, write_ms);
816  }
817  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
818  read_rate, write_rate);
819  appendStringInfo(&buf, _("buffer usage: %lld hits, %lld reads, %lld dirtied\n"),
820  (long long) total_blks_hit,
821  (long long) total_blks_read,
822  (long long) total_blks_dirtied);
824  _("WAL usage: %lld records, %lld full page images, %llu bytes\n"),
825  (long long) walusage.wal_records,
826  (long long) walusage.wal_fpi,
827  (unsigned long long) walusage.wal_bytes);
828  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
829 
830  ereport(verbose ? INFO : LOG,
831  (errmsg_internal("%s", buf.data)));
832 
833  pfree(buf.data);
834  }
835  }
836 
837  /* Roll back any GUC changes executed by index functions */
838  AtEOXact_GUC(false, save_nestlevel);
839 
840  /* Restore userid and security context */
841  SetUserIdAndSecContext(save_userid, save_sec_context);
842 
843  /* Restore current context and release memory */
844  MemoryContextSwitchTo(caller_context);
846  anl_context = NULL;
847 }
#define InvalidAttrNumber
Definition: attnum.h:23
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:131
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1756
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1780
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
bool track_io_timing
Definition: bufmgr.c:143
double float8
Definition: c.h:584
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1777
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1634
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1370
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition: analyze.c:1024
static void compute_index_stats(Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
Definition: analyze.c:853
int64 TimestampTz
Definition: timestamp.h:39
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3187
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode(int sqlerrcode)
Definition: elog.c:853
#define _(x)
Definition: elog.c:90
#define LOG
Definition: elog.h:31
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
int ComputeExtStatisticsRows(Relation onerel, int natts, VacAttrStats **vacattrstats)
void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
Oid MyDatabaseId
Definition: globals.c:93
int NewGUCNestLevel(void)
Definition: guc.c:2235
void RestrictSearchPath(void)
Definition: guc.c:2246
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2262
int verbose
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2425
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition: indexam.c:771
WalUsage pgWalUsage
Definition: instrument.c:22
void WalUsageAccumDiff(WalUsage *dst, const WalUsage *add, const WalUsage *sub)
Definition: instrument.c:286
BufferUsage pgBufferUsage
Definition: instrument.c:20
void BufferUsageAccumDiff(BufferUsage *dst, const BufferUsage *add, const BufferUsage *sub)
Definition: instrument.c:248
void list_free(List *list)
Definition: list.c:1546
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc0(Size size)
Definition: mcxt.c:1347
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:373
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:312
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:667
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:674
#define InvalidMultiXactId
Definition: multixact.h:24
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define lfirst(lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
static char * buf
Definition: pg_test_fsync.c:72
int64 PgStat_Counter
Definition: pgstat.h:120
PgStat_Counter pgStatBlockReadTime
PgStat_Counter pgStatBlockWriteTime
void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
#define PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE
Definition: progress.h:55
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH
Definition: progress.h:52
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:41
#define PROGRESS_ANALYZE_PHASE_COMPUTE_STATS
Definition: progress.h:53
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS
Definition: progress.h:51
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4766
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:94
void initStringInfo(StringInfo str)
Definition: stringinfo.c:56
float8 n_distinct
Definition: attoptcache.h:22
float8 n_distinct_inherited
Definition: attoptcache.h:23
int64 shared_blks_dirtied
Definition: instrument.h:28
int64 local_blks_hit
Definition: instrument.h:30
int64 shared_blks_read
Definition: instrument.h:27
int64 local_blks_read
Definition: instrument.h:31
int64 local_blks_dirtied
Definition: instrument.h:32
int64 shared_blks_hit
Definition: instrument.h:26
int ii_NumIndexAttrs
Definition: execnodes.h:186
List * ii_Expressions
Definition: execnodes.h:189
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:188
Relation index
Definition: genam.h:48
double num_heap_tuples
Definition: genam.h:54
bool analyze_only
Definition: genam.h:50
BufferAccessStrategy strategy
Definition: genam.h:55
Relation heaprel
Definition: genam.h:49
int message_level
Definition: genam.h:53
bool estimated_count
Definition: genam.h:52
Definition: nodes.h:129
TupleDesc rd_att
Definition: rel.h:112
HeapTuple * rows
Definition: vacuum.h:172
int minrows
Definition: vacuum.h:137
TupleDesc tupDesc
Definition: vacuum.h:173
uint64 wal_bytes
Definition: instrument.h:55
int64 wal_fpi
Definition: instrument.h:54
int64 wal_records
Definition: instrument.h:53
#define InvalidTransactionId
Definition: transam.h:31
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:2298
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool *frozenxid_updated, bool *minmulti_updated, bool in_outer_xact)
Definition: vacuum.c:1410
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2341
#define strVal(v)
Definition: value.h:82
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)

References _, AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AmAutoVacuumWorkerProcess, IndexVacuumInfo::analyze_only, anl_context, appendStringInfo(), AtEOXact_GUC(), attnameAttNum(), AnlIndexData::attr_cnt, bms_add_member(), bms_is_member(), buf, BufferUsageAccumDiff(), BuildIndexInfo(), BuildRelationExtStatistics(), CommandCounterIncrement(), compute_index_stats(), VacAttrStats::compute_stats, ComputeExtStatisticsRows(), CurrentMemoryContext, elog, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, IndexVacuumInfo::estimated_count, examine_attribute(), get_attribute_options(), get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GetUserIdAndSecContext(), IndexVacuumInfo::heaprel, i, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexVacuumInfo::index, index_vacuum_cleanup(), AnlIndexData::indexInfo, INFO, initStringInfo(), InvalidAttrNumber, InvalidMultiXactId, InvalidTransactionId, lfirst, list_free(), list_head(), list_length(), lnext(), BufferUsage::local_blks_dirtied, BufferUsage::local_blks_hit, BufferUsage::local_blks_read, LOG, VacuumParams::log_min_duration, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), IndexVacuumInfo::message_level, VacAttrStats::minrows, MyDatabaseId, AttributeOpts::n_distinct, AttributeOpts::n_distinct_inherited, TupleDescData::natts, NewGUCNestLevel(), NIL, NoLock, IndexVacuumInfo::num_heap_tuples, VacuumParams::options, palloc(), palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgBufferUsage, pgstat_progress_update_param(), pgstat_report_analyze(), pgStatBlockReadTime, pgStatBlockWriteTime, pgWalUsage, PROGRESS_ANALYZE_PHASE, PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS, PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH, PROGRESS_ANALYZE_PHASE_COMPUTE_STATS, PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE, RelationData::rd_att, RelationData::rd_id, RelationData::rd_rel, RelationGetIndexList(), RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, RestrictSearchPath(), VacAttrStats::rows, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), BufferUsage::shared_blks_dirtied, BufferUsage::shared_blks_hit, BufferUsage::shared_blks_read, VacAttrStats::stadistinct, std_fetch_func(), IndexVacuumInfo::strategy, strVal, TimestampDifferenceExceeds(), TimestampDifferenceMilliseconds(), track_io_timing, VacAttrStats::tupattnum, VacAttrStats::tupDesc, AnlIndexData::tupleFract, update_attstats(), vac_close_indexes(), vac_open_indexes(), vac_strategy, vac_update_relstats(), AnlIndexData::vacattrstats, VACOPT_VACUUM, VACOPT_VERBOSE, verbose, visibilitymap_count(), WalUsage::wal_bytes, WalUsage::wal_fpi, WalUsage::wal_records, and WalUsageAccumDiff().

Referenced by analyze_rel().

◆ examine_attribute()

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

Definition at line 1024 of file analyze.c.

1025 {
1026  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1027  int attstattarget;
1028  HeapTuple atttuple;
1029  Datum dat;
1030  bool isnull;
1031  HeapTuple typtuple;
1032  VacAttrStats *stats;
1033  int i;
1034  bool ok;
1035 
1036  /* Never analyze dropped columns */
1037  if (attr->attisdropped)
1038  return NULL;
1039 
1040  /*
1041  * Get attstattarget value. Set to -1 if null. (Analyze functions expect
1042  * -1 to mean use default_statistics_target; see for example
1043  * std_typanalyze.)
1044  */
1045  atttuple = SearchSysCache2(ATTNUM, ObjectIdGetDatum(RelationGetRelid(onerel)), Int16GetDatum(attnum));
1046  if (!HeapTupleIsValid(atttuple))
1047  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1048  attnum, RelationGetRelid(onerel));
1049  dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
1050  attstattarget = isnull ? -1 : DatumGetInt16(dat);
1051  ReleaseSysCache(atttuple);
1052 
1053  /* Don't analyze column if user has specified not to */
1054  if (attstattarget == 0)
1055  return NULL;
1056 
1057  /*
1058  * Create the VacAttrStats struct.
1059  */
1060  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
1061  stats->attstattarget = attstattarget;
1062 
1063  /*
1064  * When analyzing an expression index, believe the expression tree's type
1065  * not the column datatype --- the latter might be the opckeytype storage
1066  * type of the opclass, which is not interesting for our purposes. (Note:
1067  * if we did anything with non-expression index columns, we'd need to
1068  * figure out where to get the correct type info from, but for now that's
1069  * not a problem.) It's not clear whether anyone will care about the
1070  * typmod, but we store that too just in case.
1071  */
1072  if (index_expr)
1073  {
1074  stats->attrtypid = exprType(index_expr);
1075  stats->attrtypmod = exprTypmod(index_expr);
1076 
1077  /*
1078  * If a collation has been specified for the index column, use that in
1079  * preference to anything else; but if not, fall back to whatever we
1080  * can get from the expression.
1081  */
1082  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1083  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1084  else
1085  stats->attrcollid = exprCollation(index_expr);
1086  }
1087  else
1088  {
1089  stats->attrtypid = attr->atttypid;
1090  stats->attrtypmod = attr->atttypmod;
1091  stats->attrcollid = attr->attcollation;
1092  }
1093 
1094  typtuple = SearchSysCacheCopy1(TYPEOID,
1095  ObjectIdGetDatum(stats->attrtypid));
1096  if (!HeapTupleIsValid(typtuple))
1097  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1098  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
1099  stats->anl_context = anl_context;
1100  stats->tupattnum = attnum;
1101 
1102  /*
1103  * The fields describing the stats->stavalues[n] element types default to
1104  * the type of the data being analyzed, but the type-specific typanalyze
1105  * function can change them if it wants to store something else.
1106  */
1107  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1108  {
1109  stats->statypid[i] = stats->attrtypid;
1110  stats->statyplen[i] = stats->attrtype->typlen;
1111  stats->statypbyval[i] = stats->attrtype->typbyval;
1112  stats->statypalign[i] = stats->attrtype->typalign;
1113  }
1114 
1115  /*
1116  * Call the type-specific typanalyze function. If none is specified, use
1117  * std_typanalyze().
1118  */
1119  if (OidIsValid(stats->attrtype->typanalyze))
1120  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1121  PointerGetDatum(stats)));
1122  else
1123  ok = std_typanalyze(stats);
1124 
1125  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1126  {
1127  heap_freetuple(typtuple);
1128  pfree(stats);
1129  return NULL;
1130  }
1131 
1132  return stats;
1133 }
#define OidIsValid(objectId)
Definition: c.h:729
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1870
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:679
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:162
Oid * rd_indcollation
Definition: rel.h:217
int32 attrtypmod
Definition: vacuum.h:127
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:162
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:165
Oid attrtypid
Definition: vacuum.h:126
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:164
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:163
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:232
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:91
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References anl_context, VacAttrStats::anl_context, attnum, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::attstattarget, VacAttrStats::compute_stats, DatumGetBool(), DatumGetInt16(), elog, ERROR, exprCollation(), exprType(), exprTypmod(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, i, Int16GetDatum(), VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0(), pfree(), PointerGetDatum(), RelationData::rd_att, RelationData::rd_indcollation, RelationGetRelid, ReleaseSysCache(), SearchSysCache2(), SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), SysCacheGetAttr(), VacAttrStats::tupattnum, and TupleDescAttr.

Referenced by do_analyze_rel().

◆ ind_fetch_func()

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

Definition at line 1793 of file analyze.c.

1794 {
1795  int i;
1796 
1797  /* exprvals and exprnulls are already offset for proper column */
1798  i = rownum * stats->rowstride;
1799  *isNull = stats->exprnulls[i];
1800  return stats->exprvals[i];
1801 }

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

Referenced by compute_index_stats().

◆ std_fetch_func()

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

Definition at line 1777 of file analyze.c.

1778 {
1779  int attnum = stats->tupattnum;
1780  HeapTuple tuple = stats->rows[rownum];
1781  TupleDesc tupDesc = stats->tupDesc;
1782 
1783  return heap_getattr(tuple, attnum, tupDesc, isNull);
1784 }
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792

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

Referenced by do_analyze_rel().

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

Definition at line 1870 of file analyze.c.

1871 {
1872  Oid ltopr;
1873  Oid eqopr;
1874  StdAnalyzeData *mystats;
1875 
1876  /* If the attstattarget column is negative, use the default value */
1877  if (stats->attstattarget < 0)
1879 
1880  /* Look for default "<" and "=" operators for column's type */
1882  false, false, false,
1883  &ltopr, &eqopr, NULL,
1884  NULL);
1885 
1886  /* Save the operator info for compute_stats routines */
1887  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1888  mystats->eqopr = eqopr;
1889  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1890  mystats->ltopr = ltopr;
1891  stats->extra_data = mystats;
1892 
1893  /*
1894  * Determine which standard statistics algorithm to use
1895  */
1896  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1897  {
1898  /* Seems to be a scalar datatype */
1900  /*--------------------
1901  * The following choice of minrows is based on the paper
1902  * "Random sampling for histogram construction: how much is enough?"
1903  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1904  * Proceedings of ACM SIGMOD International Conference on Management
1905  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1906  * says that for table size n, histogram size k, maximum relative
1907  * error in bin size f, and error probability gamma, the minimum
1908  * random sample size is
1909  * r = 4 * k * ln(2*n/gamma) / f^2
1910  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1911  * r = 305.82 * k
1912  * Note that because of the log function, the dependence on n is
1913  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1914  * bin size error with probability 0.99. So there's no real need to
1915  * scale for n, which is a good thing because we don't necessarily
1916  * know it at this point.
1917  *--------------------
1918  */
1919  stats->minrows = 300 * stats->attstattarget;
1920  }
1921  else if (OidIsValid(eqopr))
1922  {
1923  /* We can still recognize distinct values */
1925  /* Might as well use the same minrows as above */
1926  stats->minrows = 300 * stats->attstattarget;
1927  }
1928  else
1929  {
1930  /* Can't do much but the trivial stuff */
1932  /* Might as well use the same minrows as above */
1933  stats->minrows = 300 * stats->attstattarget;
1934  }
1935 
1936  return true;
1937 }
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2381
int default_statistics_target
Definition: analyze.c:71
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2038
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1948
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
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:180
#define InvalidOid
Definition: postgres_ext.h:36

References VacAttrStats::attrtypid, VacAttrStats::attstattarget, 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(), examine_attribute(), and examine_expression().

◆ update_attstats()

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

Definition at line 1634 of file analyze.c.

1635 {
1636  Relation sd;
1637  int attno;
1638  CatalogIndexState indstate = NULL;
1639 
1640  if (natts <= 0)
1641  return; /* nothing to do */
1642 
1643  sd = table_open(StatisticRelationId, RowExclusiveLock);
1644 
1645  for (attno = 0; attno < natts; attno++)
1646  {
1647  VacAttrStats *stats = vacattrstats[attno];
1648  HeapTuple stup,
1649  oldtup;
1650  int i,
1651  k,
1652  n;
1653  Datum values[Natts_pg_statistic];
1654  bool nulls[Natts_pg_statistic];
1655  bool replaces[Natts_pg_statistic];
1656 
1657  /* Ignore attr if we weren't able to collect stats */
1658  if (!stats->stats_valid)
1659  continue;
1660 
1661  /*
1662  * Construct a new pg_statistic tuple
1663  */
1664  for (i = 0; i < Natts_pg_statistic; ++i)
1665  {
1666  nulls[i] = false;
1667  replaces[i] = true;
1668  }
1669 
1670  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1671  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
1672  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1673  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1674  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1675  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1676  i = Anum_pg_statistic_stakind1 - 1;
1677  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1678  {
1679  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1680  }
1681  i = Anum_pg_statistic_staop1 - 1;
1682  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1683  {
1684  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1685  }
1686  i = Anum_pg_statistic_stacoll1 - 1;
1687  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1688  {
1689  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1690  }
1691  i = Anum_pg_statistic_stanumbers1 - 1;
1692  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1693  {
1694  int nnum = stats->numnumbers[k];
1695 
1696  if (nnum > 0)
1697  {
1698  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1699  ArrayType *arry;
1700 
1701  for (n = 0; n < nnum; n++)
1702  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1703  arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
1704  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1705  }
1706  else
1707  {
1708  nulls[i] = true;
1709  values[i++] = (Datum) 0;
1710  }
1711  }
1712  i = Anum_pg_statistic_stavalues1 - 1;
1713  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1714  {
1715  if (stats->numvalues[k] > 0)
1716  {
1717  ArrayType *arry;
1718 
1719  arry = construct_array(stats->stavalues[k],
1720  stats->numvalues[k],
1721  stats->statypid[k],
1722  stats->statyplen[k],
1723  stats->statypbyval[k],
1724  stats->statypalign[k]);
1725  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1726  }
1727  else
1728  {
1729  nulls[i] = true;
1730  values[i++] = (Datum) 0;
1731  }
1732  }
1733 
1734  /* Is there already a pg_statistic tuple for this attribute? */
1735  oldtup = SearchSysCache3(STATRELATTINH,
1736  ObjectIdGetDatum(relid),
1737  Int16GetDatum(stats->tupattnum),
1738  BoolGetDatum(inh));
1739 
1740  /* Open index information when we know we need it */
1741  if (indstate == NULL)
1742  indstate = CatalogOpenIndexes(sd);
1743 
1744  if (HeapTupleIsValid(oldtup))
1745  {
1746  /* Yes, replace it */
1747  stup = heap_modify_tuple(oldtup,
1748  RelationGetDescr(sd),
1749  values,
1750  nulls,
1751  replaces);
1752  ReleaseSysCache(oldtup);
1753  CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
1754  }
1755  else
1756  {
1757  /* No, insert new tuple */
1758  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1759  CatalogTupleInsertWithInfo(sd, stup, indstate);
1760  }
1761 
1762  heap_freetuple(stup);
1763  }
1764 
1765  if (indstate != NULL)
1766  CatalogCloseIndexes(indstate);
1768 }
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3381
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3361
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void CatalogTupleInsertWithInfo(Relation heapRel, HeapTuple tup, CatalogIndexState indstate)
Definition: indexing.c:256
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
void CatalogTupleUpdateWithInfo(Relation heapRel, ItemPointer otid, HeapTuple tup, CatalogIndexState indstate)
Definition: indexing.c:337
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:475
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:243

References BoolGetDatum(), CatalogCloseIndexes(), CatalogOpenIndexes(), CatalogTupleInsertWithInfo(), CatalogTupleUpdateWithInfo(), construct_array(), construct_array_builtin(), Float4GetDatum(), heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, i, Int16GetDatum(), Int32GetDatum(), VacAttrStats::numnumbers, VacAttrStats::numvalues, ObjectIdGetDatum(), palloc(), PointerGetDatum(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3(), VacAttrStats::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_NUM_SLOTS, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, HeapTupleData::t_self, table_close(), table_open(), VacAttrStats::tupattnum, and values.

Referenced by do_analyze_rel().

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 74 of file analyze.c.

Referenced by compute_index_stats(), do_analyze_rel(), and examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 75 of file analyze.c.

Referenced by acquire_sample_rows(), analyze_rel(), and do_analyze_rel().