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 "postmaster/autovacuum.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/spccache.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 1819 of file analyze.c.

◆ swapInt

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

Definition at line 1818 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1816 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 1363 of file analyze.c.

1366 {
1367  List *tableOIDs;
1368  Relation *rels;
1369  AcquireSampleRowsFunc *acquirefuncs;
1370  double *relblocks;
1371  double totalblocks;
1372  int numrows,
1373  nrels,
1374  i;
1375  ListCell *lc;
1376  bool has_child;
1377 
1378  /* Initialize output parameters to zero now, in case we exit early */
1379  *totalrows = 0;
1380  *totaldeadrows = 0;
1381 
1382  /*
1383  * Find all members of inheritance set. We only need AccessShareLock on
1384  * the children.
1385  */
1386  tableOIDs =
1388 
1389  /*
1390  * Check that there's at least one descendant, else fail. This could
1391  * happen despite analyze_rel's relhassubclass check, if table once had a
1392  * child but no longer does. In that case, we can clear the
1393  * relhassubclass field so as not to make the same mistake again later.
1394  * (This is safe because we hold ShareUpdateExclusiveLock.)
1395  */
1396  if (list_length(tableOIDs) < 2)
1397  {
1398  /* CCI because we already updated the pg_class row in this command */
1400  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1401  ereport(elevel,
1402  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1404  RelationGetRelationName(onerel))));
1405  return 0;
1406  }
1407 
1408  /*
1409  * Identify acquirefuncs to use, and count blocks in all the relations.
1410  * The result could overflow BlockNumber, so we use double arithmetic.
1411  */
1412  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1413  acquirefuncs = (AcquireSampleRowsFunc *)
1414  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1415  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1416  totalblocks = 0;
1417  nrels = 0;
1418  has_child = false;
1419  foreach(lc, tableOIDs)
1420  {
1421  Oid childOID = lfirst_oid(lc);
1422  Relation childrel;
1423  AcquireSampleRowsFunc acquirefunc = NULL;
1424  BlockNumber relpages = 0;
1425 
1426  /* We already got the needed lock */
1427  childrel = table_open(childOID, NoLock);
1428 
1429  /* Ignore if temp table of another backend */
1430  if (RELATION_IS_OTHER_TEMP(childrel))
1431  {
1432  /* ... but release the lock on it */
1433  Assert(childrel != onerel);
1434  table_close(childrel, AccessShareLock);
1435  continue;
1436  }
1437 
1438  /* Check table type (MATVIEW can't happen, but might as well allow) */
1439  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1440  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1441  {
1442  /* Regular table, so use the regular row acquisition function */
1443  acquirefunc = acquire_sample_rows;
1444  relpages = RelationGetNumberOfBlocks(childrel);
1445  }
1446  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1447  {
1448  /*
1449  * For a foreign table, call the FDW's hook function to see
1450  * whether it supports analysis.
1451  */
1452  FdwRoutine *fdwroutine;
1453  bool ok = false;
1454 
1455  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1456 
1457  if (fdwroutine->AnalyzeForeignTable != NULL)
1458  ok = fdwroutine->AnalyzeForeignTable(childrel,
1459  &acquirefunc,
1460  &relpages);
1461 
1462  if (!ok)
1463  {
1464  /* ignore, but release the lock on it */
1465  Assert(childrel != onerel);
1466  table_close(childrel, AccessShareLock);
1467  continue;
1468  }
1469  }
1470  else
1471  {
1472  /*
1473  * ignore, but release the lock on it. don't try to unlock the
1474  * passed-in relation
1475  */
1476  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1477  if (childrel != onerel)
1478  table_close(childrel, AccessShareLock);
1479  else
1480  table_close(childrel, NoLock);
1481  continue;
1482  }
1483 
1484  /* OK, we'll process this child */
1485  has_child = true;
1486  rels[nrels] = childrel;
1487  acquirefuncs[nrels] = acquirefunc;
1488  relblocks[nrels] = (double) relpages;
1489  totalblocks += (double) relpages;
1490  nrels++;
1491  }
1492 
1493  /*
1494  * If we don't have at least one child table to consider, fail. If the
1495  * relation is a partitioned table, it's not counted as a child table.
1496  */
1497  if (!has_child)
1498  {
1499  ereport(elevel,
1500  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1502  RelationGetRelationName(onerel))));
1503  return 0;
1504  }
1505 
1506  /*
1507  * Now sample rows from each relation, proportionally to its fraction of
1508  * the total block count. (This might be less than desirable if the child
1509  * rels have radically different free-space percentages, but it's not
1510  * clear that it's worth working harder.)
1511  */
1513  nrels);
1514  numrows = 0;
1515  for (i = 0; i < nrels; i++)
1516  {
1517  Relation childrel = rels[i];
1518  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1519  double childblocks = relblocks[i];
1520 
1521  /*
1522  * Report progress. The sampling function will normally report blocks
1523  * done/total, but we need to reset them to 0 here, so that they don't
1524  * show an old value until that.
1525  */
1526  {
1527  const int progress_index[] = {
1531  };
1532  const int64 progress_vals[] = {
1533  RelationGetRelid(childrel),
1534  0,
1535  0,
1536  };
1537 
1538  pgstat_progress_update_multi_param(3, progress_index, progress_vals);
1539  }
1540 
1541  if (childblocks > 0)
1542  {
1543  int childtargrows;
1544 
1545  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1546  /* Make sure we don't overrun due to roundoff error */
1547  childtargrows = Min(childtargrows, targrows - numrows);
1548  if (childtargrows > 0)
1549  {
1550  int childrows;
1551  double trows,
1552  tdrows;
1553 
1554  /* Fetch a random sample of the child's rows */
1555  childrows = (*acquirefunc) (childrel, elevel,
1556  rows + numrows, childtargrows,
1557  &trows, &tdrows);
1558 
1559  /* We may need to convert from child's rowtype to parent's */
1560  if (childrows > 0 &&
1561  !equalRowTypes(RelationGetDescr(childrel),
1562  RelationGetDescr(onerel)))
1563  {
1564  TupleConversionMap *map;
1565 
1566  map = convert_tuples_by_name(RelationGetDescr(childrel),
1567  RelationGetDescr(onerel));
1568  if (map != NULL)
1569  {
1570  int j;
1571 
1572  for (j = 0; j < childrows; j++)
1573  {
1574  HeapTuple newtup;
1575 
1576  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1577  heap_freetuple(rows[numrows + j]);
1578  rows[numrows + j] = newtup;
1579  }
1580  free_conversion_map(map);
1581  }
1582  }
1583 
1584  /* And add to counts */
1585  numrows += childrows;
1586  *totalrows += trows;
1587  *totaldeadrows += tdrows;
1588  }
1589  }
1590 
1591  /*
1592  * Note: we cannot release the child-table locks, since we may have
1593  * pointers to their TOAST tables in the sampled rows.
1594  */
1595  table_close(childrel, NoLock);
1597  i + 1);
1598  }
1599 
1600  return numrows;
1601 }
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:1004
#define Assert(condition)
Definition: c.h:858
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1176
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:74
int i
Definition: isn.c:73
#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:3480
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 1176 of file analyze.c.

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

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

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

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

1136 {
1137  BlockSamplerData *bs = callback_private_data;
1138 
1140 }
#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 2934 of file analyze.c.

2935 {
2936  int da = ((const ScalarMCVItem *) a)->first;
2937  int db = ((const ScalarMCVItem *) b)->first;
2938 
2939  return da - db;
2940 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69

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

1334 {
1335  HeapTuple ha = *(const HeapTuple *) a;
1336  HeapTuple hb = *(const HeapTuple *) b;
1341 
1342  if (ba < bb)
1343  return -1;
1344  if (ba > bb)
1345  return 1;
1346  if (oa < ob)
1347  return -1;
1348  if (oa > ob)
1349  return 1;
1350  return 0;
1351 }
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 2903 of file analyze.c.

2904 {
2905  Datum da = ((const ScalarItem *) a)->value;
2906  int ta = ((const ScalarItem *) a)->tupno;
2907  Datum db = ((const ScalarItem *) b)->value;
2908  int tb = ((const ScalarItem *) b)->tupno;
2910  int compare;
2911 
2912  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2913  if (compare != 0)
2914  return compare;
2915 
2916  /*
2917  * The two datums are equal, so update cxt->tupnoLink[].
2918  */
2919  if (cxt->tupnoLink[ta] < tb)
2920  cxt->tupnoLink[ta] = tb;
2921  if (cxt->tupnoLink[tb] < ta)
2922  cxt->tupnoLink[tb] = ta;
2923 
2924  /*
2925  * For equal datums, sort by tupno
2926  */
2927  return ta - tb;
2928 }
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:1832

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

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

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

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

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

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

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

Referenced by analyze_rel().

◆ examine_attribute()

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

Definition at line 1017 of file analyze.c.

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

1787 {
1788  int i;
1789 
1790  /* exprvals and exprnulls are already offset for proper column */
1791  i = rownum * stats->rowstride;
1792  *isNull = stats->exprnulls[i];
1793  return stats->exprvals[i];
1794 }

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

1771 {
1772  int attnum = stats->tupattnum;
1773  HeapTuple tuple = stats->rows[rownum];
1774  TupleDesc tupDesc = stats->tupDesc;
1775 
1776  return heap_getattr(tuple, attnum, tupDesc, isNull);
1777 }
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 1863 of file analyze.c.

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

1628 {
1629  Relation sd;
1630  int attno;
1631  CatalogIndexState indstate = NULL;
1632 
1633  if (natts <= 0)
1634  return; /* nothing to do */
1635 
1636  sd = table_open(StatisticRelationId, RowExclusiveLock);
1637 
1638  for (attno = 0; attno < natts; attno++)
1639  {
1640  VacAttrStats *stats = vacattrstats[attno];
1641  HeapTuple stup,
1642  oldtup;
1643  int i,
1644  k,
1645  n;
1646  Datum values[Natts_pg_statistic];
1647  bool nulls[Natts_pg_statistic];
1648  bool replaces[Natts_pg_statistic];
1649 
1650  /* Ignore attr if we weren't able to collect stats */
1651  if (!stats->stats_valid)
1652  continue;
1653 
1654  /*
1655  * Construct a new pg_statistic tuple
1656  */
1657  for (i = 0; i < Natts_pg_statistic; ++i)
1658  {
1659  nulls[i] = false;
1660  replaces[i] = true;
1661  }
1662 
1663  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1664  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
1665  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1666  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1667  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1668  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1669  i = Anum_pg_statistic_stakind1 - 1;
1670  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1671  {
1672  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1673  }
1674  i = Anum_pg_statistic_staop1 - 1;
1675  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1676  {
1677  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1678  }
1679  i = Anum_pg_statistic_stacoll1 - 1;
1680  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1681  {
1682  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1683  }
1684  i = Anum_pg_statistic_stanumbers1 - 1;
1685  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1686  {
1687  int nnum = stats->numnumbers[k];
1688 
1689  if (nnum > 0)
1690  {
1691  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1692  ArrayType *arry;
1693 
1694  for (n = 0; n < nnum; n++)
1695  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1696  arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
1697  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1698  }
1699  else
1700  {
1701  nulls[i] = true;
1702  values[i++] = (Datum) 0;
1703  }
1704  }
1705  i = Anum_pg_statistic_stavalues1 - 1;
1706  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1707  {
1708  if (stats->numvalues[k] > 0)
1709  {
1710  ArrayType *arry;
1711 
1712  arry = construct_array(stats->stavalues[k],
1713  stats->numvalues[k],
1714  stats->statypid[k],
1715  stats->statyplen[k],
1716  stats->statypbyval[k],
1717  stats->statypalign[k]);
1718  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1719  }
1720  else
1721  {
1722  nulls[i] = true;
1723  values[i++] = (Datum) 0;
1724  }
1725  }
1726 
1727  /* Is there already a pg_statistic tuple for this attribute? */
1728  oldtup = SearchSysCache3(STATRELATTINH,
1729  ObjectIdGetDatum(relid),
1730  Int16GetDatum(stats->tupattnum),
1731  BoolGetDatum(inh));
1732 
1733  /* Open index information when we know we need it */
1734  if (indstate == NULL)
1735  indstate = CatalogOpenIndexes(sd);
1736 
1737  if (HeapTupleIsValid(oldtup))
1738  {
1739  /* Yes, replace it */
1740  stup = heap_modify_tuple(oldtup,
1741  RelationGetDescr(sd),
1742  values,
1743  nulls,
1744  replaces);
1745  ReleaseSysCache(oldtup);
1746  CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
1747  }
1748  else
1749  {
1750  /* No, insert new tuple */
1751  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1752  CatalogTupleInsertWithInfo(sd, stup, indstate);
1753  }
1754 
1755  heap_freetuple(stup);
1756  }
1757 
1758  if (indstate != NULL)
1759  CatalogCloseIndexes(indstate);
1761 }
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:240

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 76 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 77 of file analyze.c.

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