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/sysattr.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/catalog.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_statistic_ext.h"
#include "commands/dbcommands.h"
#include "commands/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/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/attoptcache.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/sampling.h"
#include "utils/sortsupport.h"
#include "utils/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 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 1832 of file analyze.c.

◆ swapInt

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

Definition at line 1831 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

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

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert(), CommandCounterIncrement(), convert_tuples_by_name(), equalTupleDescs(), 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 1129 of file analyze.c.

1132 {
1133  int numrows = 0; /* # rows now in reservoir */
1134  double samplerows = 0; /* total # rows collected */
1135  double liverows = 0; /* # live rows seen */
1136  double deadrows = 0; /* # dead rows seen */
1137  double rowstoskip = -1; /* -1 means not set yet */
1138  uint32 randseed; /* Seed for block sampler(s) */
1139  BlockNumber totalblocks;
1140  TransactionId OldestXmin;
1141  BlockSamplerData bs;
1142  ReservoirStateData rstate;
1143  TupleTableSlot *slot;
1144  TableScanDesc scan;
1145  BlockNumber nblocks;
1146  BlockNumber blksdone = 0;
1147 #ifdef USE_PREFETCH
1148  int prefetch_maximum = 0; /* blocks to prefetch if enabled */
1149  BlockSamplerData prefetch_bs;
1150 #endif
1151 
1152  Assert(targrows > 0);
1153 
1154  totalblocks = RelationGetNumberOfBlocks(onerel);
1155 
1156  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1157  OldestXmin = GetOldestNonRemovableTransactionId(onerel);
1158 
1159  /* Prepare for sampling block numbers */
1160  randseed = pg_prng_uint32(&pg_global_prng_state);
1161  nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1162 
1163 #ifdef USE_PREFETCH
1164  prefetch_maximum = get_tablespace_maintenance_io_concurrency(onerel->rd_rel->reltablespace);
1165  /* Create another BlockSampler, using the same seed, for prefetching */
1166  if (prefetch_maximum)
1167  (void) BlockSampler_Init(&prefetch_bs, totalblocks, targrows, randseed);
1168 #endif
1169 
1170  /* Report sampling block numbers */
1172  nblocks);
1173 
1174  /* Prepare for sampling rows */
1175  reservoir_init_selection_state(&rstate, targrows);
1176 
1177  scan = table_beginscan_analyze(onerel);
1178  slot = table_slot_create(onerel, NULL);
1179 
1180 #ifdef USE_PREFETCH
1181 
1182  /*
1183  * If we are doing prefetching, then go ahead and tell the kernel about
1184  * the first set of pages we are going to want. This also moves our
1185  * iterator out ahead of the main one being used, where we will keep it so
1186  * that we're always pre-fetching out prefetch_maximum number of blocks
1187  * ahead.
1188  */
1189  if (prefetch_maximum)
1190  {
1191  for (int i = 0; i < prefetch_maximum; i++)
1192  {
1193  BlockNumber prefetch_block;
1194 
1195  if (!BlockSampler_HasMore(&prefetch_bs))
1196  break;
1197 
1198  prefetch_block = BlockSampler_Next(&prefetch_bs);
1199  PrefetchBuffer(scan->rs_rd, MAIN_FORKNUM, prefetch_block);
1200  }
1201  }
1202 #endif
1203 
1204  /* Outer loop over blocks to sample */
1205  while (BlockSampler_HasMore(&bs))
1206  {
1207  bool block_accepted;
1208  BlockNumber targblock = BlockSampler_Next(&bs);
1209 #ifdef USE_PREFETCH
1210  BlockNumber prefetch_targblock = InvalidBlockNumber;
1211 
1212  /*
1213  * Make sure that every time the main BlockSampler is moved forward
1214  * that our prefetch BlockSampler also gets moved forward, so that we
1215  * always stay out ahead.
1216  */
1217  if (prefetch_maximum && BlockSampler_HasMore(&prefetch_bs))
1218  prefetch_targblock = BlockSampler_Next(&prefetch_bs);
1219 #endif
1220 
1222 
1223  block_accepted = table_scan_analyze_next_block(scan, targblock, vac_strategy);
1224 
1225 #ifdef USE_PREFETCH
1226 
1227  /*
1228  * When pre-fetching, after we get a block, tell the kernel about the
1229  * next one we will want, if there's any left.
1230  *
1231  * We want to do this even if the table_scan_analyze_next_block() call
1232  * above decides against analyzing the block it picked.
1233  */
1234  if (prefetch_maximum && prefetch_targblock != InvalidBlockNumber)
1235  PrefetchBuffer(scan->rs_rd, MAIN_FORKNUM, prefetch_targblock);
1236 #endif
1237 
1238  /*
1239  * Don't analyze if table_scan_analyze_next_block() indicated this
1240  * block is unsuitable for analyzing.
1241  */
1242  if (!block_accepted)
1243  continue;
1244 
1245  while (table_scan_analyze_next_tuple(scan, OldestXmin, &liverows, &deadrows, slot))
1246  {
1247  /*
1248  * The first targrows sample rows are simply copied into the
1249  * reservoir. Then we start replacing tuples in the sample until
1250  * we reach the end of the relation. This algorithm is from Jeff
1251  * Vitter's paper (see full citation in utils/misc/sampling.c). It
1252  * works by repeatedly computing the number of tuples to skip
1253  * before selecting a tuple, which replaces a randomly chosen
1254  * element of the reservoir (current set of tuples). At all times
1255  * the reservoir is a true random sample of the tuples we've
1256  * passed over so far, so when we fall off the end of the relation
1257  * we're done.
1258  */
1259  if (numrows < targrows)
1260  rows[numrows++] = ExecCopySlotHeapTuple(slot);
1261  else
1262  {
1263  /*
1264  * t in Vitter's paper is the number of records already
1265  * processed. If we need to compute a new S value, we must
1266  * use the not-yet-incremented value of samplerows as t.
1267  */
1268  if (rowstoskip < 0)
1269  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1270 
1271  if (rowstoskip <= 0)
1272  {
1273  /*
1274  * Found a suitable tuple, so save it, replacing one old
1275  * tuple at random
1276  */
1277  int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1278 
1279  Assert(k >= 0 && k < targrows);
1280  heap_freetuple(rows[k]);
1281  rows[k] = ExecCopySlotHeapTuple(slot);
1282  }
1283 
1284  rowstoskip -= 1;
1285  }
1286 
1287  samplerows += 1;
1288  }
1289 
1291  ++blksdone);
1292  }
1293 
1295  table_endscan(scan);
1296 
1297  /*
1298  * If we didn't find as many tuples as we wanted then we're done. No sort
1299  * is needed, since they're already in order.
1300  *
1301  * Otherwise we need to sort the collected tuples by position
1302  * (itempointer). It's not worth worrying about corner cases where the
1303  * tuples are already sorted.
1304  */
1305  if (numrows == targrows)
1306  qsort_interruptible(rows, numrows, sizeof(HeapTuple),
1307  compare_rows, NULL);
1308 
1309  /*
1310  * Estimate total numbers of live and dead rows in relation, extrapolating
1311  * on the assumption that the average tuple density in pages we didn't
1312  * scan is the same as in the pages we did scan. Since what we scanned is
1313  * a random sample of the pages in the relation, this should be a good
1314  * assumption.
1315  */
1316  if (bs.m > 0)
1317  {
1318  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1319  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1320  }
1321  else
1322  {
1323  *totalrows = 0.0;
1324  *totaldeadrows = 0.0;
1325  }
1326 
1327  /*
1328  * Emit some interesting relation info
1329  */
1330  ereport(elevel,
1331  (errmsg("\"%s\": scanned %d of %u pages, "
1332  "containing %.0f live rows and %.0f dead rows; "
1333  "%d rows in sample, %.0f estimated total rows",
1334  RelationGetRelationName(onerel),
1335  bs.m, totalblocks,
1336  liverows, deadrows,
1337  numrows, *totalrows)));
1338 
1339  return numrows;
1340 }
#define InvalidBlockNumber
Definition: block.h:33
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:601
unsigned int uint32
Definition: c.h:495
uint32 TransactionId
Definition: c.h:641
static BufferAccessStrategy vac_strategy
Definition: analyze.c:87
static int compare_rows(const void *a, const void *b, void *arg)
Definition: analyze.c:1346
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1255
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:191
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:1986
@ MAIN_FORKNUM
Definition: relpath.h:50
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
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:58
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:64
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:147
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition: spccache.c:229
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 bool table_scan_analyze_next_block(TableScanDesc scan, BlockNumber blockno, BufferAccessStrategy bstrategy)
Definition: tableam.h:1717
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009
static bool table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition: tableam.h:1735
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition: tableam.h:998
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:459
void vacuum_delay_point(void)
Definition: vacuum.c:2322

References Assert(), BlockSampler_HasMore(), BlockSampler_Init(), BlockSampler_Next(), compare_rows(), ereport, errmsg(), ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), get_tablespace_maintenance_io_concurrency(), GetOldestNonRemovableTransactionId(), heap_freetuple(), i, InvalidBlockNumber, BlockSamplerData::m, MAIN_FORKNUM, pg_global_prng_state, pg_prng_uint32(), pgstat_progress_update_param(), PrefetchBuffer(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, qsort_interruptible(), ReservoirStateData::randstate, RelationData::rd_rel, 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 2965 of file analyze.c.

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

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

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_ANALYZE, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_relation_owner(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

◆ compare_mcvs()

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

Definition at line 2947 of file analyze.c.

2948 {
2949  int da = ((const ScalarMCVItem *) a)->first;
2950  int db = ((const ScalarMCVItem *) b)->first;
2951 
2952  return da - db;
2953 }
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 1346 of file analyze.c.

1347 {
1348  HeapTuple ha = *(const HeapTuple *) a;
1349  HeapTuple hb = *(const HeapTuple *) b;
1354 
1355  if (ba < bb)
1356  return -1;
1357  if (ba > bb)
1358  return 1;
1359  if (oa < ob)
1360  return -1;
1361  if (oa > ob)
1362  return 1;
1363  return 0;
1364 }
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 2916 of file analyze.c.

2917 {
2918  Datum da = ((const ScalarItem *) a)->value;
2919  int ta = ((const ScalarItem *) a)->tupno;
2920  Datum db = ((const ScalarItem *) b)->value;
2921  int tb = ((const ScalarItem *) b)->tupno;
2923  int compare;
2924 
2925  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2926  if (compare != 0)
2927  return compare;
2928 
2929  /*
2930  * The two datums are equal, so update cxt->tupnoLink[].
2931  */
2932  if (cxt->tupnoLink[ta] < tb)
2933  cxt->tupnoLink[ta] = tb;
2934  if (cxt->tupnoLink[tb] < ta)
2935  cxt->tupnoLink[tb] = ta;
2936 
2937  /*
2938  * For equal datums, sort by tupno
2939  */
2940  return ta - tb;
2941 }
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:1845

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

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

834 {
835  MemoryContext ind_context,
836  old_context;
838  bool isnull[INDEX_MAX_KEYS];
839  int ind,
840  i;
841 
842  ind_context = AllocSetContextCreate(anl_context,
843  "Analyze Index",
845  old_context = MemoryContextSwitchTo(ind_context);
846 
847  for (ind = 0; ind < nindexes; ind++)
848  {
849  AnlIndexData *thisdata = &indexdata[ind];
850  IndexInfo *indexInfo = thisdata->indexInfo;
851  int attr_cnt = thisdata->attr_cnt;
852  TupleTableSlot *slot;
853  EState *estate;
854  ExprContext *econtext;
855  ExprState *predicate;
856  Datum *exprvals;
857  bool *exprnulls;
858  int numindexrows,
859  tcnt,
860  rowno;
861  double totalindexrows;
862 
863  /* Ignore index if no columns to analyze and not partial */
864  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
865  continue;
866 
867  /*
868  * Need an EState for evaluation of index expressions and
869  * partial-index predicates. Create it in the per-index context to be
870  * sure it gets cleaned up at the bottom of the loop.
871  */
872  estate = CreateExecutorState();
873  econtext = GetPerTupleExprContext(estate);
874  /* Need a slot to hold the current heap tuple, too */
876  &TTSOpsHeapTuple);
877 
878  /* Arrange for econtext's scan tuple to be the tuple under test */
879  econtext->ecxt_scantuple = slot;
880 
881  /* Set up execution state for predicate. */
882  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
883 
884  /* Compute and save index expression values */
885  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
886  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
887  numindexrows = 0;
888  tcnt = 0;
889  for (rowno = 0; rowno < numrows; rowno++)
890  {
891  HeapTuple heapTuple = rows[rowno];
892 
894 
895  /*
896  * Reset the per-tuple context each time, to reclaim any cruft
897  * left behind by evaluating the predicate or index expressions.
898  */
899  ResetExprContext(econtext);
900 
901  /* Set up for predicate or expression evaluation */
902  ExecStoreHeapTuple(heapTuple, slot, false);
903 
904  /* If index is partial, check predicate */
905  if (predicate != NULL)
906  {
907  if (!ExecQual(predicate, econtext))
908  continue;
909  }
910  numindexrows++;
911 
912  if (attr_cnt > 0)
913  {
914  /*
915  * Evaluate the index row to compute expression values. We
916  * could do this by hand, but FormIndexDatum is convenient.
917  */
918  FormIndexDatum(indexInfo,
919  slot,
920  estate,
921  values,
922  isnull);
923 
924  /*
925  * Save just the columns we care about. We copy the values
926  * into ind_context from the estate's per-tuple context.
927  */
928  for (i = 0; i < attr_cnt; i++)
929  {
930  VacAttrStats *stats = thisdata->vacattrstats[i];
931  int attnum = stats->tupattnum;
932 
933  if (isnull[attnum - 1])
934  {
935  exprvals[tcnt] = (Datum) 0;
936  exprnulls[tcnt] = true;
937  }
938  else
939  {
940  exprvals[tcnt] = datumCopy(values[attnum - 1],
941  stats->attrtype->typbyval,
942  stats->attrtype->typlen);
943  exprnulls[tcnt] = false;
944  }
945  tcnt++;
946  }
947  }
948  }
949 
950  /*
951  * Having counted the number of rows that pass the predicate in the
952  * sample, we can estimate the total number of rows in the index.
953  */
954  thisdata->tupleFract = (double) numindexrows / (double) numrows;
955  totalindexrows = ceil(thisdata->tupleFract * totalrows);
956 
957  /*
958  * Now we can compute the statistics for the expression columns.
959  */
960  if (numindexrows > 0)
961  {
962  MemoryContextSwitchTo(col_context);
963  for (i = 0; i < attr_cnt; i++)
964  {
965  VacAttrStats *stats = thisdata->vacattrstats[i];
966 
967  stats->exprvals = exprvals + i;
968  stats->exprnulls = exprnulls + i;
969  stats->rowstride = attr_cnt;
970  stats->compute_stats(stats,
972  numindexrows,
973  totalindexrows);
974 
976  }
977  }
978 
979  /* And clean up */
980  MemoryContextSwitchTo(ind_context);
981 
983  FreeExecutorState(estate);
985  }
986 
987  MemoryContextSwitchTo(old_context);
988  MemoryContextDelete(ind_context);
989 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
static MemoryContext anl_context
Definition: analyze.c:86
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1799
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:764
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1353
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1239
EState * CreateExecutorState(void)
Definition: execUtils.c:93
void FreeExecutorState(EState *estate)
Definition: execUtils.c:194
#define GetPerTupleExprContext(estate)
Definition: executor.h:549
#define ResetExprContext(econtext)
Definition: executor.h:543
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:412
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2726
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:70
int16 attnum
Definition: pg_attribute.h:74
#define INDEX_MAX_KEYS
#define NIL
Definition: pg_list.h:68
double tupleFract
Definition: analyze.c:76
int attr_cnt
Definition: analyze.c:78
IndexInfo * indexInfo
Definition: analyze.c:75
VacAttrStats ** vacattrstats
Definition: analyze.c:77
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:249
List * ii_Predicate
Definition: execnodes.h:182
int tupattnum
Definition: vacuum.h:170
int rowstride
Definition: vacuum.h:175
bool * exprnulls
Definition: vacuum.h:174
Datum * exprvals
Definition: vacuum.h:173
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:135

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(), MemoryContextResetAndDeleteChildren, 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 2387 of file analyze.c.

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

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

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

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

Referenced by analyze_rel().

◆ examine_attribute()

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

Definition at line 1001 of file analyze.c.

1002 {
1003  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1004  HeapTuple typtuple;
1005  VacAttrStats *stats;
1006  int i;
1007  bool ok;
1008 
1009  /* Never analyze dropped columns */
1010  if (attr->attisdropped)
1011  return NULL;
1012 
1013  /* Don't analyze column if user has specified not to */
1014  if (attr->attstattarget == 0)
1015  return NULL;
1016 
1017  /*
1018  * Create the VacAttrStats struct.
1019  */
1020  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
1021  stats->attstattarget = attr->attstattarget;
1022 
1023  /*
1024  * When analyzing an expression index, believe the expression tree's type
1025  * not the column datatype --- the latter might be the opckeytype storage
1026  * type of the opclass, which is not interesting for our purposes. (Note:
1027  * if we did anything with non-expression index columns, we'd need to
1028  * figure out where to get the correct type info from, but for now that's
1029  * not a problem.) It's not clear whether anyone will care about the
1030  * typmod, but we store that too just in case.
1031  */
1032  if (index_expr)
1033  {
1034  stats->attrtypid = exprType(index_expr);
1035  stats->attrtypmod = exprTypmod(index_expr);
1036 
1037  /*
1038  * If a collation has been specified for the index column, use that in
1039  * preference to anything else; but if not, fall back to whatever we
1040  * can get from the expression.
1041  */
1042  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1043  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1044  else
1045  stats->attrcollid = exprCollation(index_expr);
1046  }
1047  else
1048  {
1049  stats->attrtypid = attr->atttypid;
1050  stats->attrtypmod = attr->atttypmod;
1051  stats->attrcollid = attr->attcollation;
1052  }
1053 
1054  typtuple = SearchSysCacheCopy1(TYPEOID,
1055  ObjectIdGetDatum(stats->attrtypid));
1056  if (!HeapTupleIsValid(typtuple))
1057  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1058  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
1059  stats->anl_context = anl_context;
1060  stats->tupattnum = attnum;
1061 
1062  /*
1063  * The fields describing the stats->stavalues[n] element types default to
1064  * the type of the data being analyzed, but the type-specific typanalyze
1065  * function can change them if it wants to store something else.
1066  */
1067  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1068  {
1069  stats->statypid[i] = stats->attrtypid;
1070  stats->statyplen[i] = stats->attrtype->typlen;
1071  stats->statypbyval[i] = stats->attrtype->typbyval;
1072  stats->statypalign[i] = stats->attrtype->typalign;
1073  }
1074 
1075  /*
1076  * Call the type-specific typanalyze function. If none is specified, use
1077  * std_typanalyze().
1078  */
1079  if (OidIsValid(stats->attrtype->typanalyze))
1080  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1081  PointerGetDatum(stats)));
1082  else
1083  ok = std_typanalyze(stats);
1084 
1085  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1086  {
1087  heap_freetuple(typtuple);
1088  pfree(stats);
1089  return NULL;
1090  }
1091 
1092  return stats;
1093 }
#define OidIsValid(objectId)
Definition: c.h:764
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1876
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:282
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:786
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 ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
Oid * rd_indcollation
Definition: rel.h:216
int32 attrtypmod
Definition: vacuum.h:126
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:161
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:164
Oid attrtypid
Definition: vacuum.h:125
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:163
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:162
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:182
@ TYPEOID
Definition: syscache.h:114
#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(), elog(), ERROR, exprCollation(), exprType(), exprTypmod(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, i, VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0(), pfree(), PointerGetDatum(), RelationData::rd_att, RelationData::rd_indcollation, SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), VacAttrStats::tupattnum, TupleDescAttr, and TYPEOID.

Referenced by do_analyze_rel().

◆ ind_fetch_func()

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

Definition at line 1799 of file analyze.c.

1800 {
1801  int i;
1802 
1803  /* exprvals and exprnulls are already offset for proper column */
1804  i = rownum * stats->rowstride;
1805  *isNull = stats->exprnulls[i];
1806  return stats->exprvals[i];
1807 }

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

1784 {
1785  int attnum = stats->tupattnum;
1786  HeapTuple tuple = stats->rows[rownum];
1787  TupleDesc tupDesc = stats->tupDesc;
1788 
1789  return heap_getattr(tuple, attnum, tupDesc, isNull);
1790 }
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 1876 of file analyze.c.

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

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

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, STATRELATTINH, 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 86 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 87 of file analyze.c.

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