PostgreSQL Source Code  git master
analyze.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/multixact.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "access/tupconvert.h"
#include "access/tuptoaster.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_fn.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_statistic_ext.h"
#include "commands/dbcommands.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/syscache.h"
#include "utils/timestamp.h"
#include "utils/tqual.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, int options, 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, int options, 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)
 
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 1701 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 1700 of file analyze.c.

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1698 of file analyze.c.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

Typedef Documentation

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

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert, CommandCounterIncrement(), convert_tuples_by_name(), do_convert_tuple(), elevel, equalTupleDescs(), ereport, errmsg(), find_all_inheritors(), free_conversion_map(), get_namespace_name(), GetFdwRoutineForRelation(), gettext_noop, heap_close, heap_freetuple(), heap_open(), i, lfirst_oid, list_length(), Min, NoLock, palloc(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, rint(), and SetRelationHasSubclass().

Referenced by do_analyze_rel().

1282 {
1283  List *tableOIDs;
1284  Relation *rels;
1285  AcquireSampleRowsFunc *acquirefuncs;
1286  double *relblocks;
1287  double totalblocks;
1288  int numrows,
1289  nrels,
1290  i;
1291  ListCell *lc;
1292  bool has_child;
1293 
1294  /*
1295  * Find all members of inheritance set. We only need AccessShareLock on
1296  * the children.
1297  */
1298  tableOIDs =
1300 
1301  /*
1302  * Check that there's at least one descendant, else fail. This could
1303  * happen despite analyze_rel's relhassubclass check, if table once had a
1304  * child but no longer does. In that case, we can clear the
1305  * relhassubclass field so as not to make the same mistake again later.
1306  * (This is safe because we hold ShareUpdateExclusiveLock.)
1307  */
1308  if (list_length(tableOIDs) < 2)
1309  {
1310  /* CCI because we already updated the pg_class row in this command */
1312  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1313  ereport(elevel,
1314  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1316  RelationGetRelationName(onerel))));
1317  return 0;
1318  }
1319 
1320  /*
1321  * Identify acquirefuncs to use, and count blocks in all the relations.
1322  * The result could overflow BlockNumber, so we use double arithmetic.
1323  */
1324  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1325  acquirefuncs = (AcquireSampleRowsFunc *)
1326  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1327  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1328  totalblocks = 0;
1329  nrels = 0;
1330  has_child = false;
1331  foreach(lc, tableOIDs)
1332  {
1333  Oid childOID = lfirst_oid(lc);
1334  Relation childrel;
1335  AcquireSampleRowsFunc acquirefunc = NULL;
1336  BlockNumber relpages = 0;
1337 
1338  /* We already got the needed lock */
1339  childrel = heap_open(childOID, NoLock);
1340 
1341  /* Ignore if temp table of another backend */
1342  if (RELATION_IS_OTHER_TEMP(childrel))
1343  {
1344  /* ... but release the lock on it */
1345  Assert(childrel != onerel);
1346  heap_close(childrel, AccessShareLock);
1347  continue;
1348  }
1349 
1350  /* Check table type (MATVIEW can't happen, but might as well allow) */
1351  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1352  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1353  {
1354  /* Regular table, so use the regular row acquisition function */
1355  acquirefunc = acquire_sample_rows;
1356  relpages = RelationGetNumberOfBlocks(childrel);
1357  }
1358  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1359  {
1360  /*
1361  * For a foreign table, call the FDW's hook function to see
1362  * whether it supports analysis.
1363  */
1364  FdwRoutine *fdwroutine;
1365  bool ok = false;
1366 
1367  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1368 
1369  if (fdwroutine->AnalyzeForeignTable != NULL)
1370  ok = fdwroutine->AnalyzeForeignTable(childrel,
1371  &acquirefunc,
1372  &relpages);
1373 
1374  if (!ok)
1375  {
1376  /* ignore, but release the lock on it */
1377  Assert(childrel != onerel);
1378  heap_close(childrel, AccessShareLock);
1379  continue;
1380  }
1381  }
1382  else
1383  {
1384  /*
1385  * ignore, but release the lock on it. don't try to unlock the
1386  * passed-in relation
1387  */
1388  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1389  if (childrel != onerel)
1390  heap_close(childrel, AccessShareLock);
1391  else
1392  heap_close(childrel, NoLock);
1393  continue;
1394  }
1395 
1396  /* OK, we'll process this child */
1397  has_child = true;
1398  rels[nrels] = childrel;
1399  acquirefuncs[nrels] = acquirefunc;
1400  relblocks[nrels] = (double) relpages;
1401  totalblocks += (double) relpages;
1402  nrels++;
1403  }
1404 
1405  /*
1406  * If we don't have at least one child table to consider, fail. If the
1407  * relation is a partitioned table, it's not counted as a child table.
1408  */
1409  if (!has_child)
1410  {
1411  ereport(elevel,
1412  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1414  RelationGetRelationName(onerel))));
1415  return 0;
1416  }
1417 
1418  /*
1419  * Now sample rows from each relation, proportionally to its fraction of
1420  * the total block count. (This might be less than desirable if the child
1421  * rels have radically different free-space percentages, but it's not
1422  * clear that it's worth working harder.)
1423  */
1424  numrows = 0;
1425  *totalrows = 0;
1426  *totaldeadrows = 0;
1427  for (i = 0; i < nrels; i++)
1428  {
1429  Relation childrel = rels[i];
1430  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1431  double childblocks = relblocks[i];
1432 
1433  if (childblocks > 0)
1434  {
1435  int childtargrows;
1436 
1437  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1438  /* Make sure we don't overrun due to roundoff error */
1439  childtargrows = Min(childtargrows, targrows - numrows);
1440  if (childtargrows > 0)
1441  {
1442  int childrows;
1443  double trows,
1444  tdrows;
1445 
1446  /* Fetch a random sample of the child's rows */
1447  childrows = (*acquirefunc) (childrel, elevel,
1448  rows + numrows, childtargrows,
1449  &trows, &tdrows);
1450 
1451  /* We may need to convert from child's rowtype to parent's */
1452  if (childrows > 0 &&
1453  !equalTupleDescs(RelationGetDescr(childrel),
1454  RelationGetDescr(onerel)))
1455  {
1456  TupleConversionMap *map;
1457 
1458  map = convert_tuples_by_name(RelationGetDescr(childrel),
1459  RelationGetDescr(onerel),
1460  gettext_noop("could not convert row type"));
1461  if (map != NULL)
1462  {
1463  int j;
1464 
1465  for (j = 0; j < childrows; j++)
1466  {
1467  HeapTuple newtup;
1468 
1469  newtup = do_convert_tuple(rows[numrows + j], map);
1470  heap_freetuple(rows[numrows + j]);
1471  rows[numrows + j] = newtup;
1472  }
1473  free_conversion_map(map);
1474  }
1475  }
1476 
1477  /* And add to counts */
1478  numrows += childrows;
1479  *totalrows += trows;
1480  *totaldeadrows += tdrows;
1481  }
1482  }
1483 
1484  /*
1485  * Note: we cannot release the child-table locks, since we may have
1486  * pointers to their TOAST tables in the sampled rows.
1487  */
1488  heap_close(childrel, NoLock);
1489  }
1490 
1491  return numrows;
1492 }
#define RelationGetDescr(relation)
Definition: rel.h:428
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:224
#define Min(x, y)
Definition: c.h:802
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define AccessShareLock
Definition: lockdefs.h:36
#define gettext_noop(x)
Definition: c.h:981
uint32 BlockNumber
Definition: block.h:31
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
unsigned int Oid
Definition: postgres_ext.h:31
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:2489
struct RelationData * Relation
Definition: relcache.h:26
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3047
#define NoLock
Definition: lockdefs.h:34
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:392
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
double rint(double x)
Definition: rint.c:22
#define ereport(elevel, rest)
Definition: elog.h:122
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:210
static int elevel
Definition: vacuumlazy.c:136
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void CommandCounterIncrement(void)
Definition: xact.c:915
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define Assert(condition)
Definition: c.h:670
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:533
static int list_length(const List *l)
Definition: pg_list.h:89
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:134
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:167
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
int i
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:337
#define RELKIND_RELATION
Definition: pg_class.h:160
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
#define lfirst_oid(lc)
Definition: pg_list.h:108
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1006
#define RelationGetNamespace(relation)
Definition: rel.h:443

◆ acquire_sample_rows()

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

Definition at line 1006 of file analyze.c.

References Assert, BlockSampler_HasMore(), BlockSampler_Init(), BlockSampler_Next(), BUFFER_LOCK_SHARE, BufferGetPage, compare_rows(), elog, ereport, errmsg(), ERROR, FirstOffsetNumber, GetOldestXmin(), heap_copytuple(), heap_freetuple(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleSatisfiesVacuum(), ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemPointerSet, LockBuffer(), BlockSamplerData::m, MAIN_FORKNUM, OldestXmin, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PROCARRAY_FLAGS_VACUUM, qsort, random(), ReservoirStateData::randstate, RBM_NORMAL, ReadBufferExtended(), RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, reservoir_get_next_S(), reservoir_init_selection_state(), sampler_random_fract(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdIsCurrentTransactionId(), UnlockReleaseBuffer(), vac_estimate_reltuples(), and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

1009 {
1010  int numrows = 0; /* # rows now in reservoir */
1011  double samplerows = 0; /* total # rows collected */
1012  double liverows = 0; /* # live rows seen */
1013  double deadrows = 0; /* # dead rows seen */
1014  double rowstoskip = -1; /* -1 means not set yet */
1015  BlockNumber totalblocks;
1017  BlockSamplerData bs;
1018  ReservoirStateData rstate;
1019 
1020  Assert(targrows > 0);
1021 
1022  totalblocks = RelationGetNumberOfBlocks(onerel);
1023 
1024  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1025  OldestXmin = GetOldestXmin(onerel, PROCARRAY_FLAGS_VACUUM);
1026 
1027  /* Prepare for sampling block numbers */
1028  BlockSampler_Init(&bs, totalblocks, targrows, random());
1029  /* Prepare for sampling rows */
1030  reservoir_init_selection_state(&rstate, targrows);
1031 
1032  /* Outer loop over blocks to sample */
1033  while (BlockSampler_HasMore(&bs))
1034  {
1035  BlockNumber targblock = BlockSampler_Next(&bs);
1036  Buffer targbuffer;
1037  Page targpage;
1038  OffsetNumber targoffset,
1039  maxoffset;
1040 
1042 
1043  /*
1044  * We must maintain a pin on the target page's buffer to ensure that
1045  * the maxoffset value stays good (else concurrent VACUUM might delete
1046  * tuples out from under us). Hence, pin the page until we are done
1047  * looking at it. We also choose to hold sharelock on the buffer
1048  * throughout --- we could release and re-acquire sharelock for each
1049  * tuple, but since we aren't doing much work per tuple, the extra
1050  * lock traffic is probably better avoided.
1051  */
1052  targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1054  LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1055  targpage = BufferGetPage(targbuffer);
1056  maxoffset = PageGetMaxOffsetNumber(targpage);
1057 
1058  /* Inner loop over all tuples on the selected page */
1059  for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1060  {
1061  ItemId itemid;
1062  HeapTupleData targtuple;
1063  bool sample_it = false;
1064 
1065  itemid = PageGetItemId(targpage, targoffset);
1066 
1067  /*
1068  * We ignore unused and redirect line pointers. DEAD line
1069  * pointers should be counted as dead, because we need vacuum to
1070  * run to get rid of them. Note that this rule agrees with the
1071  * way that heap_page_prune() counts things.
1072  */
1073  if (!ItemIdIsNormal(itemid))
1074  {
1075  if (ItemIdIsDead(itemid))
1076  deadrows += 1;
1077  continue;
1078  }
1079 
1080  ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1081 
1082  targtuple.t_tableOid = RelationGetRelid(onerel);
1083  targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1084  targtuple.t_len = ItemIdGetLength(itemid);
1085 
1086  switch (HeapTupleSatisfiesVacuum(&targtuple,
1087  OldestXmin,
1088  targbuffer))
1089  {
1090  case HEAPTUPLE_LIVE:
1091  sample_it = true;
1092  liverows += 1;
1093  break;
1094 
1095  case HEAPTUPLE_DEAD:
1097  /* Count dead and recently-dead rows */
1098  deadrows += 1;
1099  break;
1100 
1102 
1103  /*
1104  * Insert-in-progress rows are not counted. We assume
1105  * that when the inserting transaction commits or aborts,
1106  * it will send a stats message to increment the proper
1107  * count. This works right only if that transaction ends
1108  * after we finish analyzing the table; if things happen
1109  * in the other order, its stats update will be
1110  * overwritten by ours. However, the error will be large
1111  * only if the other transaction runs long enough to
1112  * insert many tuples, so assuming it will finish after us
1113  * is the safer option.
1114  *
1115  * A special case is that the inserting transaction might
1116  * be our own. In this case we should count and sample
1117  * the row, to accommodate users who load a table and
1118  * analyze it in one transaction. (pgstat_report_analyze
1119  * has to adjust the numbers we send to the stats
1120  * collector to make this come out right.)
1121  */
1123  {
1124  sample_it = true;
1125  liverows += 1;
1126  }
1127  break;
1128 
1130 
1131  /*
1132  * We count delete-in-progress rows as still live, using
1133  * the same reasoning given above; but we don't bother to
1134  * include them in the sample.
1135  *
1136  * If the delete was done by our own transaction, however,
1137  * we must count the row as dead to make
1138  * pgstat_report_analyze's stats adjustments come out
1139  * right. (Note: this works out properly when the row was
1140  * both inserted and deleted in our xact.)
1141  */
1143  deadrows += 1;
1144  else
1145  liverows += 1;
1146  break;
1147 
1148  default:
1149  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1150  break;
1151  }
1152 
1153  if (sample_it)
1154  {
1155  /*
1156  * The first targrows sample rows are simply copied into the
1157  * reservoir. Then we start replacing tuples in the sample
1158  * until we reach the end of the relation. This algorithm is
1159  * from Jeff Vitter's paper (see full citation below). It
1160  * works by repeatedly computing the number of tuples to skip
1161  * before selecting a tuple, which replaces a randomly chosen
1162  * element of the reservoir (current set of tuples). At all
1163  * times the reservoir is a true random sample of the tuples
1164  * we've passed over so far, so when we fall off the end of
1165  * the relation we're done.
1166  */
1167  if (numrows < targrows)
1168  rows[numrows++] = heap_copytuple(&targtuple);
1169  else
1170  {
1171  /*
1172  * t in Vitter's paper is the number of records already
1173  * processed. If we need to compute a new S value, we
1174  * must use the not-yet-incremented value of samplerows as
1175  * t.
1176  */
1177  if (rowstoskip < 0)
1178  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1179 
1180  if (rowstoskip <= 0)
1181  {
1182  /*
1183  * Found a suitable tuple, so save it, replacing one
1184  * old tuple at random
1185  */
1186  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1187 
1188  Assert(k >= 0 && k < targrows);
1189  heap_freetuple(rows[k]);
1190  rows[k] = heap_copytuple(&targtuple);
1191  }
1192 
1193  rowstoskip -= 1;
1194  }
1195 
1196  samplerows += 1;
1197  }
1198  }
1199 
1200  /* Now release the lock and pin on the page */
1201  UnlockReleaseBuffer(targbuffer);
1202  }
1203 
1204  /*
1205  * If we didn't find as many tuples as we wanted then we're done. No sort
1206  * is needed, since they're already in order.
1207  *
1208  * Otherwise we need to sort the collected tuples by position
1209  * (itempointer). It's not worth worrying about corner cases where the
1210  * tuples are already sorted.
1211  */
1212  if (numrows == targrows)
1213  qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1214 
1215  /*
1216  * Estimate total numbers of rows in relation. For live rows, use
1217  * vac_estimate_reltuples; for dead rows, we have no source of old
1218  * information, so we have to assume the density is the same in unseen
1219  * pages as in the pages we scanned.
1220  */
1221  *totalrows = vac_estimate_reltuples(onerel, true,
1222  totalblocks,
1223  bs.m,
1224  liverows);
1225  if (bs.m > 0)
1226  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1227  else
1228  *totaldeadrows = 0.0;
1229 
1230  /*
1231  * Emit some interesting relation info
1232  */
1233  ereport(elevel,
1234  (errmsg("\"%s\": scanned %d of %u pages, "
1235  "containing %.0f live rows and %.0f dead rows; "
1236  "%d rows in sample, %.0f estimated total rows",
1237  RelationGetRelationName(onerel),
1238  bs.m, totalblocks,
1239  liverows, deadrows,
1240  numrows, *totalrows)));
1241 
1242  return numrows;
1243 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:364
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:54
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:611
double vac_estimate_reltuples(Relation relation, bool is_analyze, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
Definition: vacuum.c:777
uint32 TransactionId
Definition: c.h:445
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:766
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:60
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
long random(void)
Definition: random.c:22
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
Definition: tqual.c:1164
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
uint32 BlockNumber
Definition: block.h:31
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:129
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:52
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define ItemIdIsDead(itemId)
Definition: itemid.h:112
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:353
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, long randseed)
Definition: sampling.c:37
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
#define FirstOffsetNumber
Definition: off.h:27
#define RelationGetRelationName(relation)
Definition: rel.h:436
static TransactionId OldestXmin
Definition: vacuumlazy.c:138
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:122
static int compare_rows(const void *a, const void *b)
Definition: analyze.c:1249
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
static int elevel
Definition: vacuumlazy.c:136
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1315
#define Assert(condition)
Definition: c.h:670
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:312
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define elog
Definition: elog.h:219
#define qsort(a, b, c, d)
Definition: port.h:408
void vacuum_delay_point(void)
Definition: vacuum.c:1658
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:416
#define PageGetItem(page, itemId)
Definition: bufpage.h:336
Pointer Page
Definition: bufpage.h:74
SamplerRandomState randstate
Definition: sampling.h:50
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:105
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142

◆ analyze_rel()

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

Definition at line 115 of file analyze.c.

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, ConditionalLockRelationOid(), DEBUG2, do_analyze_rel(), elevel, ereport, errcode(), errmsg(), GetFdwRoutineForRelation(), GetUserId(), INFO, IsAutoVacuumWorkerProcess(), LOG, VacuumParams::log_min_duration, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, MyPgXact, NoLock, PG_CATALOG_NAMESPACE, pg_class_ownercheck(), pg_database_ownercheck(), PROC_IN_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RangeVar::relname, ShareUpdateExclusiveLock, StatisticRelationId, try_relation_open(), VACOPT_NOWAIT, VACOPT_VACUUM, VACOPT_VERBOSE, PGXACT::vacuumFlags, and WARNING.

Referenced by vacuum().

118 {
119  Relation onerel;
120  int elevel;
121  AcquireSampleRowsFunc acquirefunc = NULL;
122  BlockNumber relpages = 0;
123 
124  /* Select logging level */
125  if (options & VACOPT_VERBOSE)
126  elevel = INFO;
127  else
128  elevel = DEBUG2;
129 
130  /* Set up static variables */
131  vac_strategy = bstrategy;
132 
133  /*
134  * Check for user-requested abort.
135  */
137 
138  /*
139  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
140  * ANALYZEs don't run on it concurrently. (This also locks out a
141  * concurrent VACUUM, which doesn't matter much at the moment but might
142  * matter if we ever try to accumulate stats on dead tuples.) If the rel
143  * has been dropped since we last saw it, we don't need to process it.
144  */
145  if (!(options & VACOPT_NOWAIT))
148  onerel = try_relation_open(relid, NoLock);
149  else
150  {
151  onerel = NULL;
152  if (relation &&
154  ereport(LOG,
155  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
156  errmsg("skipping analyze of \"%s\" --- lock not available",
157  relation->relname)));
158  }
159  if (!onerel)
160  return;
161 
162  /*
163  * Check permissions --- this should match vacuum's check!
164  */
165  if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
166  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
167  {
168  /* No need for a WARNING if we already complained during VACUUM */
169  if (!(options & VACOPT_VACUUM))
170  {
171  if (onerel->rd_rel->relisshared)
173  (errmsg("skipping \"%s\" --- only superuser can analyze it",
174  RelationGetRelationName(onerel))));
175  else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
177  (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
178  RelationGetRelationName(onerel))));
179  else
181  (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
182  RelationGetRelationName(onerel))));
183  }
185  return;
186  }
187 
188  /*
189  * Silently ignore tables that are temp tables of other backends ---
190  * trying to analyze these is rather pointless, since their contents are
191  * probably not up-to-date on disk. (We don't throw a warning here; it
192  * would just lead to chatter during a database-wide ANALYZE.)
193  */
194  if (RELATION_IS_OTHER_TEMP(onerel))
195  {
197  return;
198  }
199 
200  /*
201  * We can ANALYZE any table except pg_statistic. See update_attstats
202  */
203  if (RelationGetRelid(onerel) == StatisticRelationId)
204  {
206  return;
207  }
208 
209  /*
210  * Check that it's of an analyzable relkind, and set up appropriately.
211  */
212  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
213  onerel->rd_rel->relkind == RELKIND_MATVIEW)
214  {
215  /* Regular table, so we'll use the regular row acquisition function */
216  acquirefunc = acquire_sample_rows;
217  /* Also get regular table's size */
218  relpages = RelationGetNumberOfBlocks(onerel);
219  }
220  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
221  {
222  /*
223  * For a foreign table, call the FDW's hook function to see whether it
224  * supports analysis.
225  */
226  FdwRoutine *fdwroutine;
227  bool ok = false;
228 
229  fdwroutine = GetFdwRoutineForRelation(onerel, false);
230 
231  if (fdwroutine->AnalyzeForeignTable != NULL)
232  ok = fdwroutine->AnalyzeForeignTable(onerel,
233  &acquirefunc,
234  &relpages);
235 
236  if (!ok)
237  {
239  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
240  RelationGetRelationName(onerel))));
242  return;
243  }
244  }
245  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
246  {
247  /*
248  * For partitioned tables, we want to do the recursive ANALYZE below.
249  */
250  }
251  else
252  {
253  /* No need for a WARNING if we already complained during VACUUM */
254  if (!(options & VACOPT_VACUUM))
256  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
257  RelationGetRelationName(onerel))));
259  return;
260  }
261 
262  /*
263  * OK, let's do it. First let other backends know I'm in ANALYZE.
264  */
265  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
267  LWLockRelease(ProcArrayLock);
268 
269  /*
270  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
271  * tables, which don't contain any rows.
272  */
273  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
274  do_analyze_rel(onerel, options, params, va_cols, acquirefunc,
275  relpages, false, in_outer_xact, elevel);
276 
277  /*
278  * If there are child tables, do recursive ANALYZE.
279  */
280  if (onerel->rd_rel->relhassubclass)
281  do_analyze_rel(onerel, options, params, va_cols, acquirefunc, relpages,
282  true, in_outer_xact, elevel);
283 
284  /*
285  * Close source relation now, but keep lock so that no one deletes it
286  * before we commit. (If someone did, they'd fail to clean up the entries
287  * we made in pg_statistic. Also, releasing the lock before commit would
288  * expose us to concurrent-update failures in update_attstats.)
289  */
290  relation_close(onerel, NoLock);
291 
292  /*
293  * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
294  * because the vacuum flag is cleared by the end-of-xact code.
295  */
296  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
298  LWLockRelease(ProcArrayLock);
299 }
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1153
Oid GetUserId(void)
Definition: miscinit.c:284
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:224
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
uint32 BlockNumber
Definition: block.h:31
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:114
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:230
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
char * relname
Definition: primnodes.h:68
#define DEBUG2
Definition: elog.h:24
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define PG_CATALOG_NAMESPACE
Definition: pg_namespace.h:71
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3256
#define ereport(elevel, rest)
Definition: elog.h:122
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
#define WARNING
Definition: elog.h:40
static void do_analyze_rel(Relation onerel, int options, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:309
static int elevel
Definition: vacuumlazy.c:136
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define StatisticRelationId
Definition: pg_statistic.h:29
Oid MyDatabaseId
Definition: globals.c:77
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:533
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
int log_min_duration
Definition: vacuum.h:145
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:134
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define PROC_IN_ANALYZE
Definition: proc.h:55
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:416
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1006

◆ compare_mcvs()

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

Definition at line 2838 of file analyze.c.

Referenced by compute_scalar_stats().

2839 {
2840  int da = ((const ScalarMCVItem *) a)->first;
2841  int db = ((const ScalarMCVItem *) b)->first;
2842 
2843  return da - db;
2844 }

◆ compare_rows()

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

Definition at line 1249 of file analyze.c.

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1250 {
1251  HeapTuple ha = *(const HeapTuple *) a;
1252  HeapTuple hb = *(const HeapTuple *) b;
1257 
1258  if (ba < bb)
1259  return -1;
1260  if (ba > bb)
1261  return 1;
1262  if (oa < ob)
1263  return -1;
1264  if (oa > ob)
1265  return 1;
1266  return 0;
1267 }
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:95
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:76

◆ compare_scalars()

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

Definition at line 2807 of file analyze.c.

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

Referenced by compute_scalar_stats().

2808 {
2809  Datum da = ((const ScalarItem *) a)->value;
2810  int ta = ((const ScalarItem *) a)->tupno;
2811  Datum db = ((const ScalarItem *) b)->value;
2812  int tb = ((const ScalarItem *) b)->tupno;
2814  int compare;
2815 
2816  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2817  if (compare != 0)
2818  return compare;
2819 
2820  /*
2821  * The two datums are equal, so update cxt->tupnoLink[].
2822  */
2823  if (cxt->tupnoLink[ta] < tb)
2824  cxt->tupnoLink[ta] = tb;
2825  if (cxt->tupnoLink[tb] < ta)
2826  cxt->tupnoLink[tb] = ta;
2827 
2828  /*
2829  * For equal datums, sort by tupno
2830  */
2831  return ta - tb;
2832 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
SortSupport ssup
Definition: analyze.c:1714
uintptr_t Datum
Definition: postgres.h:372
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:201

◆ compute_distinct_stats()

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

Definition at line 1909 of file analyze.c.

References VacAttrStats::anl_context, VacAttrStats::attr, VacAttrStats::attrtype, datumCopy(), DatumGetBool, DatumGetCString, DatumGetPointer, DEFAULT_COLLATION_OID, StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, fmgr_info(), FunctionCall2Coll(), i, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_KIND_MCV, 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().

1913 {
1914  int i;
1915  int null_cnt = 0;
1916  int nonnull_cnt = 0;
1917  int toowide_cnt = 0;
1918  double total_width = 0;
1919  bool is_varlena = (!stats->attrtype->typbyval &&
1920  stats->attrtype->typlen == -1);
1921  bool is_varwidth = (!stats->attrtype->typbyval &&
1922  stats->attrtype->typlen < 0);
1923  FmgrInfo f_cmpeq;
1924  typedef struct
1925  {
1926  Datum value;
1927  int count;
1928  } TrackItem;
1929  TrackItem *track;
1930  int track_cnt,
1931  track_max;
1932  int num_mcv = stats->attr->attstattarget;
1933  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1934 
1935  /*
1936  * We track up to 2*n values for an n-element MCV list; but at least 10
1937  */
1938  track_max = 2 * num_mcv;
1939  if (track_max < 10)
1940  track_max = 10;
1941  track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1942  track_cnt = 0;
1943 
1944  fmgr_info(mystats->eqfunc, &f_cmpeq);
1945 
1946  for (i = 0; i < samplerows; i++)
1947  {
1948  Datum value;
1949  bool isnull;
1950  bool match;
1951  int firstcount1,
1952  j;
1953 
1955 
1956  value = fetchfunc(stats, i, &isnull);
1957 
1958  /* Check for null/nonnull */
1959  if (isnull)
1960  {
1961  null_cnt++;
1962  continue;
1963  }
1964  nonnull_cnt++;
1965 
1966  /*
1967  * If it's a variable-width field, add up widths for average width
1968  * calculation. Note that if the value is toasted, we use the toasted
1969  * width. We don't bother with this calculation if it's a fixed-width
1970  * type.
1971  */
1972  if (is_varlena)
1973  {
1974  total_width += VARSIZE_ANY(DatumGetPointer(value));
1975 
1976  /*
1977  * If the value is toasted, we want to detoast it just once to
1978  * avoid repeated detoastings and resultant excess memory usage
1979  * during the comparisons. Also, check to see if the value is
1980  * excessively wide, and if so don't detoast at all --- just
1981  * ignore the value.
1982  */
1984  {
1985  toowide_cnt++;
1986  continue;
1987  }
1988  value = PointerGetDatum(PG_DETOAST_DATUM(value));
1989  }
1990  else if (is_varwidth)
1991  {
1992  /* must be cstring */
1993  total_width += strlen(DatumGetCString(value)) + 1;
1994  }
1995 
1996  /*
1997  * See if the value matches anything we're already tracking.
1998  */
1999  match = false;
2000  firstcount1 = track_cnt;
2001  for (j = 0; j < track_cnt; j++)
2002  {
2003  /* We always use the default collation for statistics */
2004  if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
2006  value, track[j].value)))
2007  {
2008  match = true;
2009  break;
2010  }
2011  if (j < firstcount1 && track[j].count == 1)
2012  firstcount1 = j;
2013  }
2014 
2015  if (match)
2016  {
2017  /* Found a match */
2018  track[j].count++;
2019  /* This value may now need to "bubble up" in the track list */
2020  while (j > 0 && track[j].count > track[j - 1].count)
2021  {
2022  swapDatum(track[j].value, track[j - 1].value);
2023  swapInt(track[j].count, track[j - 1].count);
2024  j--;
2025  }
2026  }
2027  else
2028  {
2029  /* No match. Insert at head of count-1 list */
2030  if (track_cnt < track_max)
2031  track_cnt++;
2032  for (j = track_cnt - 1; j > firstcount1; j--)
2033  {
2034  track[j].value = track[j - 1].value;
2035  track[j].count = track[j - 1].count;
2036  }
2037  if (firstcount1 < track_cnt)
2038  {
2039  track[firstcount1].value = value;
2040  track[firstcount1].count = 1;
2041  }
2042  }
2043  }
2044 
2045  /* We can only compute real stats if we found some non-null values. */
2046  if (nonnull_cnt > 0)
2047  {
2048  int nmultiple,
2049  summultiple;
2050 
2051  stats->stats_valid = true;
2052  /* Do the simple null-frac and width stats */
2053  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2054  if (is_varwidth)
2055  stats->stawidth = total_width / (double) nonnull_cnt;
2056  else
2057  stats->stawidth = stats->attrtype->typlen;
2058 
2059  /* Count the number of values we found multiple times */
2060  summultiple = 0;
2061  for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2062  {
2063  if (track[nmultiple].count == 1)
2064  break;
2065  summultiple += track[nmultiple].count;
2066  }
2067 
2068  if (nmultiple == 0)
2069  {
2070  /*
2071  * If we found no repeated non-null values, assume it's a unique
2072  * column; but be sure to discount for any nulls we found.
2073  */
2074  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2075  }
2076  else if (track_cnt < track_max && toowide_cnt == 0 &&
2077  nmultiple == track_cnt)
2078  {
2079  /*
2080  * Our track list includes every value in the sample, and every
2081  * value appeared more than once. Assume the column has just
2082  * these values. (This case is meant to address columns with
2083  * small, fixed sets of possible values, such as boolean or enum
2084  * columns. If there are any values that appear just once in the
2085  * sample, including too-wide values, we should assume that that's
2086  * not what we're dealing with.)
2087  */
2088  stats->stadistinct = track_cnt;
2089  }
2090  else
2091  {
2092  /*----------
2093  * Estimate the number of distinct values using the estimator
2094  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2095  * n*d / (n - f1 + f1*n/N)
2096  * where f1 is the number of distinct values that occurred
2097  * exactly once in our sample of n rows (from a total of N),
2098  * and d is the total number of distinct values in the sample.
2099  * This is their Duj1 estimator; the other estimators they
2100  * recommend are considerably more complex, and are numerically
2101  * very unstable when n is much smaller than N.
2102  *
2103  * In this calculation, we consider only non-nulls. We used to
2104  * include rows with null values in the n and N counts, but that
2105  * leads to inaccurate answers in columns with many nulls, and
2106  * it's intuitively bogus anyway considering the desired result is
2107  * the number of distinct non-null values.
2108  *
2109  * We assume (not very reliably!) that all the multiply-occurring
2110  * values are reflected in the final track[] list, and the other
2111  * nonnull values all appeared but once. (XXX this usually
2112  * results in a drastic overestimate of ndistinct. Can we do
2113  * any better?)
2114  *----------
2115  */
2116  int f1 = nonnull_cnt - summultiple;
2117  int d = f1 + nmultiple;
2118  double n = samplerows - null_cnt;
2119  double N = totalrows * (1.0 - stats->stanullfrac);
2120  double stadistinct;
2121 
2122  /* N == 0 shouldn't happen, but just in case ... */
2123  if (N > 0)
2124  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2125  else
2126  stadistinct = 0;
2127 
2128  /* Clamp to sane range in case of roundoff error */
2129  if (stadistinct < d)
2130  stadistinct = d;
2131  if (stadistinct > N)
2132  stadistinct = N;
2133  /* And round to integer */
2134  stats->stadistinct = floor(stadistinct + 0.5);
2135  }
2136 
2137  /*
2138  * If we estimated the number of distinct values at more than 10% of
2139  * the total row count (a very arbitrary limit), then assume that
2140  * stadistinct should scale with the row count rather than be a fixed
2141  * value.
2142  */
2143  if (stats->stadistinct > 0.1 * totalrows)
2144  stats->stadistinct = -(stats->stadistinct / totalrows);
2145 
2146  /*
2147  * Decide how many values are worth storing as most-common values. If
2148  * we are able to generate a complete MCV list (all the values in the
2149  * sample will fit, and we think these are all the ones in the table),
2150  * then do so. Otherwise, store only those values that are
2151  * significantly more common than the (estimated) average. We set the
2152  * threshold rather arbitrarily at 25% more than average, with at
2153  * least 2 instances in the sample.
2154  *
2155  * Note: the first of these cases is meant to address columns with
2156  * small, fixed sets of possible values, such as boolean or enum
2157  * columns. If we can *completely* represent the column population by
2158  * an MCV list that will fit into the stats target, then we should do
2159  * so and thus provide the planner with complete information. But if
2160  * the MCV list is not complete, it's generally worth being more
2161  * selective, and not just filling it all the way up to the stats
2162  * target. So for an incomplete list, we try to take only MCVs that
2163  * are significantly more common than average.
2164  */
2165  if (track_cnt < track_max && toowide_cnt == 0 &&
2166  stats->stadistinct > 0 &&
2167  track_cnt <= num_mcv)
2168  {
2169  /* Track list includes all values seen, and all will fit */
2170  num_mcv = track_cnt;
2171  }
2172  else
2173  {
2174  double ndistinct_table = stats->stadistinct;
2175  double avgcount,
2176  mincount;
2177 
2178  /* Re-extract estimate of # distinct nonnull values in table */
2179  if (ndistinct_table < 0)
2180  ndistinct_table = -ndistinct_table * totalrows;
2181  /* estimate # occurrences in sample of a typical nonnull value */
2182  avgcount = (double) nonnull_cnt / ndistinct_table;
2183  /* set minimum threshold count to store a value */
2184  mincount = avgcount * 1.25;
2185  if (mincount < 2)
2186  mincount = 2;
2187  if (num_mcv > track_cnt)
2188  num_mcv = track_cnt;
2189  for (i = 0; i < num_mcv; i++)
2190  {
2191  if (track[i].count < mincount)
2192  {
2193  num_mcv = i;
2194  break;
2195  }
2196  }
2197  }
2198 
2199  /* Generate MCV slot entry */
2200  if (num_mcv > 0)
2201  {
2202  MemoryContext old_context;
2203  Datum *mcv_values;
2204  float4 *mcv_freqs;
2205 
2206  /* Must copy the target values into anl_context */
2207  old_context = MemoryContextSwitchTo(stats->anl_context);
2208  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2209  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2210  for (i = 0; i < num_mcv; i++)
2211  {
2212  mcv_values[i] = datumCopy(track[i].value,
2213  stats->attrtype->typbyval,
2214  stats->attrtype->typlen);
2215  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2216  }
2217  MemoryContextSwitchTo(old_context);
2218 
2219  stats->stakind[0] = STATISTIC_KIND_MCV;
2220  stats->staop[0] = mystats->eqopr;
2221  stats->stanumbers[0] = mcv_freqs;
2222  stats->numnumbers[0] = num_mcv;
2223  stats->stavalues[0] = mcv_values;
2224  stats->numvalues[0] = num_mcv;
2225 
2226  /*
2227  * Accept the defaults for stats->statypid and others. They have
2228  * been set before we were called (see vacuum.h)
2229  */
2230  }
2231  }
2232  else if (null_cnt > 0)
2233  {
2234  /* We found only nulls; assume the column is entirely null */
2235  stats->stats_valid = true;
2236  stats->stanullfrac = 1.0;
2237  if (is_varwidth)
2238  stats->stawidth = 0; /* "unknown" */
2239  else
2240  stats->stawidth = stats->attrtype->typlen;
2241  stats->stadistinct = 0.0; /* "unknown" */
2242  }
2243 
2244  /* We don't need to bother cleaning up any of our temporary palloc's */
2245 }
Definition: fmgr.h:56
#define PointerGetDatum(X)
Definition: postgres.h:562
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1042
Form_pg_attribute attr
Definition: vacuum.h:81
#define swapDatum(a, b)
Definition: analyze.c:1701
Size toast_raw_datum_size(Datum value)
Definition: tuptoaster.c:353
#define DatumGetCString(X)
Definition: postgres.h:572
int32 stawidth
Definition: vacuum.h:101
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:122
static struct @121 value
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
#define DatumGetBool(X)
Definition: postgres.h:399
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
float4 stanullfrac
Definition: vacuum.h:100
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
bool stats_valid
Definition: vacuum.h:99
float float4
Definition: c.h:428
#define WIDTH_THRESHOLD
Definition: analyze.c:1698
uintptr_t Datum
Definition: postgres.h:372
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:103
#define VARSIZE_ANY(PTR)
Definition: postgres.h:334
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
MemoryContext anl_context
Definition: vacuum.h:85
#define swapInt(a, b)
Definition: analyze.c:1700
#define DatumGetPointer(X)
Definition: postgres.h:555
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
Form_pg_type attrtype
Definition: vacuum.h:84
void * palloc(Size size)
Definition: mcxt.c:848
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:205
void * extra_data
Definition: vacuum.h:93
void vacuum_delay_point(void)
Definition: vacuum.c:1658
float4 stadistinct
Definition: vacuum.h:102

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

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), VacAttrStats::attr, AnlIndexData::attr_cnt, VacAttrStats::attrtype, VacAttrStats::compute_stats, CreateExecutorState(), datumCopy(), ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreTuple(), VacAttrStats::exprnulls, VacAttrStats::exprvals, FormIndexDatum(), FreeExecutorState(), get_attribute_options(), GetPerTupleExprContext, i, IndexInfo::ii_Predicate, ind_fetch_func(), INDEX_MAX_KEYS, AnlIndexData::indexInfo, InvalidBuffer, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), AttributeOpts::n_distinct, NIL, palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, VacAttrStats::stadistinct, AnlIndexData::tupleFract, AnlIndexData::vacattrstats, vacuum_delay_point(), and values.

Referenced by do_analyze_rel().

709 {
710  MemoryContext ind_context,
711  old_context;
713  bool isnull[INDEX_MAX_KEYS];
714  int ind,
715  i;
716 
717  ind_context = AllocSetContextCreate(anl_context,
718  "Analyze Index",
720  old_context = MemoryContextSwitchTo(ind_context);
721 
722  for (ind = 0; ind < nindexes; ind++)
723  {
724  AnlIndexData *thisdata = &indexdata[ind];
725  IndexInfo *indexInfo = thisdata->indexInfo;
726  int attr_cnt = thisdata->attr_cnt;
727  TupleTableSlot *slot;
728  EState *estate;
729  ExprContext *econtext;
730  ExprState *predicate;
731  Datum *exprvals;
732  bool *exprnulls;
733  int numindexrows,
734  tcnt,
735  rowno;
736  double totalindexrows;
737 
738  /* Ignore index if no columns to analyze and not partial */
739  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
740  continue;
741 
742  /*
743  * Need an EState for evaluation of index expressions and
744  * partial-index predicates. Create it in the per-index context to be
745  * sure it gets cleaned up at the bottom of the loop.
746  */
747  estate = CreateExecutorState();
748  econtext = GetPerTupleExprContext(estate);
749  /* Need a slot to hold the current heap tuple, too */
751 
752  /* Arrange for econtext's scan tuple to be the tuple under test */
753  econtext->ecxt_scantuple = slot;
754 
755  /* Set up execution state for predicate. */
756  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
757 
758  /* Compute and save index expression values */
759  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
760  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
761  numindexrows = 0;
762  tcnt = 0;
763  for (rowno = 0; rowno < numrows; rowno++)
764  {
765  HeapTuple heapTuple = rows[rowno];
766 
768 
769  /*
770  * Reset the per-tuple context each time, to reclaim any cruft
771  * left behind by evaluating the predicate or index expressions.
772  */
773  ResetExprContext(econtext);
774 
775  /* Set up for predicate or expression evaluation */
776  ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
777 
778  /* If index is partial, check predicate */
779  if (predicate != NULL)
780  {
781  if (!ExecQual(predicate, econtext))
782  continue;
783  }
784  numindexrows++;
785 
786  if (attr_cnt > 0)
787  {
788  /*
789  * Evaluate the index row to compute expression values. We
790  * could do this by hand, but FormIndexDatum is convenient.
791  */
792  FormIndexDatum(indexInfo,
793  slot,
794  estate,
795  values,
796  isnull);
797 
798  /*
799  * Save just the columns we care about. We copy the values
800  * into ind_context from the estate's per-tuple context.
801  */
802  for (i = 0; i < attr_cnt; i++)
803  {
804  VacAttrStats *stats = thisdata->vacattrstats[i];
805  int attnum = stats->attr->attnum;
806 
807  if (isnull[attnum - 1])
808  {
809  exprvals[tcnt] = (Datum) 0;
810  exprnulls[tcnt] = true;
811  }
812  else
813  {
814  exprvals[tcnt] = datumCopy(values[attnum - 1],
815  stats->attrtype->typbyval,
816  stats->attrtype->typlen);
817  exprnulls[tcnt] = false;
818  }
819  tcnt++;
820  }
821  }
822  }
823 
824  /*
825  * Having counted the number of rows that pass the predicate in the
826  * sample, we can estimate the total number of rows in the index.
827  */
828  thisdata->tupleFract = (double) numindexrows / (double) numrows;
829  totalindexrows = ceil(thisdata->tupleFract * totalrows);
830 
831  /*
832  * Now we can compute the statistics for the expression columns.
833  */
834  if (numindexrows > 0)
835  {
836  MemoryContextSwitchTo(col_context);
837  for (i = 0; i < attr_cnt; i++)
838  {
839  VacAttrStats *stats = thisdata->vacattrstats[i];
840  AttributeOpts *aopt =
841  get_attribute_options(stats->attr->attrelid,
842  stats->attr->attnum);
843 
844  stats->exprvals = exprvals + i;
845  stats->exprnulls = exprnulls + i;
846  stats->rowstride = attr_cnt;
847  stats->compute_stats(stats,
849  numindexrows,
850  totalindexrows);
851 
852  /*
853  * If the n_distinct option is specified, it overrides the
854  * above computation. For indices, we always use just
855  * n_distinct, not n_distinct_inherited.
856  */
857  if (aopt != NULL && aopt->n_distinct != 0.0)
858  stats->stadistinct = aopt->n_distinct;
859 
861  }
862  }
863 
864  /* And clean up */
865  MemoryContextSwitchTo(ind_context);
866 
868  FreeExecutorState(estate);
870  }
871 
872  MemoryContextSwitchTo(old_context);
873  MemoryContextDelete(ind_context);
874 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
int rowstride
Definition: vacuum.h:130
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1774
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
List * ii_Predicate
Definition: execnodes.h:138
#define RelationGetDescr(relation)
Definition: rel.h:428
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:356
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:81
int attr_cnt
Definition: analyze.c:72
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:467
bool * exprnulls
Definition: vacuum.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
static MemoryContext anl_context
Definition: analyze.c:80
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:216
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:465
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:199
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:80
Datum * exprvals
Definition: vacuum.h:128
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
uintptr_t Datum
Definition: postgres.h:372
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1668
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:197
double tupleFract
Definition: analyze.c:70
static Datum values[MAXATTR]
Definition: bootstrap.c:164
Form_pg_type attrtype
Definition: vacuum.h:84
void * palloc(Size size)
Definition: mcxt.c:848
VacAttrStats ** vacattrstats
Definition: analyze.c:71
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
void vacuum_delay_point(void)
Definition: vacuum.c:1658
#define ResetExprContext(econtext)
Definition: executor.h:461
float4 stadistinct
Definition: vacuum.h:102
IndexInfo * indexInfo
Definition: analyze.c:69

◆ compute_scalar_stats()

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

Definition at line 2261 of file analyze.c.

References SortSupportData::abbreviate, VacAttrStats::anl_context, Assert, VacAttrStats::attr, VacAttrStats::attrtype, compare_mcvs(), compare_scalars(), ScalarMCVItem::count, CurrentMemoryContext, datumCopy(), DatumGetCString, DatumGetPointer, DEFAULT_COLLATION_OID, generate_unaccent_rules::dest, StdAnalyzeData::eqopr, VacAttrStats::extra_data, ScalarMCVItem::first, i, StdAnalyzeData::ltopr, memmove, 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::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_KIND_CORRELATION, STATISTIC_KIND_HISTOGRAM, STATISTIC_KIND_MCV, 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().

2265 {
2266  int i;
2267  int null_cnt = 0;
2268  int nonnull_cnt = 0;
2269  int toowide_cnt = 0;
2270  double total_width = 0;
2271  bool is_varlena = (!stats->attrtype->typbyval &&
2272  stats->attrtype->typlen == -1);
2273  bool is_varwidth = (!stats->attrtype->typbyval &&
2274  stats->attrtype->typlen < 0);
2275  double corr_xysum;
2276  SortSupportData ssup;
2277  ScalarItem *values;
2278  int values_cnt = 0;
2279  int *tupnoLink;
2280  ScalarMCVItem *track;
2281  int track_cnt = 0;
2282  int num_mcv = stats->attr->attstattarget;
2283  int num_bins = stats->attr->attstattarget;
2284  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2285 
2286  values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2287  tupnoLink = (int *) palloc(samplerows * sizeof(int));
2288  track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2289 
2290  memset(&ssup, 0, sizeof(ssup));
2292  /* We always use the default collation for statistics */
2294  ssup.ssup_nulls_first = false;
2295 
2296  /*
2297  * For now, don't perform abbreviated key conversion, because full values
2298  * are required for MCV slot generation. Supporting that optimization
2299  * would necessitate teaching compare_scalars() to call a tie-breaker.
2300  */
2301  ssup.abbreviate = false;
2302 
2303  PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2304 
2305  /* Initial scan to find sortable values */
2306  for (i = 0; i < samplerows; i++)
2307  {
2308  Datum value;
2309  bool isnull;
2310 
2312 
2313  value = fetchfunc(stats, i, &isnull);
2314 
2315  /* Check for null/nonnull */
2316  if (isnull)
2317  {
2318  null_cnt++;
2319  continue;
2320  }
2321  nonnull_cnt++;
2322 
2323  /*
2324  * If it's a variable-width field, add up widths for average width
2325  * calculation. Note that if the value is toasted, we use the toasted
2326  * width. We don't bother with this calculation if it's a fixed-width
2327  * type.
2328  */
2329  if (is_varlena)
2330  {
2331  total_width += VARSIZE_ANY(DatumGetPointer(value));
2332 
2333  /*
2334  * If the value is toasted, we want to detoast it just once to
2335  * avoid repeated detoastings and resultant excess memory usage
2336  * during the comparisons. Also, check to see if the value is
2337  * excessively wide, and if so don't detoast at all --- just
2338  * ignore the value.
2339  */
2341  {
2342  toowide_cnt++;
2343  continue;
2344  }
2345  value = PointerGetDatum(PG_DETOAST_DATUM(value));
2346  }
2347  else if (is_varwidth)
2348  {
2349  /* must be cstring */
2350  total_width += strlen(DatumGetCString(value)) + 1;
2351  }
2352 
2353  /* Add it to the list to be sorted */
2354  values[values_cnt].value = value;
2355  values[values_cnt].tupno = values_cnt;
2356  tupnoLink[values_cnt] = values_cnt;
2357  values_cnt++;
2358  }
2359 
2360  /* We can only compute real stats if we found some sortable values. */
2361  if (values_cnt > 0)
2362  {
2363  int ndistinct, /* # distinct values in sample */
2364  nmultiple, /* # that appear multiple times */
2365  num_hist,
2366  dups_cnt;
2367  int slot_idx = 0;
2369 
2370  /* Sort the collected values */
2371  cxt.ssup = &ssup;
2372  cxt.tupnoLink = tupnoLink;
2373  qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2374  compare_scalars, (void *) &cxt);
2375 
2376  /*
2377  * Now scan the values in order, find the most common ones, and also
2378  * accumulate ordering-correlation statistics.
2379  *
2380  * To determine which are most common, we first have to count the
2381  * number of duplicates of each value. The duplicates are adjacent in
2382  * the sorted list, so a brute-force approach is to compare successive
2383  * datum values until we find two that are not equal. However, that
2384  * requires N-1 invocations of the datum comparison routine, which are
2385  * completely redundant with work that was done during the sort. (The
2386  * sort algorithm must at some point have compared each pair of items
2387  * that are adjacent in the sorted order; otherwise it could not know
2388  * that it's ordered the pair correctly.) We exploit this by having
2389  * compare_scalars remember the highest tupno index that each
2390  * ScalarItem has been found equal to. At the end of the sort, a
2391  * ScalarItem's tupnoLink will still point to itself if and only if it
2392  * is the last item of its group of duplicates (since the group will
2393  * be ordered by tupno).
2394  */
2395  corr_xysum = 0;
2396  ndistinct = 0;
2397  nmultiple = 0;
2398  dups_cnt = 0;
2399  for (i = 0; i < values_cnt; i++)
2400  {
2401  int tupno = values[i].tupno;
2402 
2403  corr_xysum += ((double) i) * ((double) tupno);
2404  dups_cnt++;
2405  if (tupnoLink[tupno] == tupno)
2406  {
2407  /* Reached end of duplicates of this value */
2408  ndistinct++;
2409  if (dups_cnt > 1)
2410  {
2411  nmultiple++;
2412  if (track_cnt < num_mcv ||
2413  dups_cnt > track[track_cnt - 1].count)
2414  {
2415  /*
2416  * Found a new item for the mcv list; find its
2417  * position, bubbling down old items if needed. Loop
2418  * invariant is that j points at an empty/ replaceable
2419  * slot.
2420  */
2421  int j;
2422 
2423  if (track_cnt < num_mcv)
2424  track_cnt++;
2425  for (j = track_cnt - 1; j > 0; j--)
2426  {
2427  if (dups_cnt <= track[j - 1].count)
2428  break;
2429  track[j].count = track[j - 1].count;
2430  track[j].first = track[j - 1].first;
2431  }
2432  track[j].count = dups_cnt;
2433  track[j].first = i + 1 - dups_cnt;
2434  }
2435  }
2436  dups_cnt = 0;
2437  }
2438  }
2439 
2440  stats->stats_valid = true;
2441  /* Do the simple null-frac and width stats */
2442  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2443  if (is_varwidth)
2444  stats->stawidth = total_width / (double) nonnull_cnt;
2445  else
2446  stats->stawidth = stats->attrtype->typlen;
2447 
2448  if (nmultiple == 0)
2449  {
2450  /*
2451  * If we found no repeated non-null values, assume it's a unique
2452  * column; but be sure to discount for any nulls we found.
2453  */
2454  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2455  }
2456  else if (toowide_cnt == 0 && nmultiple == ndistinct)
2457  {
2458  /*
2459  * Every value in the sample appeared more than once. Assume the
2460  * column has just these values. (This case is meant to address
2461  * columns with small, fixed sets of possible values, such as
2462  * boolean or enum columns. If there are any values that appear
2463  * just once in the sample, including too-wide values, we should
2464  * assume that that's not what we're dealing with.)
2465  */
2466  stats->stadistinct = ndistinct;
2467  }
2468  else
2469  {
2470  /*----------
2471  * Estimate the number of distinct values using the estimator
2472  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2473  * n*d / (n - f1 + f1*n/N)
2474  * where f1 is the number of distinct values that occurred
2475  * exactly once in our sample of n rows (from a total of N),
2476  * and d is the total number of distinct values in the sample.
2477  * This is their Duj1 estimator; the other estimators they
2478  * recommend are considerably more complex, and are numerically
2479  * very unstable when n is much smaller than N.
2480  *
2481  * In this calculation, we consider only non-nulls. We used to
2482  * include rows with null values in the n and N counts, but that
2483  * leads to inaccurate answers in columns with many nulls, and
2484  * it's intuitively bogus anyway considering the desired result is
2485  * the number of distinct non-null values.
2486  *
2487  * Overwidth values are assumed to have been distinct.
2488  *----------
2489  */
2490  int f1 = ndistinct - nmultiple + toowide_cnt;
2491  int d = f1 + nmultiple;
2492  double n = samplerows - null_cnt;
2493  double N = totalrows * (1.0 - stats->stanullfrac);
2494  double stadistinct;
2495 
2496  /* N == 0 shouldn't happen, but just in case ... */
2497  if (N > 0)
2498  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2499  else
2500  stadistinct = 0;
2501 
2502  /* Clamp to sane range in case of roundoff error */
2503  if (stadistinct < d)
2504  stadistinct = d;
2505  if (stadistinct > N)
2506  stadistinct = N;
2507  /* And round to integer */
2508  stats->stadistinct = floor(stadistinct + 0.5);
2509  }
2510 
2511  /*
2512  * If we estimated the number of distinct values at more than 10% of
2513  * the total row count (a very arbitrary limit), then assume that
2514  * stadistinct should scale with the row count rather than be a fixed
2515  * value.
2516  */
2517  if (stats->stadistinct > 0.1 * totalrows)
2518  stats->stadistinct = -(stats->stadistinct / totalrows);
2519 
2520  /*
2521  * Decide how many values are worth storing as most-common values. If
2522  * we are able to generate a complete MCV list (all the values in the
2523  * sample will fit, and we think these are all the ones in the table),
2524  * then do so. Otherwise, store only those values that are
2525  * significantly more common than the (estimated) average. We set the
2526  * threshold rather arbitrarily at 25% more than average, with at
2527  * least 2 instances in the sample. Also, we won't suppress values
2528  * that have a frequency of at least 1/K where K is the intended
2529  * number of histogram bins; such values might otherwise cause us to
2530  * emit duplicate histogram bin boundaries. (We might end up with
2531  * duplicate histogram entries anyway, if the distribution is skewed;
2532  * but we prefer to treat such values as MCVs if at all possible.)
2533  *
2534  * Note: the first of these cases is meant to address columns with
2535  * small, fixed sets of possible values, such as boolean or enum
2536  * columns. If we can *completely* represent the column population by
2537  * an MCV list that will fit into the stats target, then we should do
2538  * so and thus provide the planner with complete information. But if
2539  * the MCV list is not complete, it's generally worth being more
2540  * selective, and not just filling it all the way up to the stats
2541  * target. So for an incomplete list, we try to take only MCVs that
2542  * are significantly more common than average.
2543  */
2544  if (track_cnt == ndistinct && toowide_cnt == 0 &&
2545  stats->stadistinct > 0 &&
2546  track_cnt <= num_mcv)
2547  {
2548  /* Track list includes all values seen, and all will fit */
2549  num_mcv = track_cnt;
2550  }
2551  else
2552  {
2553  double ndistinct_table = stats->stadistinct;
2554  double avgcount,
2555  mincount,
2556  maxmincount;
2557 
2558  /* Re-extract estimate of # distinct nonnull values in table */
2559  if (ndistinct_table < 0)
2560  ndistinct_table = -ndistinct_table * totalrows;
2561  /* estimate # occurrences in sample of a typical nonnull value */
2562  avgcount = (double) nonnull_cnt / ndistinct_table;
2563  /* set minimum threshold count to store a value */
2564  mincount = avgcount * 1.25;
2565  if (mincount < 2)
2566  mincount = 2;
2567  /* don't let threshold exceed 1/K, however */
2568  maxmincount = (double) values_cnt / (double) num_bins;
2569  if (mincount > maxmincount)
2570  mincount = maxmincount;
2571  if (num_mcv > track_cnt)
2572  num_mcv = track_cnt;
2573  for (i = 0; i < num_mcv; i++)
2574  {
2575  if (track[i].count < mincount)
2576  {
2577  num_mcv = i;
2578  break;
2579  }
2580  }
2581  }
2582 
2583  /* Generate MCV slot entry */
2584  if (num_mcv > 0)
2585  {
2586  MemoryContext old_context;
2587  Datum *mcv_values;
2588  float4 *mcv_freqs;
2589 
2590  /* Must copy the target values into anl_context */
2591  old_context = MemoryContextSwitchTo(stats->anl_context);
2592  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2593  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2594  for (i = 0; i < num_mcv; i++)
2595  {
2596  mcv_values[i] = datumCopy(values[track[i].first].value,
2597  stats->attrtype->typbyval,
2598  stats->attrtype->typlen);
2599  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2600  }
2601  MemoryContextSwitchTo(old_context);
2602 
2603  stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2604  stats->staop[slot_idx] = mystats->eqopr;
2605  stats->stanumbers[slot_idx] = mcv_freqs;
2606  stats->numnumbers[slot_idx] = num_mcv;
2607  stats->stavalues[slot_idx] = mcv_values;
2608  stats->numvalues[slot_idx] = num_mcv;
2609 
2610  /*
2611  * Accept the defaults for stats->statypid and others. They have
2612  * been set before we were called (see vacuum.h)
2613  */
2614  slot_idx++;
2615  }
2616 
2617  /*
2618  * Generate a histogram slot entry if there are at least two distinct
2619  * values not accounted for in the MCV list. (This ensures the
2620  * histogram won't collapse to empty or a singleton.)
2621  */
2622  num_hist = ndistinct - num_mcv;
2623  if (num_hist > num_bins)
2624  num_hist = num_bins + 1;
2625  if (num_hist >= 2)
2626  {
2627  MemoryContext old_context;
2628  Datum *hist_values;
2629  int nvals;
2630  int pos,
2631  posfrac,
2632  delta,
2633  deltafrac;
2634 
2635  /* Sort the MCV items into position order to speed next loop */
2636  qsort((void *) track, num_mcv,
2637  sizeof(ScalarMCVItem), compare_mcvs);
2638 
2639  /*
2640  * Collapse out the MCV items from the values[] array.
2641  *
2642  * Note we destroy the values[] array here... but we don't need it
2643  * for anything more. We do, however, still need values_cnt.
2644  * nvals will be the number of remaining entries in values[].
2645  */
2646  if (num_mcv > 0)
2647  {
2648  int src,
2649  dest;
2650  int j;
2651 
2652  src = dest = 0;
2653  j = 0; /* index of next interesting MCV item */
2654  while (src < values_cnt)
2655  {
2656  int ncopy;
2657 
2658  if (j < num_mcv)
2659  {
2660  int first = track[j].first;
2661 
2662  if (src >= first)
2663  {
2664  /* advance past this MCV item */
2665  src = first + track[j].count;
2666  j++;
2667  continue;
2668  }
2669  ncopy = first - src;
2670  }
2671  else
2672  ncopy = values_cnt - src;
2673  memmove(&values[dest], &values[src],
2674  ncopy * sizeof(ScalarItem));
2675  src += ncopy;
2676  dest += ncopy;
2677  }
2678  nvals = dest;
2679  }
2680  else
2681  nvals = values_cnt;
2682  Assert(nvals >= num_hist);
2683 
2684  /* Must copy the target values into anl_context */
2685  old_context = MemoryContextSwitchTo(stats->anl_context);
2686  hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2687 
2688  /*
2689  * The object of this loop is to copy the first and last values[]
2690  * entries along with evenly-spaced values in between. So the
2691  * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2692  * computing that subscript directly risks integer overflow when
2693  * the stats target is more than a couple thousand. Instead we
2694  * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2695  * the integral and fractional parts of the sum separately.
2696  */
2697  delta = (nvals - 1) / (num_hist - 1);
2698  deltafrac = (nvals - 1) % (num_hist - 1);
2699  pos = posfrac = 0;
2700 
2701  for (i = 0; i < num_hist; i++)
2702  {
2703  hist_values[i] = datumCopy(values[pos].value,
2704  stats->attrtype->typbyval,
2705  stats->attrtype->typlen);
2706  pos += delta;
2707  posfrac += deltafrac;
2708  if (posfrac >= (num_hist - 1))
2709  {
2710  /* fractional part exceeds 1, carry to integer part */
2711  pos++;
2712  posfrac -= (num_hist - 1);
2713  }
2714  }
2715 
2716  MemoryContextSwitchTo(old_context);
2717 
2718  stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2719  stats->staop[slot_idx] = mystats->ltopr;
2720  stats->stavalues[slot_idx] = hist_values;
2721  stats->numvalues[slot_idx] = num_hist;
2722 
2723  /*
2724  * Accept the defaults for stats->statypid and others. They have
2725  * been set before we were called (see vacuum.h)
2726  */
2727  slot_idx++;
2728  }
2729 
2730  /* Generate a correlation entry if there are multiple values */
2731  if (values_cnt > 1)
2732  {
2733  MemoryContext old_context;
2734  float4 *corrs;
2735  double corr_xsum,
2736  corr_x2sum;
2737 
2738  /* Must copy the target values into anl_context */
2739  old_context = MemoryContextSwitchTo(stats->anl_context);
2740  corrs = (float4 *) palloc(sizeof(float4));
2741  MemoryContextSwitchTo(old_context);
2742 
2743  /*----------
2744  * Since we know the x and y value sets are both
2745  * 0, 1, ..., values_cnt-1
2746  * we have sum(x) = sum(y) =
2747  * (values_cnt-1)*values_cnt / 2
2748  * and sum(x^2) = sum(y^2) =
2749  * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2750  *----------
2751  */
2752  corr_xsum = ((double) (values_cnt - 1)) *
2753  ((double) values_cnt) / 2.0;
2754  corr_x2sum = ((double) (values_cnt - 1)) *
2755  ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2756 
2757  /* And the correlation coefficient reduces to */
2758  corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2759  (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2760 
2761  stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2762  stats->staop[slot_idx] = mystats->ltopr;
2763  stats->stanumbers[slot_idx] = corrs;
2764  stats->numnumbers[slot_idx] = 1;
2765  slot_idx++;
2766  }
2767  }
2768  else if (nonnull_cnt > 0)
2769  {
2770  /* We found some non-null values, but they were all too wide */
2771  Assert(nonnull_cnt == toowide_cnt);
2772  stats->stats_valid = true;
2773  /* Do the simple null-frac and width stats */
2774  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2775  if (is_varwidth)
2776  stats->stawidth = total_width / (double) nonnull_cnt;
2777  else
2778  stats->stawidth = stats->attrtype->typlen;
2779  /* Assume all too-wide values are distinct, so it's a unique column */
2780  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2781  }
2782  else if (null_cnt > 0)
2783  {
2784  /* We found only nulls; assume the column is entirely null */
2785  stats->stats_valid = true;
2786  stats->stanullfrac = 1.0;
2787  if (is_varwidth)
2788  stats->stawidth = 0; /* "unknown" */
2789  else
2790  stats->stawidth = stats->attrtype->typlen;
2791  stats->stadistinct = 0.0; /* "unknown" */
2792  }
2793 
2794  /* We don't need to bother cleaning up any of our temporary palloc's */
2795 }
bool ssup_nulls_first
Definition: sortsupport.h:75
static int compare_mcvs(const void *a, const void *b)
Definition: analyze.c:2838
#define STATISTIC_KIND_HISTOGRAM
Definition: pg_statistic.h:222
#define PointerGetDatum(X)
Definition: postgres.h:562
static int compare_scalars(const void *a, const void *b, void *arg)
Definition: analyze.c:2807
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:133
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Form_pg_attribute attr
Definition: vacuum.h:81
Size toast_raw_datum_size(Datum value)
Definition: tuptoaster.c:353
#define DatumGetCString(X)
Definition: postgres.h:572
int32 stawidth
Definition: vacuum.h:101
MemoryContext ssup_cxt
Definition: sortsupport.h:66
static struct @121 value
SortSupport ssup
Definition: analyze.c:1714
#define STATISTIC_KIND_CORRELATION
Definition: pg_statistic.h:233
#define memmove(d, s, c)
Definition: c.h:1045
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:75
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define STATISTIC_KIND_MCV
Definition: pg_statistic.h:204
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
float4 stanullfrac
Definition: vacuum.h:100
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:113
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
bool stats_valid
Definition: vacuum.h:99
float float4
Definition: c.h:428
#define WIDTH_THRESHOLD
Definition: analyze.c:1698
uintptr_t Datum
Definition: postgres.h:372
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:103
#define VARSIZE_ANY(PTR)
Definition: postgres.h:334
#define Assert(condition)
Definition: c.h:670
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
MemoryContext anl_context
Definition: vacuum.h:85
#define DatumGetPointer(X)
Definition: postgres.h:555
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
Form_pg_type attrtype
Definition: vacuum.h:84
void * palloc(Size size)
Definition: mcxt.c:848
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:205
void * extra_data
Definition: vacuum.h:93
#define qsort(a, b, c, d)
Definition: port.h:408
void vacuum_delay_point(void)
Definition: vacuum.c:1658
float4 stadistinct
Definition: vacuum.h:102

◆ compute_trivial_stats()

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

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

1823 {
1824  int i;
1825  int null_cnt = 0;
1826  int nonnull_cnt = 0;
1827  double total_width = 0;
1828  bool is_varlena = (!stats->attrtype->typbyval &&
1829  stats->attrtype->typlen == -1);
1830  bool is_varwidth = (!stats->attrtype->typbyval &&
1831  stats->attrtype->typlen < 0);
1832 
1833  for (i = 0; i < samplerows; i++)
1834  {
1835  Datum value;
1836  bool isnull;
1837 
1839 
1840  value = fetchfunc(stats, i, &isnull);
1841 
1842  /* Check for null/nonnull */
1843  if (isnull)
1844  {
1845  null_cnt++;
1846  continue;
1847  }
1848  nonnull_cnt++;
1849 
1850  /*
1851  * If it's a variable-width field, add up widths for average width
1852  * calculation. Note that if the value is toasted, we use the toasted
1853  * width. We don't bother with this calculation if it's a fixed-width
1854  * type.
1855  */
1856  if (is_varlena)
1857  {
1858  total_width += VARSIZE_ANY(DatumGetPointer(value));
1859  }
1860  else if (is_varwidth)
1861  {
1862  /* must be cstring */
1863  total_width += strlen(DatumGetCString(value)) + 1;
1864  }
1865  }
1866 
1867  /* We can only compute average width if we found some non-null values. */
1868  if (nonnull_cnt > 0)
1869  {
1870  stats->stats_valid = true;
1871  /* Do the simple null-frac and width stats */
1872  stats->stanullfrac = (double) null_cnt / (double) samplerows;
1873  if (is_varwidth)
1874  stats->stawidth = total_width / (double) nonnull_cnt;
1875  else
1876  stats->stawidth = stats->attrtype->typlen;
1877  stats->stadistinct = 0.0; /* "unknown" */
1878  }
1879  else if (null_cnt > 0)
1880  {
1881  /* We found only nulls; assume the column is entirely null */
1882  stats->stats_valid = true;
1883  stats->stanullfrac = 1.0;
1884  if (is_varwidth)
1885  stats->stawidth = 0; /* "unknown" */
1886  else
1887  stats->stawidth = stats->attrtype->typlen;
1888  stats->stadistinct = 0.0; /* "unknown" */
1889  }
1890 }
#define DatumGetCString(X)
Definition: postgres.h:572
int32 stawidth
Definition: vacuum.h:101
static struct @121 value
float4 stanullfrac
Definition: vacuum.h:100
bool stats_valid
Definition: vacuum.h:99
uintptr_t Datum
Definition: postgres.h:372
#define VARSIZE_ANY(PTR)
Definition: postgres.h:334
#define DatumGetPointer(X)
Definition: postgres.h:555
Form_pg_type attrtype
Definition: vacuum.h:84
int i
void vacuum_delay_point(void)
Definition: vacuum.c:1658
float4 stadistinct
Definition: vacuum.h:102

◆ do_analyze_rel()

static void do_analyze_rel ( Relation  onerel,
int  options,
VacuumParams params,
List va_cols,
AcquireSampleRowsFunc  acquirefunc,
BlockNumber  relpages,
bool  inh,
bool  in_outer_xact,
int  elevel 
)
static

Definition at line 309 of file analyze.c.

References AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), IndexVacuumInfo::analyze_only, AtEOXact_GUC(), attnameAttNum(), VacAttrStats::attr, AnlIndexData::attr_cnt, bms_add_member(), bms_is_member(), BuildIndexInfo(), BuildRelationExtStatistics(), compute_index_stats(), VacAttrStats::compute_stats, CurrentMemoryContext, elevel, elog, ereport, errcode(), errmsg(), ERROR, IndexVacuumInfo::estimated_count, examine_attribute(), get_attribute_options(), get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GetUserIdAndSecContext(), i, IndexInfo::ii_Expressions, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexVacuumInfo::index, index_vacuum_cleanup(), AnlIndexData::indexInfo, 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, tupleDesc::natts, NewGUCNestLevel(), NIL, NoLock, IndexVacuumInfo::num_heap_tuples, palloc(), palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_report_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(), VacAttrStats::tupDesc, AnlIndexData::tupleFract, update_attstats(), vac_close_indexes(), vac_open_indexes(), vac_strategy, vac_update_relstats(), AnlIndexData::vacattrstats, VACOPT_VACUUM, and visibilitymap_count().

Referenced by analyze_rel().

313 {
314  int attr_cnt,
315  tcnt,
316  i,
317  ind;
318  Relation *Irel;
319  int nindexes;
320  bool hasindex;
321  VacAttrStats **vacattrstats;
322  AnlIndexData *indexdata;
323  int targrows,
324  numrows;
325  double totalrows,
326  totaldeadrows;
327  HeapTuple *rows;
328  PGRUsage ru0;
329  TimestampTz starttime = 0;
330  MemoryContext caller_context;
331  Oid save_userid;
332  int save_sec_context;
333  int save_nestlevel;
334 
335  if (inh)
336  ereport(elevel,
337  (errmsg("analyzing \"%s.%s\" inheritance tree",
339  RelationGetRelationName(onerel))));
340  else
341  ereport(elevel,
342  (errmsg("analyzing \"%s.%s\"",
344  RelationGetRelationName(onerel))));
345 
346  /*
347  * Set up a working context so that we can easily free whatever junk gets
348  * created.
349  */
351  "Analyze",
353  caller_context = MemoryContextSwitchTo(anl_context);
354 
355  /*
356  * Switch to the table owner's userid, so that any index functions are run
357  * as that user. Also lock down security-restricted operations and
358  * arrange to make GUC variable changes local to this command.
359  */
360  GetUserIdAndSecContext(&save_userid, &save_sec_context);
361  SetUserIdAndSecContext(onerel->rd_rel->relowner,
362  save_sec_context | SECURITY_RESTRICTED_OPERATION);
363  save_nestlevel = NewGUCNestLevel();
364 
365  /* measure elapsed time iff autovacuum logging requires it */
366  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
367  {
368  pg_rusage_init(&ru0);
369  if (params->log_min_duration > 0)
370  starttime = GetCurrentTimestamp();
371  }
372 
373  /*
374  * Determine which columns to analyze
375  *
376  * Note that system attributes are never analyzed, so we just reject them
377  * at the lookup stage. We also reject duplicate column mentions. (We
378  * could alternatively ignore duplicates, but analyzing a column twice
379  * won't work; we'd end up making a conflicting update in pg_statistic.)
380  */
381  if (va_cols != NIL)
382  {
383  Bitmapset *unique_cols = NULL;
384  ListCell *le;
385 
386  vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
387  sizeof(VacAttrStats *));
388  tcnt = 0;
389  foreach(le, va_cols)
390  {
391  char *col = strVal(lfirst(le));
392 
393  i = attnameAttNum(onerel, col, false);
394  if (i == InvalidAttrNumber)
395  ereport(ERROR,
396  (errcode(ERRCODE_UNDEFINED_COLUMN),
397  errmsg("column \"%s\" of relation \"%s\" does not exist",
398  col, RelationGetRelationName(onerel))));
399  if (bms_is_member(i, unique_cols))
400  ereport(ERROR,
401  (errcode(ERRCODE_DUPLICATE_COLUMN),
402  errmsg("column \"%s\" of relation \"%s\" appears more than once",
403  col, RelationGetRelationName(onerel))));
404  unique_cols = bms_add_member(unique_cols, i);
405 
406  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
407  if (vacattrstats[tcnt] != NULL)
408  tcnt++;
409  }
410  attr_cnt = tcnt;
411  }
412  else
413  {
414  attr_cnt = onerel->rd_att->natts;
415  vacattrstats = (VacAttrStats **)
416  palloc(attr_cnt * sizeof(VacAttrStats *));
417  tcnt = 0;
418  for (i = 1; i <= attr_cnt; i++)
419  {
420  vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
421  if (vacattrstats[tcnt] != NULL)
422  tcnt++;
423  }
424  attr_cnt = tcnt;
425  }
426 
427  /*
428  * Open all indexes of the relation, and see if there are any analyzable
429  * columns in the indexes. We do not analyze index columns if there was
430  * an explicit column list in the ANALYZE command, however. If we are
431  * doing a recursive scan, we don't want to touch the parent's indexes at
432  * all.
433  */
434  if (!inh)
435  vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
436  else
437  {
438  Irel = NULL;
439  nindexes = 0;
440  }
441  hasindex = (nindexes > 0);
442  indexdata = NULL;
443  if (hasindex)
444  {
445  indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
446  for (ind = 0; ind < nindexes; ind++)
447  {
448  AnlIndexData *thisdata = &indexdata[ind];
449  IndexInfo *indexInfo;
450 
451  thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
452  thisdata->tupleFract = 1.0; /* fix later if partial */
453  if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
454  {
455  ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
456 
457  thisdata->vacattrstats = (VacAttrStats **)
458  palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
459  tcnt = 0;
460  for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
461  {
462  int keycol = indexInfo->ii_KeyAttrNumbers[i];
463 
464  if (keycol == 0)
465  {
466  /* Found an index expression */
467  Node *indexkey;
468 
469  if (indexpr_item == NULL) /* shouldn't happen */
470  elog(ERROR, "too few entries in indexprs list");
471  indexkey = (Node *) lfirst(indexpr_item);
472  indexpr_item = lnext(indexpr_item);
473  thisdata->vacattrstats[tcnt] =
474  examine_attribute(Irel[ind], i + 1, indexkey);
475  if (thisdata->vacattrstats[tcnt] != NULL)
476  tcnt++;
477  }
478  }
479  thisdata->attr_cnt = tcnt;
480  }
481  }
482  }
483 
484  /*
485  * Determine how many rows we need to sample, using the worst case from
486  * all analyzable columns. We use a lower bound of 100 rows to avoid
487  * possible overflow in Vitter's algorithm. (Note: that will also be the
488  * target in the corner case where there are no analyzable columns.)
489  */
490  targrows = 100;
491  for (i = 0; i < attr_cnt; i++)
492  {
493  if (targrows < vacattrstats[i]->minrows)
494  targrows = vacattrstats[i]->minrows;
495  }
496  for (ind = 0; ind < nindexes; ind++)
497  {
498  AnlIndexData *thisdata = &indexdata[ind];
499 
500  for (i = 0; i < thisdata->attr_cnt; i++)
501  {
502  if (targrows < thisdata->vacattrstats[i]->minrows)
503  targrows = thisdata->vacattrstats[i]->minrows;
504  }
505  }
506 
507  /*
508  * Acquire the sample rows
509  */
510  rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
511  if (inh)
512  numrows = acquire_inherited_sample_rows(onerel, elevel,
513  rows, targrows,
514  &totalrows, &totaldeadrows);
515  else
516  numrows = (*acquirefunc) (onerel, elevel,
517  rows, targrows,
518  &totalrows, &totaldeadrows);
519 
520  /*
521  * Compute the statistics. Temporary results during the calculations for
522  * each column are stored in a child context. The calc routines are
523  * responsible to make sure that whatever they store into the VacAttrStats
524  * structure is allocated in anl_context.
525  */
526  if (numrows > 0)
527  {
528  MemoryContext col_context,
529  old_context;
530 
531  col_context = AllocSetContextCreate(anl_context,
532  "Analyze Column",
534  old_context = MemoryContextSwitchTo(col_context);
535 
536  for (i = 0; i < attr_cnt; i++)
537  {
538  VacAttrStats *stats = vacattrstats[i];
539  AttributeOpts *aopt;
540 
541  stats->rows = rows;
542  stats->tupDesc = onerel->rd_att;
543  stats->compute_stats(stats,
545  numrows,
546  totalrows);
547 
548  /*
549  * If the appropriate flavor of the n_distinct option is
550  * specified, override with the corresponding value.
551  */
552  aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
553  if (aopt != NULL)
554  {
555  float8 n_distinct;
556 
557  n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
558  if (n_distinct != 0.0)
559  stats->stadistinct = n_distinct;
560  }
561 
563  }
564 
565  if (hasindex)
566  compute_index_stats(onerel, totalrows,
567  indexdata, nindexes,
568  rows, numrows,
569  col_context);
570 
571  MemoryContextSwitchTo(old_context);
572  MemoryContextDelete(col_context);
573 
574  /*
575  * Emit the completed stats rows into pg_statistic, replacing any
576  * previous statistics for the target columns. (If there are stats in
577  * pg_statistic for columns we didn't process, we leave them alone.)
578  */
579  update_attstats(RelationGetRelid(onerel), inh,
580  attr_cnt, vacattrstats);
581 
582  for (ind = 0; ind < nindexes; ind++)
583  {
584  AnlIndexData *thisdata = &indexdata[ind];
585 
586  update_attstats(RelationGetRelid(Irel[ind]), false,
587  thisdata->attr_cnt, thisdata->vacattrstats);
588  }
589 
590  /* Build extended statistics (if there are any). */
591  BuildRelationExtStatistics(onerel, totalrows, numrows, rows, attr_cnt,
592  vacattrstats);
593  }
594 
595  /*
596  * Update pages/tuples stats in pg_class ... but not if we're doing
597  * inherited stats.
598  */
599  if (!inh)
600  {
601  BlockNumber relallvisible;
602 
603  visibilitymap_count(onerel, &relallvisible, NULL);
604 
605  vac_update_relstats(onerel,
606  relpages,
607  totalrows,
608  relallvisible,
609  hasindex,
612  in_outer_xact);
613  }
614 
615  /*
616  * Same for indexes. Vacuum always scans all indexes, so if we're part of
617  * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
618  * VACUUM.
619  */
620  if (!inh && !(options & VACOPT_VACUUM))
621  {
622  for (ind = 0; ind < nindexes; ind++)
623  {
624  AnlIndexData *thisdata = &indexdata[ind];
625  double totalindexrows;
626 
627  totalindexrows = ceil(thisdata->tupleFract * totalrows);
628  vac_update_relstats(Irel[ind],
629  RelationGetNumberOfBlocks(Irel[ind]),
630  totalindexrows,
631  0,
632  false,
635  in_outer_xact);
636  }
637  }
638 
639  /*
640  * Report ANALYZE to the stats collector, too. However, if doing
641  * inherited stats we shouldn't report, because the stats collector only
642  * tracks per-table stats. Reset the changes_since_analyze counter only
643  * if we analyzed all columns; otherwise, there is still work for
644  * auto-analyze to do.
645  */
646  if (!inh)
647  pgstat_report_analyze(onerel, totalrows, totaldeadrows,
648  (va_cols == NIL));
649 
650  /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
651  if (!(options & VACOPT_VACUUM))
652  {
653  for (ind = 0; ind < nindexes; ind++)
654  {
655  IndexBulkDeleteResult *stats;
656  IndexVacuumInfo ivinfo;
657 
658  ivinfo.index = Irel[ind];
659  ivinfo.analyze_only = true;
660  ivinfo.estimated_count = true;
661  ivinfo.message_level = elevel;
662  ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
663  ivinfo.strategy = vac_strategy;
664 
665  stats = index_vacuum_cleanup(&ivinfo, NULL);
666 
667  if (stats)
668  pfree(stats);
669  }
670  }
671 
672  /* Done with indexes */
673  vac_close_indexes(nindexes, Irel, NoLock);
674 
675  /* Log the action if appropriate */
676  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
677  {
678  if (params->log_min_duration == 0 ||
680  params->log_min_duration))
681  ereport(LOG,
682  (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
685  RelationGetRelationName(onerel),
686  pg_rusage_show(&ru0))));
687  }
688 
689  /* Roll back any GUC changes executed by index functions */
690  AtEOXact_GUC(false, save_nestlevel);
691 
692  /* Restore userid and security context */
693  SetUserIdAndSecContext(save_userid, save_sec_context);
694 
695  /* Restore current context and release memory */
696  MemoryContextSwitchTo(caller_context);
698  anl_context = NULL;
699 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
#define NIL
Definition: pg_list.h:69
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1637
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1279
int minrows
Definition: vacuum.h:92
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:294
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
HeapTuple * rows
Definition: vacuum.h:126
bool analyze_only
Definition: genam.h:47
void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter)
Definition: pgstat.c:1433
BufferAccessStrategy strategy
Definition: genam.h:51
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:510
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
Relation index
Definition: genam.h:46
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
TupleDesc tupDesc
Definition: vacuum.h:127
uint32 BlockNumber
Definition: block.h:31
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1518
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:1645
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:114
unsigned int Oid
Definition: postgres_ext.h:31
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
int natts
Definition: tupdesc.h:79
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:81
int attr_cnt
Definition: analyze.c:72
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:429
void BuildRelationExtStatistics(Relation onerel, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
static MemoryContext anl_context
Definition: analyze.c:80
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3047
#define NoLock
Definition: lockdefs.h:34
float8 n_distinct_inherited
Definition: attoptcache.h:23
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:389
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5098
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:436
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3256
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1594
static int elevel
Definition: vacuumlazy.c:136
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:877
int ii_NumIndexAttrs
Definition: execnodes.h:134
Oid MyDatabaseId
Definition: globals.c:77
#define InvalidMultiXactId
Definition: multixact.h:23
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
TupleDesc rd_att
Definition: rel.h:115
int message_level
Definition: genam.h:49
double num_heap_tuples
Definition: genam.h:50
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:705
List * ii_Expressions
Definition: execnodes.h:136
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int log_min_duration
Definition: vacuum.h:145
AttrNumber ii_KeyAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:135
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:764
double tupleFract
Definition: analyze.c:70
#define InvalidAttrNumber
Definition: attnum.h:23
int NewGUCNestLevel(void)
Definition: guc.c:5084
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
VacAttrStats ** vacattrstats
Definition: analyze.c:71
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
#define elog
Definition: elog.h:219
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:877
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition: analyze.c:886
#define RelationGetRelid(relation)
Definition: rel.h:416
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1652
bool estimated_count
Definition: genam.h:48
float4 stadistinct
Definition: vacuum.h:102
IndexInfo * indexInfo
Definition: analyze.c:69
#define RelationGetNamespace(relation)
Definition: rel.h:443

◆ examine_attribute()

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

Definition at line 886 of file analyze.c.

References anl_context, VacAttrStats::anl_context, VacAttrStats::attr, ATTRIBUTE_FIXED_PART_SIZE, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::compute_stats, DatumGetBool, elog, ERROR, exprType(), exprTypmod(), GETSTRUCT, heap_freetuple(), HeapTupleIsValid, i, VacAttrStats::minrows, ObjectIdGetDatum, OidFunctionCall1, OidIsValid, palloc(), palloc0(), pfree(), PointerGetDatum, RelationData::rd_att, SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), VacAttrStats::tupattnum, TupleDescAttr, and TYPEOID.

Referenced by do_analyze_rel().

887 {
888  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
889  HeapTuple typtuple;
890  VacAttrStats *stats;
891  int i;
892  bool ok;
893 
894  /* Never analyze dropped columns */
895  if (attr->attisdropped)
896  return NULL;
897 
898  /* Don't analyze column if user has specified not to */
899  if (attr->attstattarget == 0)
900  return NULL;
901 
902  /*
903  * Create the VacAttrStats struct. Note that we only have a copy of the
904  * fixed fields of the pg_attribute tuple.
905  */
906  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
908  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
909 
910  /*
911  * When analyzing an expression index, believe the expression tree's type
912  * not the column datatype --- the latter might be the opckeytype storage
913  * type of the opclass, which is not interesting for our purposes. (Note:
914  * if we did anything with non-expression index columns, we'd need to
915  * figure out where to get the correct type info from, but for now that's
916  * not a problem.) It's not clear whether anyone will care about the
917  * typmod, but we store that too just in case.
918  */
919  if (index_expr)
920  {
921  stats->attrtypid = exprType(index_expr);
922  stats->attrtypmod = exprTypmod(index_expr);
923  }
924  else
925  {
926  stats->attrtypid = attr->atttypid;
927  stats->attrtypmod = attr->atttypmod;
928  }
929 
930  typtuple = SearchSysCacheCopy1(TYPEOID,
931  ObjectIdGetDatum(stats->attrtypid));
932  if (!HeapTupleIsValid(typtuple))
933  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
934  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
935  stats->anl_context = anl_context;
936  stats->tupattnum = attnum;
937 
938  /*
939  * The fields describing the stats->stavalues[n] element types default to
940  * the type of the data being analyzed, but the type-specific typanalyze
941  * function can change them if it wants to store something else.
942  */
943  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
944  {
945  stats->statypid[i] = stats->attrtypid;
946  stats->statyplen[i] = stats->attrtype->typlen;
947  stats->statypbyval[i] = stats->attrtype->typbyval;
948  stats->statypalign[i] = stats->attrtype->typalign;
949  }
950 
951  /*
952  * Call the type-specific typanalyze function. If none is specified, use
953  * std_typanalyze().
954  */
955  if (OidIsValid(stats->attrtype->typanalyze))
956  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
957  PointerGetDatum(stats)));
958  else
959  ok = std_typanalyze(stats);
960 
961  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
962  {
963  heap_freetuple(typtuple);
964  pfree(stats->attr);
965  pfree(stats);
966  return NULL;
967  }
968 
969  return stats;
970 }
int minrows
Definition: vacuum.h:92
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
#define PointerGetDatum(X)
Definition: postgres.h:562
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
int tupattnum
Definition: vacuum.h:125
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1739
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
int32 attrtypmod
Definition: vacuum.h:83
#define OidIsValid(objectId)
Definition: c.h:576
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
Form_pg_attribute attr
Definition: vacuum.h:81
void pfree(void *pointer)
Definition: mcxt.c:949
Oid attrtypid
Definition: vacuum.h:82
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
static MemoryContext anl_context
Definition: analyze.c:80
#define DatumGetBool(X)
Definition: postgres.h:399
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:179
void * palloc0(Size size)
Definition: mcxt.c:877
TupleDesc rd_att
Definition: rel.h:115
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:116
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:121
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
MemoryContext anl_context
Definition: vacuum.h:85
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
Form_pg_type attrtype
Definition: vacuum.h:84
void * palloc(Size size)
Definition: mcxt.c:848
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
#define elog
Definition: elog.h:219

◆ ind_fetch_func()

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

Definition at line 1668 of file analyze.c.

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

Referenced by compute_index_stats().

1669 {
1670  int i;
1671 
1672  /* exprvals and exprnulls are already offset for proper column */
1673  i = rownum * stats->rowstride;
1674  *isNull = stats->exprnulls[i];
1675  return stats->exprvals[i];
1676 }
int rowstride
Definition: vacuum.h:130
bool * exprnulls
Definition: vacuum.h:129
Datum * exprvals
Definition: vacuum.h:128
int i

◆ std_fetch_func()

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

Definition at line 1652 of file analyze.c.

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

Referenced by do_analyze_rel().

1653 {
1654  int attnum = stats->tupattnum;
1655  HeapTuple tuple = stats->rows[rownum];
1656  TupleDesc tupDesc = stats->tupDesc;
1657 
1658  return heap_getattr(tuple, attnum, tupDesc, isNull);
1659 }
HeapTuple * rows
Definition: vacuum.h:126
int tupattnum
Definition: vacuum.h:125
TupleDesc tupDesc
Definition: vacuum.h:127
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:774

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

Definition at line 1739 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(), and examine_attribute().

1740 {
1741  Form_pg_attribute attr = stats->attr;
1742  Oid ltopr;
1743  Oid eqopr;
1744  StdAnalyzeData *mystats;
1745 
1746  /* If the attstattarget column is negative, use the default value */
1747  /* NB: it is okay to scribble on stats->attr since it's a copy */
1748  if (attr->attstattarget < 0)
1749  attr->attstattarget = default_statistics_target;
1750 
1751  /* Look for default "<" and "=" operators for column's type */
1753  false, false, false,
1754  &ltopr, &eqopr, NULL,
1755  NULL);
1756 
1757  /* Save the operator info for compute_stats routines */
1758  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1759  mystats->eqopr = eqopr;
1760  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1761  mystats->ltopr = ltopr;
1762  stats->extra_data = mystats;
1763 
1764  /*
1765  * Determine which standard statistics algorithm to use
1766  */
1767  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1768  {
1769  /* Seems to be a scalar datatype */
1771  /*--------------------
1772  * The following choice of minrows is based on the paper
1773  * "Random sampling for histogram construction: how much is enough?"
1774  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1775  * Proceedings of ACM SIGMOD International Conference on Management
1776  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1777  * says that for table size n, histogram size k, maximum relative
1778  * error in bin size f, and error probability gamma, the minimum
1779  * random sample size is
1780  * r = 4 * k * ln(2*n/gamma) / f^2
1781  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1782  * r = 305.82 * k
1783  * Note that because of the log function, the dependence on n is
1784  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1785  * bin size error with probability 0.99. So there's no real need to
1786  * scale for n, which is a good thing because we don't necessarily
1787  * know it at this point.
1788  *--------------------
1789  */
1790  stats->minrows = 300 * attr->attstattarget;
1791  }
1792  else if (OidIsValid(eqopr))
1793  {
1794  /* We can still recognize distinct values */
1796  /* Might as well use the same minrows as above */
1797  stats->minrows = 300 * attr->attstattarget;
1798  }
1799  else
1800  {
1801  /* Can't do much but the trivial stuff */
1803  /* Might as well use the same minrows as above */
1804  stats->minrows = 300 * attr->attstattarget;
1805  }
1806 
1807  return true;
1808 }
int minrows
Definition: vacuum.h:92
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2261
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
Form_pg_attribute attr
Definition: vacuum.h:81
Oid attrtypid
Definition: vacuum.h:82
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1909
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
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:187
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1819
void * palloc(Size size)
Definition: mcxt.c:848
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
void * extra_data
Definition: vacuum.h:93
int default_statistics_target
Definition: analyze.c:77

◆ update_attstats()

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

Definition at line 1518 of file analyze.c.

References Anum_pg_statistic_staattnum, Anum_pg_statistic_stadistinct, Anum_pg_statistic_stainherit, Anum_pg_statistic_stakind1, Anum_pg_statistic_stanullfrac, Anum_pg_statistic_stanumbers1, Anum_pg_statistic_staop1, Anum_pg_statistic_starelid, Anum_pg_statistic_stavalues1, Anum_pg_statistic_stawidth, VacAttrStats::attr, BoolGetDatum, CatalogTupleInsert(), CatalogTupleUpdate(), construct_array(), Float4GetDatum(), FLOAT4OID, heap_close, heap_form_tuple(), heap_freetuple(), heap_modify_tuple(), heap_open(), HeapTupleIsValid, i, Int16GetDatum, Int32GetDatum, Natts_pg_statistic, VacAttrStats::numnumbers, VacAttrStats::numvalues, ObjectIdGetDatum, palloc(), PointerGetDatum, RelationGetDescr, ReleaseSysCache(), RowExclusiveLock, SearchSysCache3(), VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_NUM_SLOTS, StatisticRelationId, STATRELATTINH, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, HeapTupleData::t_self, and values.

Referenced by do_analyze_rel().

1519 {
1520  Relation sd;
1521  int attno;
1522 
1523  if (natts <= 0)
1524  return; /* nothing to do */
1525 
1527 
1528  for (attno = 0; attno < natts; attno++)
1529  {
1530  VacAttrStats *stats = vacattrstats[attno];
1531  HeapTuple stup,
1532  oldtup;
1533  int i,
1534  k,
1535  n;
1537  bool nulls[Natts_pg_statistic];
1538  bool replaces[Natts_pg_statistic];
1539 
1540  /* Ignore attr if we weren't able to collect stats */
1541  if (!stats->stats_valid)
1542  continue;
1543 
1544  /*
1545  * Construct a new pg_statistic tuple
1546  */
1547  for (i = 0; i < Natts_pg_statistic; ++i)
1548  {
1549  nulls[i] = false;
1550  replaces[i] = true;
1551  }
1552 
1553  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1554  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1555  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1557  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1560  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1561  {
1562  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1563  }
1564  i = Anum_pg_statistic_staop1 - 1;
1565  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1566  {
1567  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1568  }
1570  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1571  {
1572  int nnum = stats->numnumbers[k];
1573 
1574  if (nnum > 0)
1575  {
1576  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1577  ArrayType *arry;
1578 
1579  for (n = 0; n < nnum; n++)
1580  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1581  /* XXX knows more than it should about type float4: */
1582  arry = construct_array(numdatums, nnum,
1583  FLOAT4OID,
1584  sizeof(float4), FLOAT4PASSBYVAL, 'i');
1585  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1586  }
1587  else
1588  {
1589  nulls[i] = true;
1590  values[i++] = (Datum) 0;
1591  }
1592  }
1594  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1595  {
1596  if (stats->numvalues[k] > 0)
1597  {
1598  ArrayType *arry;
1599 
1600  arry = construct_array(stats->stavalues[k],
1601  stats->numvalues[k],
1602  stats->statypid[k],
1603  stats->statyplen[k],
1604  stats->statypbyval[k],
1605  stats->statypalign[k]);
1606  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1607  }
1608  else
1609  {
1610  nulls[i] = true;
1611  values[i++] = (Datum) 0;
1612  }
1613  }
1614 
1615  /* Is there already a pg_statistic tuple for this attribute? */
1616  oldtup = SearchSysCache3(STATRELATTINH,
1617  ObjectIdGetDatum(relid),
1618  Int16GetDatum(stats->attr->attnum),
1619  BoolGetDatum(inh));
1620 
1621  if (HeapTupleIsValid(oldtup))
1622  {
1623  /* Yes, replace it */
1624  stup = heap_modify_tuple(oldtup,
1625  RelationGetDescr(sd),
1626  values,
1627  nulls,
1628  replaces);
1629  ReleaseSysCache(oldtup);
1630  CatalogTupleUpdate(sd, &stup->t_self, stup);
1631  }
1632  else
1633  {
1634  /* No, insert new tuple */
1635  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1636  CatalogTupleInsert(sd, stup);
1637  }
1638 
1639  heap_freetuple(stup);
1640  }
1641 
1643 }
#define Anum_pg_statistic_staop1
Definition: pg_statistic.h:147
#define Anum_pg_statistic_stavalues1
Definition: pg_statistic.h:157
#define RelationGetDescr(relation)
Definition: rel.h:428
#define Anum_pg_statistic_stainherit
Definition: pg_statistic.h:138
#define Anum_pg_statistic_stadistinct
Definition: pg_statistic.h:141
#define Anum_pg_statistic_stanullfrac
Definition: pg_statistic.h:139
#define PointerGetDatum(X)
Definition: postgres.h:562
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
#define Int16GetDatum(X)
Definition: postgres.h:457
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3279
#define Anum_pg_statistic_staattnum
Definition: pg_statistic.h:137
#define Anum_pg_statistic_stawidth
Definition: pg_statistic.h:140
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:695
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define Anum_pg_statistic_stakind1
Definition: pg_statistic.h:142
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
Form_pg_attribute attr
Definition: vacuum.h:81
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
int32 stawidth
Definition: vacuum.h:101
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
Datum Float4GetDatum(float4 X)
Definition: fmgr.c:1798
ItemPointerData t_self
Definition: htup.h:65
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
#define Natts_pg_statistic
Definition: pg_statistic.h:135
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Anum_pg_statistic_starelid
Definition: pg_statistic.h:136
float4 stanullfrac
Definition: vacuum.h:100
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
bool stats_valid
Definition: vacuum.h:99
float float4
Definition: c.h:428
#define FLOAT4OID
Definition: pg_type.h:416
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define StatisticRelationId
Definition: pg_statistic.h:29
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:103
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:116
#define BoolGetDatum(X)
Definition: postgres.h:408
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:121
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
#define Anum_pg_statistic_stanumbers1
Definition: pg_statistic.h:152
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define Int32GetDatum(X)
Definition: postgres.h:485
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
void * palloc(Size size)
Definition: mcxt.c:848
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
int i
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
float4 stadistinct
Definition: vacuum.h:102

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 80 of file analyze.c.

Referenced by examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

Definition at line 77 of file analyze.c.

Referenced by range_typanalyze(), std_typanalyze(), and ts_typanalyze().

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 81 of file analyze.c.

Referenced by do_analyze_rel().