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

Go to the source code of this file.

Data Structures

struct  AnlIndexData
 
struct  ScalarMCVItem
 
struct  CompareScalarsContext
 

Macros

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

Typedefs

typedef struct AnlIndexData AnlIndexData
 

Functions

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

Variables

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

Macro Definition Documentation

◆ swapDatum

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

Definition at line 1814 of file analyze.c.

◆ swapInt

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

Definition at line 1813 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

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

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

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

References Assert(), BlockSampler_HasMore(), BlockSampler_Init(), BlockSampler_Next(), compare_rows(), ereport, errmsg(), ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), get_tablespace_maintenance_io_concurrency(), GetOldestNonRemovableTransactionId(), heap_freetuple(), i, InvalidBlockNumber, BlockSamplerData::m, MAIN_FORKNUM, pg_global_prng_state, pg_prng_uint32(), pgstat_progress_update_param(), PrefetchBuffer(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, qsort_interruptible(), ReservoirStateData::randstate, RelationData::rd_rel, RelationGetNumberOfBlocks, RelationGetRelationName, reservoir_get_next_S(), reservoir_init_selection_state(), TableScanDescData::rs_rd, sampler_random_fract(), table_beginscan_analyze(), table_endscan(), table_scan_analyze_next_block(), table_scan_analyze_next_tuple(), table_slot_create(), vac_strategy, and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

◆ analyze_mcv_list()

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

Definition at line 2949 of file analyze.c.

2955 {
2956  double ndistinct_table;
2957  double sumcount;
2958  int i;
2959 
2960  /*
2961  * If the entire table was sampled, keep the whole list. This also
2962  * protects us against division by zero in the code below.
2963  */
2964  if (samplerows == totalrows || totalrows <= 1.0)
2965  return num_mcv;
2966 
2967  /* Re-extract the estimated number of distinct nonnull values in table */
2968  ndistinct_table = stadistinct;
2969  if (ndistinct_table < 0)
2970  ndistinct_table = -ndistinct_table * totalrows;
2971 
2972  /*
2973  * Exclude the least common values from the MCV list, if they are not
2974  * significantly more common than the estimated selectivity they would
2975  * have if they weren't in the list. All non-MCV values are assumed to be
2976  * equally common, after taking into account the frequencies of all the
2977  * values in the MCV list and the number of nulls (c.f. eqsel()).
2978  *
2979  * Here sumcount tracks the total count of all but the last (least common)
2980  * value in the MCV list, allowing us to determine the effect of excluding
2981  * that value from the list.
2982  *
2983  * Note that we deliberately do this by removing values from the full
2984  * list, rather than starting with an empty list and adding values,
2985  * because the latter approach can fail to add any values if all the most
2986  * common values have around the same frequency and make up the majority
2987  * of the table, so that the overall average frequency of all values is
2988  * roughly the same as that of the common values. This would lead to any
2989  * uncommon values being significantly overestimated.
2990  */
2991  sumcount = 0.0;
2992  for (i = 0; i < num_mcv - 1; i++)
2993  sumcount += mcv_counts[i];
2994 
2995  while (num_mcv > 0)
2996  {
2997  double selec,
2998  otherdistinct,
2999  N,
3000  n,
3001  K,
3002  variance,
3003  stddev;
3004 
3005  /*
3006  * Estimated selectivity the least common value would have if it
3007  * wasn't in the MCV list (c.f. eqsel()).
3008  */
3009  selec = 1.0 - sumcount / samplerows - stanullfrac;
3010  if (selec < 0.0)
3011  selec = 0.0;
3012  if (selec > 1.0)
3013  selec = 1.0;
3014  otherdistinct = ndistinct_table - (num_mcv - 1);
3015  if (otherdistinct > 1)
3016  selec /= otherdistinct;
3017 
3018  /*
3019  * If the value is kept in the MCV list, its population frequency is
3020  * assumed to equal its sample frequency. We use the lower end of a
3021  * textbook continuity-corrected Wald-type confidence interval to
3022  * determine if that is significantly more common than the non-MCV
3023  * frequency --- specifically we assume the population frequency is
3024  * highly likely to be within around 2 standard errors of the sample
3025  * frequency, which equates to an interval of 2 standard deviations
3026  * either side of the sample count, plus an additional 0.5 for the
3027  * continuity correction. Since we are sampling without replacement,
3028  * this is a hypergeometric distribution.
3029  *
3030  * XXX: Empirically, this approach seems to work quite well, but it
3031  * may be worth considering more advanced techniques for estimating
3032  * the confidence interval of the hypergeometric distribution.
3033  */
3034  N = totalrows;
3035  n = samplerows;
3036  K = N * mcv_counts[num_mcv - 1] / n;
3037  variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
3038  stddev = sqrt(variance);
3039 
3040  if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
3041  {
3042  /*
3043  * The value is significantly more common than the non-MCV
3044  * selectivity would suggest. Keep it, and all the other more
3045  * common values in the list.
3046  */
3047  break;
3048  }
3049  else
3050  {
3051  /* Discard this value and consider the next least common value */
3052  num_mcv--;
3053  if (num_mcv == 0)
3054  break;
3055  sumcount -= mcv_counts[num_mcv - 1];
3056  }
3057  }
3058  return num_mcv;
3059 }
#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 privileges. 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 privileges could have changed
166  * in-between. Make sure to generate only logs for ANALYZE in this case.
167  */
169  onerel->rd_rel,
171  {
173  return;
174  }
175 
176  /*
177  * Silently ignore tables that are temp tables of other backends ---
178  * trying to analyze these is rather pointless, since their contents are
179  * probably not up-to-date on disk. (We don't throw a warning here; it
180  * would just lead to chatter during a database-wide ANALYZE.)
181  */
182  if (RELATION_IS_OTHER_TEMP(onerel))
183  {
185  return;
186  }
187 
188  /*
189  * We can ANALYZE any table except pg_statistic. See update_attstats
190  */
191  if (RelationGetRelid(onerel) == StatisticRelationId)
192  {
194  return;
195  }
196 
197  /*
198  * Check that it's of an analyzable relkind, and set up appropriately.
199  */
200  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
201  onerel->rd_rel->relkind == RELKIND_MATVIEW)
202  {
203  /* Regular table, so we'll use the regular row acquisition function */
204  acquirefunc = acquire_sample_rows;
205  /* Also get regular table's size */
206  relpages = RelationGetNumberOfBlocks(onerel);
207  }
208  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
209  {
210  /*
211  * For a foreign table, call the FDW's hook function to see whether it
212  * supports analysis.
213  */
214  FdwRoutine *fdwroutine;
215  bool ok = false;
216 
217  fdwroutine = GetFdwRoutineForRelation(onerel, false);
218 
219  if (fdwroutine->AnalyzeForeignTable != NULL)
220  ok = fdwroutine->AnalyzeForeignTable(onerel,
221  &acquirefunc,
222  &relpages);
223 
224  if (!ok)
225  {
227  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
228  RelationGetRelationName(onerel))));
230  return;
231  }
232  }
233  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
234  {
235  /*
236  * For partitioned tables, we want to do the recursive ANALYZE below.
237  */
238  }
239  else
240  {
241  /* No need for a WARNING if we already complained during VACUUM */
242  if (!(params->options & VACOPT_VACUUM))
244  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
245  RelationGetRelationName(onerel))));
247  return;
248  }
249 
250  /*
251  * OK, let's do it. First, initialize progress reporting.
252  */
254  RelationGetRelid(onerel));
255 
256  /*
257  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
258  * tables, which don't contain any rows.
259  */
260  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
261  do_analyze_rel(onerel, params, va_cols, acquirefunc,
262  relpages, false, in_outer_xact, elevel);
263 
264  /*
265  * If there are child tables, do recursive ANALYZE.
266  */
267  if (onerel->rd_rel->relhassubclass)
268  do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
269  true, in_outer_xact, elevel);
270 
271  /*
272  * Close source relation now, but keep lock so that no one deletes it
273  * before we commit. (If someone did, they'd fail to clean up the entries
274  * we made in pg_statistic. Also, releasing the lock before commit would
275  * expose us to concurrent-update failures in update_attstats.)
276  */
277  relation_close(onerel, NoLock);
278 
280 }
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:290
#define WARNING
Definition: elog.h:32
#define DEBUG2
Definition: elog.h:25
#define INFO
Definition: elog.h:30
#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:614
bool vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple, bits32 options)
Definition: vacuum.c:556
#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_permitted_for_relation(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

◆ compare_mcvs()

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

Definition at line 2931 of file analyze.c.

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

References a, and b.

Referenced by compute_scalar_stats().

◆ compare_rows()

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

Definition at line 1347 of file analyze.c.

1348 {
1349  HeapTuple ha = *(const HeapTuple *) a;
1350  HeapTuple hb = *(const HeapTuple *) b;
1355 
1356  if (ba < bb)
1357  return -1;
1358  if (ba > bb)
1359  return 1;
1360  if (oa < ob)
1361  return -1;
1362  if (oa > ob)
1363  return 1;
1364  return 0;
1365 }
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65

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

Referenced by acquire_sample_rows().

◆ compare_scalars()

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

Definition at line 2900 of file analyze.c.

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

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

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

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

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

Referenced by std_typanalyze().

◆ compute_trivial_stats()

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

Definition at line 1938 of file analyze.c.

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

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

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

References _, AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, IndexVacuumInfo::analyze_only, anl_context, appendStringInfo(), AtEOXact_GUC(), attnameAttNum(), 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 999 of file analyze.c.

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

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

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

1766 {
1767  int attnum = stats->tupattnum;
1768  HeapTuple tuple = stats->rows[rownum];
1769  TupleDesc tupDesc = stats->tupDesc;
1770 
1771  return heap_getattr(tuple, attnum, tupDesc, isNull);
1772 }
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 1858 of file analyze.c.

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

1623 {
1624  Relation sd;
1625  int attno;
1626  CatalogIndexState indstate = NULL;
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  arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
1692  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1693  }
1694  else
1695  {
1696  nulls[i] = true;
1697  values[i++] = (Datum) 0;
1698  }
1699  }
1700  i = Anum_pg_statistic_stavalues1 - 1;
1701  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1702  {
1703  if (stats->numvalues[k] > 0)
1704  {
1705  ArrayType *arry;
1706 
1707  arry = construct_array(stats->stavalues[k],
1708  stats->numvalues[k],
1709  stats->statypid[k],
1710  stats->statyplen[k],
1711  stats->statypbyval[k],
1712  stats->statypalign[k]);
1713  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1714  }
1715  else
1716  {
1717  nulls[i] = true;
1718  values[i++] = (Datum) 0;
1719  }
1720  }
1721 
1722  /* Is there already a pg_statistic tuple for this attribute? */
1723  oldtup = SearchSysCache3(STATRELATTINH,
1724  ObjectIdGetDatum(relid),
1725  Int16GetDatum(stats->attr->attnum),
1726  BoolGetDatum(inh));
1727 
1728  /* Open index information when we know we need it */
1729  if (indstate == NULL)
1730  indstate = CatalogOpenIndexes(sd);
1731 
1732  if (HeapTupleIsValid(oldtup))
1733  {
1734  /* Yes, replace it */
1735  stup = heap_modify_tuple(oldtup,
1736  RelationGetDescr(sd),
1737  values,
1738  nulls,
1739  replaces);
1740  ReleaseSysCache(oldtup);
1741  CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
1742  }
1743  else
1744  {
1745  /* No, insert new tuple */
1746  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1747  CatalogTupleInsertWithInfo(sd, stup, indstate);
1748  }
1749 
1750  heap_freetuple(stup);
1751  }
1752 
1753  if (indstate != NULL)
1754  CatalogCloseIndexes(indstate);
1756 }
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3338
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
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 CatalogTupleInsertWithInfo(Relation heapRel, HeapTuple tup, CatalogIndexState indstate)
Definition: indexing.c:244
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
void CatalogTupleUpdateWithInfo(Relation heapRel, ItemPointer otid, HeapTuple tup, CatalogIndexState indstate)
Definition: indexing.c:324
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:823
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:520
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
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(), CatalogCloseIndexes(), CatalogOpenIndexes(), CatalogTupleInsertWithInfo(), CatalogTupleUpdateWithInfo(), construct_array(), construct_array_builtin(), Float4GetDatum(), heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, i, Int16GetDatum(), Int32GetDatum(), VacAttrStats::numnumbers, VacAttrStats::numvalues, ObjectIdGetDatum(), palloc(), PointerGetDatum(), RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3(), VacAttrStats::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_NUM_SLOTS, STATRELATTINH, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, HeapTupleData::t_self, table_close(), table_open(), 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().