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

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1826 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 1396 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().

1399 {
1400  List *tableOIDs;
1401  Relation *rels;
1402  AcquireSampleRowsFunc *acquirefuncs;
1403  double *relblocks;
1404  double totalblocks;
1405  int numrows,
1406  nrels,
1407  i;
1408  ListCell *lc;
1409  bool has_child;
1410 
1411  /*
1412  * Find all members of inheritance set. We only need AccessShareLock on
1413  * the children.
1414  */
1415  tableOIDs =
1417 
1418  /*
1419  * Check that there's at least one descendant, else fail. This could
1420  * happen despite analyze_rel's relhassubclass check, if table once had a
1421  * child but no longer does. In that case, we can clear the
1422  * relhassubclass field so as not to make the same mistake again later.
1423  * (This is safe because we hold ShareUpdateExclusiveLock.)
1424  */
1425  if (list_length(tableOIDs) < 2)
1426  {
1427  /* CCI because we already updated the pg_class row in this command */
1429  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1430  ereport(elevel,
1431  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1433  RelationGetRelationName(onerel))));
1434  return 0;
1435  }
1436 
1437  /*
1438  * Identify acquirefuncs to use, and count blocks in all the relations.
1439  * The result could overflow BlockNumber, so we use double arithmetic.
1440  */
1441  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1442  acquirefuncs = (AcquireSampleRowsFunc *)
1443  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1444  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1445  totalblocks = 0;
1446  nrels = 0;
1447  has_child = false;
1448  foreach(lc, tableOIDs)
1449  {
1450  Oid childOID = lfirst_oid(lc);
1451  Relation childrel;
1452  AcquireSampleRowsFunc acquirefunc = NULL;
1453  BlockNumber relpages = 0;
1454 
1455  /* We already got the needed lock */
1456  childrel = table_open(childOID, NoLock);
1457 
1458  /* Ignore if temp table of another backend */
1459  if (RELATION_IS_OTHER_TEMP(childrel))
1460  {
1461  /* ... but release the lock on it */
1462  Assert(childrel != onerel);
1463  table_close(childrel, AccessShareLock);
1464  continue;
1465  }
1466 
1467  /* Check table type (MATVIEW can't happen, but might as well allow) */
1468  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1469  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1470  {
1471  /* Regular table, so use the regular row acquisition function */
1472  acquirefunc = acquire_sample_rows;
1473  relpages = RelationGetNumberOfBlocks(childrel);
1474  }
1475  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1476  {
1477  /*
1478  * For a foreign table, call the FDW's hook function to see
1479  * whether it supports analysis.
1480  */
1481  FdwRoutine *fdwroutine;
1482  bool ok = false;
1483 
1484  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1485 
1486  if (fdwroutine->AnalyzeForeignTable != NULL)
1487  ok = fdwroutine->AnalyzeForeignTable(childrel,
1488  &acquirefunc,
1489  &relpages);
1490 
1491  if (!ok)
1492  {
1493  /* ignore, but release the lock on it */
1494  Assert(childrel != onerel);
1495  table_close(childrel, AccessShareLock);
1496  continue;
1497  }
1498  }
1499  else
1500  {
1501  /*
1502  * ignore, but release the lock on it. don't try to unlock the
1503  * passed-in relation
1504  */
1505  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1506  if (childrel != onerel)
1507  table_close(childrel, AccessShareLock);
1508  else
1509  table_close(childrel, NoLock);
1510  continue;
1511  }
1512 
1513  /* OK, we'll process this child */
1514  has_child = true;
1515  rels[nrels] = childrel;
1516  acquirefuncs[nrels] = acquirefunc;
1517  relblocks[nrels] = (double) relpages;
1518  totalblocks += (double) relpages;
1519  nrels++;
1520  }
1521 
1522  /*
1523  * If we don't have at least one child table to consider, fail. If the
1524  * relation is a partitioned table, it's not counted as a child table.
1525  */
1526  if (!has_child)
1527  {
1528  ereport(elevel,
1529  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1531  RelationGetRelationName(onerel))));
1532  return 0;
1533  }
1534 
1535  /*
1536  * Now sample rows from each relation, proportionally to its fraction of
1537  * the total block count. (This might be less than desirable if the child
1538  * rels have radically different free-space percentages, but it's not
1539  * clear that it's worth working harder.)
1540  */
1542  nrels);
1543  numrows = 0;
1544  *totalrows = 0;
1545  *totaldeadrows = 0;
1546  for (i = 0; i < nrels; i++)
1547  {
1548  Relation childrel = rels[i];
1549  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1550  double childblocks = relblocks[i];
1551 
1553  RelationGetRelid(childrel));
1554 
1555  if (childblocks > 0)
1556  {
1557  int childtargrows;
1558 
1559  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1560  /* Make sure we don't overrun due to roundoff error */
1561  childtargrows = Min(childtargrows, targrows - numrows);
1562  if (childtargrows > 0)
1563  {
1564  int childrows;
1565  double trows,
1566  tdrows;
1567 
1568  /* Fetch a random sample of the child's rows */
1569  childrows = (*acquirefunc) (childrel, elevel,
1570  rows + numrows, childtargrows,
1571  &trows, &tdrows);
1572 
1573  /* We may need to convert from child's rowtype to parent's */
1574  if (childrows > 0 &&
1575  !equalTupleDescs(RelationGetDescr(childrel),
1576  RelationGetDescr(onerel)))
1577  {
1578  TupleConversionMap *map;
1579 
1580  map = convert_tuples_by_name(RelationGetDescr(childrel),
1581  RelationGetDescr(onerel));
1582  if (map != NULL)
1583  {
1584  int j;
1585 
1586  for (j = 0; j < childrows; j++)
1587  {
1588  HeapTuple newtup;
1589 
1590  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1591  heap_freetuple(rows[numrows + j]);
1592  rows[numrows + j] = newtup;
1593  }
1594  free_conversion_map(map);
1595  }
1596  }
1597 
1598  /* And add to counts */
1599  numrows += childrows;
1600  *totalrows += trows;
1601  *totaldeadrows += tdrows;
1602  }
1603  }
1604 
1605  /*
1606  * Note: we cannot release the child-table locks, since we may have
1607  * pointers to their TOAST tables in the sampled rows.
1608  */
1609  table_close(childrel, NoLock);
1611  i + 1);
1612  }
1613 
1614  return numrows;
1615 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:483
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:258
#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:110
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:3253
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:491
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:139
static int elevel
Definition: vacuumlazy.c:400
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:600
#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:213
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:457
#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:1150
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ acquire_sample_rows()

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

Definition at line 1150 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().

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

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

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

◆ compare_mcvs()

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

Definition at line 2946 of file analyze.c.

Referenced by compute_scalar_stats().

2947 {
2948  int da = ((const ScalarMCVItem *) a)->first;
2949  int db = ((const ScalarMCVItem *) b)->first;
2950 
2951  return da - db;
2952 }

◆ compare_rows()

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

Definition at line 1366 of file analyze.c.

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1367 {
1368  HeapTuple ha = *(const HeapTuple *) a;
1369  HeapTuple hb = *(const HeapTuple *) b;
1374 
1375  if (ba < bb)
1376  return -1;
1377  if (ba > bb)
1378  return 1;
1379  if (oa < ob)
1380  return -1;
1381  if (oa > ob)
1382  return 1;
1383  return 0;
1384 }
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 2915 of file analyze.c.

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

Referenced by compute_scalar_stats().

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

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

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

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

1957 {
1958  int i;
1959  int null_cnt = 0;
1960  int nonnull_cnt = 0;
1961  double total_width = 0;
1962  bool is_varlena = (!stats->attrtype->typbyval &&
1963  stats->attrtype->typlen == -1);
1964  bool is_varwidth = (!stats->attrtype->typbyval &&
1965  stats->attrtype->typlen < 0);
1966 
1967  for (i = 0; i < samplerows; i++)
1968  {
1969  Datum value;
1970  bool isnull;
1971 
1973 
1974  value = fetchfunc(stats, i, &isnull);
1975 
1976  /* Check for null/nonnull */
1977  if (isnull)
1978  {
1979  null_cnt++;
1980  continue;
1981  }
1982  nonnull_cnt++;
1983 
1984  /*
1985  * If it's a variable-width field, add up widths for average width
1986  * calculation. Note that if the value is toasted, we use the toasted
1987  * width. We don't bother with this calculation if it's a fixed-width
1988  * type.
1989  */
1990  if (is_varlena)
1991  {
1992  total_width += VARSIZE_ANY(DatumGetPointer(value));
1993  }
1994  else if (is_varwidth)
1995  {
1996  /* must be cstring */
1997  total_width += strlen(DatumGetCString(value)) + 1;
1998  }
1999  }
2000 
2001  /* We can only compute average width if we found some non-null values. */
2002  if (nonnull_cnt > 0)
2003  {
2004  stats->stats_valid = true;
2005  /* Do the simple null-frac and width stats */
2006  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2007  if (is_varwidth)
2008  stats->stawidth = total_width / (double) nonnull_cnt;
2009  else
2010  stats->stawidth = stats->attrtype->typlen;
2011  stats->stadistinct = 0.0; /* "unknown" */
2012  }
2013  else if (null_cnt > 0)
2014  {
2015  /* We found only nulls; assume the column is entirely null */
2016  stats->stats_valid = true;
2017  stats->stanullfrac = 1.0;
2018  if (is_varwidth)
2019  stats->stawidth = 0; /* "unknown" */
2020  else
2021  stats->stawidth = stats->attrtype->typlen;
2022  stats->stadistinct = 0.0; /* "unknown" */
2023  }
2024 }
static struct @142 value
#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
#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:2116
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_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, 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. If we are
424  * doing a recursive scan, we don't want to touch the parent's indexes at
425  * all.
426  */
427  if (!inh)
428  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
429  else
430  {
431  Irel = NULL;
432  nindexes = 0;
433  }
434  hasindex = (nindexes > 0);
435  indexdata = NULL;
436  if (hasindex)
437  {
438  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
439  for (ind = 0; ind < nindexes; ind++)
440  {
441  AnlIndexData *thisdata = &indexdata[ind];
442  IndexInfo *indexInfo;
443 
444  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
445  thisdata->tupleFract = 1.0; /* fix later if partial */
446  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
447  {
448  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
449 
450  thisdata->vacattrstats = (VacAttrStats **)
451  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
452  tcnt = 0;
453  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
454  {
455  int keycol = indexInfo->ii_IndexAttrNumbers[i];
456 
457  if (keycol == 0)
458  {
459  /* Found an index expression */
460  Node *indexkey;
461 
462  if (indexpr_item == NULL) /* shouldn't happen */
463  elog(ERROR, "too few entries in indexprs list");
464  indexkey = (Node *) lfirst(indexpr_item);
465  indexpr_item = lnext(indexInfo->ii_Expressions,
466  indexpr_item);
467  thisdata->vacattrstats[tcnt] =
468  examine_attribute(Irel[ind], i + 1, indexkey);
469  if (thisdata->vacattrstats[tcnt] != NULL)
470  tcnt++;
471  }
472  }
473  thisdata->attr_cnt = tcnt;
474  }
475  }
476  }
477 
478  /*
479  * Determine how many rows we need to sample, using the worst case from
480  * all analyzable columns. We use a lower bound of 100 rows to avoid
481  * possible overflow in Vitter's algorithm. (Note: that will also be the
482  * target in the corner case where there are no analyzable columns.)
483  */
484  targrows = 100;
485  for (i = 0; i < attr_cnt; i++)
486  {
487  if (targrows < vacattrstats[i]->minrows)
488  targrows = vacattrstats[i]->minrows;
489  }
490  for (ind = 0; ind < nindexes; ind++)
491  {
492  AnlIndexData *thisdata = &indexdata[ind];
493 
494  for (i = 0; i < thisdata->attr_cnt; i++)
495  {
496  if (targrows < thisdata->vacattrstats[i]->minrows)
497  targrows = thisdata->vacattrstats[i]->minrows;
498  }
499  }
500 
501  /*
502  * Look at extended statistics objects too, as those may define custom
503  * statistics target. So we may need to sample more rows and then build
504  * the statistics with enough detail.
505  */
506  minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
507 
508  if (targrows < minrows)
509  targrows = minrows;
510 
511  /*
512  * Acquire the sample rows
513  */
514  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
518  if (inh)
519  numrows = acquire_inherited_sample_rows(onerel, elevel,
520  rows, targrows,
521  &totalrows, &totaldeadrows);
522  else
523  numrows = (*acquirefunc) (onerel, elevel,
524  rows, targrows,
525  &totalrows, &totaldeadrows);
526 
527  /*
528  * Compute the statistics. Temporary results during the calculations for
529  * each column are stored in a child context. The calc routines are
530  * responsible to make sure that whatever they store into the VacAttrStats
531  * structure is allocated in anl_context.
532  */
533  if (numrows > 0)
534  {
535  MemoryContext col_context,
536  old_context;
537 
540 
541  col_context = AllocSetContextCreate(anl_context,
542  "Analyze Column",
544  old_context = MemoryContextSwitchTo(col_context);
545 
546  for (i = 0; i < attr_cnt; i++)
547  {
548  VacAttrStats *stats = vacattrstats[i];
549  AttributeOpts *aopt;
550 
551  stats->rows = rows;
552  stats->tupDesc = onerel->rd_att;
553  stats->compute_stats(stats,
555  numrows,
556  totalrows);
557 
558  /*
559  * If the appropriate flavor of the n_distinct option is
560  * specified, override with the corresponding value.
561  */
562  aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
563  if (aopt != NULL)
564  {
565  float8 n_distinct;
566 
567  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
568  if (n_distinct != 0.0)
569  stats->stadistinct = n_distinct;
570  }
571 
573  }
574 
575  if (hasindex)
576  compute_index_stats(onerel, totalrows,
577  indexdata, nindexes,
578  rows, numrows,
579  col_context);
580 
581  MemoryContextSwitchTo(old_context);
582  MemoryContextDelete(col_context);
583 
584  /*
585  * Emit the completed stats rows into pg_statistic, replacing any
586  * previous statistics for the target columns. (If there are stats in
587  * pg_statistic for columns we didn't process, we leave them alone.)
588  */
589  update_attstats(RelationGetRelid(onerel), inh,
590  attr_cnt, vacattrstats);
591 
592  for (ind = 0; ind < nindexes; ind++)
593  {
594  AnlIndexData *thisdata = &indexdata[ind];
595 
596  update_attstats(RelationGetRelid(Irel[ind]), false,
597  thisdata->attr_cnt, thisdata->vacattrstats);
598  }
599 
600  /*
601  * Build extended statistics (if there are any).
602  *
603  * For now we only build extended statistics on individual relations,
604  * not for relations representing inheritance trees.
605  */
606  if (!inh)
607  BuildRelationExtStatistics(onerel, totalrows, numrows, rows,
608  attr_cnt, vacattrstats);
609  }
610 
613 
614  /*
615  * Update pages/tuples stats in pg_class ... but not if we're doing
616  * inherited stats.
617  *
618  * We assume that VACUUM hasn't set pg_class.reltuples already, even
619  * during a VACUUM ANALYZE. Although VACUUM often updates pg_class,
620  * exceptions exist. A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command
621  * will never update pg_class entries for index relations. It's also
622  * possible that an individual index's pg_class entry won't be updated
623  * during VACUUM if the index AM returns NULL from its amvacuumcleanup()
624  * routine.
625  */
626  if (!inh)
627  {
628  BlockNumber relallvisible;
629 
630  visibilitymap_count(onerel, &relallvisible, NULL);
631 
632  /* Update pg_class for table relation */
633  vac_update_relstats(onerel,
634  relpages,
635  totalrows,
636  relallvisible,
637  hasindex,
640  in_outer_xact);
641 
642  /* Same for indexes */
643  for (ind = 0; ind < nindexes; ind++)
644  {
645  AnlIndexData *thisdata = &indexdata[ind];
646  double totalindexrows;
647 
648  totalindexrows = ceil(thisdata->tupleFract * totalrows);
649  vac_update_relstats(Irel[ind],
650  RelationGetNumberOfBlocks(Irel[ind]),
651  totalindexrows,
652  0,
653  false,
656  in_outer_xact);
657  }
658  }
659  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
660  {
661  /*
662  * Partitioned tables don't have storage, so we don't set any fields in
663  * their pg_class entries except for reltuples, which is necessary for
664  * auto-analyze to work properly.
665  */
666  vac_update_relstats(onerel, -1, totalrows,
667  0, false, InvalidTransactionId,
669  in_outer_xact);
670  }
671 
672  /*
673  * Now report ANALYZE to the stats collector. For regular tables, we do
674  * it only if not doing inherited stats. For partitioned tables, we only
675  * do it for inherited stats. (We're never called for not-inherited stats
676  * on partitioned tables anyway.)
677  *
678  * Reset the changes_since_analyze counter only if we analyzed all
679  * columns; otherwise, there is still work for auto-analyze to do.
680  */
681  if (!inh || onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
682  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
683  (va_cols == NIL));
684 
685  /*
686  * If this is a manual analyze of all columns of a permanent leaf
687  * partition, and not doing inherited stats, also let the collector know
688  * about the ancestor tables of this partition. Autovacuum does the
689  * equivalent of this at the start of its run, so there's no reason to do
690  * it there.
691  */
692  if (!inh && !IsAutoVacuumWorkerProcess() &&
693  (va_cols == NIL) &&
694  onerel->rd_rel->relispartition &&
695  onerel->rd_rel->relkind == RELKIND_RELATION &&
696  onerel->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
697  {
699  }
700 
701  /*
702  * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
703  *
704  * Note that most index AMs perform a no-op as a matter of policy for
705  * amvacuumcleanup() when called in ANALYZE-only mode. The only exception
706  * among core index AMs is GIN/ginvacuumcleanup().
707  */
708  if (!(params->options & VACOPT_VACUUM))
709  {
710  for (ind = 0; ind < nindexes; ind++)
711  {
712  IndexBulkDeleteResult *stats;
713  IndexVacuumInfo ivinfo;
714 
715  ivinfo.index = Irel[ind];
716  ivinfo.analyze_only = true;
717  ivinfo.estimated_count = true;
718  ivinfo.message_level = elevel;
719  ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
720  ivinfo.strategy = vac_strategy;
721 
722  stats = index_vacuum_cleanup(&ivinfo, NULL);
723 
724  if (stats)
725  pfree(stats);
726  }
727  }
728 
729  /* Done with indexes */
730  vac_close_indexes(nindexes, Irel, NoLock);
731 
732  /* Log the action if appropriate */
733  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
734  {
735  TimestampTz endtime = GetCurrentTimestamp();
736 
737  if (params->log_min_duration == 0 ||
738  TimestampDifferenceExceeds(starttime, endtime,
739  params->log_min_duration))
740  {
741  long delay_in_ms;
742  double read_rate = 0;
743  double write_rate = 0;
745 
746  /*
747  * Calculate the difference in the Page Hit/Miss/Dirty that
748  * happened as part of the analyze by subtracting out the
749  * pre-analyze values which we saved above.
750  */
751  AnalyzePageHit = VacuumPageHit - AnalyzePageHit;
752  AnalyzePageMiss = VacuumPageMiss - AnalyzePageMiss;
753  AnalyzePageDirty = VacuumPageDirty - AnalyzePageDirty;
754 
755  /*
756  * We do not expect an analyze to take > 25 days and it simplifies
757  * things a bit to use TimestampDifferenceMilliseconds.
758  */
759  delay_in_ms = TimestampDifferenceMilliseconds(starttime, endtime);
760 
761  /*
762  * Note that we are reporting these read/write rates in the same
763  * manner as VACUUM does, which means that while the 'average read
764  * rate' here actually corresponds to page misses and resulting
765  * reads which are also picked up by track_io_timing, if enabled,
766  * the 'average write rate' is actually talking about the rate of
767  * pages being dirtied, not being written out, so it's typical to
768  * have a non-zero 'avg write rate' while I/O Timings only reports
769  * reads.
770  *
771  * It's not clear that an ANALYZE will ever result in
772  * FlushBuffer() being called, but we track and support reporting
773  * on I/O write time in case that changes as it's practically free
774  * to do so anyway.
775  */
776 
777  if (delay_in_ms > 0)
778  {
779  read_rate = (double) BLCKSZ * AnalyzePageMiss / (1024 * 1024) /
780  (delay_in_ms / 1000.0);
781  write_rate = (double) BLCKSZ * AnalyzePageDirty / (1024 * 1024) /
782  (delay_in_ms / 1000.0);
783  }
784 
785  /*
786  * We split this up so we don't emit empty I/O timing values when
787  * track_io_timing isn't enabled.
788  */
789 
790  initStringInfo(&buf);
791  appendStringInfo(&buf, _("automatic analyze of table \"%s.%s.%s\"\n"),
794  RelationGetRelationName(onerel));
795  appendStringInfo(&buf, _("buffer usage: %lld hits, %lld misses, %lld dirtied\n"),
796  (long long) AnalyzePageHit,
797  (long long) AnalyzePageMiss,
798  (long long) AnalyzePageDirty);
799  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
800  read_rate, write_rate);
801  if (track_io_timing)
802  {
803  appendStringInfoString(&buf, _("I/O Timings:"));
804  if (pgStatBlockReadTime - startreadtime > 0)
805  appendStringInfo(&buf, _(" read=%.3f"),
806  (double) (pgStatBlockReadTime - startreadtime) / 1000);
807  if (pgStatBlockWriteTime - startwritetime > 0)
808  appendStringInfo(&buf, _(" write=%.3f"),
809  (double) (pgStatBlockWriteTime - startwritetime) / 1000);
810  appendStringInfoChar(&buf, '\n');
811  }
812  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
813 
814  ereport(LOG,
815  (errmsg_internal("%s", buf.data)));
816 
817  pfree(buf.data);
818  }
819  }
820 
821  /* Roll back any GUC changes executed by index functions */
822  AtEOXact_GUC(false, save_nestlevel);
823 
824  /* Restore userid and security context */
825  SetUserIdAndSecContext(save_userid, save_sec_context);
826 
827  /* Restore current context and release memory */
828  MemoryContextSwitchTo(caller_context);
830  anl_context = NULL;
831 }
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:2095
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:1396
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:92
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:38
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:300
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:1616
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:1641
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2543
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:110
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:208
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:2155
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:6235
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:491
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3448
#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:2052
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH
Definition: progress.h:49
static int elevel
Definition: vacuumlazy.c:400
#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:111
#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:837
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:216
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
double tupleFract
Definition: analyze.c:75
#define InvalidAttrNumber
Definition: attnum.h:23
int NewGUCNestLevel(void)
Definition: guc.c:6221
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
VacAttrStats ** vacattrstats
Definition: analyze.c:76
#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:1292
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:1019
#define _(x)
Definition: elog.c:89
#define RelationGetRelid(relation)
Definition: rel.h:457
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:1780
void pgstat_report_anl_ancestors(Oid relid)
Definition: pgstat.c:1682
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:498

◆ examine_attribute()

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

Definition at line 1019 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().

1020 {
1021  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1022  HeapTuple typtuple;
1023  VacAttrStats *stats;
1024  int i;
1025  bool ok;
1026 
1027  /* Never analyze dropped columns */
1028  if (attr->attisdropped)
1029  return NULL;
1030 
1031  /* Don't analyze column if user has specified not to */
1032  if (attr->attstattarget == 0)
1033  return NULL;
1034 
1035  /*
1036  * Create the VacAttrStats struct. Note that we only have a copy of the
1037  * fixed fields of the pg_attribute tuple.
1038  */
1039  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
1041  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
1042 
1043  /*
1044  * When analyzing an expression index, believe the expression tree's type
1045  * not the column datatype --- the latter might be the opckeytype storage
1046  * type of the opclass, which is not interesting for our purposes. (Note:
1047  * if we did anything with non-expression index columns, we'd need to
1048  * figure out where to get the correct type info from, but for now that's
1049  * not a problem.) It's not clear whether anyone will care about the
1050  * typmod, but we store that too just in case.
1051  */
1052  if (index_expr)
1053  {
1054  stats->attrtypid = exprType(index_expr);
1055  stats->attrtypmod = exprTypmod(index_expr);
1056 
1057  /*
1058  * If a collation has been specified for the index column, use that in
1059  * preference to anything else; but if not, fall back to whatever we
1060  * can get from the expression.
1061  */
1062  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1063  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1064  else
1065  stats->attrcollid = exprCollation(index_expr);
1066  }
1067  else
1068  {
1069  stats->attrtypid = attr->atttypid;
1070  stats->attrtypmod = attr->atttypmod;
1071  stats->attrcollid = attr->attcollation;
1072  }
1073 
1074  typtuple = SearchSysCacheCopy1(TYPEOID,
1075  ObjectIdGetDatum(stats->attrtypid));
1076  if (!HeapTupleIsValid(typtuple))
1077  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1078  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
1079  stats->anl_context = anl_context;
1080  stats->tupattnum = attnum;
1081 
1082  /*
1083  * The fields describing the stats->stavalues[n] element types default to
1084  * the type of the data being analyzed, but the type-specific typanalyze
1085  * function can change them if it wants to store something else.
1086  */
1087  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1088  {
1089  stats->statypid[i] = stats->attrtypid;
1090  stats->statyplen[i] = stats->attrtype->typlen;
1091  stats->statypbyval[i] = stats->attrtype->typbyval;
1092  stats->statypalign[i] = stats->attrtype->typalign;
1093  }
1094 
1095  /*
1096  * Call the type-specific typanalyze function. If none is specified, use
1097  * std_typanalyze().
1098  */
1099  if (OidIsValid(stats->attrtype->typanalyze))
1100  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1101  PointerGetDatum(stats)));
1102  else
1103  ok = std_typanalyze(stats);
1104 
1105  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1106  {
1107  heap_freetuple(typtuple);
1108  pfree(stats->attr);
1109  pfree(stats);
1110  return NULL;
1111  }
1112 
1113  return stats;
1114 }
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:1873
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:200
#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:203
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:195
void * palloc0(Size size)
Definition: mcxt.c:1093
TupleDesc rd_att
Definition: rel.h:111
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 1796 of file analyze.c.

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

Referenced by compute_index_stats().

1797 {
1798  int i;
1799 
1800  /* exprvals and exprnulls are already offset for proper column */
1801  i = rownum * stats->rowstride;
1802  *isNull = stats->exprnulls[i];
1803  return stats->exprvals[i];
1804 }
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 1780 of file analyze.c.

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

Referenced by do_analyze_rel().

1781 {
1782  int attnum = stats->tupattnum;
1783  HeapTuple tuple = stats->rows[rownum];
1784  TupleDesc tupDesc = stats->tupDesc;
1785 
1786  return heap_getattr(tuple, attnum, tupDesc, isNull);
1787 }
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 1873 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().

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

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