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

Go to the source code of this file.

Data Structures

struct  AnlIndexData
 
struct  ScalarMCVItem
 
struct  CompareScalarsContext
 

Macros

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

Typedefs

typedef struct AnlIndexData AnlIndexData
 

Functions

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

Variables

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

Macro Definition Documentation

◆ swapDatum

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

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

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

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

Referenced by do_analyze_rel().

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

◆ acquire_sample_rows()

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

Definition at line 1042 of file analyze.c.

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

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

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

◆ analyze_rel()

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

Definition at line 115 of file analyze.c.

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

Referenced by vacuum().

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

◆ compare_mcvs()

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

Definition at line 2874 of file analyze.c.

Referenced by compute_scalar_stats().

2875 {
2876  int da = ((const ScalarMCVItem *) a)->first;
2877  int db = ((const ScalarMCVItem *) b)->first;
2878 
2879  return da - db;
2880 }

◆ compare_rows()

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

Definition at line 1285 of file analyze.c.

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1286 {
1287  HeapTuple ha = *(const HeapTuple *) a;
1288  HeapTuple hb = *(const HeapTuple *) b;
1293 
1294  if (ba < bb)
1295  return -1;
1296  if (ba > bb)
1297  return 1;
1298  if (oa < ob)
1299  return -1;
1300  if (oa > ob)
1301  return 1;
1302  return 0;
1303 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:95
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:76

◆ compare_scalars()

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

Definition at line 2843 of file analyze.c.

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

Referenced by compute_scalar_stats().

2844 {
2845  Datum da = ((const ScalarItem *) a)->value;
2846  int ta = ((const ScalarItem *) a)->tupno;
2847  Datum db = ((const ScalarItem *) b)->value;
2848  int tb = ((const ScalarItem *) b)->tupno;
2850  int compare;
2851 
2852  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2853  if (compare != 0)
2854  return compare;
2855 
2856  /*
2857  * The two datums are equal, so update cxt->tupnoLink[].
2858  */
2859  if (cxt->tupnoLink[ta] < tb)
2860  cxt->tupnoLink[ta] = tb;
2861  if (cxt->tupnoLink[tb] < ta)
2862  cxt->tupnoLink[tb] = ta;
2863 
2864  /*
2865  * For equal datums, sort by tupno
2866  */
2867  return ta - tb;
2868 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
SortSupport ssup
Definition: analyze.c:1750
uintptr_t Datum
Definition: postgres.h:365
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:201

◆ compute_distinct_stats()

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

Definition at line 1945 of file analyze.c.

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

Referenced by std_typanalyze().

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

◆ compute_index_stats()

static void compute_index_stats ( Relation  onerel,
double  totalrows,
AnlIndexData indexdata,
int  nindexes,
HeapTuple rows,
int  numrows,
MemoryContext  col_context 
)
static

Definition at line 741 of file analyze.c.

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

Referenced by do_analyze_rel().

745 {
746  MemoryContext ind_context,
747  old_context;
749  bool isnull[INDEX_MAX_KEYS];
750  int ind,
751  i;
752 
753  ind_context = AllocSetContextCreate(anl_context,
754  "Analyze Index",
756  old_context = MemoryContextSwitchTo(ind_context);
757 
758  for (ind = 0; ind < nindexes; ind++)
759  {
760  AnlIndexData *thisdata = &indexdata[ind];
761  IndexInfo *indexInfo = thisdata->indexInfo;
762  int attr_cnt = thisdata->attr_cnt;
763  TupleTableSlot *slot;
764  EState *estate;
765  ExprContext *econtext;
766  ExprState *predicate;
767  Datum *exprvals;
768  bool *exprnulls;
769  int numindexrows,
770  tcnt,
771  rowno;
772  double totalindexrows;
773 
774  /* Ignore index if no columns to analyze and not partial */
775  if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
776  continue;
777 
778  /*
779  * Need an EState for evaluation of index expressions and
780  * partial-index predicates. Create it in the per-index context to be
781  * sure it gets cleaned up at the bottom of the loop.
782  */
783  estate = CreateExecutorState();
784  econtext = GetPerTupleExprContext(estate);
785  /* Need a slot to hold the current heap tuple, too */
787 
788  /* Arrange for econtext's scan tuple to be the tuple under test */
789  econtext->ecxt_scantuple = slot;
790 
791  /* Set up execution state for predicate. */
792  predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
793 
794  /* Compute and save index expression values */
795  exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
796  exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
797  numindexrows = 0;
798  tcnt = 0;
799  for (rowno = 0; rowno < numrows; rowno++)
800  {
801  HeapTuple heapTuple = rows[rowno];
802 
804 
805  /*
806  * Reset the per-tuple context each time, to reclaim any cruft
807  * left behind by evaluating the predicate or index expressions.
808  */
809  ResetExprContext(econtext);
810 
811  /* Set up for predicate or expression evaluation */
812  ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
813 
814  /* If index is partial, check predicate */
815  if (predicate != NULL)
816  {
817  if (!ExecQual(predicate, econtext))
818  continue;
819  }
820  numindexrows++;
821 
822  if (attr_cnt > 0)
823  {
824  /*
825  * Evaluate the index row to compute expression values. We
826  * could do this by hand, but FormIndexDatum is convenient.
827  */
828  FormIndexDatum(indexInfo,
829  slot,
830  estate,
831  values,
832  isnull);
833 
834  /*
835  * Save just the columns we care about. We copy the values
836  * into ind_context from the estate's per-tuple context.
837  */
838  for (i = 0; i < attr_cnt; i++)
839  {
840  VacAttrStats *stats = thisdata->vacattrstats[i];
841  int attnum = stats->attr->attnum;
842 
843  if (isnull[attnum - 1])
844  {
845  exprvals[tcnt] = (Datum) 0;
846  exprnulls[tcnt] = true;
847  }
848  else
849  {
850  exprvals[tcnt] = datumCopy(values[attnum - 1],
851  stats->attrtype->typbyval,
852  stats->attrtype->typlen);
853  exprnulls[tcnt] = false;
854  }
855  tcnt++;
856  }
857  }
858  }
859 
860  /*
861  * Having counted the number of rows that pass the predicate in the
862  * sample, we can estimate the total number of rows in the index.
863  */
864  thisdata->tupleFract = (double) numindexrows / (double) numrows;
865  totalindexrows = ceil(thisdata->tupleFract * totalrows);
866 
867  /*
868  * Now we can compute the statistics for the expression columns.
869  */
870  if (numindexrows > 0)
871  {
872  MemoryContextSwitchTo(col_context);
873  for (i = 0; i < attr_cnt; i++)
874  {
875  VacAttrStats *stats = thisdata->vacattrstats[i];
876  AttributeOpts *aopt =
877  get_attribute_options(stats->attr->attrelid,
878  stats->attr->attnum);
879 
880  stats->exprvals = exprvals + i;
881  stats->exprnulls = exprnulls + i;
882  stats->rowstride = attr_cnt;
883  stats->compute_stats(stats,
885  numindexrows,
886  totalindexrows);
887 
888  /*
889  * If the n_distinct option is specified, it overrides the
890  * above computation. For indices, we always use just
891  * n_distinct, not n_distinct_inherited.
892  */
893  if (aopt != NULL && aopt->n_distinct != 0.0)
894  stats->stadistinct = aopt->n_distinct;
895 
897  }
898  }
899 
900  /* And clean up */
901  MemoryContextSwitchTo(ind_context);
902 
904  FreeExecutorState(estate);
906  }
907 
908  MemoryContextSwitchTo(old_context);
909  MemoryContextDelete(ind_context);
910 }
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:104
int rowstride
Definition: vacuum.h:130
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:1981
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:356
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
List * ii_Predicate
Definition: execnodes.h:150
#define RelationGetDescr(relation)
Definition: rel.h:437
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:362
float8 n_distinct
Definition: attoptcache.h:22
Form_pg_attribute attr
Definition: vacuum.h:81
int attr_cnt
Definition: analyze.c:72
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:490
bool * exprnulls
Definition: vacuum.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
static MemoryContext anl_context
Definition: analyze.c:80
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:247
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:515
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc)
Definition: execTuples.c:232
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
EState * CreateExecutorState(void)
Definition: execUtils.c:80
Datum * exprvals
Definition: vacuum.h:128
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
uintptr_t Datum
Definition: postgres.h:365
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1704
#define INDEX_MAX_KEYS
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:211
double tupleFract
Definition: analyze.c:70
static Datum values[MAXATTR]
Definition: bootstrap.c:164
Form_pg_type attrtype
Definition: vacuum.h:84
void * palloc(Size size)
Definition: mcxt.c:835
VacAttrStats ** vacattrstats
Definition: analyze.c:71
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
void vacuum_delay_point(void)
Definition: vacuum.c:1696
#define ResetExprContext(econtext)
Definition: executor.h:484
float4 stadistinct
Definition: vacuum.h:102
IndexInfo * indexInfo
Definition: analyze.c:69

◆ compute_scalar_stats()

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

Definition at line 2297 of file analyze.c.

References SortSupportData::abbreviate, VacAttrStats::anl_context, Assert, VacAttrStats::attr, VacAttrStats::attrtype, compare_mcvs(), compare_scalars(), ScalarMCVItem::count, CurrentMemoryContext, datumCopy(), DatumGetCString, DatumGetPointer, DEFAULT_COLLATION_OID, generate_unaccent_rules::dest, StdAnalyzeData::eqopr, VacAttrStats::extra_data, ScalarMCVItem::first, i, StdAnalyzeData::ltopr, memmove, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), PG_DETOAST_DATUM, PointerGetDatum, PrepareSortSupportFromOrderingOp(), qsort, qsort_arg(), CompareScalarsContext::ssup, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, VacAttrStats::stadistinct, VacAttrStats::stakind, VacAttrStats::stanullfrac, VacAttrStats::stanumbers, VacAttrStats::staop, STATISTIC_KIND_CORRELATION, STATISTIC_KIND_HISTOGRAM, STATISTIC_KIND_MCV, VacAttrStats::stats_valid, VacAttrStats::stavalues, VacAttrStats::stawidth, toast_raw_datum_size(), ScalarItem::tupno, CompareScalarsContext::tupnoLink, vacuum_delay_point(), ScalarItem::value, value, values, VARSIZE_ANY, and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

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

◆ compute_trivial_stats()

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

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

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

◆ do_analyze_rel()

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

Definition at line 345 of file analyze.c.

References AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, IndexVacuumInfo::analyze_only, AtEOXact_GUC(), attnameAttNum(), VacAttrStats::attr, AnlIndexData::attr_cnt, bms_add_member(), bms_is_member(), BuildIndexInfo(), BuildRelationExtStatistics(), compute_index_stats(), VacAttrStats::compute_stats, CurrentMemoryContext, elevel, elog, ereport, errcode(), errmsg(), ERROR, IndexVacuumInfo::estimated_count, examine_attribute(), get_attribute_options(), get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GetUserIdAndSecContext(), i, IndexInfo::ii_Expressions, IndexInfo::ii_KeyAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexVacuumInfo::index, index_vacuum_cleanup(), AnlIndexData::indexInfo, InvalidAttrNumber, InvalidMultiXactId, InvalidTransactionId, IsAutoVacuumWorkerProcess(), lfirst, list_head(), list_length(), lnext, LOG, VacuumParams::log_min_duration, MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), IndexVacuumInfo::message_level, VacAttrStats::minrows, MyDatabaseId, AttributeOpts::n_distinct, AttributeOpts::n_distinct_inherited, tupleDesc::natts, NewGUCNestLevel(), NIL, NoLock, IndexVacuumInfo::num_heap_tuples, palloc(), palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_report_analyze(), RelationData::rd_att, RelationData::rd_rel, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, VacAttrStats::rows, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), VacAttrStats::stadistinct, std_fetch_func(), IndexVacuumInfo::strategy, strVal, TimestampDifferenceExceeds(), VacAttrStats::tupDesc, AnlIndexData::tupleFract, update_attstats(), vac_close_indexes(), vac_open_indexes(), vac_strategy, vac_update_relstats(), AnlIndexData::vacattrstats, VACOPT_VACUUM, and visibilitymap_count().

Referenced by analyze_rel().

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

◆ examine_attribute()

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

Definition at line 922 of file analyze.c.

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

Referenced by do_analyze_rel().

923 {
924  Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
925  HeapTuple typtuple;
926  VacAttrStats *stats;
927  int i;
928  bool ok;
929 
930  /* Never analyze dropped columns */
931  if (attr->attisdropped)
932  return NULL;
933 
934  /* Don't analyze column if user has specified not to */
935  if (attr->attstattarget == 0)
936  return NULL;
937 
938  /*
939  * Create the VacAttrStats struct. Note that we only have a copy of the
940  * fixed fields of the pg_attribute tuple.
941  */
942  stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
944  memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
945 
946  /*
947  * When analyzing an expression index, believe the expression tree's type
948  * not the column datatype --- the latter might be the opckeytype storage
949  * type of the opclass, which is not interesting for our purposes. (Note:
950  * if we did anything with non-expression index columns, we'd need to
951  * figure out where to get the correct type info from, but for now that's
952  * not a problem.) It's not clear whether anyone will care about the
953  * typmod, but we store that too just in case.
954  */
955  if (index_expr)
956  {
957  stats->attrtypid = exprType(index_expr);
958  stats->attrtypmod = exprTypmod(index_expr);
959  }
960  else
961  {
962  stats->attrtypid = attr->atttypid;
963  stats->attrtypmod = attr->atttypmod;
964  }
965 
966  typtuple = SearchSysCacheCopy1(TYPEOID,
967  ObjectIdGetDatum(stats->attrtypid));
968  if (!HeapTupleIsValid(typtuple))
969  elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
970  stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
971  stats->anl_context = anl_context;
972  stats->tupattnum = attnum;
973 
974  /*
975  * The fields describing the stats->stavalues[n] element types default to
976  * the type of the data being analyzed, but the type-specific typanalyze
977  * function can change them if it wants to store something else.
978  */
979  for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
980  {
981  stats->statypid[i] = stats->attrtypid;
982  stats->statyplen[i] = stats->attrtype->typlen;
983  stats->statypbyval[i] = stats->attrtype->typbyval;
984  stats->statypalign[i] = stats->attrtype->typalign;
985  }
986 
987  /*
988  * Call the type-specific typanalyze function. If none is specified, use
989  * std_typanalyze().
990  */
991  if (OidIsValid(stats->attrtype->typanalyze))
992  ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
993  PointerGetDatum(stats)));
994  else
995  ok = std_typanalyze(stats);
996 
997  if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
998  {
999  heap_freetuple(typtuple);
1000  pfree(stats->attr);
1001  pfree(stats);
1002  return NULL;
1003  }
1004 
1005  return stats;
1006 }
int minrows
Definition: vacuum.h:92
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
#define PointerGetDatum(X)
Definition: postgres.h:539
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:90
int tupattnum
Definition: vacuum.h:125
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1775
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
int32 attrtypmod
Definition: vacuum.h:83
#define OidIsValid(objectId)
Definition: c.h:594
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
Form_pg_attribute attr
Definition: vacuum.h:81
void pfree(void *pointer)
Definition: mcxt.c:936
Oid attrtypid
Definition: vacuum.h:82
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
#define ERROR
Definition: elog.h:43
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
static MemoryContext anl_context
Definition: analyze.c:80
#define DatumGetBool(X)
Definition: postgres.h:376
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ATTRIBUTE_FIXED_PART_SIZE
Definition: pg_attribute.h:179
void * palloc0(Size size)
Definition: mcxt.c:864
TupleDesc rd_att
Definition: rel.h:115
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:116
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:121
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
MemoryContext anl_context
Definition: vacuum.h:85
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:173
Form_pg_type attrtype
Definition: vacuum.h:84
void * palloc(Size size)
Definition: mcxt.c:835
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
int i
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
#define elog
Definition: elog.h:219

◆ ind_fetch_func()

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

Definition at line 1704 of file analyze.c.

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

Referenced by compute_index_stats().

1705 {
1706  int i;
1707 
1708  /* exprvals and exprnulls are already offset for proper column */
1709  i = rownum * stats->rowstride;
1710  *isNull = stats->exprnulls[i];
1711  return stats->exprvals[i];
1712 }
int rowstride
Definition: vacuum.h:130
bool * exprnulls
Definition: vacuum.h:129
Datum * exprvals
Definition: vacuum.h:128
int i

◆ std_fetch_func()

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

Definition at line 1688 of file analyze.c.

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

Referenced by do_analyze_rel().

1689 {
1690  int attnum = stats->tupattnum;
1691  HeapTuple tuple = stats->rows[rownum];
1692  TupleDesc tupDesc = stats->tupDesc;
1693 
1694  return heap_getattr(tuple, attnum, tupDesc, isNull);
1695 }
HeapTuple * rows
Definition: vacuum.h:126
int tupattnum
Definition: vacuum.h:125
TupleDesc tupDesc
Definition: vacuum.h:127
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:774

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

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

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

◆ update_attstats()

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

Definition at line 1554 of file analyze.c.

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

Referenced by do_analyze_rel().

1555 {
1556  Relation sd;
1557  int attno;
1558 
1559  if (natts <= 0)
1560  return; /* nothing to do */
1561 
1563 
1564  for (attno = 0; attno < natts; attno++)
1565  {
1566  VacAttrStats *stats = vacattrstats[attno];
1567  HeapTuple stup,
1568  oldtup;
1569  int i,
1570  k,
1571  n;
1573  bool nulls[Natts_pg_statistic];
1574  bool replaces[Natts_pg_statistic];
1575 
1576  /* Ignore attr if we weren't able to collect stats */
1577  if (!stats->stats_valid)
1578  continue;
1579 
1580  /*
1581  * Construct a new pg_statistic tuple
1582  */
1583  for (i = 0; i < Natts_pg_statistic; ++i)
1584  {
1585  nulls[i] = false;
1586  replaces[i] = true;
1587  }
1588 
1589  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1590  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1591  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1593  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1596  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1597  {
1598  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1599  }
1600  i = Anum_pg_statistic_staop1 - 1;
1601  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1602  {
1603  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1604  }
1606  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1607  {
1608  int nnum = stats->numnumbers[k];
1609 
1610  if (nnum > 0)
1611  {
1612  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1613  ArrayType *arry;
1614 
1615  for (n = 0; n < nnum; n++)
1616  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1617  /* XXX knows more than it should about type float4: */
1618  arry = construct_array(numdatums, nnum,
1619  FLOAT4OID,
1620  sizeof(float4), FLOAT4PASSBYVAL, 'i');
1621  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1622  }
1623  else
1624  {
1625  nulls[i] = true;
1626  values[i++] = (Datum) 0;
1627  }
1628  }
1630  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1631  {
1632  if (stats->numvalues[k] > 0)
1633  {
1634  ArrayType *arry;
1635 
1636  arry = construct_array(stats->stavalues[k],
1637  stats->numvalues[k],
1638  stats->statypid[k],
1639  stats->statyplen[k],
1640  stats->statypbyval[k],
1641  stats->statypalign[k]);
1642  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1643  }
1644  else
1645  {
1646  nulls[i] = true;
1647  values[i++] = (Datum) 0;
1648  }
1649  }
1650 
1651  /* Is there already a pg_statistic tuple for this attribute? */
1652  oldtup = SearchSysCache3(STATRELATTINH,
1653  ObjectIdGetDatum(relid),
1654  Int16GetDatum(stats->attr->attnum),
1655  BoolGetDatum(inh));
1656 
1657  if (HeapTupleIsValid(oldtup))
1658  {
1659  /* Yes, replace it */
1660  stup = heap_modify_tuple(oldtup,
1661  RelationGetDescr(sd),
1662  values,
1663  nulls,
1664  replaces);
1665  ReleaseSysCache(oldtup);
1666  CatalogTupleUpdate(sd, &stup->t_self, stup);
1667  }
1668  else
1669  {
1670  /* No, insert new tuple */
1671  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1672  CatalogTupleInsert(sd, stup);
1673  }
1674 
1675  heap_freetuple(stup);
1676  }
1677 
1679 }
#define Anum_pg_statistic_staop1
Definition: pg_statistic.h:147
#define Anum_pg_statistic_stavalues1
Definition: pg_statistic.h:157
#define RelationGetDescr(relation)
Definition: rel.h:437
#define Anum_pg_statistic_stainherit
Definition: pg_statistic.h:138
#define Anum_pg_statistic_stadistinct
Definition: pg_statistic.h:141
#define Anum_pg_statistic_stanullfrac
Definition: pg_statistic.h:139
#define PointerGetDatum(X)
Definition: postgres.h:539
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
#define Int16GetDatum(X)
Definition: postgres.h:434
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3279
#define Anum_pg_statistic_staattnum
Definition: pg_statistic.h:137
#define Anum_pg_statistic_stawidth
Definition: pg_statistic.h:140
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:118
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:695
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
#define Anum_pg_statistic_stakind1
Definition: pg_statistic.h:142
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:119
Form_pg_attribute attr
Definition: vacuum.h:81
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
int32 stawidth
Definition: vacuum.h:101
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
Datum Float4GetDatum(float4 X)
Definition: fmgr.c:1798
ItemPointerData t_self
Definition: htup.h:65
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:105
#define Natts_pg_statistic
Definition: pg_statistic.h:135
#define RowExclusiveLock
Definition: lockdefs.h:38
#define Anum_pg_statistic_starelid
Definition: pg_statistic.h:136
float4 stanullfrac
Definition: vacuum.h:100
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:104
bool stats_valid
Definition: vacuum.h:99
float float4
Definition: c.h:446
#define FLOAT4OID
Definition: pg_type.h:416
uintptr_t Datum
Definition: postgres.h:365
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define StatisticRelationId
Definition: pg_statistic.h:29
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:103
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:116
#define BoolGetDatum(X)
Definition: postgres.h:385
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:121
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:106
#define Anum_pg_statistic_stanumbers1
Definition: pg_statistic.h:152
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define Int32GetDatum(X)
Definition: postgres.h:462
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:107
void * palloc(Size size)
Definition: mcxt.c:835
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:117
int i
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
float4 stadistinct
Definition: vacuum.h:102

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 80 of file analyze.c.

Referenced by examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

Definition at line 77 of file analyze.c.

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

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 81 of file analyze.c.

Referenced by do_analyze_rel().