PostgreSQL Source Code  git master
analyze.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/heapam.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.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)
 
static int analyze_mcv_list (int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
 
bool std_typanalyze (VacAttrStats *stats)
 

Variables

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

Macro Definition Documentation

◆ swapDatum

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

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

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

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

Referenced by do_analyze_rel().

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

◆ acquire_sample_rows()

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

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

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

1006 {
1007  int numrows = 0; /* # rows now in reservoir */
1008  double samplerows = 0; /* total # rows collected */
1009  double liverows = 0; /* # live rows seen */
1010  double deadrows = 0; /* # dead rows seen */
1011  double rowstoskip = -1; /* -1 means not set yet */
1012  BlockNumber totalblocks;
1014  BlockSamplerData bs;
1015  ReservoirStateData rstate;
1016 
1017  Assert(targrows > 0);
1018 
1019  totalblocks = RelationGetNumberOfBlocks(onerel);
1020 
1021  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1022  OldestXmin = GetOldestXmin(onerel, PROCARRAY_FLAGS_VACUUM);
1023 
1024  /* Prepare for sampling block numbers */
1025  BlockSampler_Init(&bs, totalblocks, targrows, random());
1026  /* Prepare for sampling rows */
1027  reservoir_init_selection_state(&rstate, targrows);
1028 
1029  /* Outer loop over blocks to sample */
1030  while (BlockSampler_HasMore(&bs))
1031  {
1032  BlockNumber targblock = BlockSampler_Next(&bs);
1033  Buffer targbuffer;
1034  Page targpage;
1035  OffsetNumber targoffset,
1036  maxoffset;
1037 
1039 
1040  /*
1041  * We must maintain a pin on the target page's buffer to ensure that
1042  * the maxoffset value stays good (else concurrent VACUUM might delete
1043  * tuples out from under us). Hence, pin the page until we are done
1044  * looking at it. We also choose to hold sharelock on the buffer
1045  * throughout --- we could release and re-acquire sharelock for each
1046  * tuple, but since we aren't doing much work per tuple, the extra
1047  * lock traffic is probably better avoided.
1048  */
1049  targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1051  LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1052  targpage = BufferGetPage(targbuffer);
1053  maxoffset = PageGetMaxOffsetNumber(targpage);
1054 
1055  /* Inner loop over all tuples on the selected page */
1056  for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1057  {
1058  ItemId itemid;
1059  HeapTupleData targtuple;
1060  bool sample_it = false;
1061 
1062  itemid = PageGetItemId(targpage, targoffset);
1063 
1064  /*
1065  * We ignore unused and redirect line pointers. DEAD line
1066  * pointers should be counted as dead, because we need vacuum to
1067  * run to get rid of them. Note that this rule agrees with the
1068  * way that heap_page_prune() counts things.
1069  */
1070  if (!ItemIdIsNormal(itemid))
1071  {
1072  if (ItemIdIsDead(itemid))
1073  deadrows += 1;
1074  continue;
1075  }
1076 
1077  ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1078 
1079  targtuple.t_tableOid = RelationGetRelid(onerel);
1080  targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1081  targtuple.t_len = ItemIdGetLength(itemid);
1082 
1083  switch (HeapTupleSatisfiesVacuum(&targtuple,
1084  OldestXmin,
1085  targbuffer))
1086  {
1087  case HEAPTUPLE_LIVE:
1088  sample_it = true;
1089  liverows += 1;
1090  break;
1091 
1092  case HEAPTUPLE_DEAD:
1094  /* Count dead and recently-dead rows */
1095  deadrows += 1;
1096  break;
1097 
1099 
1100  /*
1101  * Insert-in-progress rows are not counted. We assume
1102  * that when the inserting transaction commits or aborts,
1103  * it will send a stats message to increment the proper
1104  * count. This works right only if that transaction ends
1105  * after we finish analyzing the table; if things happen
1106  * in the other order, its stats update will be
1107  * overwritten by ours. However, the error will be large
1108  * only if the other transaction runs long enough to
1109  * insert many tuples, so assuming it will finish after us
1110  * is the safer option.
1111  *
1112  * A special case is that the inserting transaction might
1113  * be our own. In this case we should count and sample
1114  * the row, to accommodate users who load a table and
1115  * analyze it in one transaction. (pgstat_report_analyze
1116  * has to adjust the numbers we send to the stats
1117  * collector to make this come out right.)
1118  */
1120  {
1121  sample_it = true;
1122  liverows += 1;
1123  }
1124  break;
1125 
1127 
1128  /*
1129  * We count and sample delete-in-progress rows the same as
1130  * live ones, so that the stats counters come out right if
1131  * the deleting transaction commits after us, per the same
1132  * reasoning given above.
1133  *
1134  * If the delete was done by our own transaction, however,
1135  * we must count the row as dead to make
1136  * pgstat_report_analyze's stats adjustments come out
1137  * right. (Note: this works out properly when the row was
1138  * both inserted and deleted in our xact.)
1139  *
1140  * The net effect of these choices is that we act as
1141  * though an IN_PROGRESS transaction hasn't happened yet,
1142  * except if it is our own transaction, which we assume
1143  * has happened.
1144  *
1145  * This approach ensures that we behave sanely if we see
1146  * both the pre-image and post-image rows for a row being
1147  * updated by a concurrent transaction: we will sample the
1148  * pre-image but not the post-image. We also get sane
1149  * results if the concurrent transaction never commits.
1150  */
1152  deadrows += 1;
1153  else
1154  {
1155  sample_it = true;
1156  liverows += 1;
1157  }
1158  break;
1159 
1160  default:
1161  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1162  break;
1163  }
1164 
1165  if (sample_it)
1166  {
1167  /*
1168  * The first targrows sample rows are simply copied into the
1169  * reservoir. Then we start replacing tuples in the sample
1170  * until we reach the end of the relation. This algorithm is
1171  * from Jeff Vitter's paper (see full citation below). It
1172  * works by repeatedly computing the number of tuples to skip
1173  * before selecting a tuple, which replaces a randomly chosen
1174  * element of the reservoir (current set of tuples). At all
1175  * times the reservoir is a true random sample of the tuples
1176  * we've passed over so far, so when we fall off the end of
1177  * the relation we're done.
1178  */
1179  if (numrows < targrows)
1180  rows[numrows++] = heap_copytuple(&targtuple);
1181  else
1182  {
1183  /*
1184  * t in Vitter's paper is the number of records already
1185  * processed. If we need to compute a new S value, we
1186  * must use the not-yet-incremented value of samplerows as
1187  * t.
1188  */
1189  if (rowstoskip < 0)
1190  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1191 
1192  if (rowstoskip <= 0)
1193  {
1194  /*
1195  * Found a suitable tuple, so save it, replacing one
1196  * old tuple at random
1197  */
1198  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1199 
1200  Assert(k >= 0 && k < targrows);
1201  heap_freetuple(rows[k]);
1202  rows[k] = heap_copytuple(&targtuple);
1203  }
1204 
1205  rowstoskip -= 1;
1206  }
1207 
1208  samplerows += 1;
1209  }
1210  }
1211 
1212  /* Now release the lock and pin on the page */
1213  UnlockReleaseBuffer(targbuffer);
1214  }
1215 
1216  /*
1217  * If we didn't find as many tuples as we wanted then we're done. No sort
1218  * is needed, since they're already in order.
1219  *
1220  * Otherwise we need to sort the collected tuples by position
1221  * (itempointer). It's not worth worrying about corner cases where the
1222  * tuples are already sorted.
1223  */
1224  if (numrows == targrows)
1225  qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1226 
1227  /*
1228  * Estimate total numbers of live and dead rows in relation, extrapolating
1229  * on the assumption that the average tuple density in pages we didn't
1230  * scan is the same as in the pages we did scan. Since what we scanned is
1231  * a random sample of the pages in the relation, this should be a good
1232  * assumption.
1233  */
1234  if (bs.m > 0)
1235  {
1236  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1237  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1238  }
1239  else
1240  {
1241  *totalrows = 0.0;
1242  *totaldeadrows = 0.0;
1243  }
1244 
1245  /*
1246  * Emit some interesting relation info
1247  */
1248  ereport(elevel,
1249  (errmsg("\"%s\": scanned %d of %u pages, "
1250  "containing %.0f live rows and %.0f dead rows; "
1251  "%d rows in sample, %.0f estimated total rows",
1252  RelationGetRelationName(onerel),
1253  bs.m, totalblocks,
1254  liverows, deadrows,
1255  numrows, *totalrows)));
1256 
1257  return numrows;
1258 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:365
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:54
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:682
uint32 TransactionId
Definition: c.h:507
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:769
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:83
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:1340
#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:68
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:3338
#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:431
static TransactionId OldestXmin
Definition: vacuumlazy.c:146
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:141
static int compare_rows(const void *a, const void *b)
Definition: analyze.c:1264
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:231
static int elevel
Definition: vacuumlazy.c:144
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3552
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1321
#define Assert(condition)
Definition: c.h:732
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define qsort(a, b, c, d)
Definition: port.h:482
void vacuum_delay_point(void)
Definition: vacuum.c:1829
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:397
#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:127
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142

◆ analyze_mcv_list()

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

Definition at line 2856 of file analyze.c.

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

2862 {
2863  double ndistinct_table;
2864  double sumcount;
2865  int i;
2866 
2867  /*
2868  * If the entire table was sampled, keep the whole list. This also
2869  * protects us against division by zero in the code below.
2870  */
2871  if (samplerows == totalrows || totalrows <= 1.0)
2872  return num_mcv;
2873 
2874  /* Re-extract the estimated number of distinct nonnull values in table */
2875  ndistinct_table = stadistinct;
2876  if (ndistinct_table < 0)
2877  ndistinct_table = -ndistinct_table * totalrows;
2878 
2879  /*
2880  * Exclude the least common values from the MCV list, if they are not
2881  * significantly more common than the estimated selectivity they would
2882  * have if they weren't in the list. All non-MCV values are assumed to be
2883  * equally common, after taking into account the frequencies of all the
2884  * values in the MCV list and the number of nulls (c.f. eqsel()).
2885  *
2886  * Here sumcount tracks the total count of all but the last (least common)
2887  * value in the MCV list, allowing us to determine the effect of excluding
2888  * that value from the list.
2889  *
2890  * Note that we deliberately do this by removing values from the full
2891  * list, rather than starting with an empty list and adding values,
2892  * because the latter approach can fail to add any values if all the most
2893  * common values have around the same frequency and make up the majority
2894  * of the table, so that the overall average frequency of all values is
2895  * roughly the same as that of the common values. This would lead to any
2896  * uncommon values being significantly overestimated.
2897  */
2898  sumcount = 0.0;
2899  for (i = 0; i < num_mcv - 1; i++)
2900  sumcount += mcv_counts[i];
2901 
2902  while (num_mcv > 0)
2903  {
2904  double selec,
2905  otherdistinct,
2906  N,
2907  n,
2908  K,
2909  variance,
2910  stddev;
2911 
2912  /*
2913  * Estimated selectivity the least common value would have if it
2914  * wasn't in the MCV list (c.f. eqsel()).
2915  */
2916  selec = 1.0 - sumcount / samplerows - stanullfrac;
2917  if (selec < 0.0)
2918  selec = 0.0;
2919  if (selec > 1.0)
2920  selec = 1.0;
2921  otherdistinct = ndistinct_table - (num_mcv - 1);
2922  if (otherdistinct > 1)
2923  selec /= otherdistinct;
2924 
2925  /*
2926  * If the value is kept in the MCV list, its population frequency is
2927  * assumed to equal its sample frequency. We use the lower end of a
2928  * textbook continuity-corrected Wald-type confidence interval to
2929  * determine if that is significantly more common than the non-MCV
2930  * frequency --- specifically we assume the population frequency is
2931  * highly likely to be within around 2 standard errors of the sample
2932  * frequency, which equates to an interval of 2 standard deviations
2933  * either side of the sample count, plus an additional 0.5 for the
2934  * continuity correction. Since we are sampling without replacement,
2935  * this is a hypergeometric distribution.
2936  *
2937  * XXX: Empirically, this approach seems to work quite well, but it
2938  * may be worth considering more advanced techniques for estimating
2939  * the confidence interval of the hypergeometric distribution.
2940  */
2941  N = totalrows;
2942  n = samplerows;
2943  K = N * mcv_counts[num_mcv - 1] / n;
2944  variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
2945  stddev = sqrt(variance);
2946 
2947  if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
2948  {
2949  /*
2950  * The value is significantly more common than the non-MCV
2951  * selectivity would suggest. Keep it, and all the other more
2952  * common values in the list.
2953  */
2954  break;
2955  }
2956  else
2957  {
2958  /* Discard this value and consider the next least common value */
2959  num_mcv--;
2960  if (num_mcv == 0)
2961  break;
2962  sumcount -= mcv_counts[num_mcv - 1];
2963  }
2964  }
2965  return num_mcv;
2966 }
#define K(t)
Definition: sha1.c:48
int i

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

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), elevel, ereport, errmsg(), GetFdwRoutineForRelation(), INFO, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyPgXact, NoLock, PROC_IN_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, relpages, ShareUpdateExclusiveLock, VACOPT_ANALYZE, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_relation_owner(), vacuum_open_relation(), PGXACT::vacuumFlags, and WARNING.

Referenced by vacuum().

120 {
121  Relation onerel;
122  int elevel;
123  AcquireSampleRowsFunc acquirefunc = NULL;
124  BlockNumber relpages = 0;
125 
126  /* Select logging level */
127  if (options & VACOPT_VERBOSE)
128  elevel = INFO;
129  else
130  elevel = DEBUG2;
131 
132  /* Set up static variables */
133  vac_strategy = bstrategy;
134 
135  /*
136  * Check for user-requested abort.
137  */
139 
140  /*
141  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
142  * ANALYZEs don't run on it concurrently. (This also locks out a
143  * concurrent VACUUM, which doesn't matter much at the moment but might
144  * matter if we ever try to accumulate stats on dead tuples.) If the rel
145  * has been dropped since we last saw it, we don't need to process it.
146  *
147  * Make sure to generate only logs for ANALYZE in this case.
148  */
149  onerel = vacuum_open_relation(relid, relation, params,
150  options & ~(VACOPT_VACUUM),
152 
153  /* leave if relation could not be opened or locked */
154  if (!onerel)
155  return;
156 
157  /*
158  * Check if relation needs to be skipped based on ownership. This check
159  * happens also when building the relation list to analyze for a manual
160  * operation, and needs to be done additionally here as ANALYZE could
161  * happen across multiple transactions where relation ownership could have
162  * changed in-between. Make sure to generate only logs for ANALYZE in
163  * this case.
164  */
166  onerel->rd_rel,
168  {
170  return;
171  }
172 
173  /*
174  * Silently ignore tables that are temp tables of other backends ---
175  * trying to analyze these is rather pointless, since their contents are
176  * probably not up-to-date on disk. (We don't throw a warning here; it
177  * would just lead to chatter during a database-wide ANALYZE.)
178  */
179  if (RELATION_IS_OTHER_TEMP(onerel))
180  {
182  return;
183  }
184 
185  /*
186  * We can ANALYZE any table except pg_statistic. See update_attstats
187  */
188  if (RelationGetRelid(onerel) == StatisticRelationId)
189  {
191  return;
192  }
193 
194  /*
195  * Check that it's of an analyzable relkind, and set up appropriately.
196  */
197  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
198  onerel->rd_rel->relkind == RELKIND_MATVIEW)
199  {
200  /* Regular table, so we'll use the regular row acquisition function */
201  acquirefunc = acquire_sample_rows;
202  /* Also get regular table's size */
203  relpages = RelationGetNumberOfBlocks(onerel);
204  }
205  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
206  {
207  /*
208  * For a foreign table, call the FDW's hook function to see whether it
209  * supports analysis.
210  */
211  FdwRoutine *fdwroutine;
212  bool ok = false;
213 
214  fdwroutine = GetFdwRoutineForRelation(onerel, false);
215 
216  if (fdwroutine->AnalyzeForeignTable != NULL)
217  ok = fdwroutine->AnalyzeForeignTable(onerel,
218  &acquirefunc,
219  &relpages);
220 
221  if (!ok)
222  {
224  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
225  RelationGetRelationName(onerel))));
227  return;
228  }
229  }
230  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
231  {
232  /*
233  * For partitioned tables, we want to do the recursive ANALYZE below.
234  */
235  }
236  else
237  {
238  /* No need for a WARNING if we already complained during VACUUM */
239  if (!(options & VACOPT_VACUUM))
241  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
242  RelationGetRelationName(onerel))));
244  return;
245  }
246 
247  /*
248  * OK, let's do it. First let other backends know I'm in ANALYZE.
249  */
250  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
252  LWLockRelease(ProcArrayLock);
253 
254  /*
255  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
256  * tables, which don't contain any rows.
257  */
258  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
259  do_analyze_rel(onerel, options, params, va_cols, acquirefunc,
260  relpages, false, in_outer_xact, elevel);
261 
262  /*
263  * If there are child tables, do recursive ANALYZE.
264  */
265  if (onerel->rd_rel->relhassubclass)
266  do_analyze_rel(onerel, options, params, va_cols, acquirefunc, relpages,
267  true, in_outer_xact, elevel);
268 
269  /*
270  * Close source relation now, but keep lock so that no one deletes it
271  * before we commit. (If someone did, they'd fail to clean up the entries
272  * we made in pg_statistic. Also, releasing the lock before commit would
273  * expose us to concurrent-update failures in update_attstats.)
274  */
275  relation_close(onerel, NoLock);
276 
277  /*
278  * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
279  * because the vacuum flag is cleared by the end-of-xact code.
280  */
281  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
283  LWLockRelease(ProcArrayLock);
284 }
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:233
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1279
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:83
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:84
int32 relpages
Definition: pg_class.h:44
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:233
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, int options)
Definition: vacuum.c:419
#define DEBUG2
Definition: elog.h:24
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:431
#define ereport(elevel, rest)
Definition: elog.h:141
#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:294
static int elevel
Definition: vacuumlazy.c:144
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:527
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
#define PROC_IN_ANALYZE
Definition: proc.h:55
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
Relation vacuum_open_relation(Oid relid, RangeVar *relation, VacuumParams *params, int options, LOCKMODE lmode)
Definition: vacuum.c:493
#define RelationGetRelid(relation)
Definition: rel.h:397
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1003

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

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1265 {
1266  HeapTuple ha = *(const HeapTuple *) a;
1267  HeapTuple hb = *(const HeapTuple *) b;
1272 
1273  if (ba < bb)
1274  return -1;
1275  if (ba > bb)
1276  return 1;
1277  if (oa < ob)
1278  return -1;
1279  if (oa > ob)
1280  return 1;
1281  return 0;
1282 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ compare_scalars()

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

Definition at line 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:1734
uintptr_t Datum
Definition: postgres.h:367
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

◆ compute_distinct_stats()

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

Definition at line 1935 of file analyze.c.

References analyze_mcv_list(), VacAttrStats::anl_context, VacAttrStats::attr, VacAttrStats::attrcollid, VacAttrStats::attrtype, datumCopy(), DatumGetBool, DatumGetCString, DatumGetPointer, StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, fmgr_info(), FunctionCall2Coll(), i, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum, VacAttrStats::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, VacAttrStats::stats_valid, VacAttrStats::stavalues, VacAttrStats::stawidth, swapDatum, swapInt, toast_raw_datum_size(), vacuum_delay_point(), value, VARSIZE_ANY, and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

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

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

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

Referenced by do_analyze_rel().

694 {
695  MemoryContext ind_context,
696  old_context;
698  bool isnull[INDEX_MAX_KEYS];
699  int ind,
700  i;
701 
702  ind_context = AllocSetContextCreate(anl_context,
703  "Analyze Index",
705  old_context = MemoryContextSwitchTo(ind_context);
706 
707  for (ind = 0; ind < nindexes; ind++)
708  {
709  AnlIndexData *thisdata = &indexdata[ind];
710  IndexInfo *indexInfo = thisdata->indexInfo;
711  int attr_cnt = thisdata->attr_cnt;
712  TupleTableSlot *slot;
713  EState *estate;
714  ExprContext *econtext;
715  ExprState *predicate;
716  Datum *exprvals;
717  bool *exprnulls;
718  int numindexrows,
719  tcnt,
720  rowno;
721  double totalindexrows;
722 
723  /* Ignore index if no columns to analyze and not partial */
724  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
725  continue;
726 
727  /*
728  * Need an EState for evaluation of index expressions and
729  * partial-index predicates. Create it in the per-index context to be
730  * sure it gets cleaned up at the bottom of the loop.
731  */
732  estate = CreateExecutorState();
733  econtext = GetPerTupleExprContext(estate);
734  /* Need a slot to hold the current heap tuple, too */
736  &TTSOpsHeapTuple);
737 
738  /* Arrange for econtext's scan tuple to be the tuple under test */
739  econtext->ecxt_scantuple = slot;
740 
741  /* Set up execution state for predicate. */
742  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
743 
744  /* Compute and save index expression values */
745  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
746  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
747  numindexrows = 0;
748  tcnt = 0;
749  for (rowno = 0; rowno < numrows; rowno++)
750  {
751  HeapTuple heapTuple = rows[rowno];
752 
754 
755  /*
756  * Reset the per-tuple context each time, to reclaim any cruft
757  * left behind by evaluating the predicate or index expressions.
758  */
759  ResetExprContext(econtext);
760 
761  /* Set up for predicate or expression evaluation */
762  ExecStoreHeapTuple(heapTuple, slot, false);
763 
764  /* If index is partial, check predicate */
765  if (predicate != NULL)
766  {
767  if (!ExecQual(predicate, econtext))
768  continue;
769  }
770  numindexrows++;
771 
772  if (attr_cnt > 0)
773  {
774  /*
775  * Evaluate the index row to compute expression values. We
776  * could do this by hand, but FormIndexDatum is convenient.
777  */
778  FormIndexDatum(indexInfo,
779  slot,
780  estate,
781  values,
782  isnull);
783 
784  /*
785  * Save just the columns we care about. We copy the values
786  * into ind_context from the estate's per-tuple context.
787  */
788  for (i = 0; i < attr_cnt; i++)
789  {
790  VacAttrStats *stats = thisdata->vacattrstats[i];
791  int attnum = stats->attr->attnum;
792 
793  if (isnull[attnum - 1])
794  {
795  exprvals[tcnt] = (Datum) 0;
796  exprnulls[tcnt] = true;
797  }
798  else
799  {
800  exprvals[tcnt] = datumCopy(values[attnum - 1],
801  stats->attrtype->typbyval,
802  stats->attrtype->typlen);
803  exprnulls[tcnt] = false;
804  }
805  tcnt++;
806  }
807  }
808  }
809 
810  /*
811  * Having counted the number of rows that pass the predicate in the
812  * sample, we can estimate the total number of rows in the index.
813  */
814  thisdata->tupleFract = (double) numindexrows / (double) numrows;
815  totalindexrows = ceil(thisdata->tupleFract * totalrows);
816 
817  /*
818  * Now we can compute the statistics for the expression columns.
819  */
820  if (numindexrows > 0)
821  {
822  MemoryContextSwitchTo(col_context);
823  for (i = 0; i < attr_cnt; i++)
824  {
825  VacAttrStats *stats = thisdata->vacattrstats[i];
826  AttributeOpts *aopt =
827  get_attribute_options(stats->attr->attrelid,
828  stats->attr->attnum);
829 
830  stats->exprvals = exprvals + i;
831  stats->exprnulls = exprnulls + i;
832  stats->rowstride = attr_cnt;
833  stats->compute_stats(stats,
835  numindexrows,
836  totalindexrows);
837 
838  /*
839  * If the n_distinct option is specified, it overrides the
840  * above computation. For indices, we always use just
841  * n_distinct, not n_distinct_inherited.
842  */
843  if (aopt != NULL && aopt->n_distinct != 0.0)
844  stats->stadistinct = aopt->n_distinct;
845 
847  }
848  }
849 
850  /* And clean up */
851  MemoryContextSwitchTo(ind_context);
852 
854  FreeExecutorState(estate);
856  }
857 
858  MemoryContextSwitchTo(old_context);
859  MemoryContextDelete(ind_context);
860 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
int rowstride
Definition: vacuum.h:136
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2005
#define NIL
Definition: pg_list.h:69
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
List * ii_Predicate
Definition: execnodes.h:159
#define RelationGetDescr(relation)
Definition: rel.h:423
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1158
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:355
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:85
int attr_cnt
Definition: analyze.c:74
void FreeExecutorState(EState *estate)
Definition: execUtils.c:195
#define GetPerTupleExprContext(estate)
Definition: executor.h:491
bool * exprnulls
Definition: vacuum.h:135
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
static MemoryContext anl_context
Definition: analyze.c:82
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1174
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:517
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:86
Datum * exprvals
Definition: vacuum.h:134
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
uintptr_t Datum
Definition: postgres.h:367
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1688
int16 attnum
Definition: pg_attribute.h:79
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:221
double tupleFract
Definition: analyze.c:72
static Datum values[MAXATTR]
Definition: bootstrap.c:167
Form_pg_type attrtype
Definition: vacuum.h:88
void * palloc(Size size)
Definition: mcxt.c:924
VacAttrStats ** vacattrstats
Definition: analyze.c:73
int i
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:81
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:96
void vacuum_delay_point(void)
Definition: vacuum.c:1829
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1272
#define ResetExprContext(econtext)
Definition: executor.h:485
float4 stadistinct
Definition: vacuum.h:107
IndexInfo * indexInfo
Definition: analyze.c:71

◆ compute_scalar_stats()

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

Definition at line 2278 of file analyze.c.

References SortSupportData::abbreviate, analyze_mcv_list(), VacAttrStats::anl_context, Assert, VacAttrStats::attr, VacAttrStats::attrcollid, VacAttrStats::attrtype, compare_mcvs(), compare_scalars(), ScalarMCVItem::count, CurrentMemoryContext, datumCopy(), DatumGetCString, DatumGetPointer, generate_unaccent_rules::dest, StdAnalyzeData::eqopr, VacAttrStats::extra_data, 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::stacoll, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, VacAttrStats::stats_valid, VacAttrStats::stavalues, VacAttrStats::stawidth, toast_raw_datum_size(), ScalarItem::tupno, CompareScalarsContext::tupnoLink, vacuum_delay_point(), ScalarItem::value, value, values, VARSIZE_ANY, and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

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

◆ compute_trivial_stats()

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

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

1849 {
1850  int i;
1851  int null_cnt = 0;
1852  int nonnull_cnt = 0;
1853  double total_width = 0;
1854  bool is_varlena = (!stats->attrtype->typbyval &&
1855  stats->attrtype->typlen == -1);
1856  bool is_varwidth = (!stats->attrtype->typbyval &&
1857  stats->attrtype->typlen < 0);
1858 
1859  for (i = 0; i < samplerows; i++)
1860  {
1861  Datum value;
1862  bool isnull;
1863 
1865 
1866  value = fetchfunc(stats, i, &isnull);
1867 
1868  /* Check for null/nonnull */
1869  if (isnull)
1870  {
1871  null_cnt++;
1872  continue;
1873  }
1874  nonnull_cnt++;
1875 
1876  /*
1877  * If it's a variable-width field, add up widths for average width
1878  * calculation. Note that if the value is toasted, we use the toasted
1879  * width. We don't bother with this calculation if it's a fixed-width
1880  * type.
1881  */
1882  if (is_varlena)
1883  {
1884  total_width += VARSIZE_ANY(DatumGetPointer(value));
1885  }
1886  else if (is_varwidth)
1887  {
1888  /* must be cstring */
1889  total_width += strlen(DatumGetCString(value)) + 1;
1890  }
1891  }
1892 
1893  /* We can only compute average width if we found some non-null values. */
1894  if (nonnull_cnt > 0)
1895  {
1896  stats->stats_valid = true;
1897  /* Do the simple null-frac and width stats */
1898  stats->stanullfrac = (double) null_cnt / (double) samplerows;
1899  if (is_varwidth)
1900  stats->stawidth = total_width / (double) nonnull_cnt;
1901  else
1902  stats->stawidth = stats->attrtype->typlen;
1903  stats->stadistinct = 0.0; /* "unknown" */
1904  }
1905  else if (null_cnt > 0)
1906  {
1907  /* We found only nulls; assume the column is entirely null */
1908  stats->stats_valid = true;
1909  stats->stanullfrac = 1.0;
1910  if (is_varwidth)
1911  stats->stawidth = 0; /* "unknown" */
1912  else
1913  stats->stawidth = stats->attrtype->typlen;
1914  stats->stadistinct = 0.0; /* "unknown" */
1915  }
1916 }
static struct @130 value
#define DatumGetCString(X)
Definition: postgres.h:551
int32 stawidth
Definition: vacuum.h:106
float4 stanullfrac
Definition: vacuum.h:105
bool stats_valid
Definition: vacuum.h:104
uintptr_t Datum
Definition: postgres.h:367
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
#define DatumGetPointer(X)
Definition: postgres.h:534
Form_pg_type attrtype
Definition: vacuum.h:88
int i
void vacuum_delay_point(void)
Definition: vacuum.c:1829
float4 stadistinct
Definition: vacuum.h:107

◆ 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 294 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_IndexAttrNumbers, 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, TupleDescData::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, relallvisible, 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().

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

◆ examine_attribute()

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

Definition at line 872 of file analyze.c.

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

Referenced by do_analyze_rel().

873 {
874  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
875  HeapTuple typtuple;
876  VacAttrStats *stats;
877  int i;
878  bool ok;
879 
880  /* Never analyze dropped columns */
881  if (attr->attisdropped)
882  return NULL;
883 
884  /* Don't analyze column if user has specified not to */
885  if (attr->attstattarget == 0)
886  return NULL;
887 
888  /*
889  * Create the VacAttrStats struct. Note that we only have a copy of the
890  * fixed fields of the pg_attribute tuple.
891  */
892  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
894  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
895 
896  /*
897  * When analyzing an expression index, believe the expression tree's type
898  * not the column datatype --- the latter might be the opckeytype storage
899  * type of the opclass, which is not interesting for our purposes. (Note:
900  * if we did anything with non-expression index columns, we'd need to
901  * figure out where to get the correct type info from, but for now that's
902  * not a problem.) It's not clear whether anyone will care about the
903  * typmod, but we store that too just in case.
904  */
905  if (index_expr)
906  {
907  stats->attrtypid = exprType(index_expr);
908  stats->attrtypmod = exprTypmod(index_expr);
909 
910  /*
911  * If a collation has been specified for the index column, use that in
912  * preference to anything else; but if not, fall back to whatever we
913  * can get from the expression.
914  */
915  if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
916  stats->attrcollid = onerel->rd_indcollation[attnum - 1];
917  else
918  stats->attrcollid = exprCollation(index_expr);
919  }
920  else
921  {
922  stats->attrtypid = attr->atttypid;
923  stats->attrtypmod = attr->atttypmod;
924  stats->attrcollid = attr->attcollation;
925  }
926 
927  typtuple = SearchSysCacheCopy1(TYPEOID,
928  ObjectIdGetDatum(stats->attrtypid));
929  if (!HeapTupleIsValid(typtuple))
930  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
931  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
932  stats->anl_context = anl_context;
933  stats->tupattnum = attnum;
934 
935  /*
936  * The fields describing the stats->stavalues[n] element types default to
937  * the type of the data being analyzed, but the type-specific typanalyze
938  * function can change them if it wants to store something else.
939  */
940  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
941  {
942  stats->statypid[i] = stats->attrtypid;
943  stats->statyplen[i] = stats->attrtype->typlen;
944  stats->statypbyval[i] = stats->attrtype->typbyval;
945  stats->statypalign[i] = stats->attrtype->typalign;
946  }
947 
948  /*
949  * Call the type-specific typanalyze function. If none is specified, use
950  * std_typanalyze().
951  */
952  if (OidIsValid(stats->attrtype->typanalyze))
953  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
954  PointerGetDatum(stats)));
955  else
956  ok = std_typanalyze(stats);
957 
958  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
959  {
960  heap_freetuple(typtuple);
961  pfree(stats->attr);
962  pfree(stats);
963  return NULL;
964  }
965 
966  return stats;
967 }
int minrows
Definition: vacuum.h:97
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
#define PointerGetDatum(X)
Definition: postgres.h:541
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:91
int tupattnum
Definition: vacuum.h:131
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1765
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:124
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1340
int32 attrtypmod
Definition: vacuum.h:87
#define OidIsValid(objectId)
Definition: c.h:638
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:125
Form_pg_attribute attr
Definition: vacuum.h:85
void pfree(void *pointer)
Definition: mcxt.c:1031
Oid attrtypid
Definition: vacuum.h:86
Oid * rd_indcollation
Definition: rel.h:162
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:628
static MemoryContext anl_context
Definition: analyze.c:82
#define DatumGetBool(X)
Definition: postgres.h:378
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:189
void * palloc0(Size size)
Definition: mcxt.c:955
TupleDesc rd_att
Definition: rel.h:85
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:122
int16 attnum
Definition: pg_attribute.h:79
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:126
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
FormData_pg_type * Form_pg_type
Definition: pg_type.h:251
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
Oid attrcollid
Definition: vacuum.h:89
MemoryContext anl_context
Definition: vacuum.h:90
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
Form_pg_type attrtype
Definition: vacuum.h:88
void * palloc(Size size)
Definition: mcxt.c:924
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:123
#define elog(elevel,...)
Definition: elog.h:226
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:96

◆ ind_fetch_func()

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

Definition at line 1688 of file analyze.c.

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

Referenced by compute_index_stats().

1689 {
1690  int i;
1691 
1692  /* exprvals and exprnulls are already offset for proper column */
1693  i = rownum * stats->rowstride;
1694  *isNull = stats->exprnulls[i];
1695  return stats->exprvals[i];
1696 }
int rowstride
Definition: vacuum.h:136
bool * exprnulls
Definition: vacuum.h:135
Datum * exprvals
Definition: vacuum.h:134
int i

◆ std_fetch_func()

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

Definition at line 1672 of file analyze.c.

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

Referenced by do_analyze_rel().

1673 {
1674  int attnum = stats->tupattnum;
1675  HeapTuple tuple = stats->rows[rownum];
1676  TupleDesc tupDesc = stats->tupDesc;
1677 
1678  return heap_getattr(tuple, attnum, tupDesc, isNull);
1679 }
HeapTuple * rows
Definition: vacuum.h:132
int tupattnum
Definition: vacuum.h:131
TupleDesc tupDesc
Definition: vacuum.h:133
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
int16 attnum
Definition: pg_attribute.h:79

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

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

1766 {
1767  Form_pg_attribute attr = stats->attr;
1768  Oid ltopr;
1769  Oid eqopr;
1770  StdAnalyzeData *mystats;
1771 
1772  /* If the attstattarget column is negative, use the default value */
1773  /* NB: it is okay to scribble on stats->attr since it's a copy */
1774  if (attr->attstattarget < 0)
1775  attr->attstattarget = default_statistics_target;
1776 
1777  /* Look for default "<" and "=" operators for column's type */
1779  false, false, false,
1780  &ltopr, &eqopr, NULL,
1781  NULL);
1782 
1783  /* Save the operator info for compute_stats routines */
1784  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1785  mystats->eqopr = eqopr;
1786  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1787  mystats->ltopr = ltopr;
1788  stats->extra_data = mystats;
1789 
1790  /*
1791  * Determine which standard statistics algorithm to use
1792  */
1793  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1794  {
1795  /* Seems to be a scalar datatype */
1797  /*--------------------
1798  * The following choice of minrows is based on the paper
1799  * "Random sampling for histogram construction: how much is enough?"
1800  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1801  * Proceedings of ACM SIGMOD International Conference on Management
1802  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1803  * says that for table size n, histogram size k, maximum relative
1804  * error in bin size f, and error probability gamma, the minimum
1805  * random sample size is
1806  * r = 4 * k * ln(2*n/gamma) / f^2
1807  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1808  * r = 305.82 * k
1809  * Note that because of the log function, the dependence on n is
1810  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1811  * bin size error with probability 0.99. So there's no real need to
1812  * scale for n, which is a good thing because we don't necessarily
1813  * know it at this point.
1814  *--------------------
1815  */
1816  stats->minrows = 300 * attr->attstattarget;
1817  }
1818  else if (OidIsValid(eqopr))
1819  {
1820  /* We can still recognize distinct values */
1822  /* Might as well use the same minrows as above */
1823  stats->minrows = 300 * attr->attstattarget;
1824  }
1825  else
1826  {
1827  /* Can't do much but the trivial stuff */
1829  /* Might as well use the same minrows as above */
1830  stats->minrows = 300 * attr->attstattarget;
1831  }
1832 
1833  return true;
1834 }
int minrows
Definition: vacuum.h:97
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2278
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
Form_pg_attribute attr
Definition: vacuum.h:85
Oid attrtypid
Definition: vacuum.h:86
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1935
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1046
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:1845
void * palloc(Size size)
Definition: mcxt.c:924
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:96
void * extra_data
Definition: vacuum.h:98
int default_statistics_target
Definition: analyze.c:79

◆ update_attstats()

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

Definition at line 1533 of file analyze.c.

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

Referenced by do_analyze_rel().

1534 {
1535  Relation sd;
1536  int attno;
1537 
1538  if (natts <= 0)
1539  return; /* nothing to do */
1540 
1541  sd = heap_open(StatisticRelationId, RowExclusiveLock);
1542 
1543  for (attno = 0; attno < natts; attno++)
1544  {
1545  VacAttrStats *stats = vacattrstats[attno];
1546  HeapTuple stup,
1547  oldtup;
1548  int i,
1549  k,
1550  n;
1551  Datum values[Natts_pg_statistic];
1552  bool nulls[Natts_pg_statistic];
1553  bool replaces[Natts_pg_statistic];
1554 
1555  /* Ignore attr if we weren't able to collect stats */
1556  if (!stats->stats_valid)
1557  continue;
1558 
1559  /*
1560  * Construct a new pg_statistic tuple
1561  */
1562  for (i = 0; i < Natts_pg_statistic; ++i)
1563  {
1564  nulls[i] = false;
1565  replaces[i] = true;
1566  }
1567 
1568  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1569  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1570  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1571  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1572  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1573  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1574  i = Anum_pg_statistic_stakind1 - 1;
1575  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1576  {
1577  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1578  }
1579  i = Anum_pg_statistic_staop1 - 1;
1580  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1581  {
1582  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1583  }
1584  i = Anum_pg_statistic_stacoll1 - 1;
1585  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1586  {
1587  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1588  }
1589  i = Anum_pg_statistic_stanumbers1 - 1;
1590  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1591  {
1592  int nnum = stats->numnumbers[k];
1593 
1594  if (nnum > 0)
1595  {
1596  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1597  ArrayType *arry;
1598 
1599  for (n = 0; n < nnum; n++)
1600  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1601  /* XXX knows more than it should about type float4: */
1602  arry = construct_array(numdatums, nnum,
1603  FLOAT4OID,
1604  sizeof(float4), FLOAT4PASSBYVAL, 'i');
1605  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1606  }
1607  else
1608  {
1609  nulls[i] = true;
1610  values[i++] = (Datum) 0;
1611  }
1612  }
1613  i = Anum_pg_statistic_stavalues1 - 1;
1614  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1615  {
1616  if (stats->numvalues[k] > 0)
1617  {
1618  ArrayType *arry;
1619 
1620  arry = construct_array(stats->stavalues[k],
1621  stats->numvalues[k],
1622  stats->statypid[k],
1623  stats->statyplen[k],
1624  stats->statypbyval[k],
1625  stats->statypalign[k]);
1626  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1627  }
1628  else
1629  {
1630  nulls[i] = true;
1631  values[i++] = (Datum) 0;
1632  }
1633  }
1634 
1635  /* Is there already a pg_statistic tuple for this attribute? */
1636  oldtup = SearchSysCache3(STATRELATTINH,
1637  ObjectIdGetDatum(relid),
1638  Int16GetDatum(stats->attr->attnum),
1639  BoolGetDatum(inh));
1640 
1641  if (HeapTupleIsValid(oldtup))
1642  {
1643  /* Yes, replace it */
1644  stup = heap_modify_tuple(oldtup,
1645  RelationGetDescr(sd),
1646  values,
1647  nulls,
1648  replaces);
1649  ReleaseSysCache(oldtup);
1650  CatalogTupleUpdate(sd, &stup->t_self, stup);
1651  }
1652  else
1653  {
1654  /* No, insert new tuple */
1655  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1656  CatalogTupleInsert(sd, stup);
1657  }
1658 
1659  heap_freetuple(stup);
1660  }
1661 
1663 }
#define RelationGetDescr(relation)
Definition: rel.h:423
#define PointerGetDatum(X)
Definition: postgres.h:541
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:114
#define Int16GetDatum(X)
Definition: postgres.h:436
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3288
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:124
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1022
#define heap_close(r, l)
Definition: heapam.h:83
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1340
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:125
Form_pg_attribute attr
Definition: vacuum.h:85
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
int32 stawidth
Definition: vacuum.h:106
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:110
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
Datum Float4GetDatum(float4 X)
Definition: fmgr.c:1889
ItemPointerData t_self
Definition: htup.h:65
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:111
#define RowExclusiveLock
Definition: lockdefs.h:38
float4 stanullfrac
Definition: vacuum.h:105
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
bool stats_valid
Definition: vacuum.h:104
float float4
Definition: c.h:490
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1303
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:122
#define BoolGetDatum(X)
Definition: postgres.h:387
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:126
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:112
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:207
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define Int32GetDatum(X)
Definition: postgres.h:464
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:113
void * palloc(Size size)
Definition: mcxt.c:924
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:123
int i
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1115
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:166
float4 stadistinct
Definition: vacuum.h:107

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 82 of file analyze.c.

Referenced by examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

Definition at line 79 of file analyze.c.

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

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 83 of file analyze.c.

Referenced by do_analyze_rel().