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

◆ swapInt

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

Definition at line 1810 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

1381 {
1382  List *tableOIDs;
1383  Relation *rels;
1384  AcquireSampleRowsFunc *acquirefuncs;
1385  double *relblocks;
1386  double totalblocks;
1387  int numrows,
1388  nrels,
1389  i;
1390  ListCell *lc;
1391  bool has_child;
1392 
1393  /*
1394  * Find all members of inheritance set. We only need AccessShareLock on
1395  * the children.
1396  */
1397  tableOIDs =
1399 
1400  /*
1401  * Check that there's at least one descendant, else fail. This could
1402  * happen despite analyze_rel's relhassubclass check, if table once had a
1403  * child but no longer does. In that case, we can clear the
1404  * relhassubclass field so as not to make the same mistake again later.
1405  * (This is safe because we hold ShareUpdateExclusiveLock.)
1406  */
1407  if (list_length(tableOIDs) < 2)
1408  {
1409  /* CCI because we already updated the pg_class row in this command */
1411  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1412  ereport(elevel,
1413  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1415  RelationGetRelationName(onerel))));
1416  return 0;
1417  }
1418 
1419  /*
1420  * Identify acquirefuncs to use, and count blocks in all the relations.
1421  * The result could overflow BlockNumber, so we use double arithmetic.
1422  */
1423  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1424  acquirefuncs = (AcquireSampleRowsFunc *)
1425  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1426  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1427  totalblocks = 0;
1428  nrels = 0;
1429  has_child = false;
1430  foreach(lc, tableOIDs)
1431  {
1432  Oid childOID = lfirst_oid(lc);
1433  Relation childrel;
1434  AcquireSampleRowsFunc acquirefunc = NULL;
1435  BlockNumber relpages = 0;
1436 
1437  /* We already got the needed lock */
1438  childrel = table_open(childOID, NoLock);
1439 
1440  /* Ignore if temp table of another backend */
1441  if (RELATION_IS_OTHER_TEMP(childrel))
1442  {
1443  /* ... but release the lock on it */
1444  Assert(childrel != onerel);
1445  table_close(childrel, AccessShareLock);
1446  continue;
1447  }
1448 
1449  /* Check table type (MATVIEW can't happen, but might as well allow) */
1450  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1451  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1452  {
1453  /* Regular table, so use the regular row acquisition function */
1454  acquirefunc = acquire_sample_rows;
1455  relpages = RelationGetNumberOfBlocks(childrel);
1456  }
1457  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1458  {
1459  /*
1460  * For a foreign table, call the FDW's hook function to see
1461  * whether it supports analysis.
1462  */
1463  FdwRoutine *fdwroutine;
1464  bool ok = false;
1465 
1466  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1467 
1468  if (fdwroutine->AnalyzeForeignTable != NULL)
1469  ok = fdwroutine->AnalyzeForeignTable(childrel,
1470  &acquirefunc,
1471  &relpages);
1472 
1473  if (!ok)
1474  {
1475  /* ignore, but release the lock on it */
1476  Assert(childrel != onerel);
1477  table_close(childrel, AccessShareLock);
1478  continue;
1479  }
1480  }
1481  else
1482  {
1483  /*
1484  * ignore, but release the lock on it. don't try to unlock the
1485  * passed-in relation
1486  */
1487  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1488  if (childrel != onerel)
1489  table_close(childrel, AccessShareLock);
1490  else
1491  table_close(childrel, NoLock);
1492  continue;
1493  }
1494 
1495  /* OK, we'll process this child */
1496  has_child = true;
1497  rels[nrels] = childrel;
1498  acquirefuncs[nrels] = acquirefunc;
1499  relblocks[nrels] = (double) relpages;
1500  totalblocks += (double) relpages;
1501  nrels++;
1502  }
1503 
1504  /*
1505  * If we don't have at least one child table to consider, fail. If the
1506  * relation is a partitioned table, it's not counted as a child table.
1507  */
1508  if (!has_child)
1509  {
1510  ereport(elevel,
1511  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1513  RelationGetRelationName(onerel))));
1514  return 0;
1515  }
1516 
1517  /*
1518  * Now sample rows from each relation, proportionally to its fraction of
1519  * the total block count. (This might be less than desirable if the child
1520  * rels have radically different free-space percentages, but it's not
1521  * clear that it's worth working harder.)
1522  */
1524  nrels);
1525  numrows = 0;
1526  *totalrows = 0;
1527  *totaldeadrows = 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 
1535  RelationGetRelid(childrel));
1536 
1537  if (childblocks > 0)
1538  {
1539  int childtargrows;
1540 
1541  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1542  /* Make sure we don't overrun due to roundoff error */
1543  childtargrows = Min(childtargrows, targrows - numrows);
1544  if (childtargrows > 0)
1545  {
1546  int childrows;
1547  double trows,
1548  tdrows;
1549 
1550  /* Fetch a random sample of the child's rows */
1551  childrows = (*acquirefunc) (childrel, elevel,
1552  rows + numrows, childtargrows,
1553  &trows, &tdrows);
1554 
1555  /* We may need to convert from child's rowtype to parent's */
1556  if (childrows > 0 &&
1557  !equalTupleDescs(RelationGetDescr(childrel),
1558  RelationGetDescr(onerel)))
1559  {
1560  TupleConversionMap *map;
1561 
1562  map = convert_tuples_by_name(RelationGetDescr(childrel),
1563  RelationGetDescr(onerel));
1564  if (map != NULL)
1565  {
1566  int j;
1567 
1568  for (j = 0; j < childrows; j++)
1569  {
1570  HeapTuple newtup;
1571 
1572  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1573  heap_freetuple(rows[numrows + j]);
1574  rows[numrows + j] = newtup;
1575  }
1576  free_conversion_map(map);
1577  }
1578  }
1579 
1580  /* And add to counts */
1581  numrows += childrows;
1582  *totalrows += trows;
1583  *totaldeadrows += tdrows;
1584  }
1585  }
1586 
1587  /*
1588  * Note: we cannot release the child-table locks, since we may have
1589  * pointers to their TOAST tables in the sampled rows.
1590  */
1591  table_close(childrel, NoLock);
1593  i + 1);
1594  }
1595 
1596  return numrows;
1597 }
void pgstat_progress_update_param(int index, int64 val)
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:216
#define Min(x, y)
Definition: c.h:986
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1132
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ereport(elevel,...)
Definition: elog.h:143
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:428
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
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:3326
void * palloc(Size size)
Definition: mcxt.c:1068
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:149
#define lfirst_oid(lc)
Definition: pg_list.h:171
unsigned int Oid
Definition: postgres_ext.h:31
#define PROGRESS_ANALYZE_CHILD_TABLES_TOTAL
Definition: progress.h:43
#define PROGRESS_ANALYZE_CHILD_TABLES_DONE
Definition: progress.h:44
#define PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID
Definition: progress.h:45
#define RelationGetRelid(relation)
Definition: rel.h:488
#define RelationGetDescr(relation)
Definition: rel.h:514
#define RelationGetRelationName(relation)
Definition: rel.h:522
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:642
#define RelationGetNamespace(relation)
Definition: rel.h:529
struct RelationData * Relation
Definition: relcache.h:26
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:257
Definition: pg_list.h:51
Form_pg_class rd_rel
Definition: rel.h:109
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3234
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:284
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:139
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:402
void CommandCounterIncrement(void)
Definition: xact.c:1074

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

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

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

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

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 
)
static

Definition at line 2928 of file analyze.c.

2929 {
2930  int da = ((const ScalarMCVItem *) a)->first;
2931  int db = ((const ScalarMCVItem *) b)->first;
2932 
2933  return da - db;
2934 }
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 
)
static

Definition at line 1348 of file analyze.c.

1349 {
1350  HeapTuple ha = *(const HeapTuple *) a;
1351  HeapTuple hb = *(const HeapTuple *) b;
1356 
1357  if (ba < bb)
1358  return -1;
1359  if (ba > bb)
1360  return 1;
1361  if (oa < ob)
1362  return -1;
1363  if (oa > ob)
1364  return 1;
1365  return 0;
1366 }
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
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 2897 of file analyze.c.

2898 {
2899  Datum da = ((const ScalarItem *) a)->value;
2900  int ta = ((const ScalarItem *) a)->tupno;
2901  Datum db = ((const ScalarItem *) b)->value;
2902  int tb = ((const ScalarItem *) b)->tupno;
2904  int compare;
2905 
2906  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2907  if (compare != 0)
2908  return compare;
2909 
2910  /*
2911  * The two datums are equal, so update cxt->tupnoLink[].
2912  */
2913  if (cxt->tupnoLink[ta] < tb)
2914  cxt->tupnoLink[ta] = tb;
2915  if (cxt->tupnoLink[tb] < ta)
2916  cxt->tupnoLink[tb] = ta;
2917 
2918  /*
2919  * For equal datums, sort by tupno
2920  */
2921  return ta - tb;
2922 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
void * arg
uintptr_t Datum
Definition: postgres.h:411
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
SortSupport ssup
Definition: analyze.c:1824

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

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

References analyze_mcv_list(), VacAttrStats::anl_context, VacAttrStats::attr, VacAttrStats::attrcollid, VacAttrStats::attrtype, 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->attr->attnum;
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:1778
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
EState * CreateExecutorState(void)
Definition: execUtils.c:90
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:537
#define ResetExprContext(econtext)
Definition: executor.h:531
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:400
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2707
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
int16 attnum
Definition: pg_attribute.h:83
#define INDEX_MAX_KEYS
#define NIL
Definition: pg_list.h:65
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:232
List * ii_Predicate
Definition: execnodes.h:166
int rowstride
Definition: vacuum.h:179
bool * exprnulls
Definition: vacuum.h:178
Datum * exprvals
Definition: vacuum.h:177
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:139

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, anl_context, attnum, VacAttrStats::attr, AnlIndexData::attr_cnt, VacAttrStats::attrtype, VacAttrStats::compute_stats, CreateExecutorState(), datumCopy(), ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreHeapTuple(), VacAttrStats::exprnulls, VacAttrStats::exprvals, FormIndexDatum(), FreeExecutorState(), GetPerTupleExprContext, i, IndexInfo::ii_Predicate, ind_fetch_func(), INDEX_MAX_KEYS, AnlIndexData::indexInfo, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), NIL, palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, TTSOpsHeapTuple, 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 2368 of file analyze.c.

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

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

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  if (params->log_min_duration >= 0)
364  starttime = GetCurrentTimestamp();
365  }
366 
367  /*
368  * Determine which columns to analyze
369  *
370  * Note that system attributes are never analyzed, so we just reject them
371  * at the lookup stage. We also reject duplicate column mentions. (We
372  * could alternatively ignore duplicates, but analyzing a column twice
373  * won't work; we'd end up making a conflicting update in pg_statistic.)
374  */
375  if (va_cols != NIL)
376  {
377  Bitmapset *unique_cols = NULL;
378  ListCell *le;
379 
380  vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
381  sizeof(VacAttrStats *));
382  tcnt = 0;
383  foreach(le, va_cols)
384  {
385  char *col = strVal(lfirst(le));
386 
387  i = attnameAttNum(onerel, col, false);
388  if (i == InvalidAttrNumber)
389  ereport(ERROR,
390  (errcode(ERRCODE_UNDEFINED_COLUMN),
391  errmsg("column \"%s\" of relation \"%s\" does not exist",
392  col, RelationGetRelationName(onerel))));
393  if (bms_is_member(i, unique_cols))
394  ereport(ERROR,
395  (errcode(ERRCODE_DUPLICATE_COLUMN),
396  errmsg("column \"%s\" of relation \"%s\" appears more than once",
397  col, RelationGetRelationName(onerel))));
398  unique_cols = bms_add_member(unique_cols, i);
399 
400  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
401  if (vacattrstats[tcnt] != NULL)
402  tcnt++;
403  }
404  attr_cnt = tcnt;
405  }
406  else
407  {
408  attr_cnt = onerel->rd_att->natts;
409  vacattrstats = (VacAttrStats **)
410  palloc(attr_cnt * sizeof(VacAttrStats *));
411  tcnt = 0;
412  for (i = 1; i <= attr_cnt; i++)
413  {
414  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
415  if (vacattrstats[tcnt] != NULL)
416  tcnt++;
417  }
418  attr_cnt = tcnt;
419  }
420 
421  /*
422  * Open all indexes of the relation, and see if there are any analyzable
423  * columns in the indexes. We do not analyze index columns if there was
424  * an explicit column list in the ANALYZE command, however.
425  *
426  * If we are doing a recursive scan, we don't want to touch the parent's
427  * indexes at all. If we're processing a partitioned table, we need to
428  * know if there are any indexes, but we don't want to process them.
429  */
430  if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
431  {
432  List *idxs = RelationGetIndexList(onerel);
433 
434  Irel = NULL;
435  nindexes = 0;
436  hasindex = idxs != NIL;
437  list_free(idxs);
438  }
439  else if (!inh)
440  {
441  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
442  hasindex = nindexes > 0;
443  }
444  else
445  {
446  Irel = NULL;
447  nindexes = 0;
448  hasindex = false;
449  }
450  indexdata = NULL;
451  if (nindexes > 0)
452  {
453  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
454  for (ind = 0; ind < nindexes; ind++)
455  {
456  AnlIndexData *thisdata = &indexdata[ind];
457  IndexInfo *indexInfo;
458 
459  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
460  thisdata->tupleFract = 1.0; /* fix later if partial */
461  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
462  {
463  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
464 
465  thisdata->vacattrstats = (VacAttrStats **)
466  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
467  tcnt = 0;
468  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
469  {
470  int keycol = indexInfo->ii_IndexAttrNumbers[i];
471 
472  if (keycol == 0)
473  {
474  /* Found an index expression */
475  Node *indexkey;
476 
477  if (indexpr_item == NULL) /* shouldn't happen */
478  elog(ERROR, "too few entries in indexprs list");
479  indexkey = (Node *) lfirst(indexpr_item);
480  indexpr_item = lnext(indexInfo->ii_Expressions,
481  indexpr_item);
482  thisdata->vacattrstats[tcnt] =
483  examine_attribute(Irel[ind], i + 1, indexkey);
484  if (thisdata->vacattrstats[tcnt] != NULL)
485  tcnt++;
486  }
487  }
488  thisdata->attr_cnt = tcnt;
489  }
490  }
491  }
492 
493  /*
494  * Determine how many rows we need to sample, using the worst case from
495  * all analyzable columns. We use a lower bound of 100 rows to avoid
496  * possible overflow in Vitter's algorithm. (Note: that will also be the
497  * target in the corner case where there are no analyzable columns.)
498  */
499  targrows = 100;
500  for (i = 0; i < attr_cnt; i++)
501  {
502  if (targrows < vacattrstats[i]->minrows)
503  targrows = vacattrstats[i]->minrows;
504  }
505  for (ind = 0; ind < nindexes; ind++)
506  {
507  AnlIndexData *thisdata = &indexdata[ind];
508 
509  for (i = 0; i < thisdata->attr_cnt; i++)
510  {
511  if (targrows < thisdata->vacattrstats[i]->minrows)
512  targrows = thisdata->vacattrstats[i]->minrows;
513  }
514  }
515 
516  /*
517  * Look at extended statistics objects too, as those may define custom
518  * statistics target. So we may need to sample more rows and then build
519  * the statistics with enough detail.
520  */
521  minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
522 
523  if (targrows < minrows)
524  targrows = minrows;
525 
526  /*
527  * Acquire the sample rows
528  */
529  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
533  if (inh)
534  numrows = acquire_inherited_sample_rows(onerel, elevel,
535  rows, targrows,
536  &totalrows, &totaldeadrows);
537  else
538  numrows = (*acquirefunc) (onerel, elevel,
539  rows, targrows,
540  &totalrows, &totaldeadrows);
541 
542  /*
543  * Compute the statistics. Temporary results during the calculations for
544  * each column are stored in a child context. The calc routines are
545  * responsible to make sure that whatever they store into the VacAttrStats
546  * structure is allocated in anl_context.
547  */
548  if (numrows > 0)
549  {
550  MemoryContext col_context,
551  old_context;
552 
555 
556  col_context = AllocSetContextCreate(anl_context,
557  "Analyze Column",
559  old_context = MemoryContextSwitchTo(col_context);
560 
561  for (i = 0; i < attr_cnt; i++)
562  {
563  VacAttrStats *stats = vacattrstats[i];
564  AttributeOpts *aopt;
565 
566  stats->rows = rows;
567  stats->tupDesc = onerel->rd_att;
568  stats->compute_stats(stats,
570  numrows,
571  totalrows);
572 
573  /*
574  * If the appropriate flavor of the n_distinct option is
575  * specified, override with the corresponding value.
576  */
577  aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
578  if (aopt != NULL)
579  {
580  float8 n_distinct;
581 
582  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
583  if (n_distinct != 0.0)
584  stats->stadistinct = n_distinct;
585  }
586 
588  }
589 
590  if (nindexes > 0)
591  compute_index_stats(onerel, totalrows,
592  indexdata, nindexes,
593  rows, numrows,
594  col_context);
595 
596  MemoryContextSwitchTo(old_context);
597  MemoryContextDelete(col_context);
598 
599  /*
600  * Emit the completed stats rows into pg_statistic, replacing any
601  * previous statistics for the target columns. (If there are stats in
602  * pg_statistic for columns we didn't process, we leave them alone.)
603  */
604  update_attstats(RelationGetRelid(onerel), inh,
605  attr_cnt, vacattrstats);
606 
607  for (ind = 0; ind < nindexes; ind++)
608  {
609  AnlIndexData *thisdata = &indexdata[ind];
610 
611  update_attstats(RelationGetRelid(Irel[ind]), false,
612  thisdata->attr_cnt, thisdata->vacattrstats);
613  }
614 
615  /* Build extended statistics (if there are any). */
616  BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
617  attr_cnt, vacattrstats);
618  }
619 
622 
623  /*
624  * Update pages/tuples stats in pg_class ... but not if we're doing
625  * inherited stats.
626  *
627  * We assume that VACUUM hasn't set pg_class.reltuples already, even
628  * during a VACUUM ANALYZE. Although VACUUM often updates pg_class,
629  * exceptions exist. A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command will
630  * never update pg_class entries for index relations. It's also possible
631  * that an individual index's pg_class entry won't be updated during
632  * VACUUM if the index AM returns NULL from its amvacuumcleanup() routine.
633  */
634  if (!inh)
635  {
636  BlockNumber relallvisible;
637 
638  visibilitymap_count(onerel, &relallvisible, NULL);
639 
640  /* Update pg_class for table relation */
641  vac_update_relstats(onerel,
642  relpages,
643  totalrows,
644  relallvisible,
645  hasindex,
648  NULL, NULL,
649  in_outer_xact);
650 
651  /* Same for indexes */
652  for (ind = 0; ind < nindexes; ind++)
653  {
654  AnlIndexData *thisdata = &indexdata[ind];
655  double totalindexrows;
656 
657  totalindexrows = ceil(thisdata->tupleFract * totalrows);
658  vac_update_relstats(Irel[ind],
660  totalindexrows,
661  0,
662  false,
665  NULL, NULL,
666  in_outer_xact);
667  }
668  }
669  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
670  {
671  /*
672  * Partitioned tables don't have storage, so we don't set any fields
673  * in their pg_class entries except for reltuples and relhasindex.
674  */
675  vac_update_relstats(onerel, -1, totalrows,
676  0, hasindex, InvalidTransactionId,
678  NULL, NULL,
679  in_outer_xact);
680  }
681 
682  /*
683  * Now report ANALYZE to the cumulative stats system. For regular tables,
684  * we do it only if not doing inherited stats. For partitioned tables, we
685  * only do it for inherited stats. (We're never called for not-inherited
686  * stats on partitioned tables anyway.)
687  *
688  * Reset the changes_since_analyze counter only if we analyzed all
689  * columns; otherwise, there is still work for auto-analyze to do.
690  */
691  if (!inh)
692  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
693  (va_cols == NIL));
694  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
695  pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL));
696 
697  /*
698  * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
699  *
700  * Note that most index AMs perform a no-op as a matter of policy for
701  * amvacuumcleanup() when called in ANALYZE-only mode. The only exception
702  * among core index AMs is GIN/ginvacuumcleanup().
703  */
704  if (!(params->options & VACOPT_VACUUM))
705  {
706  for (ind = 0; ind < nindexes; ind++)
707  {
708  IndexBulkDeleteResult *stats;
709  IndexVacuumInfo ivinfo;
710 
711  ivinfo.index = Irel[ind];
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:103
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3309
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1687
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1705
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
bool track_io_timing
Definition: bufmgr.c:137
double float8
Definition: c.h:565
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1762
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1623
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1378
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:2994
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errcode(int sqlerrcode)
Definition: elog.c:693
#define _(x)
Definition: elog.c:89
#define LOG
Definition: elog.h:25
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
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:148
int64 VacuumPageMiss
Definition: globals.c:149
int64 VacuumPageDirty
Definition: globals.c:150
Oid MyDatabaseId
Definition: globals.c:89
int NewGUCNestLevel(void)
Definition: guc.c:6476
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6490
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2418
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition: indexam.c:712
void list_free(List *list)
Definition: list.c:1505
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc0(Size size)
Definition: mcxt.c:1099
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:313
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:603
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:610
#define InvalidMultiXactId
Definition: multixact.h:24
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define lfirst(lc)
Definition: pg_list.h:169
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
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:88
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:52
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH
Definition: progress.h:49
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:38
#define PROGRESS_ANALYZE_PHASE_COMPUTE_STATS
Definition: progress.h:50
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS
Definition: progress.h:48
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4675
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:161
List * ii_Expressions
Definition: execnodes.h:164
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:163
Relation index
Definition: genam.h:46
double num_heap_tuples
Definition: genam.h:51
bool analyze_only
Definition: genam.h:47
BufferAccessStrategy strategy
Definition: genam.h:52
int message_level
Definition: genam.h:50
bool estimated_count
Definition: genam.h:49
Definition: nodes.h:574
TupleDesc rd_att
Definition: rel.h:110
HeapTuple * rows
Definition: vacuum.h:175
int minrows
Definition: vacuum.h:140
TupleDesc tupDesc
Definition: vacuum.h:176
#define InvalidTransactionId
Definition: transam.h:31
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:2143
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:1324
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2186
#define strVal(v)
Definition: value.h:72
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(), VacAttrStats::attr, 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(), 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::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. Note that we only have a copy of the
1019  * fixed fields of the pg_attribute tuple.
1020  */
1021  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
1023  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
1024 
1025  /*
1026  * When analyzing an expression index, believe the expression tree's type
1027  * not the column datatype --- the latter might be the opckeytype storage
1028  * type of the opclass, which is not interesting for our purposes. (Note:
1029  * if we did anything with non-expression index columns, we'd need to
1030  * figure out where to get the correct type info from, but for now that's
1031  * not a problem.) It's not clear whether anyone will care about the
1032  * typmod, but we store that too just in case.
1033  */
1034  if (index_expr)
1035  {
1036  stats->attrtypid = exprType(index_expr);
1037  stats->attrtypmod = exprTypmod(index_expr);
1038 
1039  /*
1040  * If a collation has been specified for the index column, use that in
1041  * preference to anything else; but if not, fall back to whatever we
1042  * can get from the expression.
1043  */
1044  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1045  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1046  else
1047  stats->attrcollid = exprCollation(index_expr);
1048  }
1049  else
1050  {
1051  stats->attrtypid = attr->atttypid;
1052  stats->attrtypmod = attr->atttypmod;
1053  stats->attrcollid = attr->attcollation;
1054  }
1055 
1056  typtuple = SearchSysCacheCopy1(TYPEOID,
1057  ObjectIdGetDatum(stats->attrtypid));
1058  if (!HeapTupleIsValid(typtuple))
1059  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1060  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
1061  stats->anl_context = anl_context;
1062  stats->tupattnum = attnum;
1063 
1064  /*
1065  * The fields describing the stats->stavalues[n] element types default to
1066  * the type of the data being analyzed, but the type-specific typanalyze
1067  * function can change them if it wants to store something else.
1068  */
1069  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1070  {
1071  stats->statypid[i] = stats->attrtypid;
1072  stats->statyplen[i] = stats->attrtype->typlen;
1073  stats->statypbyval[i] = stats->attrtype->typbyval;
1074  stats->statypalign[i] = stats->attrtype->typalign;
1075  }
1076 
1077  /*
1078  * Call the type-specific typanalyze function. If none is specified, use
1079  * std_typanalyze().
1080  */
1081  if (OidIsValid(stats->attrtype->typanalyze))
1082  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1083  PointerGetDatum(stats)));
1084  else
1085  ok = std_typanalyze(stats);
1086 
1087  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1088  {
1089  heap_freetuple(typtuple);
1090  pfree(stats->attr);
1091  pfree(stats);
1092  return NULL;
1093  }
1094 
1095  return stats;
1096 }
#define OidIsValid(objectId)
Definition: c.h:710
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1855
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:669
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:286
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:788
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:199
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
Oid * rd_indcollation
Definition: rel.h:212
int32 attrtypmod
Definition: vacuum.h:130
int tupattnum
Definition: vacuum.h:174
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:165
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:168
Oid attrtypid
Definition: vacuum.h:129
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:167
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:166
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ TYPEOID
Definition: syscache.h:114
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References anl_context, VacAttrStats::anl_context, attnum, VacAttrStats::attr, VacAttrStats::attrcollid, ATTRIBUTE_FIXED_PART_SIZE, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::compute_stats, DatumGetBool, elog, ERROR, exprCollation(), exprType(), exprTypmod(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, i, VacAttrStats::minrows, ObjectIdGetDatum, OidFunctionCall1, OidIsValid, palloc(), 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 1778 of file analyze.c.

1779 {
1780  int i;
1781 
1782  /* exprvals and exprnulls are already offset for proper column */
1783  i = rownum * stats->rowstride;
1784  *isNull = stats->exprnulls[i];
1785  return stats->exprvals[i];
1786 }

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

1763 {
1764  int attnum = stats->tupattnum;
1765  HeapTuple tuple = stats->rows[rownum];
1766  TupleDesc tupDesc = stats->tupDesc;
1767 
1768  return heap_getattr(tuple, attnum, tupDesc, isNull);
1769 }
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:788

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

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

Referenced by array_typanalyze(), examine_attribute(), and examine_expression().

◆ update_attstats()

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

Definition at line 1623 of file analyze.c.

1624 {
1625  Relation sd;
1626  int attno;
1627 
1628  if (natts <= 0)
1629  return; /* nothing to do */
1630 
1631  sd = table_open(StatisticRelationId, RowExclusiveLock);
1632 
1633  for (attno = 0; attno < natts; attno++)
1634  {
1635  VacAttrStats *stats = vacattrstats[attno];
1636  HeapTuple stup,
1637  oldtup;
1638  int i,
1639  k,
1640  n;
1641  Datum values[Natts_pg_statistic];
1642  bool nulls[Natts_pg_statistic];
1643  bool replaces[Natts_pg_statistic];
1644 
1645  /* Ignore attr if we weren't able to collect stats */
1646  if (!stats->stats_valid)
1647  continue;
1648 
1649  /*
1650  * Construct a new pg_statistic tuple
1651  */
1652  for (i = 0; i < Natts_pg_statistic; ++i)
1653  {
1654  nulls[i] = false;
1655  replaces[i] = true;
1656  }
1657 
1658  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1659  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1660  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1661  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1662  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1663  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1664  i = Anum_pg_statistic_stakind1 - 1;
1665  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1666  {
1667  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1668  }
1669  i = Anum_pg_statistic_staop1 - 1;
1670  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1671  {
1672  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1673  }
1674  i = Anum_pg_statistic_stacoll1 - 1;
1675  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1676  {
1677  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1678  }
1679  i = Anum_pg_statistic_stanumbers1 - 1;
1680  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1681  {
1682  int nnum = stats->numnumbers[k];
1683 
1684  if (nnum > 0)
1685  {
1686  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1687  ArrayType *arry;
1688 
1689  for (n = 0; n < nnum; n++)
1690  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1691  /* XXX knows more than it should about type float4: */
1692  arry = construct_array(numdatums, nnum,
1693  FLOAT4OID,
1694  sizeof(float4), true, TYPALIGN_INT);
1695  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1696  }
1697  else
1698  {
1699  nulls[i] = true;
1700  values[i++] = (Datum) 0;
1701  }
1702  }
1703  i = Anum_pg_statistic_stavalues1 - 1;
1704  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1705  {
1706  if (stats->numvalues[k] > 0)
1707  {
1708  ArrayType *arry;
1709 
1710  arry = construct_array(stats->stavalues[k],
1711  stats->numvalues[k],
1712  stats->statypid[k],
1713  stats->statyplen[k],
1714  stats->statypbyval[k],
1715  stats->statypalign[k]);
1716  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1717  }
1718  else
1719  {
1720  nulls[i] = true;
1721  values[i++] = (Datum) 0;
1722  }
1723  }
1724 
1725  /* Is there already a pg_statistic tuple for this attribute? */
1726  oldtup = SearchSysCache3(STATRELATTINH,
1727  ObjectIdGetDatum(relid),
1728  Int16GetDatum(stats->attr->attnum),
1729  BoolGetDatum(inh));
1730 
1731  if (HeapTupleIsValid(oldtup))
1732  {
1733  /* Yes, replace it */
1734  stup = heap_modify_tuple(oldtup,
1735  RelationGetDescr(sd),
1736  values,
1737  nulls,
1738  replaces);
1739  ReleaseSysCache(oldtup);
1740  CatalogTupleUpdate(sd, &stup->t_self, stup);
1741  }
1742  else
1743  {
1744  /* No, insert new tuple */
1745  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1746  CatalogTupleInsert(sd, stup);
1747  }
1748 
1749  heap_freetuple(stup);
1750  }
1751 
1753 }
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3319
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:725
#define BoolGetDatum(X)
Definition: postgres.h:446
#define Int32GetDatum(X)
Definition: postgres.h:523
#define Int16GetDatum(X)
Definition: postgres.h:495
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1195
@ STATRELATTINH
Definition: syscache.h:97

References VacAttrStats::attr, BoolGetDatum, CatalogTupleInsert(), CatalogTupleUpdate(), construct_array(), 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(), 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().