PostgreSQL Source Code git master
analyze.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/detoast.h"
#include "access/genam.h"
#include "access/multixact.h"
#include "access/relation.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/tupconvert.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_inherits.h"
#include "commands/progress.h"
#include "commands/tablecmds.h"
#include "commands/vacuum.h"
#include "common/pg_prng.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 "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "storage/procarray.h"
#include "utils/attoptcache.h"
#include "utils/datum.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, const 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, void *arg)
 
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, const VacuumParams params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
 
static BlockNumber block_sampling_read_stream_next (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
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, void *arg)
 
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,
  b 
)    do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)

Definition at line 1852 of file analyze.c.

◆ swapInt

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

Definition at line 1851 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1849 of file analyze.c.

Typedef Documentation

◆ AnlIndexData

typedef struct AnlIndexData AnlIndexData

Function Documentation

◆ acquire_inherited_sample_rows()

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

Definition at line 1397 of file analyze.c.

1400{
1401 List *tableOIDs;
1402 Relation *rels;
1403 AcquireSampleRowsFunc *acquirefuncs;
1404 double *relblocks;
1405 double totalblocks;
1406 int numrows,
1407 nrels,
1408 i;
1409 ListCell *lc;
1410 bool has_child;
1411
1412 /* Initialize output parameters to zero now, in case we exit early */
1413 *totalrows = 0;
1414 *totaldeadrows = 0;
1415
1416 /*
1417 * Find all members of inheritance set. We only need AccessShareLock on
1418 * the children.
1419 */
1420 tableOIDs =
1422
1423 /*
1424 * Check that there's at least one descendant, else fail. This could
1425 * happen despite analyze_rel's relhassubclass check, if table once had a
1426 * child but no longer does. In that case, we can clear the
1427 * relhassubclass field so as not to make the same mistake again later.
1428 * (This is safe because we hold ShareUpdateExclusiveLock.)
1429 */
1430 if (list_length(tableOIDs) < 2)
1431 {
1432 /* CCI because we already updated the pg_class row in this command */
1435 ereport(elevel,
1436 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1438 RelationGetRelationName(onerel))));
1439 return 0;
1440 }
1441
1442 /*
1443 * Identify acquirefuncs to use, and count blocks in all the relations.
1444 * The result could overflow BlockNumber, so we use double arithmetic.
1445 */
1446 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1447 acquirefuncs = (AcquireSampleRowsFunc *)
1448 palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1449 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1450 totalblocks = 0;
1451 nrels = 0;
1452 has_child = false;
1453 foreach(lc, tableOIDs)
1454 {
1455 Oid childOID = lfirst_oid(lc);
1456 Relation childrel;
1457 AcquireSampleRowsFunc acquirefunc = NULL;
1458 BlockNumber relpages = 0;
1459
1460 /* We already got the needed lock */
1461 childrel = table_open(childOID, NoLock);
1462
1463 /* Ignore if temp table of another backend */
1464 if (RELATION_IS_OTHER_TEMP(childrel))
1465 {
1466 /* ... but release the lock on it */
1467 Assert(childrel != onerel);
1468 table_close(childrel, AccessShareLock);
1469 continue;
1470 }
1471
1472 /* Check table type (MATVIEW can't happen, but might as well allow) */
1473 if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1474 childrel->rd_rel->relkind == RELKIND_MATVIEW)
1475 {
1476 /* Regular table, so use the regular row acquisition function */
1477 acquirefunc = acquire_sample_rows;
1478 relpages = RelationGetNumberOfBlocks(childrel);
1479 }
1480 else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1481 {
1482 /*
1483 * For a foreign table, call the FDW's hook function to see
1484 * whether it supports analysis.
1485 */
1486 FdwRoutine *fdwroutine;
1487 bool ok = false;
1488
1489 fdwroutine = GetFdwRoutineForRelation(childrel, false);
1490
1491 if (fdwroutine->AnalyzeForeignTable != NULL)
1492 ok = fdwroutine->AnalyzeForeignTable(childrel,
1493 &acquirefunc,
1494 &relpages);
1495
1496 if (!ok)
1497 {
1498 /* ignore, but release the lock on it */
1499 Assert(childrel != onerel);
1500 table_close(childrel, AccessShareLock);
1501 continue;
1502 }
1503 }
1504 else
1505 {
1506 /*
1507 * ignore, but release the lock on it. don't try to unlock the
1508 * passed-in relation
1509 */
1510 Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1511 if (childrel != onerel)
1512 table_close(childrel, AccessShareLock);
1513 else
1514 table_close(childrel, NoLock);
1515 continue;
1516 }
1517
1518 /* OK, we'll process this child */
1519 has_child = true;
1520 rels[nrels] = childrel;
1521 acquirefuncs[nrels] = acquirefunc;
1522 relblocks[nrels] = (double) relpages;
1523 totalblocks += (double) relpages;
1524 nrels++;
1525 }
1526
1527 /*
1528 * If we don't have at least one child table to consider, fail. If the
1529 * relation is a partitioned table, it's not counted as a child table.
1530 */
1531 if (!has_child)
1532 {
1533 ereport(elevel,
1534 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1536 RelationGetRelationName(onerel))));
1537 return 0;
1538 }
1539
1540 /*
1541 * Now sample rows from each relation, proportionally to its fraction of
1542 * the total block count. (This might be less than desirable if the child
1543 * rels have radically different free-space percentages, but it's not
1544 * clear that it's worth working harder.)
1545 */
1547 nrels);
1548 numrows = 0;
1549 for (i = 0; i < nrels; i++)
1550 {
1551 Relation childrel = rels[i];
1552 AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1553 double childblocks = relblocks[i];
1554
1555 /*
1556 * Report progress. The sampling function will normally report blocks
1557 * done/total, but we need to reset them to 0 here, so that they don't
1558 * show an old value until that.
1559 */
1560 {
1561 const int progress_index[] = {
1565 };
1566 const int64 progress_vals[] = {
1567 RelationGetRelid(childrel),
1568 0,
1569 0,
1570 };
1571
1572 pgstat_progress_update_multi_param(3, progress_index, progress_vals);
1573 }
1574
1575 if (childblocks > 0)
1576 {
1577 int childtargrows;
1578
1579 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1580 /* Make sure we don't overrun due to roundoff error */
1581 childtargrows = Min(childtargrows, targrows - numrows);
1582 if (childtargrows > 0)
1583 {
1584 int childrows;
1585 double trows,
1586 tdrows;
1587
1588 /* Fetch a random sample of the child's rows */
1589 childrows = (*acquirefunc) (childrel, elevel,
1590 rows + numrows, childtargrows,
1591 &trows, &tdrows);
1592
1593 /* We may need to convert from child's rowtype to parent's */
1594 if (childrows > 0 &&
1596 RelationGetDescr(onerel)))
1597 {
1598 TupleConversionMap *map;
1599
1601 RelationGetDescr(onerel));
1602 if (map != NULL)
1603 {
1604 int j;
1605
1606 for (j = 0; j < childrows; j++)
1607 {
1608 HeapTuple newtup;
1609
1610 newtup = execute_attr_map_tuple(rows[numrows + j], map);
1611 heap_freetuple(rows[numrows + j]);
1612 rows[numrows + j] = newtup;
1613 }
1615 }
1616 }
1617
1618 /* And add to counts */
1619 numrows += childrows;
1620 *totalrows += trows;
1621 *totaldeadrows += tdrows;
1622 }
1623 }
1624
1625 /*
1626 * Note: we cannot release the child-table locks, since we may have
1627 * pointers to their TOAST tables in the sampled rows.
1628 */
1629 table_close(childrel, NoLock);
1631 i + 1);
1632 }
1633
1634 return numrows;
1635}
void pgstat_progress_update_param(int index, int64 val)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:294
#define Min(x, y)
Definition: c.h:1006
int64_t int64
Definition: c.h:538
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1205
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ereport(elevel,...)
Definition: elog.h:150
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:151
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:443
struct RelationData * Relation
Definition: genam.h:30
Assert(PointerIsAligned(start, uint64))
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
int j
Definition: isn.c:78
int i
Definition: isn.c:77
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3531
void * palloc(Size size)
Definition: mcxt.c:1365
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:255
static int list_length(const List *l)
Definition: pg_list.h:152
#define lfirst_oid(lc)
Definition: pg_list.h:174
unsigned int Oid
Definition: postgres_ext.h:32
#define PROGRESS_ANALYZE_BLOCKS_DONE
Definition: progress.h:56
#define PROGRESS_ANALYZE_CHILD_TABLES_TOTAL
Definition: progress.h:59
#define PROGRESS_ANALYZE_BLOCKS_TOTAL
Definition: progress.h:55
#define PROGRESS_ANALYZE_CHILD_TABLES_DONE
Definition: progress.h:60
#define PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID
Definition: progress.h:61
#define RelationGetRelid(relation)
Definition: rel.h:515
#define RelationGetDescr(relation)
Definition: rel.h:541
#define RelationGetRelationName(relation)
Definition: rel.h:549
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:668
#define RelationGetNamespace(relation)
Definition: rel.h:556
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:257
Definition: pg_list.h:54
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
void SetRelationHasSubclass(Oid relationId, bool relhassubclass)
Definition: tablecmds.c:3639
TupleConversionMap * convert_tuples_by_name(TupleDesc indesc, TupleDesc outdesc)
Definition: tupconvert.c:103
void free_conversion_map(TupleConversionMap *map)
Definition: tupconvert.c:300
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:155
bool equalRowTypes(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tupdesc.c:777
void CommandCounterIncrement(void)
Definition: xact.c:1101

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert(), CommandCounterIncrement(), convert_tuples_by_name(), equalRowTypes(), ereport, errmsg(), execute_attr_map_tuple(), find_all_inheritors(), free_conversion_map(), get_namespace_name(), GetFdwRoutineForRelation(), heap_freetuple(), i, j, lfirst_oid, list_length(), Min, NoLock, palloc(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, PROGRESS_ANALYZE_CHILD_TABLES_DONE, PROGRESS_ANALYZE_CHILD_TABLES_TOTAL, PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetDescr, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, SetRelationHasSubclass(), table_close(), and table_open().

Referenced by do_analyze_rel().

◆ acquire_sample_rows()

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

Definition at line 1205 of file analyze.c.

1208{
1209 int numrows = 0; /* # rows now in reservoir */
1210 double samplerows = 0; /* total # rows collected */
1211 double liverows = 0; /* # live rows seen */
1212 double deadrows = 0; /* # dead rows seen */
1213 double rowstoskip = -1; /* -1 means not set yet */
1214 uint32 randseed; /* Seed for block sampler(s) */
1215 BlockNumber totalblocks;
1216 TransactionId OldestXmin;
1218 ReservoirStateData rstate;
1219 TupleTableSlot *slot;
1220 TableScanDesc scan;
1221 BlockNumber nblocks;
1222 BlockNumber blksdone = 0;
1223 ReadStream *stream;
1224
1225 Assert(targrows > 0);
1226
1227 totalblocks = RelationGetNumberOfBlocks(onerel);
1228
1229 /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1230 OldestXmin = GetOldestNonRemovableTransactionId(onerel);
1231
1232 /* Prepare for sampling block numbers */
1234 nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1235
1236 /* Report sampling block numbers */
1238 nblocks);
1239
1240 /* Prepare for sampling rows */
1241 reservoir_init_selection_state(&rstate, targrows);
1242
1243 scan = table_beginscan_analyze(onerel);
1244 slot = table_slot_create(onerel, NULL);
1245
1246 /*
1247 * It is safe to use batching, as block_sampling_read_stream_next never
1248 * blocks.
1249 */
1253 scan->rs_rd,
1256 &bs,
1257 0);
1258
1259 /* Outer loop over blocks to sample */
1260 while (table_scan_analyze_next_block(scan, stream))
1261 {
1262 vacuum_delay_point(true);
1263
1264 while (table_scan_analyze_next_tuple(scan, OldestXmin, &liverows, &deadrows, slot))
1265 {
1266 /*
1267 * The first targrows sample rows are simply copied into the
1268 * reservoir. Then we start replacing tuples in the sample until
1269 * we reach the end of the relation. This algorithm is from Jeff
1270 * Vitter's paper (see full citation in utils/misc/sampling.c). It
1271 * works by repeatedly computing the number of tuples to skip
1272 * before selecting a tuple, which replaces a randomly chosen
1273 * element of the reservoir (current set of tuples). At all times
1274 * the reservoir is a true random sample of the tuples we've
1275 * passed over so far, so when we fall off the end of the relation
1276 * we're done.
1277 */
1278 if (numrows < targrows)
1279 rows[numrows++] = ExecCopySlotHeapTuple(slot);
1280 else
1281 {
1282 /*
1283 * t in Vitter's paper is the number of records already
1284 * processed. If we need to compute a new S value, we must
1285 * use the not-yet-incremented value of samplerows as t.
1286 */
1287 if (rowstoskip < 0)
1288 rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1289
1290 if (rowstoskip <= 0)
1291 {
1292 /*
1293 * Found a suitable tuple, so save it, replacing one old
1294 * tuple at random
1295 */
1296 int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1297
1298 Assert(k >= 0 && k < targrows);
1299 heap_freetuple(rows[k]);
1300 rows[k] = ExecCopySlotHeapTuple(slot);
1301 }
1302
1303 rowstoskip -= 1;
1304 }
1305
1306 samplerows += 1;
1307 }
1308
1310 ++blksdone);
1311 }
1312
1313 read_stream_end(stream);
1314
1316 table_endscan(scan);
1317
1318 /*
1319 * If we didn't find as many tuples as we wanted then we're done. No sort
1320 * is needed, since they're already in order.
1321 *
1322 * Otherwise we need to sort the collected tuples by position
1323 * (itempointer). It's not worth worrying about corner cases where the
1324 * tuples are already sorted.
1325 */
1326 if (numrows == targrows)
1327 qsort_interruptible(rows, numrows, sizeof(HeapTuple),
1328 compare_rows, NULL);
1329
1330 /*
1331 * Estimate total numbers of live and dead rows in relation, extrapolating
1332 * on the assumption that the average tuple density in pages we didn't
1333 * scan is the same as in the pages we did scan. Since what we scanned is
1334 * a random sample of the pages in the relation, this should be a good
1335 * assumption.
1336 */
1337 if (bs.m > 0)
1338 {
1339 *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1340 *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1341 }
1342 else
1343 {
1344 *totalrows = 0.0;
1345 *totaldeadrows = 0.0;
1346 }
1347
1348 /*
1349 * Emit some interesting relation info
1350 */
1351 ereport(elevel,
1352 (errmsg("\"%s\": scanned %d of %u pages, "
1353 "containing %.0f live rows and %.0f dead rows; "
1354 "%d rows in sample, %.0f estimated total rows",
1356 bs.m, totalblocks,
1357 liverows, deadrows,
1358 numrows, *totalrows)));
1359
1360 return numrows;
1361}
uint32_t uint32
Definition: c.h:541
uint32 TransactionId
Definition: c.h:660
static BufferAccessStrategy vac_strategy
Definition: analyze.c:74
static BlockNumber block_sampling_read_stream_next(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: analyze.c:1162
static int compare_rows(const void *a, const void *b, void *arg)
Definition: analyze.c:1367
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1443
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:227
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
void qsort_interruptible(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:1953
ReadStream * read_stream_begin_relation(int flags, BufferAccessStrategy strategy, Relation rel, ForkNumber forknum, ReadStreamBlockNumberCB callback, void *callback_private_data, size_t per_buffer_data_size)
Definition: read_stream.c:737
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:1089
#define READ_STREAM_MAINTENANCE
Definition: read_stream.h:28
#define READ_STREAM_USE_BATCHING
Definition: read_stream.h:64
@ MAIN_FORKNUM
Definition: relpath.h:58
BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize, uint32 randseed)
Definition: sampling.c:39
void reservoir_init_selection_state(ReservoirState rs, int n)
Definition: sampling.c:133
double sampler_random_fract(pg_prng_state *randstate)
Definition: sampling.c:241
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:147
pg_prng_state randstate
Definition: sampling.h:49
Relation rs_rd
Definition: relscan.h:36
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:92
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:985
static bool table_scan_analyze_next_tuple(TableScanDesc scan, TransactionId OldestXmin, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition: tableam.h:1717
static bool table_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
Definition: tableam.h:1701
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition: tableam.h:974
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:484
void vacuum_delay_point(bool is_analyze)
Definition: vacuum.c:2426

References Assert(), block_sampling_read_stream_next(), BlockSampler_Init(), compare_rows(), ereport, errmsg(), ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), GetOldestNonRemovableTransactionId(), heap_freetuple(), BlockSamplerData::m, MAIN_FORKNUM, pg_global_prng_state, pg_prng_uint32(), pgstat_progress_update_param(), PROGRESS_ANALYZE_BLOCKS_DONE, PROGRESS_ANALYZE_BLOCKS_TOTAL, qsort_interruptible(), ReservoirStateData::randstate, read_stream_begin_relation(), read_stream_end(), READ_STREAM_MAINTENANCE, READ_STREAM_USE_BATCHING, RelationGetNumberOfBlocks, RelationGetRelationName, reservoir_get_next_S(), reservoir_init_selection_state(), TableScanDescData::rs_rd, sampler_random_fract(), table_beginscan_analyze(), table_endscan(), table_scan_analyze_next_block(), table_scan_analyze_next_tuple(), table_slot_create(), vac_strategy, and vacuum_delay_point().

Referenced by acquire_inherited_sample_rows(), and analyze_rel().

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

2991{
2992 double ndistinct_table;
2993 double sumcount;
2994 int i;
2995
2996 /*
2997 * If the entire table was sampled, keep the whole list. This also
2998 * protects us against division by zero in the code below.
2999 */
3000 if (samplerows == totalrows || totalrows <= 1.0)
3001 return num_mcv;
3002
3003 /* Re-extract the estimated number of distinct nonnull values in table */
3004 ndistinct_table = stadistinct;
3005 if (ndistinct_table < 0)
3006 ndistinct_table = -ndistinct_table * totalrows;
3007
3008 /*
3009 * Exclude the least common values from the MCV list, if they are not
3010 * significantly more common than the estimated selectivity they would
3011 * have if they weren't in the list. All non-MCV values are assumed to be
3012 * equally common, after taking into account the frequencies of all the
3013 * values in the MCV list and the number of nulls (c.f. eqsel()).
3014 *
3015 * Here sumcount tracks the total count of all but the last (least common)
3016 * value in the MCV list, allowing us to determine the effect of excluding
3017 * that value from the list.
3018 *
3019 * Note that we deliberately do this by removing values from the full
3020 * list, rather than starting with an empty list and adding values,
3021 * because the latter approach can fail to add any values if all the most
3022 * common values have around the same frequency and make up the majority
3023 * of the table, so that the overall average frequency of all values is
3024 * roughly the same as that of the common values. This would lead to any
3025 * uncommon values being significantly overestimated.
3026 */
3027 sumcount = 0.0;
3028 for (i = 0; i < num_mcv - 1; i++)
3029 sumcount += mcv_counts[i];
3030
3031 while (num_mcv > 0)
3032 {
3033 double selec,
3034 otherdistinct,
3035 N,
3036 n,
3037 K,
3038 variance,
3039 stddev;
3040
3041 /*
3042 * Estimated selectivity the least common value would have if it
3043 * wasn't in the MCV list (c.f. eqsel()).
3044 */
3045 selec = 1.0 - sumcount / samplerows - stanullfrac;
3046 if (selec < 0.0)
3047 selec = 0.0;
3048 if (selec > 1.0)
3049 selec = 1.0;
3050 otherdistinct = ndistinct_table - (num_mcv - 1);
3051 if (otherdistinct > 1)
3052 selec /= otherdistinct;
3053
3054 /*
3055 * If the value is kept in the MCV list, its population frequency is
3056 * assumed to equal its sample frequency. We use the lower end of a
3057 * textbook continuity-corrected Wald-type confidence interval to
3058 * determine if that is significantly more common than the non-MCV
3059 * frequency --- specifically we assume the population frequency is
3060 * highly likely to be within around 2 standard errors of the sample
3061 * frequency, which equates to an interval of 2 standard deviations
3062 * either side of the sample count, plus an additional 0.5 for the
3063 * continuity correction. Since we are sampling without replacement,
3064 * this is a hypergeometric distribution.
3065 *
3066 * XXX: Empirically, this approach seems to work quite well, but it
3067 * may be worth considering more advanced techniques for estimating
3068 * the confidence interval of the hypergeometric distribution.
3069 */
3070 N = totalrows;
3071 n = samplerows;
3072 K = N * mcv_counts[num_mcv - 1] / n;
3073 variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
3074 stddev = sqrt(variance);
3075
3076 if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
3077 {
3078 /*
3079 * The value is significantly more common than the non-MCV
3080 * selectivity would suggest. Keep it, and all the other more
3081 * common values in the list.
3082 */
3083 break;
3084 }
3085 else
3086 {
3087 /* Discard this value and consider the next least common value */
3088 num_mcv--;
3089 if (num_mcv == 0)
3090 break;
3091 sumcount -= mcv_counts[num_mcv - 1];
3092 }
3093 }
3094 return num_mcv;
3095}
#define K(t)
Definition: sha1.c:66

References i, and K.

Referenced by compute_distinct_stats(), and compute_scalar_stats().

◆ analyze_rel()

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

Definition at line 108 of file analyze.c.

111{
112 Relation onerel;
113 int elevel;
114 AcquireSampleRowsFunc acquirefunc = NULL;
115 BlockNumber relpages = 0;
116
117 /* Select logging level */
118 if (params.options & VACOPT_VERBOSE)
119 elevel = INFO;
120 else
121 elevel = DEBUG2;
122
123 /* Set up static variables */
124 vac_strategy = bstrategy;
125
126 /*
127 * Check for user-requested abort.
128 */
130
131 /*
132 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
133 * ANALYZEs don't run on it concurrently. (This also locks out a
134 * concurrent VACUUM, which doesn't matter much at the moment but might
135 * matter if we ever try to accumulate stats on dead tuples.) If the rel
136 * has been dropped since we last saw it, we don't need to process it.
137 *
138 * Make sure to generate only logs for ANALYZE in this case.
139 */
140 onerel = vacuum_open_relation(relid, relation, params.options & ~(VACOPT_VACUUM),
141 params.log_analyze_min_duration >= 0,
143
144 /* leave if relation could not be opened or locked */
145 if (!onerel)
146 return;
147
148 /*
149 * Check if relation needs to be skipped based on privileges. This check
150 * happens also when building the relation list to analyze for a manual
151 * operation, and needs to be done additionally here as ANALYZE could
152 * happen across multiple transactions where privileges could have changed
153 * in-between. Make sure to generate only logs for ANALYZE in this case.
154 */
156 onerel->rd_rel,
157 params.options & ~VACOPT_VACUUM))
158 {
160 return;
161 }
162
163 /*
164 * Silently ignore tables that are temp tables of other backends ---
165 * trying to analyze these is rather pointless, since their contents are
166 * probably not up-to-date on disk. (We don't throw a warning here; it
167 * would just lead to chatter during a database-wide ANALYZE.)
168 */
169 if (RELATION_IS_OTHER_TEMP(onerel))
170 {
172 return;
173 }
174
175 /*
176 * We can ANALYZE any table except pg_statistic. See update_attstats
177 */
178 if (RelationGetRelid(onerel) == StatisticRelationId)
179 {
181 return;
182 }
183
184 /*
185 * Check that it's of an analyzable relkind, and set up appropriately.
186 */
187 if (onerel->rd_rel->relkind == RELKIND_RELATION ||
188 onerel->rd_rel->relkind == RELKIND_MATVIEW)
189 {
190 /* Regular table, so we'll use the regular row acquisition function */
191 acquirefunc = acquire_sample_rows;
192 /* Also get regular table's size */
193 relpages = RelationGetNumberOfBlocks(onerel);
194 }
195 else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
196 {
197 /*
198 * For a foreign table, call the FDW's hook function to see whether it
199 * supports analysis.
200 */
201 FdwRoutine *fdwroutine;
202 bool ok = false;
203
204 fdwroutine = GetFdwRoutineForRelation(onerel, false);
205
206 if (fdwroutine->AnalyzeForeignTable != NULL)
207 ok = fdwroutine->AnalyzeForeignTable(onerel,
208 &acquirefunc,
209 &relpages);
210
211 if (!ok)
212 {
214 (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
215 RelationGetRelationName(onerel))));
217 return;
218 }
219 }
220 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
221 {
222 /*
223 * For partitioned tables, we want to do the recursive ANALYZE below.
224 */
225 }
226 else
227 {
228 /* No need for a WARNING if we already complained during VACUUM */
229 if (!(params.options & VACOPT_VACUUM))
231 (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
232 RelationGetRelationName(onerel))));
234 return;
235 }
236
237 /*
238 * OK, let's do it. First, initialize progress reporting.
239 */
241 RelationGetRelid(onerel));
245 else
248
249 /*
250 * Do the normal non-recursive ANALYZE. We can skip this for partitioned
251 * tables, which don't contain any rows.
252 */
253 if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
254 do_analyze_rel(onerel, params, va_cols, acquirefunc,
255 relpages, false, in_outer_xact, elevel);
256
257 /*
258 * If there are child tables, do recursive ANALYZE.
259 */
260 if (onerel->rd_rel->relhassubclass)
261 do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
262 true, in_outer_xact, elevel);
263
264 /*
265 * Close source relation now, but keep lock so that no one deletes it
266 * before we commit. (If someone did, they'd fail to clean up the entries
267 * we made in pg_statistic. Also, releasing the lock before commit would
268 * expose us to concurrent-update failures in update_attstats.)
269 */
270 relation_close(onerel, NoLock);
271
273}
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_ANALYZE
static void do_analyze_rel(Relation onerel, const VacuumParams params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:283
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
#define INFO
Definition: elog.h:34
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:383
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
#define PROGRESS_ANALYZE_STARTED_BY
Definition: progress.h:63
#define PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM
Definition: progress.h:74
#define PROGRESS_ANALYZE_STARTED_BY_MANUAL
Definition: progress.h:73
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
bits32 options
Definition: vacuum.h:219
int log_analyze_min_duration
Definition: vacuum.h:231
Relation vacuum_open_relation(Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:771
bool vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple, bits32 options)
Definition: vacuum.c:719
#define VACOPT_VACUUM
Definition: vacuum.h:180
#define VACOPT_VERBOSE
Definition: vacuum.h:182

References acquire_sample_rows(), AmAutoVacuumWorkerProcess, FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), ereport, errmsg(), GetFdwRoutineForRelation(), INFO, VacuumParams::log_analyze_min_duration, NoLock, VacuumParams::options, pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), PROGRESS_ANALYZE_STARTED_BY, PROGRESS_ANALYZE_STARTED_BY_AUTOVACUUM, PROGRESS_ANALYZE_STARTED_BY_MANUAL, PROGRESS_COMMAND_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, ShareUpdateExclusiveLock, vac_strategy, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_permitted_for_relation(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

◆ block_sampling_read_stream_next()

static BlockNumber block_sampling_read_stream_next ( ReadStream stream,
void *  callback_private_data,
void *  per_buffer_data 
)
static

Definition at line 1162 of file analyze.c.

1165{
1166 BlockSamplerData *bs = callback_private_data;
1167
1169}
#define InvalidBlockNumber
Definition: block.h:33
bool BlockSampler_HasMore(BlockSampler bs)
Definition: sampling.c:58
BlockNumber BlockSampler_Next(BlockSampler bs)
Definition: sampling.c:64

References BlockSampler_HasMore(), BlockSampler_Next(), and InvalidBlockNumber.

Referenced by acquire_sample_rows().

◆ compare_mcvs()

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

Definition at line 2967 of file analyze.c.

2968{
2969 int da = ((const ScalarMCVItem *) a)->first;
2970 int db = ((const ScalarMCVItem *) b)->first;
2971
2972 return da - db;
2973}
int b
Definition: isn.c:74
int a
Definition: isn.c:73

References a, and b.

Referenced by compute_scalar_stats().

◆ compare_rows()

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

Definition at line 1367 of file analyze.c.

1368{
1369 HeapTuple ha = *(const HeapTuple *) a;
1370 HeapTuple hb = *(const HeapTuple *) b;
1375
1376 if (ba < bb)
1377 return -1;
1378 if (ba > bb)
1379 return 1;
1380 if (oa < ob)
1381 return -1;
1382 if (oa > ob)
1383 return 1;
1384 return 0;
1385}
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
uint16 OffsetNumber
Definition: off.h:24
ItemPointerData t_self
Definition: htup.h:65

References a, b, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), and HeapTupleData::t_self.

Referenced by acquire_sample_rows().

◆ compare_scalars()

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

Definition at line 2936 of file analyze.c.

2937{
2938 Datum da = ((const ScalarItem *) a)->value;
2939 int ta = ((const ScalarItem *) a)->tupno;
2940 Datum db = ((const ScalarItem *) b)->value;
2941 int tb = ((const ScalarItem *) b)->tupno;
2943 int compare;
2944
2945 compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2946 if (compare != 0)
2947 return compare;
2948
2949 /*
2950 * The two datums are equal, so update cxt->tupnoLink[].
2951 */
2952 if (cxt->tupnoLink[ta] < tb)
2953 cxt->tupnoLink[ta] = tb;
2954 if (cxt->tupnoLink[tb] < ta)
2955 cxt->tupnoLink[tb] = ta;
2956
2957 /*
2958 * For equal datums, sort by tupno
2959 */
2960 return ta - tb;
2961}
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
void * arg
uint64_t Datum
Definition: postgres.h:70
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
SortSupport ssup
Definition: analyze.c:1865

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

Referenced by compute_scalar_stats().

◆ compute_distinct_stats()

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

Definition at line 2064 of file analyze.c.

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

References analyze_mcv_list(), VacAttrStats::anl_context, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attstattarget, datumCopy(), DatumGetBool(), DatumGetCString(), DatumGetPointer(), StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, f1, fmgr_info(), FunctionCall2Coll(), i, if(), j, 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().

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

875{
876 MemoryContext ind_context,
877 old_context;
879 bool isnull[INDEX_MAX_KEYS];
880 int ind,
881 i;
882
884 "Analyze Index",
886 old_context = MemoryContextSwitchTo(ind_context);
887
888 for (ind = 0; ind < nindexes; ind++)
889 {
890 AnlIndexData *thisdata = &indexdata[ind];
891 IndexInfo *indexInfo = thisdata->indexInfo;
892 int attr_cnt = thisdata->attr_cnt;
893 TupleTableSlot *slot;
894 EState *estate;
895 ExprContext *econtext;
896 ExprState *predicate;
897 Datum *exprvals;
898 bool *exprnulls;
899 int numindexrows,
900 tcnt,
901 rowno;
902 double totalindexrows;
903
904 /* Ignore index if no columns to analyze and not partial */
905 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
906 continue;
907
908 /*
909 * Need an EState for evaluation of index expressions and
910 * partial-index predicates. Create it in the per-index context to be
911 * sure it gets cleaned up at the bottom of the loop.
912 */
913 estate = CreateExecutorState();
914 econtext = GetPerTupleExprContext(estate);
915 /* Need a slot to hold the current heap tuple, too */
918
919 /* Arrange for econtext's scan tuple to be the tuple under test */
920 econtext->ecxt_scantuple = slot;
921
922 /* Set up execution state for predicate. */
923 predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
924
925 /* Compute and save index expression values */
926 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
927 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
928 numindexrows = 0;
929 tcnt = 0;
930 for (rowno = 0; rowno < numrows; rowno++)
931 {
932 HeapTuple heapTuple = rows[rowno];
933
934 vacuum_delay_point(true);
935
936 /*
937 * Reset the per-tuple context each time, to reclaim any cruft
938 * left behind by evaluating the predicate or index expressions.
939 */
940 ResetExprContext(econtext);
941
942 /* Set up for predicate or expression evaluation */
943 ExecStoreHeapTuple(heapTuple, slot, false);
944
945 /* If index is partial, check predicate */
946 if (predicate != NULL)
947 {
948 if (!ExecQual(predicate, econtext))
949 continue;
950 }
951 numindexrows++;
952
953 if (attr_cnt > 0)
954 {
955 /*
956 * Evaluate the index row to compute expression values. We
957 * could do this by hand, but FormIndexDatum is convenient.
958 */
959 FormIndexDatum(indexInfo,
960 slot,
961 estate,
962 values,
963 isnull);
964
965 /*
966 * Save just the columns we care about. We copy the values
967 * into ind_context from the estate's per-tuple context.
968 */
969 for (i = 0; i < attr_cnt; i++)
970 {
971 VacAttrStats *stats = thisdata->vacattrstats[i];
972 int attnum = stats->tupattnum;
973
974 if (isnull[attnum - 1])
975 {
976 exprvals[tcnt] = (Datum) 0;
977 exprnulls[tcnt] = true;
978 }
979 else
980 {
981 exprvals[tcnt] = datumCopy(values[attnum - 1],
982 stats->attrtype->typbyval,
983 stats->attrtype->typlen);
984 exprnulls[tcnt] = false;
985 }
986 tcnt++;
987 }
988 }
989 }
990
991 /*
992 * Having counted the number of rows that pass the predicate in the
993 * sample, we can estimate the total number of rows in the index.
994 */
995 thisdata->tupleFract = (double) numindexrows / (double) numrows;
996 totalindexrows = ceil(thisdata->tupleFract * totalrows);
997
998 /*
999 * Now we can compute the statistics for the expression columns.
1000 */
1001 if (numindexrows > 0)
1002 {
1003 MemoryContextSwitchTo(col_context);
1004 for (i = 0; i < attr_cnt; i++)
1005 {
1006 VacAttrStats *stats = thisdata->vacattrstats[i];
1007
1008 stats->exprvals = exprvals + i;
1009 stats->exprnulls = exprnulls + i;
1010 stats->rowstride = attr_cnt;
1011 stats->compute_stats(stats,
1013 numindexrows,
1014 totalindexrows);
1015
1016 MemoryContextReset(col_context);
1017 }
1018 }
1019
1020 /* And clean up */
1021 MemoryContextSwitchTo(ind_context);
1022
1024 FreeExecutorState(estate);
1025 MemoryContextReset(ind_context);
1026 }
1027
1028 MemoryContextSwitchTo(old_context);
1029 MemoryContextDelete(ind_context);
1030}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
static MemoryContext anl_context
Definition: analyze.c:73
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1819
ExprState * ExecPrepareQual(List *qual, EState *estate)
Definition: execExpr.c:793
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1427
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:85
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1541
void FreeExecutorState(EState *estate)
Definition: execUtils.c:192
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition: executor.h:656
#define ResetExprContext(econtext)
Definition: executor.h:650
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:519
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2730
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:400
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:469
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
int16 attnum
Definition: pg_attribute.h:74
#define INDEX_MAX_KEYS
#define NIL
Definition: pg_list.h:68
double tupleFract
Definition: analyze.c:63
int attr_cnt
Definition: analyze.c:65
IndexInfo * indexInfo
Definition: analyze.c:62
VacAttrStats ** vacattrstats
Definition: analyze.c:64
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:273
List * ii_Predicate
Definition: execnodes.h:183
int tupattnum
Definition: vacuum.h:171
int rowstride
Definition: vacuum.h:176
bool * exprnulls
Definition: vacuum.h:175
Datum * exprvals
Definition: vacuum.h:174
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:136

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

Referenced by do_analyze_rel().

◆ compute_scalar_stats()

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

Definition at line 2407 of file analyze.c.

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

References SortSupportData::abbreviate, analyze_mcv_list(), VacAttrStats::anl_context, Assert(), VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attstattarget, compare_mcvs(), compare_scalars(), ScalarMCVItem::count, CurrentMemoryContext, datumCopy(), DatumGetCString(), DatumGetPointer(), generate_unaccent_rules::dest, StdAnalyzeData::eqopr, VacAttrStats::extra_data, f1, ScalarMCVItem::first, i, j, StdAnalyzeData::ltopr, MemoryContextSwitchTo(), VacAttrStats::numnumbers, VacAttrStats::numvalues, palloc(), palloc_object, PG_DETOAST_DATUM, PointerGetDatum(), PrepareSortSupportFromOrderingOp(), qsort_interruptible(), 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(), CompareScalarsContext::tupnoLink, vacuum_delay_point(), value, values, VARSIZE_ANY(), and WIDTH_THRESHOLD.

Referenced by std_typanalyze().

◆ compute_trivial_stats()

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

Definition at line 1974 of file analyze.c.

1978{
1979 int i;
1980 int null_cnt = 0;
1981 int nonnull_cnt = 0;
1982 double total_width = 0;
1983 bool is_varlena = (!stats->attrtype->typbyval &&
1984 stats->attrtype->typlen == -1);
1985 bool is_varwidth = (!stats->attrtype->typbyval &&
1986 stats->attrtype->typlen < 0);
1987
1988 for (i = 0; i < samplerows; i++)
1989 {
1990 Datum value;
1991 bool isnull;
1992
1993 vacuum_delay_point(true);
1994
1995 value = fetchfunc(stats, i, &isnull);
1996
1997 /* Check for null/nonnull */
1998 if (isnull)
1999 {
2000 null_cnt++;
2001 continue;
2002 }
2003 nonnull_cnt++;
2004
2005 /*
2006 * If it's a variable-width field, add up widths for average width
2007 * calculation. Note that if the value is toasted, we use the toasted
2008 * width. We don't bother with this calculation if it's a fixed-width
2009 * type.
2010 */
2011 if (is_varlena)
2012 {
2013 total_width += VARSIZE_ANY(DatumGetPointer(value));
2014 }
2015 else if (is_varwidth)
2016 {
2017 /* must be cstring */
2018 total_width += strlen(DatumGetCString(value)) + 1;
2019 }
2020 }
2021
2022 /* We can only compute average width if we found some non-null values. */
2023 if (nonnull_cnt > 0)
2024 {
2025 stats->stats_valid = true;
2026 /* Do the simple null-frac and width stats */
2027 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2028 if (is_varwidth)
2029 stats->stawidth = total_width / (double) nonnull_cnt;
2030 else
2031 stats->stawidth = stats->attrtype->typlen;
2032 stats->stadistinct = 0.0; /* "unknown" */
2033 }
2034 else if (null_cnt > 0)
2035 {
2036 /* We found only nulls; assume the column is entirely null */
2037 stats->stats_valid = true;
2038 stats->stanullfrac = 1.0;
2039 if (is_varwidth)
2040 stats->stawidth = 0; /* "unknown" */
2041 else
2042 stats->stawidth = stats->attrtype->typlen;
2043 stats->stadistinct = 0.0; /* "unknown" */
2044 }
2045}

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().

◆ do_analyze_rel()

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

Definition at line 283 of file analyze.c.

287{
288 int attr_cnt,
289 tcnt,
290 i,
291 ind;
292 Relation *Irel;
293 int nindexes;
294 bool verbose,
295 instrument,
296 hasindex;
297 VacAttrStats **vacattrstats;
298 AnlIndexData *indexdata;
299 int targrows,
300 numrows,
301 minrows;
302 double totalrows,
303 totaldeadrows;
304 HeapTuple *rows;
305 PGRUsage ru0;
306 TimestampTz starttime = 0;
307 MemoryContext caller_context;
308 Oid save_userid;
309 int save_sec_context;
310 int save_nestlevel;
311 WalUsage startwalusage = pgWalUsage;
312 BufferUsage startbufferusage = pgBufferUsage;
313 BufferUsage bufferusage;
314 PgStat_Counter startreadtime = 0;
315 PgStat_Counter startwritetime = 0;
316
317 verbose = (params.options & VACOPT_VERBOSE) != 0;
318 instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
319 params.log_analyze_min_duration >= 0));
320 if (inh)
321 ereport(elevel,
322 (errmsg("analyzing \"%s.%s\" inheritance tree",
324 RelationGetRelationName(onerel))));
325 else
326 ereport(elevel,
327 (errmsg("analyzing \"%s.%s\"",
329 RelationGetRelationName(onerel))));
330
331 /*
332 * Set up a working context so that we can easily free whatever junk gets
333 * created.
334 */
336 "Analyze",
338 caller_context = MemoryContextSwitchTo(anl_context);
339
340 /*
341 * Switch to the table owner's userid, so that any index functions are run
342 * as that user. Also lock down security-restricted operations and
343 * arrange to make GUC variable changes local to this command.
344 */
345 GetUserIdAndSecContext(&save_userid, &save_sec_context);
346 SetUserIdAndSecContext(onerel->rd_rel->relowner,
347 save_sec_context | SECURITY_RESTRICTED_OPERATION);
348 save_nestlevel = NewGUCNestLevel();
350
351 /*
352 * When verbose or autovacuum logging is used, initialize a resource usage
353 * snapshot and optionally track I/O timing.
354 */
355 if (instrument)
356 {
357 if (track_io_timing)
358 {
359 startreadtime = pgStatBlockReadTime;
360 startwritetime = pgStatBlockWriteTime;
361 }
362
363 pg_rusage_init(&ru0);
364 }
365
366 /* Used for instrumentation and stats report */
367 starttime = GetCurrentTimestamp();
368
369 /*
370 * Determine which columns to analyze
371 *
372 * Note that system attributes are never analyzed, so we just reject them
373 * at the lookup stage. We also reject duplicate column mentions. (We
374 * could alternatively ignore duplicates, but analyzing a column twice
375 * won't work; we'd end up making a conflicting update in pg_statistic.)
376 */
377 if (va_cols != NIL)
378 {
379 Bitmapset *unique_cols = NULL;
380 ListCell *le;
381
382 vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
383 sizeof(VacAttrStats *));
384 tcnt = 0;
385 foreach(le, va_cols)
386 {
387 char *col = strVal(lfirst(le));
388
389 i = attnameAttNum(onerel, col, false);
390 if (i == InvalidAttrNumber)
392 (errcode(ERRCODE_UNDEFINED_COLUMN),
393 errmsg("column \"%s\" of relation \"%s\" does not exist",
394 col, RelationGetRelationName(onerel))));
395 if (bms_is_member(i, unique_cols))
397 (errcode(ERRCODE_DUPLICATE_COLUMN),
398 errmsg("column \"%s\" of relation \"%s\" appears more than once",
399 col, RelationGetRelationName(onerel))));
400 unique_cols = bms_add_member(unique_cols, i);
401
402 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
403 if (vacattrstats[tcnt] != NULL)
404 tcnt++;
405 }
406 attr_cnt = tcnt;
407 }
408 else
409 {
410 attr_cnt = onerel->rd_att->natts;
411 vacattrstats = (VacAttrStats **)
412 palloc(attr_cnt * sizeof(VacAttrStats *));
413 tcnt = 0;
414 for (i = 1; i <= attr_cnt; i++)
415 {
416 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
417 if (vacattrstats[tcnt] != NULL)
418 tcnt++;
419 }
420 attr_cnt = tcnt;
421 }
422
423 /*
424 * Open all indexes of the relation, and see if there are any analyzable
425 * columns in the indexes. We do not analyze index columns if there was
426 * an explicit column list in the ANALYZE command, however.
427 *
428 * If we are doing a recursive scan, we don't want to touch the parent's
429 * indexes at all. If we're processing a partitioned table, we need to
430 * know if there are any indexes, but we don't want to process them.
431 */
432 if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
433 {
434 List *idxs = RelationGetIndexList(onerel);
435
436 Irel = NULL;
437 nindexes = 0;
438 hasindex = idxs != NIL;
439 list_free(idxs);
440 }
441 else if (!inh)
442 {
443 vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
444 hasindex = nindexes > 0;
445 }
446 else
447 {
448 Irel = NULL;
449 nindexes = 0;
450 hasindex = false;
451 }
452 indexdata = NULL;
453 if (nindexes > 0)
454 {
455 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
456 for (ind = 0; ind < nindexes; ind++)
457 {
458 AnlIndexData *thisdata = &indexdata[ind];
459 IndexInfo *indexInfo;
460
461 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
462 thisdata->tupleFract = 1.0; /* fix later if partial */
463 if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
464 {
465 ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
466
467 thisdata->vacattrstats = (VacAttrStats **)
468 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
469 tcnt = 0;
470 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
471 {
472 int keycol = indexInfo->ii_IndexAttrNumbers[i];
473
474 if (keycol == 0)
475 {
476 /* Found an index expression */
477 Node *indexkey;
478
479 if (indexpr_item == NULL) /* shouldn't happen */
480 elog(ERROR, "too few entries in indexprs list");
481 indexkey = (Node *) lfirst(indexpr_item);
482 indexpr_item = lnext(indexInfo->ii_Expressions,
483 indexpr_item);
484 thisdata->vacattrstats[tcnt] =
485 examine_attribute(Irel[ind], i + 1, indexkey);
486 if (thisdata->vacattrstats[tcnt] != NULL)
487 tcnt++;
488 }
489 }
490 thisdata->attr_cnt = tcnt;
491 }
492 }
493 }
494
495 /*
496 * Determine how many rows we need to sample, using the worst case from
497 * all analyzable columns. We use a lower bound of 100 rows to avoid
498 * possible overflow in Vitter's algorithm. (Note: that will also be the
499 * target in the corner case where there are no analyzable columns.)
500 */
501 targrows = 100;
502 for (i = 0; i < attr_cnt; i++)
503 {
504 if (targrows < vacattrstats[i]->minrows)
505 targrows = vacattrstats[i]->minrows;
506 }
507 for (ind = 0; ind < nindexes; ind++)
508 {
509 AnlIndexData *thisdata = &indexdata[ind];
510
511 for (i = 0; i < thisdata->attr_cnt; i++)
512 {
513 if (targrows < thisdata->vacattrstats[i]->minrows)
514 targrows = thisdata->vacattrstats[i]->minrows;
515 }
516 }
517
518 /*
519 * Look at extended statistics objects too, as those may define custom
520 * statistics target. So we may need to sample more rows and then build
521 * the statistics with enough detail.
522 */
523 minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
524
525 if (targrows < minrows)
526 targrows = minrows;
527
528 /*
529 * Acquire the sample rows
530 */
531 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
535 if (inh)
536 numrows = acquire_inherited_sample_rows(onerel, elevel,
537 rows, targrows,
538 &totalrows, &totaldeadrows);
539 else
540 numrows = (*acquirefunc) (onerel, elevel,
541 rows, targrows,
542 &totalrows, &totaldeadrows);
543
544 /*
545 * Compute the statistics. Temporary results during the calculations for
546 * each column are stored in a child context. The calc routines are
547 * responsible to make sure that whatever they store into the VacAttrStats
548 * structure is allocated in anl_context.
549 */
550 if (numrows > 0)
551 {
552 MemoryContext col_context,
553 old_context;
554
557
559 "Analyze Column",
561 old_context = MemoryContextSwitchTo(col_context);
562
563 for (i = 0; i < attr_cnt; i++)
564 {
565 VacAttrStats *stats = vacattrstats[i];
566 AttributeOpts *aopt;
567
568 stats->rows = rows;
569 stats->tupDesc = onerel->rd_att;
570 stats->compute_stats(stats,
572 numrows,
573 totalrows);
574
575 /*
576 * If the appropriate flavor of the n_distinct option is
577 * specified, override with the corresponding value.
578 */
579 aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
580 if (aopt != NULL)
581 {
582 float8 n_distinct;
583
584 n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
585 if (n_distinct != 0.0)
586 stats->stadistinct = n_distinct;
587 }
588
589 MemoryContextReset(col_context);
590 }
591
592 if (nindexes > 0)
593 compute_index_stats(onerel, totalrows,
594 indexdata, nindexes,
595 rows, numrows,
596 col_context);
597
598 MemoryContextSwitchTo(old_context);
599 MemoryContextDelete(col_context);
600
601 /*
602 * Emit the completed stats rows into pg_statistic, replacing any
603 * previous statistics for the target columns. (If there are stats in
604 * pg_statistic for columns we didn't process, we leave them alone.)
605 */
607 attr_cnt, vacattrstats);
608
609 for (ind = 0; ind < nindexes; ind++)
610 {
611 AnlIndexData *thisdata = &indexdata[ind];
612
614 thisdata->attr_cnt, thisdata->vacattrstats);
615 }
616
617 /* Build extended statistics (if there are any). */
618 BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
619 attr_cnt, vacattrstats);
620 }
621
624
625 /*
626 * Update pages/tuples stats in pg_class ... but not if we're doing
627 * inherited stats.
628 *
629 * We assume that VACUUM hasn't set pg_class.reltuples already, even
630 * during a VACUUM ANALYZE. Although VACUUM often updates pg_class,
631 * exceptions exist. A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command will
632 * never update pg_class entries for index relations. It's also possible
633 * that an individual index's pg_class entry won't be updated during
634 * VACUUM if the index AM returns NULL from its amvacuumcleanup() routine.
635 */
636 if (!inh)
637 {
638 BlockNumber relallvisible = 0;
639 BlockNumber relallfrozen = 0;
640
641 if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
642 visibilitymap_count(onerel, &relallvisible, &relallfrozen);
643
644 /*
645 * Update pg_class for table relation. CCI first, in case acquirefunc
646 * updated pg_class.
647 */
649 vac_update_relstats(onerel,
650 relpages,
651 totalrows,
652 relallvisible,
653 relallfrozen,
654 hasindex,
657 NULL, NULL,
658 in_outer_xact);
659
660 /* Same for indexes */
661 for (ind = 0; ind < nindexes; ind++)
662 {
663 AnlIndexData *thisdata = &indexdata[ind];
664 double totalindexrows;
665
666 totalindexrows = ceil(thisdata->tupleFract * totalrows);
669 totalindexrows,
670 0, 0,
671 false,
674 NULL, NULL,
675 in_outer_xact);
676 }
677 }
678 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
679 {
680 /*
681 * Partitioned tables don't have storage, so we don't set any fields
682 * in their pg_class entries except for reltuples and relhasindex.
683 */
685 vac_update_relstats(onerel, -1, totalrows,
686 0, 0, hasindex, InvalidTransactionId,
688 NULL, NULL,
689 in_outer_xact);
690 }
691
692 /*
693 * Now report ANALYZE to the cumulative stats system. For regular tables,
694 * we do it only if not doing inherited stats. For partitioned tables, we
695 * only do it for inherited stats. (We're never called for not-inherited
696 * stats on partitioned tables anyway.)
697 *
698 * Reset the mod_since_analyze counter only if we analyzed all columns;
699 * otherwise, there is still work for auto-analyze to do.
700 */
701 if (!inh)
702 pgstat_report_analyze(onerel, totalrows, totaldeadrows,
703 (va_cols == NIL), starttime);
704 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
705 pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL), starttime);
706
707 /*
708 * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
709 *
710 * Note that most index AMs perform a no-op as a matter of policy for
711 * amvacuumcleanup() when called in ANALYZE-only mode. The only exception
712 * among core index AMs is GIN/ginvacuumcleanup().
713 */
714 if (!(params.options & VACOPT_VACUUM))
715 {
716 for (ind = 0; ind < nindexes; ind++)
717 {
719 IndexVacuumInfo ivinfo;
720
721 ivinfo.index = Irel[ind];
722 ivinfo.heaprel = onerel;
723 ivinfo.analyze_only = true;
724 ivinfo.estimated_count = true;
725 ivinfo.message_level = elevel;
726 ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
727 ivinfo.strategy = vac_strategy;
728
729 stats = index_vacuum_cleanup(&ivinfo, NULL);
730
731 if (stats)
732 pfree(stats);
733 }
734 }
735
736 /* Done with indexes */
737 vac_close_indexes(nindexes, Irel, NoLock);
738
739 /* Log the action if appropriate */
740 if (instrument)
741 {
743
744 if (verbose || params.log_analyze_min_duration == 0 ||
745 TimestampDifferenceExceeds(starttime, endtime,
747 {
748 long delay_in_ms;
749 WalUsage walusage;
750 double read_rate = 0;
751 double write_rate = 0;
752 char *msgfmt;
754 int64 total_blks_hit;
755 int64 total_blks_read;
756 int64 total_blks_dirtied;
757
758 memset(&bufferusage, 0, sizeof(BufferUsage));
759 BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
760 memset(&walusage, 0, sizeof(WalUsage));
761 WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
762
763 total_blks_hit = bufferusage.shared_blks_hit +
764 bufferusage.local_blks_hit;
765 total_blks_read = bufferusage.shared_blks_read +
766 bufferusage.local_blks_read;
767 total_blks_dirtied = bufferusage.shared_blks_dirtied +
768 bufferusage.local_blks_dirtied;
769
770 /*
771 * We do not expect an analyze to take > 25 days and it simplifies
772 * things a bit to use TimestampDifferenceMilliseconds.
773 */
774 delay_in_ms = TimestampDifferenceMilliseconds(starttime, endtime);
775
776 /*
777 * Note that we are reporting these read/write rates in the same
778 * manner as VACUUM does, which means that while the 'average read
779 * rate' here actually corresponds to page misses and resulting
780 * reads which are also picked up by track_io_timing, if enabled,
781 * the 'average write rate' is actually talking about the rate of
782 * pages being dirtied, not being written out, so it's typical to
783 * have a non-zero 'avg write rate' while I/O timings only reports
784 * reads.
785 *
786 * It's not clear that an ANALYZE will ever result in
787 * FlushBuffer() being called, but we track and support reporting
788 * on I/O write time in case that changes as it's practically free
789 * to do so anyway.
790 */
791
792 if (delay_in_ms > 0)
793 {
794 read_rate = (double) BLCKSZ * total_blks_read /
795 (1024 * 1024) / (delay_in_ms / 1000.0);
796 write_rate = (double) BLCKSZ * total_blks_dirtied /
797 (1024 * 1024) / (delay_in_ms / 1000.0);
798 }
799
800 /*
801 * We split this up so we don't emit empty I/O timing values when
802 * track_io_timing isn't enabled.
803 */
804
806
808 msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
809 else
810 msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
811
812 appendStringInfo(&buf, msgfmt,
817 {
818 /*
819 * We bypass the changecount mechanism because this value is
820 * only updated by the calling process.
821 */
822 appendStringInfo(&buf, _("delay time: %.3f ms\n"),
824 }
825 if (track_io_timing)
826 {
827 double read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
828 double write_ms = (double) (pgStatBlockWriteTime - startwritetime) / 1000;
829
830 appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
831 read_ms, write_ms);
832 }
833 appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
834 read_rate, write_rate);
835 appendStringInfo(&buf, _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
836 total_blks_hit,
837 total_blks_read,
838 total_blks_dirtied);
840 _("WAL usage: %" PRId64 " records, %" PRId64 " full page images, %" PRIu64 " bytes, %" PRIu64 " full page image bytes, %" PRId64 " buffers full\n"),
841 walusage.wal_records,
842 walusage.wal_fpi,
843 walusage.wal_bytes,
844 walusage.wal_fpi_bytes,
845 walusage.wal_buffers_full);
846 appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
847
849 (errmsg_internal("%s", buf.data)));
850
851 pfree(buf.data);
852 }
853 }
854
855 /* Roll back any GUC changes executed by index functions */
856 AtEOXact_GUC(false, save_nestlevel);
857
858 /* Restore userid and security context */
859 SetUserIdAndSecContext(save_userid, save_sec_context);
860
861 /* Restore current context and release memory */
862 MemoryContextSwitchTo(caller_context);
864 anl_context = NULL;
865}
#define InvalidAttrNumber
Definition: attnum.h:23
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
Definition: attoptcache.c:131
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1757
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1781
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
PgBackendStatus * MyBEEntry
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
bool track_io_timing
Definition: bufmgr.c:147
double float8
Definition: c.h:638
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition: analyze.c:1803
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition: analyze.c:1661
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1397
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition: analyze.c:1042
static void compute_index_stats(Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
Definition: analyze.c:871
int64 TimestampTz
Definition: timestamp.h:39
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
int errcode(int sqlerrcode)
Definition: elog.c:863
#define _(x)
Definition: elog.c:91
#define LOG
Definition: elog.h:31
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
int ComputeExtStatisticsRows(Relation onerel, int natts, VacAttrStats **vacattrstats)
void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats)
Oid MyDatabaseId
Definition: globals.c:94
int NewGUCNestLevel(void)
Definition: guc.c:2110
void RestrictSearchPath(void)
Definition: guc.c:2121
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2137
int verbose
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2428
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition: indexam.c:826
WalUsage pgWalUsage
Definition: instrument.c:22
void WalUsageAccumDiff(WalUsage *dst, const WalUsage *add, const WalUsage *sub)
Definition: instrument.c:288
BufferUsage pgBufferUsage
Definition: instrument.c:20
void BufferUsageAccumDiff(BufferUsage *dst, const BufferUsage *add, const BufferUsage *sub)
Definition: instrument.c:248
void list_free(List *list)
Definition: list.c:1546
char * get_database_name(Oid dbid)
Definition: lsyscache.c:1257
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:319
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:612
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:619
#define InvalidMultiXactId
Definition: multixact.h:25
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define lfirst(lc)
Definition: pg_list.h:172
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
static char buf[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:71
int64 PgStat_Counter
Definition: pgstat.h:67
PgStat_Counter pgStatBlockReadTime
PgStat_Counter pgStatBlockWriteTime
void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter, TimestampTz starttime)
#define PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE
Definition: progress.h:70
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH
Definition: progress.h:67
#define PROGRESS_ANALYZE_PHASE
Definition: progress.h:54
#define PROGRESS_ANALYZE_PHASE_COMPUTE_STATS
Definition: progress.h:68
#define PROGRESS_ANALYZE_DELAY_TIME
Definition: progress.h:62
#define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS
Definition: progress.h:66
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4836
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
float8 n_distinct
Definition: attoptcache.h:22
float8 n_distinct_inherited
Definition: attoptcache.h:23
int64 shared_blks_dirtied
Definition: instrument.h:28
int64 local_blks_hit
Definition: instrument.h:30
int64 shared_blks_read
Definition: instrument.h:27
int64 local_blks_read
Definition: instrument.h:31
int64 local_blks_dirtied
Definition: instrument.h:32
int64 shared_blks_hit
Definition: instrument.h:26
int ii_NumIndexAttrs
Definition: execnodes.h:167
List * ii_Expressions
Definition: execnodes.h:178
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:175
Relation index
Definition: genam.h:73
double num_heap_tuples
Definition: genam.h:79
bool analyze_only
Definition: genam.h:75
BufferAccessStrategy strategy
Definition: genam.h:80
Relation heaprel
Definition: genam.h:74
int message_level
Definition: genam.h:78
bool estimated_count
Definition: genam.h:77
Definition: nodes.h:135
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
TupleDesc rd_att
Definition: rel.h:112
HeapTuple * rows
Definition: vacuum.h:172
int minrows
Definition: vacuum.h:137
TupleDesc tupDesc
Definition: vacuum.h:173
int64 wal_buffers_full
Definition: instrument.h:57
uint64 wal_bytes
Definition: instrument.h:55
int64 wal_fpi
Definition: instrument.h:54
uint64 wal_fpi_bytes
Definition: instrument.h:56
int64 wal_records
Definition: instrument.h:53
#define InvalidTransactionId
Definition: transam.h:31
bool track_cost_delay_timing
Definition: vacuum.c:82
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:2362
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2405
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, BlockNumber num_all_frozen_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool *frozenxid_updated, bool *minmulti_updated, bool in_outer_xact)
Definition: vacuum.c:1426
#define strVal(v)
Definition: value.h:82
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)

References _, AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AmAutoVacuumWorkerProcess, IndexVacuumInfo::analyze_only, anl_context, appendStringInfo(), AtEOXact_GUC(), attnameAttNum(), AnlIndexData::attr_cnt, bms_add_member(), bms_is_member(), buf, BufferUsageAccumDiff(), BuildIndexInfo(), BuildRelationExtStatistics(), CommandCounterIncrement(), compute_index_stats(), VacAttrStats::compute_stats, ComputeExtStatisticsRows(), CurrentMemoryContext, elog, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, IndexVacuumInfo::estimated_count, examine_attribute(), get_attribute_options(), get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GetUserIdAndSecContext(), IndexVacuumInfo::heaprel, i, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexVacuumInfo::index, index_vacuum_cleanup(), AnlIndexData::indexInfo, INFO, initStringInfo(), InvalidAttrNumber, InvalidMultiXactId, InvalidTransactionId, lfirst, list_free(), list_head(), list_length(), lnext(), BufferUsage::local_blks_dirtied, BufferUsage::local_blks_hit, BufferUsage::local_blks_read, LOG, VacuumParams::log_analyze_min_duration, MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), IndexVacuumInfo::message_level, VacAttrStats::minrows, MyBEEntry, 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(), pgBufferUsage, pgstat_progress_update_param(), pgstat_report_analyze(), pgStatBlockReadTime, pgStatBlockWriteTime, pgWalUsage, PROGRESS_ANALYZE_DELAY_TIME, PROGRESS_ANALYZE_PHASE, PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS, PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH, PROGRESS_ANALYZE_PHASE_COMPUTE_STATS, PROGRESS_ANALYZE_PHASE_FINALIZE_ANALYZE, RelationData::rd_att, RelationData::rd_id, RelationData::rd_rel, RelationGetIndexList(), RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, RestrictSearchPath(), VacAttrStats::rows, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), BufferUsage::shared_blks_dirtied, BufferUsage::shared_blks_hit, BufferUsage::shared_blks_read, PgBackendStatus::st_progress_param, VacAttrStats::stadistinct, std_fetch_func(), IndexVacuumInfo::strategy, strVal, TimestampDifferenceExceeds(), TimestampDifferenceMilliseconds(), track_cost_delay_timing, track_io_timing, VacAttrStats::tupattnum, VacAttrStats::tupDesc, AnlIndexData::tupleFract, update_attstats(), vac_close_indexes(), vac_open_indexes(), vac_strategy, vac_update_relstats(), AnlIndexData::vacattrstats, VACOPT_VACUUM, VACOPT_VERBOSE, verbose, visibilitymap_count(), WalUsage::wal_buffers_full, WalUsage::wal_bytes, WalUsage::wal_fpi, WalUsage::wal_fpi_bytes, WalUsage::wal_records, and WalUsageAccumDiff().

Referenced by analyze_rel().

◆ examine_attribute()

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

Definition at line 1042 of file analyze.c.

1043{
1044 Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1045 int attstattarget;
1046 HeapTuple atttuple;
1047 Datum dat;
1048 bool isnull;
1049 HeapTuple typtuple;
1050 VacAttrStats *stats;
1051 int i;
1052 bool ok;
1053
1054 /* Never analyze dropped columns */
1055 if (attr->attisdropped)
1056 return NULL;
1057
1058 /* Don't analyze virtual generated columns */
1059 if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
1060 return NULL;
1061
1062 /*
1063 * Get attstattarget value. Set to -1 if null. (Analyze functions expect
1064 * -1 to mean use default_statistics_target; see for example
1065 * std_typanalyze.)
1066 */
1068 if (!HeapTupleIsValid(atttuple))
1069 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1070 attnum, RelationGetRelid(onerel));
1071 dat = SysCacheGetAttr(ATTNUM, atttuple, Anum_pg_attribute_attstattarget, &isnull);
1072 attstattarget = isnull ? -1 : DatumGetInt16(dat);
1073 ReleaseSysCache(atttuple);
1074
1075 /* Don't analyze column if user has specified not to */
1076 if (attstattarget == 0)
1077 return NULL;
1078
1079 /*
1080 * Create the VacAttrStats struct.
1081 */
1083 stats->attstattarget = attstattarget;
1084
1085 /*
1086 * When analyzing an expression index, believe the expression tree's type
1087 * not the column datatype --- the latter might be the opckeytype storage
1088 * type of the opclass, which is not interesting for our purposes. (Note:
1089 * if we did anything with non-expression index columns, we'd need to
1090 * figure out where to get the correct type info from, but for now that's
1091 * not a problem.) It's not clear whether anyone will care about the
1092 * typmod, but we store that too just in case.
1093 */
1094 if (index_expr)
1095 {
1096 stats->attrtypid = exprType(index_expr);
1097 stats->attrtypmod = exprTypmod(index_expr);
1098
1099 /*
1100 * If a collation has been specified for the index column, use that in
1101 * preference to anything else; but if not, fall back to whatever we
1102 * can get from the expression.
1103 */
1104 if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1105 stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1106 else
1107 stats->attrcollid = exprCollation(index_expr);
1108 }
1109 else
1110 {
1111 stats->attrtypid = attr->atttypid;
1112 stats->attrtypmod = attr->atttypmod;
1113 stats->attrcollid = attr->attcollation;
1114 }
1115
1116 typtuple = SearchSysCacheCopy1(TYPEOID,
1117 ObjectIdGetDatum(stats->attrtypid));
1118 if (!HeapTupleIsValid(typtuple))
1119 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1120 stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
1121 stats->anl_context = anl_context;
1122 stats->tupattnum = attnum;
1123
1124 /*
1125 * The fields describing the stats->stavalues[n] element types default to
1126 * the type of the data being analyzed, but the type-specific typanalyze
1127 * function can change them if it wants to store something else.
1128 */
1129 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1130 {
1131 stats->statypid[i] = stats->attrtypid;
1132 stats->statyplen[i] = stats->attrtype->typlen;
1133 stats->statypbyval[i] = stats->attrtype->typbyval;
1134 stats->statypalign[i] = stats->attrtype->typalign;
1135 }
1136
1137 /*
1138 * Call the type-specific typanalyze function. If none is specified, use
1139 * std_typanalyze().
1140 */
1141 if (OidIsValid(stats->attrtype->typanalyze))
1142 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1143 PointerGetDatum(stats)));
1144 else
1145 ok = std_typanalyze(stats);
1146
1147 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1148 {
1149 heap_freetuple(typtuple);
1150 pfree(stats);
1151 return NULL;
1152 }
1153
1154 return stats;
1155}
#define OidIsValid(objectId)
Definition: c.h:777
bool std_typanalyze(VacAttrStats *stats)
Definition: analyze.c:1896
#define palloc0_object(type)
Definition: fe_memutils.h:75
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define STATISTIC_NUM_SLOTS
Definition: pg_statistic.h:127
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:182
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:172
Oid * rd_indcollation
Definition: rel.h:217
int32 attrtypmod
Definition: vacuum.h:127
Oid statypid[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:162
char statypalign[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:165
Oid attrtypid
Definition: vacuum.h:126
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:164
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition: vacuum.h:163
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:230
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:91
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

References anl_context, VacAttrStats::anl_context, attnum, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::attstattarget, VacAttrStats::compute_stats, DatumGetBool(), DatumGetInt16(), elog, ERROR, exprCollation(), exprType(), exprTypmod(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, i, Int16GetDatum(), VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0_object, pfree(), PointerGetDatum(), RelationData::rd_att, RelationData::rd_indcollation, RelationGetRelid, ReleaseSysCache(), SearchSysCache2(), SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), SysCacheGetAttr(), VacAttrStats::tupattnum, and TupleDescAttr().

Referenced by do_analyze_rel().

◆ ind_fetch_func()

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

Definition at line 1819 of file analyze.c.

1820{
1821 int i;
1822
1823 /* exprvals and exprnulls are already offset for proper column */
1824 i = rownum * stats->rowstride;
1825 *isNull = stats->exprnulls[i];
1826 return stats->exprvals[i];
1827}

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

Referenced by compute_index_stats().

◆ std_fetch_func()

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

Definition at line 1803 of file analyze.c.

1804{
1805 int attnum = stats->tupattnum;
1806 HeapTuple tuple = stats->rows[rownum];
1807 TupleDesc tupDesc = stats->tupDesc;
1808
1809 return heap_getattr(tuple, attnum, tupDesc, isNull);
1810}
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:904

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

Referenced by do_analyze_rel().

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

Definition at line 1896 of file analyze.c.

1897{
1898 Oid ltopr;
1899 Oid eqopr;
1900 StdAnalyzeData *mystats;
1901
1902 /* If the attstattarget column is negative, use the default value */
1903 if (stats->attstattarget < 0)
1905
1906 /* Look for default "<" and "=" operators for column's type */
1908 false, false, false,
1909 &ltopr, &eqopr, NULL,
1910 NULL);
1911
1912 /* Save the operator info for compute_stats routines */
1913 mystats = palloc_object(StdAnalyzeData);
1914 mystats->eqopr = eqopr;
1915 mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1916 mystats->ltopr = ltopr;
1917 stats->extra_data = mystats;
1918
1919 /*
1920 * Determine which standard statistics algorithm to use
1921 */
1922 if (OidIsValid(eqopr) && OidIsValid(ltopr))
1923 {
1924 /* Seems to be a scalar datatype */
1926 /*--------------------
1927 * The following choice of minrows is based on the paper
1928 * "Random sampling for histogram construction: how much is enough?"
1929 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1930 * Proceedings of ACM SIGMOD International Conference on Management
1931 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1932 * says that for table size n, histogram size k, maximum relative
1933 * error in bin size f, and error probability gamma, the minimum
1934 * random sample size is
1935 * r = 4 * k * ln(2*n/gamma) / f^2
1936 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1937 * r = 305.82 * k
1938 * Note that because of the log function, the dependence on n is
1939 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1940 * bin size error with probability 0.99. So there's no real need to
1941 * scale for n, which is a good thing because we don't necessarily
1942 * know it at this point.
1943 *--------------------
1944 */
1945 stats->minrows = 300 * stats->attstattarget;
1946 }
1947 else if (OidIsValid(eqopr))
1948 {
1949 /* We can still recognize distinct values */
1951 /* Might as well use the same minrows as above */
1952 stats->minrows = 300 * stats->attstattarget;
1953 }
1954 else
1955 {
1956 /* Can't do much but the trivial stuff */
1958 /* Might as well use the same minrows as above */
1959 stats->minrows = 300 * stats->attstattarget;
1960 }
1961
1962 return true;
1963}
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2407
int default_statistics_target
Definition: analyze.c:70
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2064
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1974
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1450
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:181
#define InvalidOid
Definition: postgres_ext.h:37

References VacAttrStats::attrtypid, VacAttrStats::attstattarget, 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_object.

Referenced by array_typanalyze(), examine_attribute(), and examine_expression().

◆ update_attstats()

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

Definition at line 1661 of file analyze.c.

1662{
1663 Relation sd;
1664 int attno;
1665 CatalogIndexState indstate = NULL;
1666
1667 if (natts <= 0)
1668 return; /* nothing to do */
1669
1670 sd = table_open(StatisticRelationId, RowExclusiveLock);
1671
1672 for (attno = 0; attno < natts; attno++)
1673 {
1674 VacAttrStats *stats = vacattrstats[attno];
1675 HeapTuple stup,
1676 oldtup;
1677 int i,
1678 k,
1679 n;
1680 Datum values[Natts_pg_statistic];
1681 bool nulls[Natts_pg_statistic];
1682 bool replaces[Natts_pg_statistic];
1683
1684 /* Ignore attr if we weren't able to collect stats */
1685 if (!stats->stats_valid)
1686 continue;
1687
1688 /*
1689 * Construct a new pg_statistic tuple
1690 */
1691 for (i = 0; i < Natts_pg_statistic; ++i)
1692 {
1693 nulls[i] = false;
1694 replaces[i] = true;
1695 }
1696
1697 values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1698 values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->tupattnum);
1699 values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1700 values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1701 values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1702 values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1703 i = Anum_pg_statistic_stakind1 - 1;
1704 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1705 {
1706 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1707 }
1708 i = Anum_pg_statistic_staop1 - 1;
1709 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1710 {
1711 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1712 }
1713 i = Anum_pg_statistic_stacoll1 - 1;
1714 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1715 {
1716 values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1717 }
1718 i = Anum_pg_statistic_stanumbers1 - 1;
1719 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1720 {
1721 if (stats->stanumbers[k] != NULL)
1722 {
1723 int nnum = stats->numnumbers[k];
1724 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1725 ArrayType *arry;
1726
1727 for (n = 0; n < nnum; n++)
1728 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1729 arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
1730 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1731 }
1732 else
1733 {
1734 nulls[i] = true;
1735 values[i++] = (Datum) 0;
1736 }
1737 }
1738 i = Anum_pg_statistic_stavalues1 - 1;
1739 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1740 {
1741 if (stats->stavalues[k] != NULL)
1742 {
1743 ArrayType *arry;
1744
1745 arry = construct_array(stats->stavalues[k],
1746 stats->numvalues[k],
1747 stats->statypid[k],
1748 stats->statyplen[k],
1749 stats->statypbyval[k],
1750 stats->statypalign[k]);
1751 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1752 }
1753 else
1754 {
1755 nulls[i] = true;
1756 values[i++] = (Datum) 0;
1757 }
1758 }
1759
1760 /* Is there already a pg_statistic tuple for this attribute? */
1761 oldtup = SearchSysCache3(STATRELATTINH,
1762 ObjectIdGetDatum(relid),
1763 Int16GetDatum(stats->tupattnum),
1764 BoolGetDatum(inh));
1765
1766 /* Open index information when we know we need it */
1767 if (indstate == NULL)
1768 indstate = CatalogOpenIndexes(sd);
1769
1770 if (HeapTupleIsValid(oldtup))
1771 {
1772 /* Yes, replace it */
1773 stup = heap_modify_tuple(oldtup,
1774 RelationGetDescr(sd),
1775 values,
1776 nulls,
1777 replaces);
1778 ReleaseSysCache(oldtup);
1779 CatalogTupleUpdateWithInfo(sd, &stup->t_self, stup, indstate);
1780 }
1781 else
1782 {
1783 /* No, insert new tuple */
1784 stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1785 CatalogTupleInsertWithInfo(sd, stup, indstate);
1786 }
1787
1788 heap_freetuple(stup);
1789 }
1790
1791 if (indstate != NULL)
1792 CatalogCloseIndexes(indstate);
1794}
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3362
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3382
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1210
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
void CatalogTupleUpdateWithInfo(Relation heapRel, const ItemPointerData *otid, HeapTuple tup, CatalogIndexState indstate)
Definition: indexing.c:337
void CatalogTupleInsertWithInfo(Relation heapRel, HeapTuple tup, CatalogIndexState indstate)
Definition: indexing.c:256
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition: indexing.c:61
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition: indexing.c:43
#define RowExclusiveLock
Definition: lockdefs.h:38
static Datum Float4GetDatum(float4 X)
Definition: postgres.h:458
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
HeapTuple SearchSysCache3(int cacheId, Datum key1, Datum key2, Datum key3)
Definition: syscache.c:240

References BoolGetDatum(), CatalogCloseIndexes(), CatalogOpenIndexes(), CatalogTupleInsertWithInfo(), CatalogTupleUpdateWithInfo(), construct_array(), construct_array_builtin(), 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, VacAttrStats::stats_valid, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, VacAttrStats::stavalues, VacAttrStats::stawidth, HeapTupleData::t_self, table_close(), table_open(), VacAttrStats::tupattnum, and values.

Referenced by do_analyze_rel().

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 73 of file analyze.c.

Referenced by compute_index_stats(), do_analyze_rel(), and examine_attribute().

◆ default_statistics_target

int default_statistics_target = 100

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 74 of file analyze.c.

Referenced by acquire_sample_rows(), analyze_rel(), and do_analyze_rel().