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 "executor/executor.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_oper.h"
#include "parser/parse_relation.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/attoptcache.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/sampling.h"
#include "utils/sortsupport.h"
#include "utils/spccache.h"
#include "utils/syscache.h"
#include "utils/timestamp.h"
Include dependency graph for analyze.c:

Go to the source code of this file.

Data Structures

struct  AnlIndexData
 
struct  ScalarMCVItem
 
struct  CompareScalarsContext
 

Macros

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

Typedefs

typedef struct AnlIndexData AnlIndexData
 

Functions

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

Variables

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

Macro Definition Documentation

◆ swapDatum

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

Definition at line 1842 of file analyze.c.

Referenced by compute_distinct_stats().

◆ swapInt

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

Definition at line 1841 of file analyze.c.

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1839 of file analyze.c.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

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

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert, CommandCounterIncrement(), convert_tuples_by_name(), elevel, equalTupleDescs(), ereport, errmsg(), execute_attr_map_tuple(), find_all_inheritors(), free_conversion_map(), get_namespace_name(), GetFdwRoutineForRelation(), heap_freetuple(), i, 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().

1412 {
1413  List *tableOIDs;
1414  Relation *rels;
1415  AcquireSampleRowsFunc *acquirefuncs;
1416  double *relblocks;
1417  double totalblocks;
1418  int numrows,
1419  nrels,
1420  i;
1421  ListCell *lc;
1422  bool has_child;
1423 
1424  /*
1425  * Find all members of inheritance set. We only need AccessShareLock on
1426  * the children.
1427  */
1428  tableOIDs =
1430 
1431  /*
1432  * Check that there's at least one descendant, else fail. This could
1433  * happen despite analyze_rel's relhassubclass check, if table once had a
1434  * child but no longer does. In that case, we can clear the
1435  * relhassubclass field so as not to make the same mistake again later.
1436  * (This is safe because we hold ShareUpdateExclusiveLock.)
1437  */
1438  if (list_length(tableOIDs) < 2)
1439  {
1440  /* CCI because we already updated the pg_class row in this command */
1442  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1443  ereport(elevel,
1444  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1446  RelationGetRelationName(onerel))));
1447  return 0;
1448  }
1449 
1450  /*
1451  * Identify acquirefuncs to use, and count blocks in all the relations.
1452  * The result could overflow BlockNumber, so we use double arithmetic.
1453  */
1454  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1455  acquirefuncs = (AcquireSampleRowsFunc *)
1456  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1457  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1458  totalblocks = 0;
1459  nrels = 0;
1460  has_child = false;
1461  foreach(lc, tableOIDs)
1462  {
1463  Oid childOID = lfirst_oid(lc);
1464  Relation childrel;
1465  AcquireSampleRowsFunc acquirefunc = NULL;
1466  BlockNumber relpages = 0;
1467 
1468  /* We already got the needed lock */
1469  childrel = table_open(childOID, NoLock);
1470 
1471  /* Ignore if temp table of another backend */
1472  if (RELATION_IS_OTHER_TEMP(childrel))
1473  {
1474  /* ... but release the lock on it */
1475  Assert(childrel != onerel);
1476  table_close(childrel, AccessShareLock);
1477  continue;
1478  }
1479 
1480  /* Check table type (MATVIEW can't happen, but might as well allow) */
1481  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1482  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1483  {
1484  /* Regular table, so use the regular row acquisition function */
1485  acquirefunc = acquire_sample_rows;
1486  relpages = RelationGetNumberOfBlocks(childrel);
1487  }
1488  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1489  {
1490  /*
1491  * For a foreign table, call the FDW's hook function to see
1492  * whether it supports analysis.
1493  */
1494  FdwRoutine *fdwroutine;
1495  bool ok = false;
1496 
1497  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1498 
1499  if (fdwroutine->AnalyzeForeignTable != NULL)
1500  ok = fdwroutine->AnalyzeForeignTable(childrel,
1501  &acquirefunc,
1502  &relpages);
1503 
1504  if (!ok)
1505  {
1506  /* ignore, but release the lock on it */
1507  Assert(childrel != onerel);
1508  table_close(childrel, AccessShareLock);
1509  continue;
1510  }
1511  }
1512  else
1513  {
1514  /*
1515  * ignore, but release the lock on it. don't try to unlock the
1516  * passed-in relation
1517  */
1518  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1519  if (childrel != onerel)
1520  table_close(childrel, AccessShareLock);
1521  else
1522  table_close(childrel, NoLock);
1523  continue;
1524  }
1525 
1526  /* OK, we'll process this child */
1527  has_child = true;
1528  rels[nrels] = childrel;
1529  acquirefuncs[nrels] = acquirefunc;
1530  relblocks[nrels] = (double) relpages;
1531  totalblocks += (double) relpages;
1532  nrels++;
1533  }
1534 
1535  /*
1536  * If we don't have at least one child table to consider, fail. If the
1537  * relation is a partitioned table, it's not counted as a child table.
1538  */
1539  if (!has_child)
1540  {
1541  ereport(elevel,
1542  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1544  RelationGetRelationName(onerel))));
1545  return 0;
1546  }
1547 
1548  /*
1549  * Now sample rows from each relation, proportionally to its fraction of
1550  * the total block count. (This might be less than desirable if the child
1551  * rels have radically different free-space percentages, but it's not
1552  * clear that it's worth working harder.)
1553  */
1555  nrels);
1556  numrows = 0;
1557  *totalrows = 0;
1558  *totaldeadrows = 0;
1559  for (i = 0; i < nrels; i++)
1560  {
1561  Relation childrel = rels[i];
1562  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1563  double childblocks = relblocks[i];
1564 
1566  RelationGetRelid(childrel));
1567 
1568  if (childblocks > 0)
1569  {
1570  int childtargrows;
1571 
1572  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1573  /* Make sure we don't overrun due to roundoff error */
1574  childtargrows = Min(childtargrows, targrows - numrows);
1575  if (childtargrows > 0)
1576  {
1577  int childrows;
1578  double trows,
1579  tdrows;
1580 
1581  /* Fetch a random sample of the child's rows */
1582  childrows = (*acquirefunc) (childrel, elevel,
1583  rows + numrows, childtargrows,
1584  &trows, &tdrows);
1585 
1586  /* We may need to convert from child's rowtype to parent's */
1587  if (childrows > 0 &&
1588  !equalTupleDescs(RelationGetDescr(childrel),
1589  RelationGetDescr(onerel)))
1590  {
1591  TupleConversionMap *map;
1592 
1593  map = convert_tuples_by_name(RelationGetDescr(childrel),
1594  RelationGetDescr(onerel));
1595  if (map != NULL)
1596  {
1597  int j;
1598 
1599  for (j = 0; j < childrows; j++)
1600  {
1601  HeapTuple newtup;
1602 
1603  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1604  heap_freetuple(rows[numrows + j]);
1605  rows[numrows + j] = newtup;
1606  }
1607  free_conversion_map(map);
1608  }
1609  }
1610 
1611  /* And add to counts */
1612  numrows += childrows;
1613  *totalrows += trows;
1614  *totaldeadrows += tdrows;
1615  }
1616  }
1617 
1618  /*
1619  * Note: we cannot release the child-table locks, since we may have
1620  * pointers to their TOAST tables in the sampled rows.
1621  */
1622  table_close(childrel, NoLock);
1624  i + 1);
1625  }
1626 
1627  return numrows;
1628 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:503
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:257
#define Min(x, y)
Definition: c.h:986
#define AccessShareLock
Definition: lockdefs.h:36
#define PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID
Definition: progress.h:45
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define PROGRESS_ANALYZE_CHILD_TABLES_TOTAL
Definition: progress.h:43
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3230
struct RelationData * Relation
Definition: relcache.h:27
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:102
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:284
#define RelationGetRelationName(relation)
Definition: rel.h:511
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:139
static int elevel
Definition: vacuumlazy.c:403
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
void pgstat_progress_update_param(int index, int64 val)
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:631
#define PROGRESS_ANALYZE_CHILD_TABLES_DONE
Definition: progress.h:44
static int list_length(const List *l)
Definition: pg_list.h:149
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:151
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
int i
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:402
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:477
#define lfirst_oid(lc)
Definition: pg_list.h:171
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1163
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ acquire_sample_rows()

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

Definition at line 1163 of file analyze.c.

References Assert, BlockSampler_HasMore(), BlockSampler_Init(), BlockSampler_Next(), compare_rows(), ereport, errmsg(), ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), get_tablespace_io_concurrency(), GetOldestNonRemovableTransactionId(), heap_freetuple(), i, InvalidBlockNumber, BlockSamplerData::m, MAIN_FORKNUM, pgstat_progress_update_param(), PrefetchBuffer(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, qsort, random(), 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(), and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

1166 {
1167  int numrows = 0; /* # rows now in reservoir */
1168  double samplerows = 0; /* total # rows collected */
1169  double liverows = 0; /* # live rows seen */
1170  double deadrows = 0; /* # dead rows seen */
1171  double rowstoskip = -1; /* -1 means not set yet */
1172  long randseed; /* Seed for block sampler(s) */
1173  BlockNumber totalblocks;
1174  TransactionId OldestXmin;
1175  BlockSamplerData bs;
1176  ReservoirStateData rstate;
1177  TupleTableSlot *slot;
1178  TableScanDesc scan;
1179  BlockNumber nblocks;
1180  BlockNumber blksdone = 0;
1181 #ifdef USE_PREFETCH
1182  int prefetch_maximum = 0; /* blocks to prefetch if enabled */
1183  BlockSamplerData prefetch_bs;
1184 #endif
1185 
1186  Assert(targrows > 0);
1187 
1188  totalblocks = RelationGetNumberOfBlocks(onerel);
1189 
1190  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1191  OldestXmin = GetOldestNonRemovableTransactionId(onerel);
1192 
1193  /* Prepare for sampling block numbers */
1194  randseed = random();
1195  nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1196 
1197 #ifdef USE_PREFETCH
1198  prefetch_maximum = get_tablespace_io_concurrency(onerel->rd_rel->reltablespace);
1199  /* Create another BlockSampler, using the same seed, for prefetching */
1200  if (prefetch_maximum)
1201  (void) BlockSampler_Init(&prefetch_bs, totalblocks, targrows, randseed);
1202 #endif
1203 
1204  /* Report sampling block numbers */
1206  nblocks);
1207 
1208  /* Prepare for sampling rows */
1209  reservoir_init_selection_state(&rstate, targrows);
1210 
1211  scan = table_beginscan_analyze(onerel);
1212  slot = table_slot_create(onerel, NULL);
1213 
1214 #ifdef USE_PREFETCH
1215 
1216  /*
1217  * If we are doing prefetching, then go ahead and tell the kernel about
1218  * the first set of pages we are going to want. This also moves our
1219  * iterator out ahead of the main one being used, where we will keep it so
1220  * that we're always pre-fetching out prefetch_maximum number of blocks
1221  * ahead.
1222  */
1223  if (prefetch_maximum)
1224  {
1225  for (int i = 0; i < prefetch_maximum; i++)
1226  {
1227  BlockNumber prefetch_block;
1228 
1229  if (!BlockSampler_HasMore(&prefetch_bs))
1230  break;
1231 
1232  prefetch_block = BlockSampler_Next(&prefetch_bs);
1233  PrefetchBuffer(scan->rs_rd, MAIN_FORKNUM, prefetch_block);
1234  }
1235  }
1236 #endif
1237 
1238  /* Outer loop over blocks to sample */
1239  while (BlockSampler_HasMore(&bs))
1240  {
1241  bool block_accepted;
1242  BlockNumber targblock = BlockSampler_Next(&bs);
1243 #ifdef USE_PREFETCH
1244  BlockNumber prefetch_targblock = InvalidBlockNumber;
1245 
1246  /*
1247  * Make sure that every time the main BlockSampler is moved forward
1248  * that our prefetch BlockSampler also gets moved forward, so that we
1249  * always stay out ahead.
1250  */
1251  if (prefetch_maximum && BlockSampler_HasMore(&prefetch_bs))
1252  prefetch_targblock = BlockSampler_Next(&prefetch_bs);
1253 #endif
1254 
1256 
1257  block_accepted = table_scan_analyze_next_block(scan, targblock, vac_strategy);
1258 
1259 #ifdef USE_PREFETCH
1260 
1261  /*
1262  * When pre-fetching, after we get a block, tell the kernel about the
1263  * next one we will want, if there's any left.
1264  *
1265  * We want to do this even if the table_scan_analyze_next_block() call
1266  * above decides against analyzing the block it picked.
1267  */
1268  if (prefetch_maximum && prefetch_targblock != InvalidBlockNumber)
1269  PrefetchBuffer(scan->rs_rd, MAIN_FORKNUM, prefetch_targblock);
1270 #endif
1271 
1272  /*
1273  * Don't analyze if table_scan_analyze_next_block() indicated this
1274  * block is unsuitable for analyzing.
1275  */
1276  if (!block_accepted)
1277  continue;
1278 
1279  while (table_scan_analyze_next_tuple(scan, OldestXmin, &liverows, &deadrows, slot))
1280  {
1281  /*
1282  * The first targrows sample rows are simply copied into the
1283  * reservoir. Then we start replacing tuples in the sample until
1284  * we reach the end of the relation. This algorithm is from Jeff
1285  * Vitter's paper (see full citation in utils/misc/sampling.c). It
1286  * works by repeatedly computing the number of tuples to skip
1287  * before selecting a tuple, which replaces a randomly chosen
1288  * element of the reservoir (current set of tuples). At all times
1289  * the reservoir is a true random sample of the tuples we've
1290  * passed over so far, so when we fall off the end of the relation
1291  * we're done.
1292  */
1293  if (numrows < targrows)
1294  rows[numrows++] = ExecCopySlotHeapTuple(slot);
1295  else
1296  {
1297  /*
1298  * t in Vitter's paper is the number of records already
1299  * processed. If we need to compute a new S value, we must
1300  * use the not-yet-incremented value of samplerows as t.
1301  */
1302  if (rowstoskip < 0)
1303  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1304 
1305  if (rowstoskip <= 0)
1306  {
1307  /*
1308  * Found a suitable tuple, so save it, replacing one old
1309  * tuple at random
1310  */
1311  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1312 
1313  Assert(k >= 0 && k < targrows);
1314  heap_freetuple(rows[k]);
1315  rows[k] = ExecCopySlotHeapTuple(slot);
1316  }
1317 
1318  rowstoskip -= 1;
1319  }
1320 
1321  samplerows += 1;
1322  }
1323 
1325  ++blksdone);
1326  }
1327 
1329  table_endscan(scan);
1330 
1331  /*
1332  * If we didn't find as many tuples as we wanted then we're done. No sort
1333  * is needed, since they're already in order.
1334  *
1335  * Otherwise we need to sort the collected tuples by position
1336  * (itempointer). It's not worth worrying about corner cases where the
1337  * tuples are already sorted.
1338  */
1339  if (numrows == targrows)
1340  qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1341 
1342  /*
1343  * Estimate total numbers of live and dead rows in relation, extrapolating
1344  * on the assumption that the average tuple density in pages we didn't
1345  * scan is the same as in the pages we did scan. Since what we scanned is
1346  * a random sample of the pages in the relation, this should be a good
1347  * assumption.
1348  */
1349  if (bs.m > 0)
1350  {
1351  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1352  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1353  }
1354  else
1355  {
1356  *totalrows = 0.0;
1357  *totaldeadrows = 0.0;
1358  }
1359 
1360  /*
1361  * Emit some interesting relation info
1362  */
1363  ereport(elevel,
1364  (errmsg("\"%s\": scanned %d of %u pages, "
1365  "containing %.0f live rows and %.0f dead rows; "
1366  "%d rows in sample, %.0f estimated total rows",
1367  RelationGetRelationName(onerel),
1368  bs.m, totalblocks,
1369  liverows, deadrows,
1370  numrows, *totalrows)));
1371 
1372  return numrows;
1373 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:58
#define PROGRESS_ANALYZE_BLOCKS_TOTAL
Definition: progress.h:39
uint32 TransactionId
Definition: c.h:587
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:64
long random(void)
Definition: random.c:22
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:242
int get_tablespace_io_concurrency(Oid spcid)
Definition: spccache.c:214
static BufferAccessStrategy vac_strategy
Definition: analyze.c:86
uint32 BlockNumber
Definition: block.h:31
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
static bool table_scan_analyze_next_block(TableScanDesc scan, BlockNumber blockno, BufferAccessStrategy bstrategy)
Definition: tableam.h:1690
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:1967
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
#define PROGRESS_ANALYZE_BLOCKS_DONE
Definition: progress.h:40
#define RelationGetRelationName(relation)
Definition: rel.h:511
static int compare_rows(const void *a, const void *b)
Definition: analyze.c:1379
BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, long randseed)
Definition: sampling.c:39
static int elevel
Definition: vacuumlazy.c:403
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
#define ereport(elevel,...)
Definition: elog.h:157
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:452
#define Assert(condition)
Definition: c.h:804
void pgstat_progress_update_param(int index, int64 val)
static bool table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition: tableam.h:1708
#define InvalidBlockNumber
Definition: block.h:33
Relation rs_rd
Definition: relscan.h:34
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:587
#define qsort(a, b, c, d)
Definition: port.h:504
void vacuum_delay_point(void)
Definition: vacuum.c:2149
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:146
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition: tableam.h:980

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

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

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

◆ analyze_rel()

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

Definition at line 120 of file analyze.c.

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), elevel, 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, VACOPT_ANALYZE, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_relation_owner(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

123 {
124  Relation onerel;
125  int elevel;
126  AcquireSampleRowsFunc acquirefunc = NULL;
127  BlockNumber relpages = 0;
128 
129  /* Select logging level */
130  if (params->options & VACOPT_VERBOSE)
131  elevel = INFO;
132  else
133  elevel = DEBUG2;
134 
135  /* Set up static variables */
136  vac_strategy = bstrategy;
137 
138  /*
139  * Check for user-requested abort.
140  */
142 
143  /*
144  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
145  * ANALYZEs don't run on it concurrently. (This also locks out a
146  * concurrent VACUUM, which doesn't matter much at the moment but might
147  * matter if we ever try to accumulate stats on dead tuples.) If the rel
148  * has been dropped since we last saw it, we don't need to process it.
149  *
150  * Make sure to generate only logs for ANALYZE in this case.
151  */
152  onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
153  params->log_min_duration >= 0,
155 
156  /* leave if relation could not be opened or locked */
157  if (!onerel)
158  return;
159 
160  /*
161  * Check if relation needs to be skipped based on ownership. This check
162  * happens also when building the relation list to analyze for a manual
163  * operation, and needs to be done additionally here as ANALYZE could
164  * happen across multiple transactions where relation ownership could have
165  * changed in-between. Make sure to generate only logs for ANALYZE in
166  * this case.
167  */
169  onerel->rd_rel,
170  params->options & VACOPT_ANALYZE))
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 }
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
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:257
#define VACOPT_ANALYZE
Definition: vacuum.h:179
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:86
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
void pgstat_progress_end_command(void)
bits32 options
Definition: vacuum.h:211
#define DEBUG2
Definition: elog.h:24
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define WARNING
Definition: elog.h:40
static int elevel
Definition: vacuumlazy.c:403
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
#define ereport(elevel,...)
Definition: elog.h:157
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define VACOPT_VACUUM
Definition: vacuum.h:178
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:631
int log_min_duration
Definition: vacuum.h:219
#define VACOPT_VERBOSE
Definition: vacuum.h:180
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:151
int errmsg(const char *fmt,...)
Definition: elog.c:909
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
Relation vacuum_open_relation(Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:633
bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, bits32 options)
Definition: vacuum.c:559
#define RelationGetRelid(relation)
Definition: rel.h:477
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1163

◆ compare_mcvs()

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

Definition at line 2959 of file analyze.c.

Referenced by compute_scalar_stats().

2960 {
2961  int da = ((const ScalarMCVItem *) a)->first;
2962  int db = ((const ScalarMCVItem *) b)->first;
2963 
2964  return da - db;
2965 }

◆ compare_rows()

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

Definition at line 1379 of file analyze.c.

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1380 {
1381  HeapTuple ha = *(const HeapTuple *) a;
1382  HeapTuple hb = *(const HeapTuple *) b;
1387 
1388  if (ba < bb)
1389  return -1;
1390  if (ba > bb)
1391  return 1;
1392  if (oa < ob)
1393  return -1;
1394  if (oa > ob)
1395  return 1;
1396  return 0;
1397 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ compare_scalars()

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

Definition at line 2928 of file analyze.c.

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

Referenced by compute_scalar_stats().

2929 {
2930  Datum da = ((const ScalarItem *) a)->value;
2931  int ta = ((const ScalarItem *) a)->tupno;
2932  Datum db = ((const ScalarItem *) b)->value;
2933  int tb = ((const ScalarItem *) b)->tupno;
2935  int compare;
2936 
2937  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2938  if (compare != 0)
2939  return compare;
2940 
2941  /*
2942  * The two datums are equal, so update cxt->tupnoLink[].
2943  */
2944  if (cxt->tupnoLink[ta] < tb)
2945  cxt->tupnoLink[ta] = tb;
2946  if (cxt->tupnoLink[tb] < ta)
2947  cxt->tupnoLink[tb] = ta;
2948 
2949  /*
2950  * For equal datums, sort by tupno
2951  */
2952  return ta - tb;
2953 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
SortSupport ssup
Definition: analyze.c:1855
uintptr_t Datum
Definition: postgres.h:411
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

◆ compute_distinct_stats()

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

Definition at line 2056 of file analyze.c.

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

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

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

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, 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(), get_attribute_options(), GetPerTupleExprContext, i, IndexInfo::ii_Predicate, ind_fetch_func(), INDEX_MAX_KEYS, AnlIndexData::indexInfo, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), AttributeOpts::n_distinct, NIL, palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, VacAttrStats::stadistinct, TTSOpsHeapTuple, AnlIndexData::tupleFract, AnlIndexData::vacattrstats, vacuum_delay_point(), and values.

Referenced by do_analyze_rel().

854 {
855  MemoryContext ind_context,
856  old_context;
858  bool isnull[INDEX_MAX_KEYS];
859  int ind,
860  i;
861 
862  ind_context = AllocSetContextCreate(anl_context,
863  "Analyze Index",
865  old_context = MemoryContextSwitchTo(ind_context);
866 
867  for (ind = 0; ind < nindexes; ind++)
868  {
869  AnlIndexData *thisdata = &indexdata[ind];
870  IndexInfo *indexInfo = thisdata->indexInfo;
871  int attr_cnt = thisdata->attr_cnt;
872  TupleTableSlot *slot;
873  EState *estate;
874  ExprContext *econtext;
875  ExprState *predicate;
876  Datum *exprvals;
877  bool *exprnulls;
878  int numindexrows,
879  tcnt,
880  rowno;
881  double totalindexrows;
882 
883  /* Ignore index if no columns to analyze and not partial */
884  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
885  continue;
886 
887  /*
888  * Need an EState for evaluation of index expressions and
889  * partial-index predicates. Create it in the per-index context to be
890  * sure it gets cleaned up at the bottom of the loop.
891  */
892  estate = CreateExecutorState();
893  econtext = GetPerTupleExprContext(estate);
894  /* Need a slot to hold the current heap tuple, too */
896  &TTSOpsHeapTuple);
897 
898  /* Arrange for econtext's scan tuple to be the tuple under test */
899  econtext->ecxt_scantuple = slot;
900 
901  /* Set up execution state for predicate. */
902  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
903 
904  /* Compute and save index expression values */
905  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
906  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
907  numindexrows = 0;
908  tcnt = 0;
909  for (rowno = 0; rowno < numrows; rowno++)
910  {
911  HeapTuple heapTuple = rows[rowno];
912 
914 
915  /*
916  * Reset the per-tuple context each time, to reclaim any cruft
917  * left behind by evaluating the predicate or index expressions.
918  */
919  ResetExprContext(econtext);
920 
921  /* Set up for predicate or expression evaluation */
922  ExecStoreHeapTuple(heapTuple, slot, false);
923 
924  /* If index is partial, check predicate */
925  if (predicate != NULL)
926  {
927  if (!ExecQual(predicate, econtext))
928  continue;
929  }
930  numindexrows++;
931 
932  if (attr_cnt > 0)
933  {
934  /*
935  * Evaluate the index row to compute expression values. We
936  * could do this by hand, but FormIndexDatum is convenient.
937  */
938  FormIndexDatum(indexInfo,
939  slot,
940  estate,
941  values,
942  isnull);
943 
944  /*
945  * Save just the columns we care about. We copy the values
946  * into ind_context from the estate's per-tuple context.
947  */
948  for (i = 0; i < attr_cnt; i++)
949  {
950  VacAttrStats *stats = thisdata->vacattrstats[i];
951  int attnum = stats->attr->attnum;
952 
953  if (isnull[attnum - 1])
954  {
955  exprvals[tcnt] = (Datum) 0;
956  exprnulls[tcnt] = true;
957  }
958  else
959  {
960  exprvals[tcnt] = datumCopy(values[attnum - 1],
961  stats->attrtype->typbyval,
962  stats->attrtype->typlen);
963  exprnulls[tcnt] = false;
964  }
965  tcnt++;
966  }
967  }
968  }
969 
970  /*
971  * Having counted the number of rows that pass the predicate in the
972  * sample, we can estimate the total number of rows in the index.
973  */
974  thisdata->tupleFract = (double) numindexrows / (double) numrows;
975  totalindexrows = ceil(thisdata->tupleFract * totalrows);
976 
977  /*
978  * Now we can compute the statistics for the expression columns.
979  */
980  if (numindexrows > 0)
981  {
982  MemoryContextSwitchTo(col_context);
983  for (i = 0; i < attr_cnt; i++)
984  {
985  VacAttrStats *stats = thisdata->vacattrstats[i];
986  AttributeOpts *aopt =
987  get_attribute_options(stats->attr->attrelid,
988  stats->attr->attnum);
989 
990  stats->exprvals = exprvals + i;
991  stats->exprnulls = exprnulls + i;
992  stats->rowstride = attr_cnt;
993  stats->compute_stats(stats,
995  numindexrows,
996  totalindexrows);
997 
998  /*
999  * If the n_distinct option is specified, it overrides the
1000  * above computation. For indices, we always use just
1001  * n_distinct, not n_distinct_inherited.
1002  */
1003  if (aopt != NULL && aopt->n_distinct != 0.0)
1004  stats->stadistinct = aopt->n_distinct;
1005 
1007  }
1008  }
1009 
1010  /* And clean up */
1011  MemoryContextSwitchTo(ind_context);
1012 
1014  FreeExecutorState(estate);
1016  }
1017 
1018  MemoryContextSwitchTo(old_context);
1019  MemoryContextDelete(ind_context);
1020 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:103
int rowstride
Definition: vacuum.h:174
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2662
#define NIL
Definition: pg_list.h:65
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
List * ii_Predicate
Definition: execnodes.h:163
#define RelationGetDescr(relation)
Definition: rel.h:503
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:396
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:123
int attr_cnt
Definition: analyze.c:77
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:533
bool * exprnulls
Definition: vacuum.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
static MemoryContext anl_context
Definition: analyze.c:85
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:774
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
EState * CreateExecutorState(void)
Definition: execUtils.c:90
Datum * exprvals
Definition: vacuum.h:172
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
uintptr_t Datum
Definition: postgres.h:411
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1809
int16 attnum
Definition: pg_attribute.h:83
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
double tupleFract
Definition: analyze.c:75
static Datum values[MAXATTR]
Definition: bootstrap.c:166
Form_pg_type attrtype
Definition: vacuum.h:126
void * palloc(Size size)
Definition: mcxt.c:1062
VacAttrStats ** vacattrstats
Definition: analyze.c:76
int i
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:134
void vacuum_delay_point(void)
Definition: vacuum.c:2149
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1352
#define ResetExprContext(econtext)
Definition: executor.h:527
float4 stadistinct
Definition: vacuum.h:145
IndexInfo * indexInfo
Definition: analyze.c:74

◆ compute_scalar_stats()

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

Definition at line 2399 of file analyze.c.

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, StdAnalyzeData::ltopr, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum, PrepareSortSupportFromOrderingOp(), qsort, qsort_arg(), CompareScalarsContext::ssup, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, VacAttrStats::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, VacAttrStats::stats_valid, VacAttrStats::stavalues, VacAttrStats::stawidth, toast_raw_datum_size(), ScalarItem::tupno, CompareScalarsContext::tupnoLink, vacuum_delay_point(), ScalarItem::value, value, values, VARSIZE_ANY, and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

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

◆ compute_trivial_stats()

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

Definition at line 1966 of file analyze.c.

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

1970 {
1971  int i;
1972  int null_cnt = 0;
1973  int nonnull_cnt = 0;
1974  double total_width = 0;
1975  bool is_varlena = (!stats->attrtype->typbyval &&
1976  stats->attrtype->typlen == -1);
1977  bool is_varwidth = (!stats->attrtype->typbyval &&
1978  stats->attrtype->typlen < 0);
1979 
1980  for (i = 0; i < samplerows; i++)
1981  {
1982  Datum value;
1983  bool isnull;
1984 
1986 
1987  value = fetchfunc(stats, i, &isnull);
1988 
1989  /* Check for null/nonnull */
1990  if (isnull)
1991  {
1992  null_cnt++;
1993  continue;
1994  }
1995  nonnull_cnt++;
1996 
1997  /*
1998  * If it's a variable-width field, add up widths for average width
1999  * calculation. Note that if the value is toasted, we use the toasted
2000  * width. We don't bother with this calculation if it's a fixed-width
2001  * type.
2002  */
2003  if (is_varlena)
2004  {
2005  total_width += VARSIZE_ANY(DatumGetPointer(value));
2006  }
2007  else if (is_varwidth)
2008  {
2009  /* must be cstring */
2010  total_width += strlen(DatumGetCString(value)) + 1;
2011  }
2012  }
2013 
2014  /* We can only compute average width if we found some non-null values. */
2015  if (nonnull_cnt > 0)
2016  {
2017  stats->stats_valid = true;
2018  /* Do the simple null-frac and width stats */
2019  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2020  if (is_varwidth)
2021  stats->stawidth = total_width / (double) nonnull_cnt;
2022  else
2023  stats->stawidth = stats->attrtype->typlen;
2024  stats->stadistinct = 0.0; /* "unknown" */
2025  }
2026  else if (null_cnt > 0)
2027  {
2028  /* We found only nulls; assume the column is entirely null */
2029  stats->stats_valid = true;
2030  stats->stanullfrac = 1.0;
2031  if (is_varwidth)
2032  stats->stawidth = 0; /* "unknown" */
2033  else
2034  stats->stawidth = stats->attrtype->typlen;
2035  stats->stadistinct = 0.0; /* "unknown" */
2036  }
2037 }
#define DatumGetCString(X)
Definition: postgres.h:610
int32 stawidth
Definition: vacuum.h:144
float4 stanullfrac
Definition: vacuum.h:143
bool stats_valid
Definition: vacuum.h:142
uintptr_t Datum
Definition: postgres.h:411
#define VARSIZE_ANY(PTR)
Definition: postgres.h:348
static struct @143 value
#define DatumGetPointer(X)
Definition: postgres.h:593
Form_pg_type attrtype
Definition: vacuum.h:126
int i
void vacuum_delay_point(void)
Definition: vacuum.c:2149
float4 stadistinct
Definition: vacuum.h:145

◆ 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.

References _, AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, IndexVacuumInfo::analyze_only, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), 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, StringInfoData::data, elevel, 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(), pgstat_report_anl_ancestors(), 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_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().

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  if (params->log_min_duration >= 0)
363  starttime = GetCurrentTimestamp();
364  }
365 
366  /*
367  * Determine which columns to analyze
368  *
369  * Note that system attributes are never analyzed, so we just reject them
370  * at the lookup stage. We also reject duplicate column mentions. (We
371  * could alternatively ignore duplicates, but analyzing a column twice
372  * won't work; we'd end up making a conflicting update in pg_statistic.)
373  */
374  if (va_cols != NIL)
375  {
376  Bitmapset *unique_cols = NULL;
377  ListCell *le;
378 
379  vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
380  sizeof(VacAttrStats *));
381  tcnt = 0;
382  foreach(le, va_cols)
383  {
384  char *col = strVal(lfirst(le));
385 
386  i = attnameAttNum(onerel, col, false);
387  if (i == InvalidAttrNumber)
388  ereport(ERROR,
389  (errcode(ERRCODE_UNDEFINED_COLUMN),
390  errmsg("column \"%s\" of relation \"%s\" does not exist",
391  col, RelationGetRelationName(onerel))));
392  if (bms_is_member(i, unique_cols))
393  ereport(ERROR,
394  (errcode(ERRCODE_DUPLICATE_COLUMN),
395  errmsg("column \"%s\" of relation \"%s\" appears more than once",
396  col, RelationGetRelationName(onerel))));
397  unique_cols = bms_add_member(unique_cols, i);
398 
399  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
400  if (vacattrstats[tcnt] != NULL)
401  tcnt++;
402  }
403  attr_cnt = tcnt;
404  }
405  else
406  {
407  attr_cnt = onerel->rd_att->natts;
408  vacattrstats = (VacAttrStats **)
409  palloc(attr_cnt * sizeof(VacAttrStats *));
410  tcnt = 0;
411  for (i = 1; i <= attr_cnt; i++)
412  {
413  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
414  if (vacattrstats[tcnt] != NULL)
415  tcnt++;
416  }
417  attr_cnt = tcnt;
418  }
419 
420  /*
421  * Open all indexes of the relation, and see if there are any analyzable
422  * columns in the indexes. We do not analyze index columns if there was
423  * an explicit column list in the ANALYZE command, however.
424  *
425  * If we are doing a recursive scan, we don't want to touch the parent's
426  * indexes at all. If we're processing a partitioned table, we need to
427  * know if there are any indexes, but we don't want to process them.
428  */
429  if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
430  {
431  List *idxs = RelationGetIndexList(onerel);
432 
433  Irel = NULL;
434  nindexes = 0;
435  hasindex = idxs != NIL;
436  list_free(idxs);
437  }
438  else if (!inh)
439  {
440  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
441  hasindex = nindexes > 0;
442  }
443  else
444  {
445  Irel = NULL;
446  nindexes = 0;
447  hasindex = false;
448  }
449  indexdata = NULL;
450  if (nindexes > 0)
451  {
452  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
453  for (ind = 0; ind < nindexes; ind++)
454  {
455  AnlIndexData *thisdata = &indexdata[ind];
456  IndexInfo *indexInfo;
457 
458  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
459  thisdata->tupleFract = 1.0; /* fix later if partial */
460  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
461  {
462  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
463 
464  thisdata->vacattrstats = (VacAttrStats **)
465  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
466  tcnt = 0;
467  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
468  {
469  int keycol = indexInfo->ii_IndexAttrNumbers[i];
470 
471  if (keycol == 0)
472  {
473  /* Found an index expression */
474  Node *indexkey;
475 
476  if (indexpr_item == NULL) /* shouldn't happen */
477  elog(ERROR, "too few entries in indexprs list");
478  indexkey = (Node *) lfirst(indexpr_item);
479  indexpr_item = lnext(indexInfo->ii_Expressions,
480  indexpr_item);
481  thisdata->vacattrstats[tcnt] =
482  examine_attribute(Irel[ind], i + 1, indexkey);
483  if (thisdata->vacattrstats[tcnt] != NULL)
484  tcnt++;
485  }
486  }
487  thisdata->attr_cnt = tcnt;
488  }
489  }
490  }
491 
492  /*
493  * Determine how many rows we need to sample, using the worst case from
494  * all analyzable columns. We use a lower bound of 100 rows to avoid
495  * possible overflow in Vitter's algorithm. (Note: that will also be the
496  * target in the corner case where there are no analyzable columns.)
497  */
498  targrows = 100;
499  for (i = 0; i < attr_cnt; i++)
500  {
501  if (targrows < vacattrstats[i]->minrows)
502  targrows = vacattrstats[i]->minrows;
503  }
504  for (ind = 0; ind < nindexes; ind++)
505  {
506  AnlIndexData *thisdata = &indexdata[ind];
507 
508  for (i = 0; i < thisdata->attr_cnt; i++)
509  {
510  if (targrows < thisdata->vacattrstats[i]->minrows)
511  targrows = thisdata->vacattrstats[i]->minrows;
512  }
513  }
514 
515  /*
516  * Look at extended statistics objects too, as those may define custom
517  * statistics target. So we may need to sample more rows and then build
518  * the statistics with enough detail.
519  */
520  minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
521 
522  if (targrows < minrows)
523  targrows = minrows;
524 
525  /*
526  * Acquire the sample rows
527  */
528  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
532  if (inh)
533  numrows = acquire_inherited_sample_rows(onerel, elevel,
534  rows, targrows,
535  &totalrows, &totaldeadrows);
536  else
537  numrows = (*acquirefunc) (onerel, elevel,
538  rows, targrows,
539  &totalrows, &totaldeadrows);
540 
541  /*
542  * Compute the statistics. Temporary results during the calculations for
543  * each column are stored in a child context. The calc routines are
544  * responsible to make sure that whatever they store into the VacAttrStats
545  * structure is allocated in anl_context.
546  */
547  if (numrows > 0)
548  {
549  MemoryContext col_context,
550  old_context;
551 
554 
555  col_context = AllocSetContextCreate(anl_context,
556  "Analyze Column",
558  old_context = MemoryContextSwitchTo(col_context);
559 
560  for (i = 0; i < attr_cnt; i++)
561  {
562  VacAttrStats *stats = vacattrstats[i];
563  AttributeOpts *aopt;
564 
565  stats->rows = rows;
566  stats->tupDesc = onerel->rd_att;
567  stats->compute_stats(stats,
569  numrows,
570  totalrows);
571 
572  /*
573  * If the appropriate flavor of the n_distinct option is
574  * specified, override with the corresponding value.
575  */
576  aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
577  if (aopt != NULL)
578  {
579  float8 n_distinct;
580 
581  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
582  if (n_distinct != 0.0)
583  stats->stadistinct = n_distinct;
584  }
585 
587  }
588 
589  if (nindexes > 0)
590  compute_index_stats(onerel, totalrows,
591  indexdata, nindexes,
592  rows, numrows,
593  col_context);
594 
595  MemoryContextSwitchTo(old_context);
596  MemoryContextDelete(col_context);
597 
598  /*
599  * Emit the completed stats rows into pg_statistic, replacing any
600  * previous statistics for the target columns. (If there are stats in
601  * pg_statistic for columns we didn't process, we leave them alone.)
602  */
603  update_attstats(RelationGetRelid(onerel), inh,
604  attr_cnt, vacattrstats);
605 
606  for (ind = 0; ind < nindexes; ind++)
607  {
608  AnlIndexData *thisdata = &indexdata[ind];
609 
610  update_attstats(RelationGetRelid(Irel[ind]), false,
611  thisdata->attr_cnt, thisdata->vacattrstats);
612  }
613 
614  /*
615  * Build extended statistics (if there are any).
616  *
617  * For now we only build extended statistics on individual relations,
618  * not for relations representing inheritance trees.
619  */
620  if (!inh)
621  BuildRelationExtStatistics(onerel, totalrows, numrows, rows,
622  attr_cnt, vacattrstats);
623  }
624 
627 
628  /*
629  * Update pages/tuples stats in pg_class ... but not if we're doing
630  * inherited stats.
631  *
632  * We assume that VACUUM hasn't set pg_class.reltuples already, even
633  * during a VACUUM ANALYZE. Although VACUUM often updates pg_class,
634  * exceptions exist. A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command will
635  * never update pg_class entries for index relations. It's also possible
636  * that an individual index's pg_class entry won't be updated during
637  * VACUUM if the index AM returns NULL from its amvacuumcleanup() routine.
638  */
639  if (!inh)
640  {
641  BlockNumber relallvisible;
642 
643  visibilitymap_count(onerel, &relallvisible, NULL);
644 
645  /* Update pg_class for table relation */
646  vac_update_relstats(onerel,
647  relpages,
648  totalrows,
649  relallvisible,
650  hasindex,
653  in_outer_xact);
654 
655  /* Same for indexes */
656  for (ind = 0; ind < nindexes; ind++)
657  {
658  AnlIndexData *thisdata = &indexdata[ind];
659  double totalindexrows;
660 
661  totalindexrows = ceil(thisdata->tupleFract * totalrows);
662  vac_update_relstats(Irel[ind],
663  RelationGetNumberOfBlocks(Irel[ind]),
664  totalindexrows,
665  0,
666  false,
669  in_outer_xact);
670  }
671  }
672  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
673  {
674  /*
675  * Partitioned tables don't have storage, so we don't set any fields
676  * in their pg_class entries except for reltuples, which is necessary
677  * for auto-analyze to work properly, and relhasindex.
678  */
679  vac_update_relstats(onerel, -1, totalrows,
680  0, hasindex, InvalidTransactionId,
682  in_outer_xact);
683  }
684 
685  /*
686  * Now report ANALYZE to the stats collector. For regular tables, we do
687  * it only if not doing inherited stats. For partitioned tables, we only
688  * do it for inherited stats. (We're never called for not-inherited stats
689  * on partitioned tables anyway.)
690  *
691  * Reset the changes_since_analyze counter only if we analyzed all
692  * columns; otherwise, there is still work for auto-analyze to do.
693  */
694  if (!inh || onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
695  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
696  (va_cols == NIL));
697 
698  /*
699  * If this is a manual analyze of all columns of a permanent leaf
700  * partition, and not doing inherited stats, also let the collector know
701  * about the ancestor tables of this partition. Autovacuum does the
702  * equivalent of this at the start of its run, so there's no reason to do
703  * it there.
704  */
705  if (!inh && !IsAutoVacuumWorkerProcess() &&
706  (va_cols == NIL) &&
707  onerel->rd_rel->relispartition &&
708  onerel->rd_rel->relkind == RELKIND_RELATION &&
709  onerel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
710  {
712  }
713 
714  /*
715  * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
716  *
717  * Note that most index AMs perform a no-op as a matter of policy for
718  * amvacuumcleanup() when called in ANALYZE-only mode. The only exception
719  * among core index AMs is GIN/ginvacuumcleanup().
720  */
721  if (!(params->options & VACOPT_VACUUM))
722  {
723  for (ind = 0; ind < nindexes; ind++)
724  {
725  IndexBulkDeleteResult *stats;
726  IndexVacuumInfo ivinfo;
727 
728  ivinfo.index = Irel[ind];
729  ivinfo.analyze_only = true;
730  ivinfo.estimated_count = true;
731  ivinfo.message_level = elevel;
732  ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
733  ivinfo.strategy = vac_strategy;
734 
735  stats = index_vacuum_cleanup(&ivinfo, NULL);
736 
737  if (stats)
738  pfree(stats);
739  }
740  }
741 
742  /* Done with indexes */
743  vac_close_indexes(nindexes, Irel, NoLock);
744 
745  /* Log the action if appropriate */
746  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
747  {
748  TimestampTz endtime = GetCurrentTimestamp();
749 
750  if (params->log_min_duration == 0 ||
751  TimestampDifferenceExceeds(starttime, endtime,
752  params->log_min_duration))
753  {
754  long delay_in_ms;
755  double read_rate = 0;
756  double write_rate = 0;
758 
759  /*
760  * Calculate the difference in the Page Hit/Miss/Dirty that
761  * happened as part of the analyze by subtracting out the
762  * pre-analyze values which we saved above.
763  */
764  AnalyzePageHit = VacuumPageHit - AnalyzePageHit;
765  AnalyzePageMiss = VacuumPageMiss - AnalyzePageMiss;
766  AnalyzePageDirty = VacuumPageDirty - AnalyzePageDirty;
767 
768  /*
769  * We do not expect an analyze to take > 25 days and it simplifies
770  * things a bit to use TimestampDifferenceMilliseconds.
771  */
772  delay_in_ms = TimestampDifferenceMilliseconds(starttime, endtime);
773 
774  /*
775  * Note that we are reporting these read/write rates in the same
776  * manner as VACUUM does, which means that while the 'average read
777  * rate' here actually corresponds to page misses and resulting
778  * reads which are also picked up by track_io_timing, if enabled,
779  * the 'average write rate' is actually talking about the rate of
780  * pages being dirtied, not being written out, so it's typical to
781  * have a non-zero 'avg write rate' while I/O Timings only reports
782  * reads.
783  *
784  * It's not clear that an ANALYZE will ever result in
785  * FlushBuffer() being called, but we track and support reporting
786  * on I/O write time in case that changes as it's practically free
787  * to do so anyway.
788  */
789 
790  if (delay_in_ms > 0)
791  {
792  read_rate = (double) BLCKSZ * AnalyzePageMiss / (1024 * 1024) /
793  (delay_in_ms / 1000.0);
794  write_rate = (double) BLCKSZ * AnalyzePageDirty / (1024 * 1024) /
795  (delay_in_ms / 1000.0);
796  }
797 
798  /*
799  * We split this up so we don't emit empty I/O timing values when
800  * track_io_timing isn't enabled.
801  */
802 
803  initStringInfo(&buf);
804  appendStringInfo(&buf, _("automatic analyze of table \"%s.%s.%s\"\n"),
807  RelationGetRelationName(onerel));
808  appendStringInfo(&buf, _("buffer usage: %lld hits, %lld misses, %lld dirtied\n"),
809  (long long) AnalyzePageHit,
810  (long long) AnalyzePageMiss,
811  (long long) AnalyzePageDirty);
812  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
813  read_rate, write_rate);
814  if (track_io_timing)
815  {
816  appendStringInfoString(&buf, _("I/O Timings:"));
817  if (pgStatBlockReadTime - startreadtime > 0)
818  appendStringInfo(&buf, _(" read=%.3f"),
819  (double) (pgStatBlockReadTime - startreadtime) / 1000);
820  if (pgStatBlockWriteTime - startwritetime > 0)
821  appendStringInfo(&buf, _(" write=%.3f"),
822  (double) (pgStatBlockWriteTime - startwritetime) / 1000);
823  appendStringInfoChar(&buf, '\n');
824  }
825  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
826 
827  ereport(LOG,
828  (errmsg_internal("%s", buf.data)));
829 
830  pfree(buf.data);
831  }
832  }
833 
834  /* Roll back any GUC changes executed by index functions */
835  AtEOXact_GUC(false, save_nestlevel);
836 
837  /* Restore userid and security context */
838  SetUserIdAndSecContext(save_userid, save_sec_context);
839 
840  /* Restore current context and release memory */
841  MemoryContextSwitchTo(caller_context);
843  anl_context = NULL;
844 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:103
#define NIL
Definition: pg_list.h:65
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2128
int ComputeExtStatisticsRows(Relation onerel, int natts, VacAttrStats **vacattrstats)
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1409
int minrows
Definition: vacuum.h:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
int64 VacuumPageMiss
Definition: globals.c:148
int64 PgStat_Counter
Definition: pgstat.h:91
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:38
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:312
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:590
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition: indexam.c:712
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
HeapTuple * rows
Definition: vacuum.h:170
bool analyze_only
Definition: genam.h:47
int64 VacuumPageHit
Definition: globals.c:147
void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
Definition: pgstat.c:1608
BufferAccessStrategy strategy
Definition: genam.h:52
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:539
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
Relation index
Definition: genam.h:46
static BufferAccessStrategy vac_strategy
Definition: analyze.c:86
int64 VacuumPageDirty
Definition: globals.c:149
TupleDesc tupDesc
Definition: vacuum.h:171
uint32 BlockNumber
Definition: block.h:31
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1654
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2378
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
#define PROGRESS_ANALYZE_PHASE_COMPUTE_STATS
Definition: progress.h:50
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:123
int attr_cnt
Definition: analyze.c:77
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
bits32 options
Definition: vacuum.h:211
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
double float8
Definition: c.h:565
PgStat_Counter pgStatBlockWriteTime
Definition: pgstat.c:247
void BuildRelationExtStatistics(Relation onerel, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2113
static MemoryContext anl_context
Definition: analyze.c:85
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
PgStat_Counter pgStatBlockReadTime
Definition: pgstat.c:246
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:68
float8 n_distinct_inherited
Definition: attoptcache.h:23
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:583
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6218
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:511
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3454
#define PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE
Definition: progress.h:52
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:2085
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH
Definition: progress.h:49
static int elevel
Definition: vacuumlazy.c:403
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
void * palloc0(Size size)
Definition: mcxt.c:1093
int ii_NumIndexAttrs
Definition: execnodes.h:158
Oid MyDatabaseId
Definition: globals.c:88
#define InvalidMultiXactId
Definition: multixact.h:24
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
TupleDesc rd_att
Definition: rel.h:110
#define ereport(elevel,...)
Definition: elog.h:157
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS
Definition: progress.h:48
int message_level
Definition: genam.h:50
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
double num_heap_tuples
Definition: genam.h:51
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
static void compute_index_stats(Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
Definition: analyze.c:850
List * ii_Expressions
Definition: execnodes.h:161
#define VACOPT_VACUUM
Definition: vacuum.h:178
#define lfirst(lc)
Definition: pg_list.h:169
void pgstat_progress_update_param(int index, int64 val)
static int list_length(const List *l)
Definition: pg_list.h:149
int log_min_duration
Definition: vacuum.h:219
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4573
double tupleFract
Definition: analyze.c:75
#define InvalidAttrNumber
Definition: attnum.h:23
int NewGUCNestLevel(void)
Definition: guc.c:6204
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
VacAttrStats ** vacattrstats
Definition: analyze.c:76
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:134
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:1306
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition: analyze.c:1032
#define _(x)
Definition: elog.c:89
#define RelationGetRelid(relation)
Definition: rel.h:477
bool track_io_timing
Definition: bufmgr.c:135
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1693
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1793
void pgstat_report_anl_ancestors(Oid relid)
Definition: pgstat.c:1674
bool estimated_count
Definition: genam.h:49
float4 stadistinct
Definition: vacuum.h:145
IndexInfo * indexInfo
Definition: analyze.c:74
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ examine_attribute()

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

Definition at line 1032 of file analyze.c.

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

1033 {
1034  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1035  HeapTuple typtuple;
1036  VacAttrStats *stats;
1037  int i;
1038  bool ok;
1039 
1040  /* Never analyze dropped columns */
1041  if (attr->attisdropped)
1042  return NULL;
1043 
1044  /* Don't analyze column if user has specified not to */
1045  if (attr->attstattarget == 0)
1046  return NULL;
1047 
1048  /*
1049  * Create the VacAttrStats struct. Note that we only have a copy of the
1050  * fixed fields of the pg_attribute tuple.
1051  */
1052  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
1054  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
1055 
1056  /*
1057  * When analyzing an expression index, believe the expression tree's type
1058  * not the column datatype --- the latter might be the opckeytype storage
1059  * type of the opclass, which is not interesting for our purposes. (Note:
1060  * if we did anything with non-expression index columns, we'd need to
1061  * figure out where to get the correct type info from, but for now that's
1062  * not a problem.) It's not clear whether anyone will care about the
1063  * typmod, but we store that too just in case.
1064  */
1065  if (index_expr)
1066  {
1067  stats->attrtypid = exprType(index_expr);
1068  stats->attrtypmod = exprTypmod(index_expr);
1069 
1070  /*
1071  * If a collation has been specified for the index column, use that in
1072  * preference to anything else; but if not, fall back to whatever we
1073  * can get from the expression.
1074  */
1075  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1076  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1077  else
1078  stats->attrcollid = exprCollation(index_expr);
1079  }
1080  else
1081  {
1082  stats->attrtypid = attr->atttypid;
1083  stats->attrtypmod = attr->atttypmod;
1084  stats->attrcollid = attr->attcollation;
1085  }
1086 
1087  typtuple = SearchSysCacheCopy1(TYPEOID,
1088  ObjectIdGetDatum(stats->attrtypid));
1089  if (!HeapTupleIsValid(typtuple))
1090  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1091  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
1092  stats->anl_context = anl_context;
1093  stats->tupattnum = attnum;
1094 
1095  /*
1096  * The fields describing the stats->stavalues[n] element types default to
1097  * the type of the data being analyzed, but the type-specific typanalyze
1098  * function can change them if it wants to store something else.
1099  */
1100  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1101  {
1102  stats->statypid[i] = stats->attrtypid;
1103  stats->statyplen[i] = stats->attrtype->typlen;
1104  stats->statypbyval[i] = stats->attrtype->typbyval;
1105  stats->statypalign[i] = stats->attrtype->typalign;
1106  }
1107 
1108  /*
1109  * Call the type-specific typanalyze function. If none is specified, use
1110  * std_typanalyze().
1111  */
1112  if (OidIsValid(stats->attrtype->typanalyze))
1113  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1114  PointerGetDatum(stats)));
1115  else
1116  ok = std_typanalyze(stats);
1117 
1118  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1119  {
1120  heap_freetuple(typtuple);
1121  pfree(stats->attr);
1122  pfree(stats);
1123  return NULL;
1124  }
1125 
1126  return stats;
1127 }
int minrows
Definition: vacuum.h:135
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:267
#define PointerGetDatum(X)
Definition: postgres.h:600
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int tupattnum
Definition: vacuum.h:169
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1886
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:162
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int32 attrtypmod
Definition: vacuum.h:125
#define OidIsValid(objectId)
Definition: c.h:710
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:163
Form_pg_attribute attr
Definition: vacuum.h:123
void pfree(void *pointer)
Definition: mcxt.c:1169
Oid attrtypid
Definition: vacuum.h:124
Oid * rd_indcollation
Definition: rel.h:212
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:664
static MemoryContext anl_context
Definition: analyze.c:85
#define DatumGetBool(X)
Definition: postgres.h:437
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:199
void * palloc0(Size size)
Definition: mcxt.c:1093
TupleDesc rd_att
Definition: rel.h:110
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:160
int16 attnum
Definition: pg_attribute.h:83
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
Oid attrcollid
Definition: vacuum.h:127
MemoryContext anl_context
Definition: vacuum.h:128
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
Form_pg_type attrtype
Definition: vacuum.h:126
void * palloc(Size size)
Definition: mcxt.c:1062
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:161
#define elog(elevel,...)
Definition: elog.h:232
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:134

◆ ind_fetch_func()

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

Definition at line 1809 of file analyze.c.

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

Referenced by compute_index_stats().

1810 {
1811  int i;
1812 
1813  /* exprvals and exprnulls are already offset for proper column */
1814  i = rownum * stats->rowstride;
1815  *isNull = stats->exprnulls[i];
1816  return stats->exprvals[i];
1817 }
int rowstride
Definition: vacuum.h:174
bool * exprnulls
Definition: vacuum.h:173
Datum * exprvals
Definition: vacuum.h:172
int i

◆ std_fetch_func()

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

Definition at line 1793 of file analyze.c.

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

Referenced by do_analyze_rel().

1794 {
1795  int attnum = stats->tupattnum;
1796  HeapTuple tuple = stats->rows[rownum];
1797  TupleDesc tupDesc = stats->tupDesc;
1798 
1799  return heap_getattr(tuple, attnum, tupDesc, isNull);
1800 }
HeapTuple * rows
Definition: vacuum.h:170
int tupattnum
Definition: vacuum.h:169
TupleDesc tupDesc
Definition: vacuum.h:171
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:761
int16 attnum
Definition: pg_attribute.h:83

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

Definition at line 1886 of file analyze.c.

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

1887 {
1888  Form_pg_attribute attr = stats->attr;
1889  Oid ltopr;
1890  Oid eqopr;
1891  StdAnalyzeData *mystats;
1892 
1893  /* If the attstattarget column is negative, use the default value */
1894  /* NB: it is okay to scribble on stats->attr since it's a copy */
1895  if (attr->attstattarget < 0)
1896  attr->attstattarget = default_statistics_target;
1897 
1898  /* Look for default "<" and "=" operators for column's type */
1900  false, false, false,
1901  &ltopr, &eqopr, NULL,
1902  NULL);
1903 
1904  /* Save the operator info for compute_stats routines */
1905  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1906  mystats->eqopr = eqopr;
1907  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1908  mystats->ltopr = ltopr;
1909  stats->extra_data = mystats;
1910 
1911  /*
1912  * Determine which standard statistics algorithm to use
1913  */
1914  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1915  {
1916  /* Seems to be a scalar datatype */
1918  /*--------------------
1919  * The following choice of minrows is based on the paper
1920  * "Random sampling for histogram construction: how much is enough?"
1921  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1922  * Proceedings of ACM SIGMOD International Conference on Management
1923  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1924  * says that for table size n, histogram size k, maximum relative
1925  * error in bin size f, and error probability gamma, the minimum
1926  * random sample size is
1927  * r = 4 * k * ln(2*n/gamma) / f^2
1928  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1929  * r = 305.82 * k
1930  * Note that because of the log function, the dependence on n is
1931  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1932  * bin size error with probability 0.99. So there's no real need to
1933  * scale for n, which is a good thing because we don't necessarily
1934  * know it at this point.
1935  *--------------------
1936  */
1937  stats->minrows = 300 * attr->attstattarget;
1938  }
1939  else if (OidIsValid(eqopr))
1940  {
1941  /* We can still recognize distinct values */
1943  /* Might as well use the same minrows as above */
1944  stats->minrows = 300 * attr->attstattarget;
1945  }
1946  else
1947  {
1948  /* Can't do much but the trivial stuff */
1950  /* Might as well use the same minrows as above */
1951  stats->minrows = 300 * attr->attstattarget;
1952  }
1953 
1954  return true;
1955 }
int minrows
Definition: vacuum.h:135
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2399
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Form_pg_attribute attr
Definition: vacuum.h:123
Oid attrtypid
Definition: vacuum.h:124
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2056
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1256
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
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1966
void * palloc(Size size)
Definition: mcxt.c:1062
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:134
void * extra_data
Definition: vacuum.h:136
int default_statistics_target
Definition: analyze.c:82

◆ update_attstats()

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

Definition at line 1654 of file analyze.c.

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

Referenced by do_analyze_rel().

1655 {
1656  Relation sd;
1657  int attno;
1658 
1659  if (natts <= 0)
1660  return; /* nothing to do */
1661 
1662  sd = table_open(StatisticRelationId, RowExclusiveLock);
1663 
1664  for (attno = 0; attno < natts; attno++)
1665  {
1666  VacAttrStats *stats = vacattrstats[attno];
1667  HeapTuple stup,
1668  oldtup;
1669  int i,
1670  k,
1671  n;
1672  Datum values[Natts_pg_statistic];
1673  bool nulls[Natts_pg_statistic];
1674  bool replaces[Natts_pg_statistic];
1675 
1676  /* Ignore attr if we weren't able to collect stats */
1677  if (!stats->stats_valid)
1678  continue;
1679 
1680  /*
1681  * Construct a new pg_statistic tuple
1682  */
1683  for (i = 0; i < Natts_pg_statistic; ++i)
1684  {
1685  nulls[i] = false;
1686  replaces[i] = true;
1687  }
1688 
1689  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1690  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1691  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1692  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1693  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1694  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1695  i = Anum_pg_statistic_stakind1 - 1;
1696  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1697  {
1698  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1699  }
1700  i = Anum_pg_statistic_staop1 - 1;
1701  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1702  {
1703  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1704  }
1705  i = Anum_pg_statistic_stacoll1 - 1;
1706  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1707  {
1708  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1709  }
1710  i = Anum_pg_statistic_stanumbers1 - 1;
1711  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1712  {
1713  int nnum = stats->numnumbers[k];
1714 
1715  if (nnum > 0)
1716  {
1717  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1718  ArrayType *arry;
1719 
1720  for (n = 0; n < nnum; n++)
1721  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1722  /* XXX knows more than it should about type float4: */
1723  arry = construct_array(numdatums, nnum,
1724  FLOAT4OID,
1725  sizeof(float4), true, TYPALIGN_INT);
1726  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1727  }
1728  else
1729  {
1730  nulls[i] = true;
1731  values[i++] = (Datum) 0;
1732  }
1733  }
1734  i = Anum_pg_statistic_stavalues1 - 1;
1735  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1736  {
1737  if (stats->numvalues[k] > 0)
1738  {
1739  ArrayType *arry;
1740 
1741  arry = construct_array(stats->stavalues[k],
1742  stats->numvalues[k],
1743  stats->statypid[k],
1744  stats->statyplen[k],
1745  stats->statypbyval[k],
1746  stats->statypalign[k]);
1747  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1748  }
1749  else
1750  {
1751  nulls[i] = true;
1752  values[i++] = (Datum) 0;
1753  }
1754  }
1755 
1756  /* Is there already a pg_statistic tuple for this attribute? */
1757  oldtup = SearchSysCache3(STATRELATTINH,
1758  ObjectIdGetDatum(relid),
1759  Int16GetDatum(stats->attr->attnum),
1760  BoolGetDatum(inh));
1761 
1762  if (HeapTupleIsValid(oldtup))
1763  {
1764  /* Yes, replace it */
1765  stup = heap_modify_tuple(oldtup,
1766  RelationGetDescr(sd),
1767  values,
1768  nulls,
1769  replaces);
1770  ReleaseSysCache(oldtup);
1771  CatalogTupleUpdate(sd, &stup->t_self, stup);
1772  }
1773  else
1774  {
1775  /* No, insert new tuple */
1776  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1777  CatalogTupleInsert(sd, stup);
1778  }
1779 
1780  heap_freetuple(stup);
1781  }
1782 
1784 }
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:725
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:503
#define PointerGetDatum(X)
Definition: postgres.h:600
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:152
#define Int16GetDatum(X)
Definition: postgres.h:495
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:162
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:163
Form_pg_attribute attr
Definition: vacuum.h:123
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
int32 stawidth
Definition: vacuum.h:144
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:148
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1149
ItemPointerData t_self
Definition: htup.h:65
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:149
#define RowExclusiveLock
Definition: lockdefs.h:38
float4 stanullfrac
Definition: vacuum.h:143
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:147
bool stats_valid
Definition: vacuum.h:142
float float4
Definition: c.h:564
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:146
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:160
#define BoolGetDatum(X)
Definition: postgres.h:446
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:150
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define Int32GetDatum(X)
Definition: postgres.h:523
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:151
void * palloc(Size size)
Definition: mcxt.c:1062
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:161
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
float4 stadistinct
Definition: vacuum.h:145

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 85 of file analyze.c.

Referenced by examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 86 of file analyze.c.

Referenced by do_analyze_rel().