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

Go to the source code of this file.

Data Structures

struct  AnlIndexData
 
struct  ScalarMCVItem
 
struct  CompareScalarsContext
 

Macros

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

Typedefs

typedef struct AnlIndexData AnlIndexData
 

Functions

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

Variables

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

Macro Definition Documentation

◆ swapDatum

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

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

Referenced by compute_distinct_stats().

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert, CommandCounterIncrement(), convert_tuples_by_name(), elevel, equalTupleDescs(), ereport, errmsg(), execute_attr_map_tuple(), find_all_inheritors(), free_conversion_map(), get_namespace_name(), GetFdwRoutineForRelation(), gettext_noop, heap_freetuple(), i, lfirst_oid, list_length(), Min, NoLock, palloc(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, relpages, rint(), SetRelationHasSubclass(), table_close(), and table_open().

Referenced by do_analyze_rel().

1175 {
1176  List *tableOIDs;
1177  Relation *rels;
1178  AcquireSampleRowsFunc *acquirefuncs;
1179  double *relblocks;
1180  double totalblocks;
1181  int numrows,
1182  nrels,
1183  i;
1184  ListCell *lc;
1185  bool has_child;
1186 
1187  /*
1188  * Find all members of inheritance set. We only need AccessShareLock on
1189  * the children.
1190  */
1191  tableOIDs =
1193 
1194  /*
1195  * Check that there's at least one descendant, else fail. This could
1196  * happen despite analyze_rel's relhassubclass check, if table once had a
1197  * child but no longer does. In that case, we can clear the
1198  * relhassubclass field so as not to make the same mistake again later.
1199  * (This is safe because we hold ShareUpdateExclusiveLock.)
1200  */
1201  if (list_length(tableOIDs) < 2)
1202  {
1203  /* CCI because we already updated the pg_class row in this command */
1205  SetRelationHasSubclass(RelationGetRelid(onerel), false);
1206  ereport(elevel,
1207  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1209  RelationGetRelationName(onerel))));
1210  return 0;
1211  }
1212 
1213  /*
1214  * Identify acquirefuncs to use, and count blocks in all the relations.
1215  * The result could overflow BlockNumber, so we use double arithmetic.
1216  */
1217  rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1218  acquirefuncs = (AcquireSampleRowsFunc *)
1219  palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1220  relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1221  totalblocks = 0;
1222  nrels = 0;
1223  has_child = false;
1224  foreach(lc, tableOIDs)
1225  {
1226  Oid childOID = lfirst_oid(lc);
1227  Relation childrel;
1228  AcquireSampleRowsFunc acquirefunc = NULL;
1229  BlockNumber relpages = 0;
1230 
1231  /* We already got the needed lock */
1232  childrel = table_open(childOID, NoLock);
1233 
1234  /* Ignore if temp table of another backend */
1235  if (RELATION_IS_OTHER_TEMP(childrel))
1236  {
1237  /* ... but release the lock on it */
1238  Assert(childrel != onerel);
1239  table_close(childrel, AccessShareLock);
1240  continue;
1241  }
1242 
1243  /* Check table type (MATVIEW can't happen, but might as well allow) */
1244  if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1245  childrel->rd_rel->relkind == RELKIND_MATVIEW)
1246  {
1247  /* Regular table, so use the regular row acquisition function */
1248  acquirefunc = acquire_sample_rows;
1249  relpages = RelationGetNumberOfBlocks(childrel);
1250  }
1251  else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1252  {
1253  /*
1254  * For a foreign table, call the FDW's hook function to see
1255  * whether it supports analysis.
1256  */
1257  FdwRoutine *fdwroutine;
1258  bool ok = false;
1259 
1260  fdwroutine = GetFdwRoutineForRelation(childrel, false);
1261 
1262  if (fdwroutine->AnalyzeForeignTable != NULL)
1263  ok = fdwroutine->AnalyzeForeignTable(childrel,
1264  &acquirefunc,
1265  &relpages);
1266 
1267  if (!ok)
1268  {
1269  /* ignore, but release the lock on it */
1270  Assert(childrel != onerel);
1271  table_close(childrel, AccessShareLock);
1272  continue;
1273  }
1274  }
1275  else
1276  {
1277  /*
1278  * ignore, but release the lock on it. don't try to unlock the
1279  * passed-in relation
1280  */
1281  Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1282  if (childrel != onerel)
1283  table_close(childrel, AccessShareLock);
1284  else
1285  table_close(childrel, NoLock);
1286  continue;
1287  }
1288 
1289  /* OK, we'll process this child */
1290  has_child = true;
1291  rels[nrels] = childrel;
1292  acquirefuncs[nrels] = acquirefunc;
1293  relblocks[nrels] = (double) relpages;
1294  totalblocks += (double) relpages;
1295  nrels++;
1296  }
1297 
1298  /*
1299  * If we don't have at least one child table to consider, fail. If the
1300  * relation is a partitioned table, it's not counted as a child table.
1301  */
1302  if (!has_child)
1303  {
1304  ereport(elevel,
1305  (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1307  RelationGetRelationName(onerel))));
1308  return 0;
1309  }
1310 
1311  /*
1312  * Now sample rows from each relation, proportionally to its fraction of
1313  * the total block count. (This might be less than desirable if the child
1314  * rels have radically different free-space percentages, but it's not
1315  * clear that it's worth working harder.)
1316  */
1317  numrows = 0;
1318  *totalrows = 0;
1319  *totaldeadrows = 0;
1320  for (i = 0; i < nrels; i++)
1321  {
1322  Relation childrel = rels[i];
1323  AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1324  double childblocks = relblocks[i];
1325 
1326  if (childblocks > 0)
1327  {
1328  int childtargrows;
1329 
1330  childtargrows = (int) rint(targrows * childblocks / totalblocks);
1331  /* Make sure we don't overrun due to roundoff error */
1332  childtargrows = Min(childtargrows, targrows - numrows);
1333  if (childtargrows > 0)
1334  {
1335  int childrows;
1336  double trows,
1337  tdrows;
1338 
1339  /* Fetch a random sample of the child's rows */
1340  childrows = (*acquirefunc) (childrel, elevel,
1341  rows + numrows, childtargrows,
1342  &trows, &tdrows);
1343 
1344  /* We may need to convert from child's rowtype to parent's */
1345  if (childrows > 0 &&
1346  !equalTupleDescs(RelationGetDescr(childrel),
1347  RelationGetDescr(onerel)))
1348  {
1349  TupleConversionMap *map;
1350 
1351  map = convert_tuples_by_name(RelationGetDescr(childrel),
1352  RelationGetDescr(onerel),
1353  gettext_noop("could not convert row type"));
1354  if (map != NULL)
1355  {
1356  int j;
1357 
1358  for (j = 0; j < childrows; j++)
1359  {
1360  HeapTuple newtup;
1361 
1362  newtup = execute_attr_map_tuple(rows[numrows + j], map);
1363  heap_freetuple(rows[numrows + j]);
1364  rows[numrows + j] = newtup;
1365  }
1366  free_conversion_map(map);
1367  }
1368  }
1369 
1370  /* And add to counts */
1371  numrows += childrows;
1372  *totalrows += trows;
1373  *totaldeadrows += tdrows;
1374  }
1375  }
1376 
1377  /*
1378  * Note: we cannot release the child-table locks, since we may have
1379  * pointers to their TOAST tables in the sampled rows.
1380  */
1381  table_close(childrel, NoLock);
1382  }
1383 
1384  return numrows;
1385 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:440
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:234
#define Min(x, y)
Definition: c.h:890
#define AccessShareLock
Definition: lockdefs.h:36
#define gettext_noop(x)
Definition: c.h:1103
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:84
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
int32 relpages
Definition: pg_class.h:60
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:2809
struct RelationData * Relation
Definition: relcache.h:26
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:484
#define RelationGetRelationName(relation)
Definition: rel.h:448
double rint(double x)
Definition: rint.c:21
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:390
#define ereport(elevel, rest)
Definition: elog.h:141
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:205
static int elevel
Definition: vacuumlazy.c:145
void CommandCounterIncrement(void)
Definition: xact.c:1004
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:198
#define Assert(condition)
Definition: c.h:732
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:544
static int list_length(const List *l)
Definition: pg_list.h:89
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:142
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:165
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
int i
bool equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:411
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:414
#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:1004
#define RelationGetNamespace(relation)
Definition: rel.h:455

◆ acquire_sample_rows()

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

Definition at line 1004 of file analyze.c.

References Assert, BlockSampler_HasMore(), BlockSampler_Init(), BlockSampler_Next(), compare_rows(), ereport, errmsg(), ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), GetOldestXmin(), heap_freetuple(), BlockSamplerData::m, OldestXmin, PROCARRAY_FLAGS_VACUUM, qsort, random(), ReservoirStateData::randstate, RelationGetNumberOfBlocks, RelationGetRelationName, reservoir_get_next_S(), reservoir_init_selection_state(), sampler_random_fract(), table_beginscan_analyze(), table_endscan(), table_scan_analyze_next_block(), table_scan_analyze_next_tuple(), table_slot_create(), and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

1007 {
1008  int numrows = 0; /* # rows now in reservoir */
1009  double samplerows = 0; /* total # rows collected */
1010  double liverows = 0; /* # live rows seen */
1011  double deadrows = 0; /* # dead rows seen */
1012  double rowstoskip = -1; /* -1 means not set yet */
1013  BlockNumber totalblocks;
1015  BlockSamplerData bs;
1016  ReservoirStateData rstate;
1017  TupleTableSlot *slot;
1018  TableScanDesc scan;
1019 
1020  Assert(targrows > 0);
1021 
1022  totalblocks = RelationGetNumberOfBlocks(onerel);
1023 
1024  /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1025  OldestXmin = GetOldestXmin(onerel, PROCARRAY_FLAGS_VACUUM);
1026 
1027  /* Prepare for sampling block numbers */
1028  BlockSampler_Init(&bs, totalblocks, targrows, random());
1029  /* Prepare for sampling rows */
1030  reservoir_init_selection_state(&rstate, targrows);
1031 
1032  scan = table_beginscan_analyze(onerel);
1033  slot = table_slot_create(onerel, NULL);
1034 
1035  /* Outer loop over blocks to sample */
1036  while (BlockSampler_HasMore(&bs))
1037  {
1038  BlockNumber targblock = BlockSampler_Next(&bs);
1039 
1041 
1042  if (!table_scan_analyze_next_block(scan, targblock, vac_strategy))
1043  continue;
1044 
1045  while (table_scan_analyze_next_tuple(scan, OldestXmin, &liverows, &deadrows, slot))
1046  {
1047  /*
1048  * The first targrows sample rows are simply copied into the
1049  * reservoir. Then we start replacing tuples in the sample until
1050  * we reach the end of the relation. This algorithm is from Jeff
1051  * Vitter's paper (see full citation below). It works by
1052  * repeatedly computing the number of tuples to skip before
1053  * selecting a tuple, which replaces a randomly chosen element of
1054  * the reservoir (current set of tuples). At all times the
1055  * reservoir is a true random sample of the tuples we've passed
1056  * over so far, so when we fall off the end of the relation we're
1057  * done.
1058  */
1059  if (numrows < targrows)
1060  rows[numrows++] = ExecCopySlotHeapTuple(slot);
1061  else
1062  {
1063  /*
1064  * t in Vitter's paper is the number of records already
1065  * processed. If we need to compute a new S value, we must
1066  * use the not-yet-incremented value of samplerows as t.
1067  */
1068  if (rowstoskip < 0)
1069  rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1070 
1071  if (rowstoskip <= 0)
1072  {
1073  /*
1074  * Found a suitable tuple, so save it, replacing one old
1075  * tuple at random
1076  */
1077  int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1078 
1079  Assert(k >= 0 && k < targrows);
1080  heap_freetuple(rows[k]);
1081  rows[k] = ExecCopySlotHeapTuple(slot);
1082  }
1083 
1084  rowstoskip -= 1;
1085  }
1086 
1087  samplerows += 1;
1088  }
1089  }
1090 
1092  table_endscan(scan);
1093 
1094  /*
1095  * If we didn't find as many tuples as we wanted then we're done. No sort
1096  * is needed, since they're already in order.
1097  *
1098  * Otherwise we need to sort the collected tuples by position
1099  * (itempointer). It's not worth worrying about corner cases where the
1100  * tuples are already sorted.
1101  */
1102  if (numrows == targrows)
1103  qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1104 
1105  /*
1106  * Estimate total numbers of live and dead rows in relation, extrapolating
1107  * on the assumption that the average tuple density in pages we didn't
1108  * scan is the same as in the pages we did scan. Since what we scanned is
1109  * a random sample of the pages in the relation, this should be a good
1110  * assumption.
1111  */
1112  if (bs.m > 0)
1113  {
1114  *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1115  *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1116  }
1117  else
1118  {
1119  *totalrows = 0.0;
1120  *totaldeadrows = 0.0;
1121  }
1122 
1123  /*
1124  * Emit some interesting relation info
1125  */
1126  ereport(elevel,
1127  (errmsg("\"%s\": scanned %d of %u pages, "
1128  "containing %.0f live rows and %.0f dead rows; "
1129  "%d rows in sample, %.0f estimated total rows",
1130  RelationGetRelationName(onerel),
1131  bs.m, totalblocks,
1132  liverows, deadrows,
1133  numrows, *totalrows)));
1134 
1135  return numrows;
1136 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:73
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:54
uint32 TransactionId
Definition: c.h:507
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:60
long random(void)
Definition: random.c:22
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
static BufferAccessStrategy vac_strategy
Definition: analyze.c:84
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:1338
void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, long randseed)
Definition: sampling.c:37
static bool table_scan_analyze_next_block(TableScanDesc scan, BlockNumber blockno, BufferAccessStrategy bstrategy)
Definition: tableam.h:1362
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1217
#define RelationGetRelationName(relation)
Definition: rel.h:448
static TransactionId OldestXmin
Definition: vacuumlazy.c:147
#define ereport(elevel, rest)
Definition: elog.h:141
static int compare_rows(const void *a, const void *b)
Definition: analyze.c:1142
static int elevel
Definition: vacuumlazy.c:145
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:198
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:453
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1307
#define Assert(condition)
Definition: c.h:732
static bool table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition: tableam.h:1380
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:763
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define qsort(a, b, c, d)
Definition: port.h:491
void vacuum_delay_point(void)
Definition: vacuum.c:1917
SamplerRandomState randstate
Definition: sampling.h:50
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition: tableam.h:752

◆ analyze_mcv_list()

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

Definition at line 2734 of file analyze.c.

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

2740 {
2741  double ndistinct_table;
2742  double sumcount;
2743  int i;
2744 
2745  /*
2746  * If the entire table was sampled, keep the whole list. This also
2747  * protects us against division by zero in the code below.
2748  */
2749  if (samplerows == totalrows || totalrows <= 1.0)
2750  return num_mcv;
2751 
2752  /* Re-extract the estimated number of distinct nonnull values in table */
2753  ndistinct_table = stadistinct;
2754  if (ndistinct_table < 0)
2755  ndistinct_table = -ndistinct_table * totalrows;
2756 
2757  /*
2758  * Exclude the least common values from the MCV list, if they are not
2759  * significantly more common than the estimated selectivity they would
2760  * have if they weren't in the list. All non-MCV values are assumed to be
2761  * equally common, after taking into account the frequencies of all the
2762  * values in the MCV list and the number of nulls (c.f. eqsel()).
2763  *
2764  * Here sumcount tracks the total count of all but the last (least common)
2765  * value in the MCV list, allowing us to determine the effect of excluding
2766  * that value from the list.
2767  *
2768  * Note that we deliberately do this by removing values from the full
2769  * list, rather than starting with an empty list and adding values,
2770  * because the latter approach can fail to add any values if all the most
2771  * common values have around the same frequency and make up the majority
2772  * of the table, so that the overall average frequency of all values is
2773  * roughly the same as that of the common values. This would lead to any
2774  * uncommon values being significantly overestimated.
2775  */
2776  sumcount = 0.0;
2777  for (i = 0; i < num_mcv - 1; i++)
2778  sumcount += mcv_counts[i];
2779 
2780  while (num_mcv > 0)
2781  {
2782  double selec,
2783  otherdistinct,
2784  N,
2785  n,
2786  K,
2787  variance,
2788  stddev;
2789 
2790  /*
2791  * Estimated selectivity the least common value would have if it
2792  * wasn't in the MCV list (c.f. eqsel()).
2793  */
2794  selec = 1.0 - sumcount / samplerows - stanullfrac;
2795  if (selec < 0.0)
2796  selec = 0.0;
2797  if (selec > 1.0)
2798  selec = 1.0;
2799  otherdistinct = ndistinct_table - (num_mcv - 1);
2800  if (otherdistinct > 1)
2801  selec /= otherdistinct;
2802 
2803  /*
2804  * If the value is kept in the MCV list, its population frequency is
2805  * assumed to equal its sample frequency. We use the lower end of a
2806  * textbook continuity-corrected Wald-type confidence interval to
2807  * determine if that is significantly more common than the non-MCV
2808  * frequency --- specifically we assume the population frequency is
2809  * highly likely to be within around 2 standard errors of the sample
2810  * frequency, which equates to an interval of 2 standard deviations
2811  * either side of the sample count, plus an additional 0.5 for the
2812  * continuity correction. Since we are sampling without replacement,
2813  * this is a hypergeometric distribution.
2814  *
2815  * XXX: Empirically, this approach seems to work quite well, but it
2816  * may be worth considering more advanced techniques for estimating
2817  * the confidence interval of the hypergeometric distribution.
2818  */
2819  N = totalrows;
2820  n = samplerows;
2821  K = N * mcv_counts[num_mcv - 1] / n;
2822  variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
2823  stddev = sqrt(variance);
2824 
2825  if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
2826  {
2827  /*
2828  * The value is significantly more common than the non-MCV
2829  * selectivity would suggest. Keep it, and all the other more
2830  * common values in the list.
2831  */
2832  break;
2833  }
2834  else
2835  {
2836  /* Discard this value and consider the next least common value */
2837  num_mcv--;
2838  if (num_mcv == 0)
2839  break;
2840  sumcount -= mcv_counts[num_mcv - 1];
2841  }
2842  }
2843  return num_mcv;
2844 }
#define K(t)
Definition: sha1.c:48
int i

◆ analyze_rel()

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

Definition at line 118 of file analyze.c.

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

Referenced by vacuum().

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

◆ compare_mcvs()

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

Definition at line 2716 of file analyze.c.

Referenced by compute_scalar_stats().

2717 {
2718  int da = ((const ScalarMCVItem *) a)->first;
2719  int db = ((const ScalarMCVItem *) b)->first;
2720 
2721  return da - db;
2722 }

◆ compare_rows()

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

Definition at line 1142 of file analyze.c.

References ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

1143 {
1144  HeapTuple ha = *(const HeapTuple *) a;
1145  HeapTuple hb = *(const HeapTuple *) b;
1150 
1151  if (ba < bb)
1152  return -1;
1153  if (ba > bb)
1154  return 1;
1155  if (oa < ob)
1156  return -1;
1157  if (oa > ob)
1158  return 1;
1159  return 0;
1160 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ compare_scalars()

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

Definition at line 2685 of file analyze.c.

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

Referenced by compute_scalar_stats().

2686 {
2687  Datum da = ((const ScalarItem *) a)->value;
2688  int ta = ((const ScalarItem *) a)->tupno;
2689  Datum db = ((const ScalarItem *) b)->value;
2690  int tb = ((const ScalarItem *) b)->tupno;
2692  int compare;
2693 
2694  compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2695  if (compare != 0)
2696  return compare;
2697 
2698  /*
2699  * The two datums are equal, so update cxt->tupnoLink[].
2700  */
2701  if (cxt->tupnoLink[ta] < tb)
2702  cxt->tupnoLink[ta] = tb;
2703  if (cxt->tupnoLink[tb] < ta)
2704  cxt->tupnoLink[tb] = ta;
2705 
2706  /*
2707  * For equal datums, sort by tupno
2708  */
2709  return ta - tb;
2710 }
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
SortSupport ssup
Definition: analyze.c:1612
uintptr_t Datum
Definition: postgres.h:367
void * arg
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

◆ compute_distinct_stats()

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

Definition at line 1813 of file analyze.c.

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

Referenced by std_typanalyze().

1817 {
1818  int i;
1819  int null_cnt = 0;
1820  int nonnull_cnt = 0;
1821  int toowide_cnt = 0;
1822  double total_width = 0;
1823  bool is_varlena = (!stats->attrtype->typbyval &&
1824  stats->attrtype->typlen == -1);
1825  bool is_varwidth = (!stats->attrtype->typbyval &&
1826  stats->attrtype->typlen < 0);
1827  FmgrInfo f_cmpeq;
1828  typedef struct
1829  {
1830  Datum value;
1831  int count;
1832  } TrackItem;
1833  TrackItem *track;
1834  int track_cnt,
1835  track_max;
1836  int num_mcv = stats->attr->attstattarget;
1837  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1838 
1839  /*
1840  * We track up to 2*n values for an n-element MCV list; but at least 10
1841  */
1842  track_max = 2 * num_mcv;
1843  if (track_max < 10)
1844  track_max = 10;
1845  track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1846  track_cnt = 0;
1847 
1848  fmgr_info(mystats->eqfunc, &f_cmpeq);
1849 
1850  for (i = 0; i < samplerows; i++)
1851  {
1852  Datum value;
1853  bool isnull;
1854  bool match;
1855  int firstcount1,
1856  j;
1857 
1859 
1860  value = fetchfunc(stats, i, &isnull);
1861 
1862  /* Check for null/nonnull */
1863  if (isnull)
1864  {
1865  null_cnt++;
1866  continue;
1867  }
1868  nonnull_cnt++;
1869 
1870  /*
1871  * If it's a variable-width field, add up widths for average width
1872  * calculation. Note that if the value is toasted, we use the toasted
1873  * width. We don't bother with this calculation if it's a fixed-width
1874  * type.
1875  */
1876  if (is_varlena)
1877  {
1878  total_width += VARSIZE_ANY(DatumGetPointer(value));
1879 
1880  /*
1881  * If the value is toasted, we want to detoast it just once to
1882  * avoid repeated detoastings and resultant excess memory usage
1883  * during the comparisons. Also, check to see if the value is
1884  * excessively wide, and if so don't detoast at all --- just
1885  * ignore the value.
1886  */
1888  {
1889  toowide_cnt++;
1890  continue;
1891  }
1892  value = PointerGetDatum(PG_DETOAST_DATUM(value));
1893  }
1894  else if (is_varwidth)
1895  {
1896  /* must be cstring */
1897  total_width += strlen(DatumGetCString(value)) + 1;
1898  }
1899 
1900  /*
1901  * See if the value matches anything we're already tracking.
1902  */
1903  match = false;
1904  firstcount1 = track_cnt;
1905  for (j = 0; j < track_cnt; j++)
1906  {
1907  if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
1908  stats->attrcollid,
1909  value, track[j].value)))
1910  {
1911  match = true;
1912  break;
1913  }
1914  if (j < firstcount1 && track[j].count == 1)
1915  firstcount1 = j;
1916  }
1917 
1918  if (match)
1919  {
1920  /* Found a match */
1921  track[j].count++;
1922  /* This value may now need to "bubble up" in the track list */
1923  while (j > 0 && track[j].count > track[j - 1].count)
1924  {
1925  swapDatum(track[j].value, track[j - 1].value);
1926  swapInt(track[j].count, track[j - 1].count);
1927  j--;
1928  }
1929  }
1930  else
1931  {
1932  /* No match. Insert at head of count-1 list */
1933  if (track_cnt < track_max)
1934  track_cnt++;
1935  for (j = track_cnt - 1; j > firstcount1; j--)
1936  {
1937  track[j].value = track[j - 1].value;
1938  track[j].count = track[j - 1].count;
1939  }
1940  if (firstcount1 < track_cnt)
1941  {
1942  track[firstcount1].value = value;
1943  track[firstcount1].count = 1;
1944  }
1945  }
1946  }
1947 
1948  /* We can only compute real stats if we found some non-null values. */
1949  if (nonnull_cnt > 0)
1950  {
1951  int nmultiple,
1952  summultiple;
1953 
1954  stats->stats_valid = true;
1955  /* Do the simple null-frac and width stats */
1956  stats->stanullfrac = (double) null_cnt / (double) samplerows;
1957  if (is_varwidth)
1958  stats->stawidth = total_width / (double) nonnull_cnt;
1959  else
1960  stats->stawidth = stats->attrtype->typlen;
1961 
1962  /* Count the number of values we found multiple times */
1963  summultiple = 0;
1964  for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
1965  {
1966  if (track[nmultiple].count == 1)
1967  break;
1968  summultiple += track[nmultiple].count;
1969  }
1970 
1971  if (nmultiple == 0)
1972  {
1973  /*
1974  * If we found no repeated non-null values, assume it's a unique
1975  * column; but be sure to discount for any nulls we found.
1976  */
1977  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
1978  }
1979  else if (track_cnt < track_max && toowide_cnt == 0 &&
1980  nmultiple == track_cnt)
1981  {
1982  /*
1983  * Our track list includes every value in the sample, and every
1984  * value appeared more than once. Assume the column has just
1985  * these values. (This case is meant to address columns with
1986  * small, fixed sets of possible values, such as boolean or enum
1987  * columns. If there are any values that appear just once in the
1988  * sample, including too-wide values, we should assume that that's
1989  * not what we're dealing with.)
1990  */
1991  stats->stadistinct = track_cnt;
1992  }
1993  else
1994  {
1995  /*----------
1996  * Estimate the number of distinct values using the estimator
1997  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
1998  * n*d / (n - f1 + f1*n/N)
1999  * where f1 is the number of distinct values that occurred
2000  * exactly once in our sample of n rows (from a total of N),
2001  * and d is the total number of distinct values in the sample.
2002  * This is their Duj1 estimator; the other estimators they
2003  * recommend are considerably more complex, and are numerically
2004  * very unstable when n is much smaller than N.
2005  *
2006  * In this calculation, we consider only non-nulls. We used to
2007  * include rows with null values in the n and N counts, but that
2008  * leads to inaccurate answers in columns with many nulls, and
2009  * it's intuitively bogus anyway considering the desired result is
2010  * the number of distinct non-null values.
2011  *
2012  * We assume (not very reliably!) that all the multiply-occurring
2013  * values are reflected in the final track[] list, and the other
2014  * nonnull values all appeared but once. (XXX this usually
2015  * results in a drastic overestimate of ndistinct. Can we do
2016  * any better?)
2017  *----------
2018  */
2019  int f1 = nonnull_cnt - summultiple;
2020  int d = f1 + nmultiple;
2021  double n = samplerows - null_cnt;
2022  double N = totalrows * (1.0 - stats->stanullfrac);
2023  double stadistinct;
2024 
2025  /* N == 0 shouldn't happen, but just in case ... */
2026  if (N > 0)
2027  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2028  else
2029  stadistinct = 0;
2030 
2031  /* Clamp to sane range in case of roundoff error */
2032  if (stadistinct < d)
2033  stadistinct = d;
2034  if (stadistinct > N)
2035  stadistinct = N;
2036  /* And round to integer */
2037  stats->stadistinct = floor(stadistinct + 0.5);
2038  }
2039 
2040  /*
2041  * If we estimated the number of distinct values at more than 10% of
2042  * the total row count (a very arbitrary limit), then assume that
2043  * stadistinct should scale with the row count rather than be a fixed
2044  * value.
2045  */
2046  if (stats->stadistinct > 0.1 * totalrows)
2047  stats->stadistinct = -(stats->stadistinct / totalrows);
2048 
2049  /*
2050  * Decide how many values are worth storing as most-common values. If
2051  * we are able to generate a complete MCV list (all the values in the
2052  * sample will fit, and we think these are all the ones in the table),
2053  * then do so. Otherwise, store only those values that are
2054  * significantly more common than the values not in the list.
2055  *
2056  * Note: the first of these cases is meant to address columns with
2057  * small, fixed sets of possible values, such as boolean or enum
2058  * columns. If we can *completely* represent the column population by
2059  * an MCV list that will fit into the stats target, then we should do
2060  * so and thus provide the planner with complete information. But if
2061  * the MCV list is not complete, it's generally worth being more
2062  * selective, and not just filling it all the way up to the stats
2063  * target.
2064  */
2065  if (track_cnt < track_max && toowide_cnt == 0 &&
2066  stats->stadistinct > 0 &&
2067  track_cnt <= num_mcv)
2068  {
2069  /* Track list includes all values seen, and all will fit */
2070  num_mcv = track_cnt;
2071  }
2072  else
2073  {
2074  int *mcv_counts;
2075 
2076  /* Incomplete list; decide how many values are worth keeping */
2077  if (num_mcv > track_cnt)
2078  num_mcv = track_cnt;
2079 
2080  if (num_mcv > 0)
2081  {
2082  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2083  for (i = 0; i < num_mcv; i++)
2084  mcv_counts[i] = track[i].count;
2085 
2086  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2087  stats->stadistinct,
2088  stats->stanullfrac,
2089  samplerows, totalrows);
2090  }
2091  }
2092 
2093  /* Generate MCV slot entry */
2094  if (num_mcv > 0)
2095  {
2096  MemoryContext old_context;
2097  Datum *mcv_values;
2098  float4 *mcv_freqs;
2099 
2100  /* Must copy the target values into anl_context */
2101  old_context = MemoryContextSwitchTo(stats->anl_context);
2102  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2103  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2104  for (i = 0; i < num_mcv; i++)
2105  {
2106  mcv_values[i] = datumCopy(track[i].value,
2107  stats->attrtype->typbyval,
2108  stats->attrtype->typlen);
2109  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2110  }
2111  MemoryContextSwitchTo(old_context);
2112 
2113  stats->stakind[0] = STATISTIC_KIND_MCV;
2114  stats->staop[0] = mystats->eqopr;
2115  stats->stacoll[0] = stats->attrcollid;
2116  stats->stanumbers[0] = mcv_freqs;
2117  stats->numnumbers[0] = num_mcv;
2118  stats->stavalues[0] = mcv_values;
2119  stats->numvalues[0] = num_mcv;
2120 
2121  /*
2122  * Accept the defaults for stats->statypid and others. They have
2123  * been set before we were called (see vacuum.h)
2124  */
2125  }
2126  }
2127  else if (null_cnt > 0)
2128  {
2129  /* We found only nulls; assume the column is entirely null */
2130  stats->stats_valid = true;
2131  stats->stanullfrac = 1.0;
2132  if (is_varwidth)
2133  stats->stawidth = 0; /* "unknown" */
2134  else
2135  stats->stawidth = stats->attrtype->typlen;
2136  stats->stadistinct = 0.0; /* "unknown" */
2137  }
2138 
2139  /* We don't need to bother cleaning up any of our temporary palloc's */
2140 }
Definition: fmgr.h:56
#define PointerGetDatum(X)
Definition: postgres.h:556
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition: analyze.c:2734
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:114
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static struct @145 value
int f1[ARRAY_SZIE]
Definition: sql-declare.c:113
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1150
Form_pg_attribute attr
Definition: vacuum.h:85
#define swapDatum(a, b)
Definition: analyze.c:1599
Size toast_raw_datum_size(Datum value)
Definition: tuptoaster.c:357
#define DatumGetCString(X)
Definition: postgres.h:566
int32 stawidth
Definition: vacuum.h:106
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:110
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:111
#define DatumGetBool(X)
Definition: postgres.h:393
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
float4 stanullfrac
Definition: vacuum.h:105
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
bool stats_valid
Definition: vacuum.h:104
float float4
Definition: c.h:490
#define WIDTH_THRESHOLD
Definition: analyze.c:1596
uintptr_t Datum
Definition: postgres.h:367
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:112
Oid attrcollid
Definition: vacuum.h:89
MemoryContext anl_context
Definition: vacuum.h:90
#define swapInt(a, b)
Definition: analyze.c:1598
#define DatumGetPointer(X)
Definition: postgres.h:549
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:113
Form_pg_type attrtype
Definition: vacuum.h:88
void * palloc(Size size)
Definition: mcxt.c:924
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:235
void * extra_data
Definition: vacuum.h:98
void vacuum_delay_point(void)
Definition: vacuum.c:1917
float4 stadistinct
Definition: vacuum.h:107

◆ compute_index_stats()

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

Definition at line 691 of file analyze.c.

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

Referenced by do_analyze_rel().

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

◆ compute_scalar_stats()

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

Definition at line 2156 of file analyze.c.

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

Referenced by std_typanalyze().

2160 {
2161  int i;
2162  int null_cnt = 0;
2163  int nonnull_cnt = 0;
2164  int toowide_cnt = 0;
2165  double total_width = 0;
2166  bool is_varlena = (!stats->attrtype->typbyval &&
2167  stats->attrtype->typlen == -1);
2168  bool is_varwidth = (!stats->attrtype->typbyval &&
2169  stats->attrtype->typlen < 0);
2170  double corr_xysum;
2171  SortSupportData ssup;
2172  ScalarItem *values;
2173  int values_cnt = 0;
2174  int *tupnoLink;
2175  ScalarMCVItem *track;
2176  int track_cnt = 0;
2177  int num_mcv = stats->attr->attstattarget;
2178  int num_bins = stats->attr->attstattarget;
2179  StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2180 
2181  values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2182  tupnoLink = (int *) palloc(samplerows * sizeof(int));
2183  track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2184 
2185  memset(&ssup, 0, sizeof(ssup));
2187  ssup.ssup_collation = stats->attrcollid;
2188  ssup.ssup_nulls_first = false;
2189 
2190  /*
2191  * For now, don't perform abbreviated key conversion, because full values
2192  * are required for MCV slot generation. Supporting that optimization
2193  * would necessitate teaching compare_scalars() to call a tie-breaker.
2194  */
2195  ssup.abbreviate = false;
2196 
2197  PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2198 
2199  /* Initial scan to find sortable values */
2200  for (i = 0; i < samplerows; i++)
2201  {
2202  Datum value;
2203  bool isnull;
2204 
2206 
2207  value = fetchfunc(stats, i, &isnull);
2208 
2209  /* Check for null/nonnull */
2210  if (isnull)
2211  {
2212  null_cnt++;
2213  continue;
2214  }
2215  nonnull_cnt++;
2216 
2217  /*
2218  * If it's a variable-width field, add up widths for average width
2219  * calculation. Note that if the value is toasted, we use the toasted
2220  * width. We don't bother with this calculation if it's a fixed-width
2221  * type.
2222  */
2223  if (is_varlena)
2224  {
2225  total_width += VARSIZE_ANY(DatumGetPointer(value));
2226 
2227  /*
2228  * If the value is toasted, we want to detoast it just once to
2229  * avoid repeated detoastings and resultant excess memory usage
2230  * during the comparisons. Also, check to see if the value is
2231  * excessively wide, and if so don't detoast at all --- just
2232  * ignore the value.
2233  */
2235  {
2236  toowide_cnt++;
2237  continue;
2238  }
2239  value = PointerGetDatum(PG_DETOAST_DATUM(value));
2240  }
2241  else if (is_varwidth)
2242  {
2243  /* must be cstring */
2244  total_width += strlen(DatumGetCString(value)) + 1;
2245  }
2246 
2247  /* Add it to the list to be sorted */
2248  values[values_cnt].value = value;
2249  values[values_cnt].tupno = values_cnt;
2250  tupnoLink[values_cnt] = values_cnt;
2251  values_cnt++;
2252  }
2253 
2254  /* We can only compute real stats if we found some sortable values. */
2255  if (values_cnt > 0)
2256  {
2257  int ndistinct, /* # distinct values in sample */
2258  nmultiple, /* # that appear multiple times */
2259  num_hist,
2260  dups_cnt;
2261  int slot_idx = 0;
2263 
2264  /* Sort the collected values */
2265  cxt.ssup = &ssup;
2266  cxt.tupnoLink = tupnoLink;
2267  qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2268  compare_scalars, (void *) &cxt);
2269 
2270  /*
2271  * Now scan the values in order, find the most common ones, and also
2272  * accumulate ordering-correlation statistics.
2273  *
2274  * To determine which are most common, we first have to count the
2275  * number of duplicates of each value. The duplicates are adjacent in
2276  * the sorted list, so a brute-force approach is to compare successive
2277  * datum values until we find two that are not equal. However, that
2278  * requires N-1 invocations of the datum comparison routine, which are
2279  * completely redundant with work that was done during the sort. (The
2280  * sort algorithm must at some point have compared each pair of items
2281  * that are adjacent in the sorted order; otherwise it could not know
2282  * that it's ordered the pair correctly.) We exploit this by having
2283  * compare_scalars remember the highest tupno index that each
2284  * ScalarItem has been found equal to. At the end of the sort, a
2285  * ScalarItem's tupnoLink will still point to itself if and only if it
2286  * is the last item of its group of duplicates (since the group will
2287  * be ordered by tupno).
2288  */
2289  corr_xysum = 0;
2290  ndistinct = 0;
2291  nmultiple = 0;
2292  dups_cnt = 0;
2293  for (i = 0; i < values_cnt; i++)
2294  {
2295  int tupno = values[i].tupno;
2296 
2297  corr_xysum += ((double) i) * ((double) tupno);
2298  dups_cnt++;
2299  if (tupnoLink[tupno] == tupno)
2300  {
2301  /* Reached end of duplicates of this value */
2302  ndistinct++;
2303  if (dups_cnt > 1)
2304  {
2305  nmultiple++;
2306  if (track_cnt < num_mcv ||
2307  dups_cnt > track[track_cnt - 1].count)
2308  {
2309  /*
2310  * Found a new item for the mcv list; find its
2311  * position, bubbling down old items if needed. Loop
2312  * invariant is that j points at an empty/ replaceable
2313  * slot.
2314  */
2315  int j;
2316 
2317  if (track_cnt < num_mcv)
2318  track_cnt++;
2319  for (j = track_cnt - 1; j > 0; j--)
2320  {
2321  if (dups_cnt <= track[j - 1].count)
2322  break;
2323  track[j].count = track[j - 1].count;
2324  track[j].first = track[j - 1].first;
2325  }
2326  track[j].count = dups_cnt;
2327  track[j].first = i + 1 - dups_cnt;
2328  }
2329  }
2330  dups_cnt = 0;
2331  }
2332  }
2333 
2334  stats->stats_valid = true;
2335  /* Do the simple null-frac and width stats */
2336  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2337  if (is_varwidth)
2338  stats->stawidth = total_width / (double) nonnull_cnt;
2339  else
2340  stats->stawidth = stats->attrtype->typlen;
2341 
2342  if (nmultiple == 0)
2343  {
2344  /*
2345  * If we found no repeated non-null values, assume it's a unique
2346  * column; but be sure to discount for any nulls we found.
2347  */
2348  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2349  }
2350  else if (toowide_cnt == 0 && nmultiple == ndistinct)
2351  {
2352  /*
2353  * Every value in the sample appeared more than once. Assume the
2354  * column has just these values. (This case is meant to address
2355  * columns with small, fixed sets of possible values, such as
2356  * boolean or enum columns. If there are any values that appear
2357  * just once in the sample, including too-wide values, we should
2358  * assume that that's not what we're dealing with.)
2359  */
2360  stats->stadistinct = ndistinct;
2361  }
2362  else
2363  {
2364  /*----------
2365  * Estimate the number of distinct values using the estimator
2366  * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2367  * n*d / (n - f1 + f1*n/N)
2368  * where f1 is the number of distinct values that occurred
2369  * exactly once in our sample of n rows (from a total of N),
2370  * and d is the total number of distinct values in the sample.
2371  * This is their Duj1 estimator; the other estimators they
2372  * recommend are considerably more complex, and are numerically
2373  * very unstable when n is much smaller than N.
2374  *
2375  * In this calculation, we consider only non-nulls. We used to
2376  * include rows with null values in the n and N counts, but that
2377  * leads to inaccurate answers in columns with many nulls, and
2378  * it's intuitively bogus anyway considering the desired result is
2379  * the number of distinct non-null values.
2380  *
2381  * Overwidth values are assumed to have been distinct.
2382  *----------
2383  */
2384  int f1 = ndistinct - nmultiple + toowide_cnt;
2385  int d = f1 + nmultiple;
2386  double n = samplerows - null_cnt;
2387  double N = totalrows * (1.0 - stats->stanullfrac);
2388  double stadistinct;
2389 
2390  /* N == 0 shouldn't happen, but just in case ... */
2391  if (N > 0)
2392  stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2393  else
2394  stadistinct = 0;
2395 
2396  /* Clamp to sane range in case of roundoff error */
2397  if (stadistinct < d)
2398  stadistinct = d;
2399  if (stadistinct > N)
2400  stadistinct = N;
2401  /* And round to integer */
2402  stats->stadistinct = floor(stadistinct + 0.5);
2403  }
2404 
2405  /*
2406  * If we estimated the number of distinct values at more than 10% of
2407  * the total row count (a very arbitrary limit), then assume that
2408  * stadistinct should scale with the row count rather than be a fixed
2409  * value.
2410  */
2411  if (stats->stadistinct > 0.1 * totalrows)
2412  stats->stadistinct = -(stats->stadistinct / totalrows);
2413 
2414  /*
2415  * Decide how many values are worth storing as most-common values. If
2416  * we are able to generate a complete MCV list (all the values in the
2417  * sample will fit, and we think these are all the ones in the table),
2418  * then do so. Otherwise, store only those values that are
2419  * significantly more common than the values not in the list.
2420  *
2421  * Note: the first of these cases is meant to address columns with
2422  * small, fixed sets of possible values, such as boolean or enum
2423  * columns. If we can *completely* represent the column population by
2424  * an MCV list that will fit into the stats target, then we should do
2425  * so and thus provide the planner with complete information. But if
2426  * the MCV list is not complete, it's generally worth being more
2427  * selective, and not just filling it all the way up to the stats
2428  * target.
2429  */
2430  if (track_cnt == ndistinct && toowide_cnt == 0 &&
2431  stats->stadistinct > 0 &&
2432  track_cnt <= num_mcv)
2433  {
2434  /* Track list includes all values seen, and all will fit */
2435  num_mcv = track_cnt;
2436  }
2437  else
2438  {
2439  int *mcv_counts;
2440 
2441  /* Incomplete list; decide how many values are worth keeping */
2442  if (num_mcv > track_cnt)
2443  num_mcv = track_cnt;
2444 
2445  if (num_mcv > 0)
2446  {
2447  mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2448  for (i = 0; i < num_mcv; i++)
2449  mcv_counts[i] = track[i].count;
2450 
2451  num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2452  stats->stadistinct,
2453  stats->stanullfrac,
2454  samplerows, totalrows);
2455  }
2456  }
2457 
2458  /* Generate MCV slot entry */
2459  if (num_mcv > 0)
2460  {
2461  MemoryContext old_context;
2462  Datum *mcv_values;
2463  float4 *mcv_freqs;
2464 
2465  /* Must copy the target values into anl_context */
2466  old_context = MemoryContextSwitchTo(stats->anl_context);
2467  mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2468  mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2469  for (i = 0; i < num_mcv; i++)
2470  {
2471  mcv_values[i] = datumCopy(values[track[i].first].value,
2472  stats->attrtype->typbyval,
2473  stats->attrtype->typlen);
2474  mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2475  }
2476  MemoryContextSwitchTo(old_context);
2477 
2478  stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2479  stats->staop[slot_idx] = mystats->eqopr;
2480  stats->stacoll[slot_idx] = stats->attrcollid;
2481  stats->stanumbers[slot_idx] = mcv_freqs;
2482  stats->numnumbers[slot_idx] = num_mcv;
2483  stats->stavalues[slot_idx] = mcv_values;
2484  stats->numvalues[slot_idx] = num_mcv;
2485 
2486  /*
2487  * Accept the defaults for stats->statypid and others. They have
2488  * been set before we were called (see vacuum.h)
2489  */
2490  slot_idx++;
2491  }
2492 
2493  /*
2494  * Generate a histogram slot entry if there are at least two distinct
2495  * values not accounted for in the MCV list. (This ensures the
2496  * histogram won't collapse to empty or a singleton.)
2497  */
2498  num_hist = ndistinct - num_mcv;
2499  if (num_hist > num_bins)
2500  num_hist = num_bins + 1;
2501  if (num_hist >= 2)
2502  {
2503  MemoryContext old_context;
2504  Datum *hist_values;
2505  int nvals;
2506  int pos,
2507  posfrac,
2508  delta,
2509  deltafrac;
2510 
2511  /* Sort the MCV items into position order to speed next loop */
2512  qsort((void *) track, num_mcv,
2513  sizeof(ScalarMCVItem), compare_mcvs);
2514 
2515  /*
2516  * Collapse out the MCV items from the values[] array.
2517  *
2518  * Note we destroy the values[] array here... but we don't need it
2519  * for anything more. We do, however, still need values_cnt.
2520  * nvals will be the number of remaining entries in values[].
2521  */
2522  if (num_mcv > 0)
2523  {
2524  int src,
2525  dest;
2526  int j;
2527 
2528  src = dest = 0;
2529  j = 0; /* index of next interesting MCV item */
2530  while (src < values_cnt)
2531  {
2532  int ncopy;
2533 
2534  if (j < num_mcv)
2535  {
2536  int first = track[j].first;
2537 
2538  if (src >= first)
2539  {
2540  /* advance past this MCV item */
2541  src = first + track[j].count;
2542  j++;
2543  continue;
2544  }
2545  ncopy = first - src;
2546  }
2547  else
2548  ncopy = values_cnt - src;
2549  memmove(&values[dest], &values[src],
2550  ncopy * sizeof(ScalarItem));
2551  src += ncopy;
2552  dest += ncopy;
2553  }
2554  nvals = dest;
2555  }
2556  else
2557  nvals = values_cnt;
2558  Assert(nvals >= num_hist);
2559 
2560  /* Must copy the target values into anl_context */
2561  old_context = MemoryContextSwitchTo(stats->anl_context);
2562  hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2563 
2564  /*
2565  * The object of this loop is to copy the first and last values[]
2566  * entries along with evenly-spaced values in between. So the
2567  * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2568  * computing that subscript directly risks integer overflow when
2569  * the stats target is more than a couple thousand. Instead we
2570  * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2571  * the integral and fractional parts of the sum separately.
2572  */
2573  delta = (nvals - 1) / (num_hist - 1);
2574  deltafrac = (nvals - 1) % (num_hist - 1);
2575  pos = posfrac = 0;
2576 
2577  for (i = 0; i < num_hist; i++)
2578  {
2579  hist_values[i] = datumCopy(values[pos].value,
2580  stats->attrtype->typbyval,
2581  stats->attrtype->typlen);
2582  pos += delta;
2583  posfrac += deltafrac;
2584  if (posfrac >= (num_hist - 1))
2585  {
2586  /* fractional part exceeds 1, carry to integer part */
2587  pos++;
2588  posfrac -= (num_hist - 1);
2589  }
2590  }
2591 
2592  MemoryContextSwitchTo(old_context);
2593 
2594  stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2595  stats->staop[slot_idx] = mystats->ltopr;
2596  stats->stacoll[slot_idx] = stats->attrcollid;
2597  stats->stavalues[slot_idx] = hist_values;
2598  stats->numvalues[slot_idx] = num_hist;
2599 
2600  /*
2601  * Accept the defaults for stats->statypid and others. They have
2602  * been set before we were called (see vacuum.h)
2603  */
2604  slot_idx++;
2605  }
2606 
2607  /* Generate a correlation entry if there are multiple values */
2608  if (values_cnt > 1)
2609  {
2610  MemoryContext old_context;
2611  float4 *corrs;
2612  double corr_xsum,
2613  corr_x2sum;
2614 
2615  /* Must copy the target values into anl_context */
2616  old_context = MemoryContextSwitchTo(stats->anl_context);
2617  corrs = (float4 *) palloc(sizeof(float4));
2618  MemoryContextSwitchTo(old_context);
2619 
2620  /*----------
2621  * Since we know the x and y value sets are both
2622  * 0, 1, ..., values_cnt-1
2623  * we have sum(x) = sum(y) =
2624  * (values_cnt-1)*values_cnt / 2
2625  * and sum(x^2) = sum(y^2) =
2626  * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2627  *----------
2628  */
2629  corr_xsum = ((double) (values_cnt - 1)) *
2630  ((double) values_cnt) / 2.0;
2631  corr_x2sum = ((double) (values_cnt - 1)) *
2632  ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2633 
2634  /* And the correlation coefficient reduces to */
2635  corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2636  (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2637 
2638  stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2639  stats->staop[slot_idx] = mystats->ltopr;
2640  stats->stacoll[slot_idx] = stats->attrcollid;
2641  stats->stanumbers[slot_idx] = corrs;
2642  stats->numnumbers[slot_idx] = 1;
2643  slot_idx++;
2644  }
2645  }
2646  else if (nonnull_cnt > 0)
2647  {
2648  /* We found some non-null values, but they were all too wide */
2649  Assert(nonnull_cnt == toowide_cnt);
2650  stats->stats_valid = true;
2651  /* Do the simple null-frac and width stats */
2652  stats->stanullfrac = (double) null_cnt / (double) samplerows;
2653  if (is_varwidth)
2654  stats->stawidth = total_width / (double) nonnull_cnt;
2655  else
2656  stats->stawidth = stats->attrtype->typlen;
2657  /* Assume all too-wide values are distinct, so it's a unique column */
2658  stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2659  }
2660  else if (null_cnt > 0)
2661  {
2662  /* We found only nulls; assume the column is entirely null */
2663  stats->stats_valid = true;
2664  stats->stanullfrac = 1.0;
2665  if (is_varwidth)
2666  stats->stawidth = 0; /* "unknown" */
2667  else
2668  stats->stawidth = stats->attrtype->typlen;
2669  stats->stadistinct = 0.0; /* "unknown" */
2670  }
2671 
2672  /* We don't need to bother cleaning up any of our temporary palloc's */
2673 }
bool ssup_nulls_first
Definition: sortsupport.h:75
static int compare_mcvs(const void *a, const void *b)
Definition: analyze.c:2716
#define PointerGetDatum(X)
Definition: postgres.h:556
static int compare_scalars(const void *a, const void *b, void *arg)
Definition: analyze.c:2685
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition: analyze.c:2734
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:134
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:114
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static struct @145 value
int f1[ARRAY_SZIE]
Definition: sql-declare.c:113
Form_pg_attribute attr
Definition: vacuum.h:85
Size toast_raw_datum_size(Datum value)
Definition: tuptoaster.c:357
#define DatumGetCString(X)
Definition: postgres.h:566
int32 stawidth
Definition: vacuum.h:106
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:110
MemoryContext ssup_cxt
Definition: sortsupport.h:66
SortSupport ssup
Definition: analyze.c:1612
#define memmove(d, s, c)
Definition: c.h:1224
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:111
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
float4 stanullfrac
Definition: vacuum.h:105
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
Definition: qsort_arg.c:113
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
bool stats_valid
Definition: vacuum.h:104
float float4
Definition: c.h:490
#define WIDTH_THRESHOLD
Definition: analyze.c:1596
uintptr_t Datum
Definition: postgres.h:367
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
#define Assert(condition)
Definition: c.h:732
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:112
Oid attrcollid
Definition: vacuum.h:89
MemoryContext anl_context
Definition: vacuum.h:90
#define DatumGetPointer(X)
Definition: postgres.h:549
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:113
Form_pg_type attrtype
Definition: vacuum.h:88
void * palloc(Size size)
Definition: mcxt.c:924
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:235
void * extra_data
Definition: vacuum.h:98
#define qsort(a, b, c, d)
Definition: port.h:491
void vacuum_delay_point(void)
Definition: vacuum.c:1917
float4 stadistinct
Definition: vacuum.h:107

◆ compute_trivial_stats()

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

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

1727 {
1728  int i;
1729  int null_cnt = 0;
1730  int nonnull_cnt = 0;
1731  double total_width = 0;
1732  bool is_varlena = (!stats->attrtype->typbyval &&
1733  stats->attrtype->typlen == -1);
1734  bool is_varwidth = (!stats->attrtype->typbyval &&
1735  stats->attrtype->typlen < 0);
1736 
1737  for (i = 0; i < samplerows; i++)
1738  {
1739  Datum value;
1740  bool isnull;
1741 
1743 
1744  value = fetchfunc(stats, i, &isnull);
1745 
1746  /* Check for null/nonnull */
1747  if (isnull)
1748  {
1749  null_cnt++;
1750  continue;
1751  }
1752  nonnull_cnt++;
1753 
1754  /*
1755  * If it's a variable-width field, add up widths for average width
1756  * calculation. Note that if the value is toasted, we use the toasted
1757  * width. We don't bother with this calculation if it's a fixed-width
1758  * type.
1759  */
1760  if (is_varlena)
1761  {
1762  total_width += VARSIZE_ANY(DatumGetPointer(value));
1763  }
1764  else if (is_varwidth)
1765  {
1766  /* must be cstring */
1767  total_width += strlen(DatumGetCString(value)) + 1;
1768  }
1769  }
1770 
1771  /* We can only compute average width if we found some non-null values. */
1772  if (nonnull_cnt > 0)
1773  {
1774  stats->stats_valid = true;
1775  /* Do the simple null-frac and width stats */
1776  stats->stanullfrac = (double) null_cnt / (double) samplerows;
1777  if (is_varwidth)
1778  stats->stawidth = total_width / (double) nonnull_cnt;
1779  else
1780  stats->stawidth = stats->attrtype->typlen;
1781  stats->stadistinct = 0.0; /* "unknown" */
1782  }
1783  else if (null_cnt > 0)
1784  {
1785  /* We found only nulls; assume the column is entirely null */
1786  stats->stats_valid = true;
1787  stats->stanullfrac = 1.0;
1788  if (is_varwidth)
1789  stats->stawidth = 0; /* "unknown" */
1790  else
1791  stats->stawidth = stats->attrtype->typlen;
1792  stats->stadistinct = 0.0; /* "unknown" */
1793  }
1794 }
static struct @145 value
#define DatumGetCString(X)
Definition: postgres.h:566
int32 stawidth
Definition: vacuum.h:106
float4 stanullfrac
Definition: vacuum.h:105
bool stats_valid
Definition: vacuum.h:104
uintptr_t Datum
Definition: postgres.h:367
#define VARSIZE_ANY(PTR)
Definition: postgres.h:335
#define DatumGetPointer(X)
Definition: postgres.h:549
Form_pg_type attrtype
Definition: vacuum.h:88
int i
void vacuum_delay_point(void)
Definition: vacuum.c:1917
float4 stadistinct
Definition: vacuum.h:107

◆ do_analyze_rel()

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

Definition at line 295 of file analyze.c.

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

Referenced by analyze_rel().

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

◆ examine_attribute()

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

Definition at line 873 of file analyze.c.

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

Referenced by do_analyze_rel().

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

◆ ind_fetch_func()

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

Definition at line 1566 of file analyze.c.

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

Referenced by compute_index_stats().

1567 {
1568  int i;
1569 
1570  /* exprvals and exprnulls are already offset for proper column */
1571  i = rownum * stats->rowstride;
1572  *isNull = stats->exprnulls[i];
1573  return stats->exprvals[i];
1574 }
int rowstride
Definition: vacuum.h:136
bool * exprnulls
Definition: vacuum.h:135
Datum * exprvals
Definition: vacuum.h:134
int i

◆ std_fetch_func()

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

Definition at line 1550 of file analyze.c.

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

Referenced by do_analyze_rel().

1551 {
1552  int attnum = stats->tupattnum;
1553  HeapTuple tuple = stats->rows[rownum];
1554  TupleDesc tupDesc = stats->tupDesc;
1555 
1556  return heap_getattr(tuple, attnum, tupDesc, isNull);
1557 }
HeapTuple * rows
Definition: vacuum.h:132
int tupattnum
Definition: vacuum.h:131
TupleDesc tupDesc
Definition: vacuum.h:133
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
int16 attnum
Definition: pg_attribute.h:79

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

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

1644 {
1645  Form_pg_attribute attr = stats->attr;
1646  Oid ltopr;
1647  Oid eqopr;
1648  StdAnalyzeData *mystats;
1649 
1650  /* If the attstattarget column is negative, use the default value */
1651  /* NB: it is okay to scribble on stats->attr since it's a copy */
1652  if (attr->attstattarget < 0)
1653  attr->attstattarget = default_statistics_target;
1654 
1655  /* Look for default "<" and "=" operators for column's type */
1657  false, false, false,
1658  &ltopr, &eqopr, NULL,
1659  NULL);
1660 
1661  /* Save the operator info for compute_stats routines */
1662  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1663  mystats->eqopr = eqopr;
1664  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1665  mystats->ltopr = ltopr;
1666  stats->extra_data = mystats;
1667 
1668  /*
1669  * Determine which standard statistics algorithm to use
1670  */
1671  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1672  {
1673  /* Seems to be a scalar datatype */
1675  /*--------------------
1676  * The following choice of minrows is based on the paper
1677  * "Random sampling for histogram construction: how much is enough?"
1678  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1679  * Proceedings of ACM SIGMOD International Conference on Management
1680  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1681  * says that for table size n, histogram size k, maximum relative
1682  * error in bin size f, and error probability gamma, the minimum
1683  * random sample size is
1684  * r = 4 * k * ln(2*n/gamma) / f^2
1685  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1686  * r = 305.82 * k
1687  * Note that because of the log function, the dependence on n is
1688  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1689  * bin size error with probability 0.99. So there's no real need to
1690  * scale for n, which is a good thing because we don't necessarily
1691  * know it at this point.
1692  *--------------------
1693  */
1694  stats->minrows = 300 * attr->attstattarget;
1695  }
1696  else if (OidIsValid(eqopr))
1697  {
1698  /* We can still recognize distinct values */
1700  /* Might as well use the same minrows as above */
1701  stats->minrows = 300 * attr->attstattarget;
1702  }
1703  else
1704  {
1705  /* Can't do much but the trivial stuff */
1707  /* Might as well use the same minrows as above */
1708  stats->minrows = 300 * attr->attstattarget;
1709  }
1710 
1711  return true;
1712 }
int minrows
Definition: vacuum.h:97
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2156
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
Form_pg_attribute attr
Definition: vacuum.h:85
Oid attrtypid
Definition: vacuum.h:86
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1813
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1092
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:1723
void * palloc(Size size)
Definition: mcxt.c:924
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:96
void * extra_data
Definition: vacuum.h:98
int default_statistics_target
Definition: analyze.c:80

◆ update_attstats()

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

Definition at line 1411 of file analyze.c.

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

Referenced by do_analyze_rel().

1412 {
1413  Relation sd;
1414  int attno;
1415 
1416  if (natts <= 0)
1417  return; /* nothing to do */
1418 
1419  sd = table_open(StatisticRelationId, RowExclusiveLock);
1420 
1421  for (attno = 0; attno < natts; attno++)
1422  {
1423  VacAttrStats *stats = vacattrstats[attno];
1424  HeapTuple stup,
1425  oldtup;
1426  int i,
1427  k,
1428  n;
1429  Datum values[Natts_pg_statistic];
1430  bool nulls[Natts_pg_statistic];
1431  bool replaces[Natts_pg_statistic];
1432 
1433  /* Ignore attr if we weren't able to collect stats */
1434  if (!stats->stats_valid)
1435  continue;
1436 
1437  /*
1438  * Construct a new pg_statistic tuple
1439  */
1440  for (i = 0; i < Natts_pg_statistic; ++i)
1441  {
1442  nulls[i] = false;
1443  replaces[i] = true;
1444  }
1445 
1446  values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1447  values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1448  values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1449  values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1450  values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1451  values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1452  i = Anum_pg_statistic_stakind1 - 1;
1453  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1454  {
1455  values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1456  }
1457  i = Anum_pg_statistic_staop1 - 1;
1458  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1459  {
1460  values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1461  }
1462  i = Anum_pg_statistic_stacoll1 - 1;
1463  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1464  {
1465  values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1466  }
1467  i = Anum_pg_statistic_stanumbers1 - 1;
1468  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1469  {
1470  int nnum = stats->numnumbers[k];
1471 
1472  if (nnum > 0)
1473  {
1474  Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1475  ArrayType *arry;
1476 
1477  for (n = 0; n < nnum; n++)
1478  numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1479  /* XXX knows more than it should about type float4: */
1480  arry = construct_array(numdatums, nnum,
1481  FLOAT4OID,
1482  sizeof(float4), FLOAT4PASSBYVAL, 'i');
1483  values[i++] = PointerGetDatum(arry); /* stanumbersN */
1484  }
1485  else
1486  {
1487  nulls[i] = true;
1488  values[i++] = (Datum) 0;
1489  }
1490  }
1491  i = Anum_pg_statistic_stavalues1 - 1;
1492  for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1493  {
1494  if (stats->numvalues[k] > 0)
1495  {
1496  ArrayType *arry;
1497 
1498  arry = construct_array(stats->stavalues[k],
1499  stats->numvalues[k],
1500  stats->statypid[k],
1501  stats->statyplen[k],
1502  stats->statypbyval[k],
1503  stats->statypalign[k]);
1504  values[i++] = PointerGetDatum(arry); /* stavaluesN */
1505  }
1506  else
1507  {
1508  nulls[i] = true;
1509  values[i++] = (Datum) 0;
1510  }
1511  }
1512 
1513  /* Is there already a pg_statistic tuple for this attribute? */
1514  oldtup = SearchSysCache3(STATRELATTINH,
1515  ObjectIdGetDatum(relid),
1516  Int16GetDatum(stats->attr->attnum),
1517  BoolGetDatum(inh));
1518 
1519  if (HeapTupleIsValid(oldtup))
1520  {
1521  /* Yes, replace it */
1522  stup = heap_modify_tuple(oldtup,
1523  RelationGetDescr(sd),
1524  values,
1525  nulls,
1526  replaces);
1527  ReleaseSysCache(oldtup);
1528  CatalogTupleUpdate(sd, &stup->t_self, stup);
1529  }
1530  else
1531  {
1532  /* No, insert new tuple */
1533  stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1534  CatalogTupleInsert(sd, stup);
1535  }
1536 
1537  heap_freetuple(stup);
1538  }
1539 
1541 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define RelationGetDescr(relation)
Definition: rel.h:440
#define PointerGetDatum(X)
Definition: postgres.h:556
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:114
#define Int16GetDatum(X)
Definition: postgres.h:451
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3291
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:124
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:125
Form_pg_attribute attr
Definition: vacuum.h:85
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
int32 stawidth
Definition: vacuum.h:106
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:110
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:1134
Datum Float4GetDatum(float4 X)
Definition: fmgr.c:1711
ItemPointerData t_self
Definition: htup.h:65
int numnumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:111
#define RowExclusiveLock
Definition: lockdefs.h:38
float4 stanullfrac
Definition: vacuum.h:105
Oid staop[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:109
bool stats_valid
Definition: vacuum.h:104
float float4
Definition: c.h:490
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
int16 stakind[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:108
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:122
#define BoolGetDatum(X)
Definition: postgres.h:402
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:126
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:112
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:207
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define Int32GetDatum(X)
Definition: postgres.h:479
int numvalues[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:113
void * palloc(Size size)
Definition: mcxt.c:924
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:123
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:166
float4 stadistinct
Definition: vacuum.h:107

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 83 of file analyze.c.

Referenced by examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

Definition at line 80 of file analyze.c.

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

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 84 of file analyze.c.

Referenced by do_analyze_rel().