PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 "executor/instrument.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 void validate_va_cols_list (Relation onerel, List *va_cols)
 
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)
 
bool attribute_is_analyzable (Relation onerel, int attnum, Form_pg_attribute attr, int *p_attstattarget)
 
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 1905 of file analyze.c.

◆ swapInt

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

Definition at line 1904 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

Definition at line 1902 of file analyze.c.

Typedef Documentation

◆ AnlIndexData

Function Documentation

◆ acquire_inherited_sample_rows()

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

Definition at line 1450 of file analyze.c.

1453{
1454 List *tableOIDs;
1455 Relation *rels;
1457 double *relblocks;
1458 double totalblocks;
1459 int numrows,
1460 nrels,
1461 i;
1462 ListCell *lc;
1463 bool has_child;
1464
1465 /* Initialize output parameters to zero now, in case we exit early */
1466 *totalrows = 0;
1467 *totaldeadrows = 0;
1468
1469 /*
1470 * Find all members of inheritance set. We only need AccessShareLock on
1471 * the children.
1472 */
1473 tableOIDs =
1475
1476 /*
1477 * Check that there's at least one descendant, else fail. This could
1478 * happen despite analyze_rel's relhassubclass check, if table once had a
1479 * child but no longer does. In that case, we can clear the
1480 * relhassubclass field so as not to make the same mistake again later.
1481 * (This is safe because we hold ShareUpdateExclusiveLock.)
1482 */
1483 if (list_length(tableOIDs) < 2)
1484 {
1485 /* CCI because we already updated the pg_class row in this command */
1488 ereport(elevel,
1489 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1492 return 0;
1493 }
1494
1495 /*
1496 * Identify acquirefuncs to use, and count blocks in all the relations.
1497 * The result could overflow BlockNumber, so we use double arithmetic.
1498 */
1499 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1502 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1503 totalblocks = 0;
1504 nrels = 0;
1505 has_child = false;
1506 foreach(lc, tableOIDs)
1507 {
1511 BlockNumber relpages = 0;
1512
1513 /* We already got the needed lock */
1515
1516 /* Ignore if temp table of another backend */
1518 {
1519 /* ... but release the lock on it */
1522 continue;
1523 }
1524
1525 /* Check table type (MATVIEW can't happen, but might as well allow) */
1526 if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1527 childrel->rd_rel->relkind == RELKIND_MATVIEW)
1528 {
1529 /* Regular table, so use the regular row acquisition function */
1532 }
1533 else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1534 {
1535 /*
1536 * For a foreign table, call the FDW's hook function to see
1537 * whether it supports analysis.
1538 */
1539 FdwRoutine *fdwroutine;
1540 bool ok = false;
1541
1542 fdwroutine = GetFdwRoutineForRelation(childrel, false);
1543
1544 if (fdwroutine->AnalyzeForeignTable != NULL)
1545 ok = fdwroutine->AnalyzeForeignTable(childrel,
1546 &acquirefunc,
1547 &relpages);
1548
1549 if (!ok)
1550 {
1551 /* ignore, but release the lock on it */
1554 continue;
1555 }
1556 }
1557 else
1558 {
1559 /*
1560 * ignore, but release the lock on it. don't try to unlock the
1561 * passed-in relation
1562 */
1563 Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1564 if (childrel != onerel)
1566 else
1568 continue;
1569 }
1570
1571 /* OK, we'll process this child */
1572 has_child = true;
1573 rels[nrels] = childrel;
1574 acquirefuncs[nrels] = acquirefunc;
1575 relblocks[nrels] = (double) relpages;
1576 totalblocks += (double) relpages;
1577 nrels++;
1578 }
1579
1580 /*
1581 * If we don't have at least one child table to consider, fail. If the
1582 * relation is a partitioned table, it's not counted as a child table.
1583 */
1584 if (!has_child)
1585 {
1586 ereport(elevel,
1587 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1590 return 0;
1591 }
1592
1593 /*
1594 * Now sample rows from each relation, proportionally to its fraction of
1595 * the total block count. (This might be less than desirable if the child
1596 * rels have radically different free-space percentages, but it's not
1597 * clear that it's worth working harder.)
1598 */
1600 nrels);
1601 numrows = 0;
1602 for (i = 0; i < nrels; i++)
1603 {
1604 Relation childrel = rels[i];
1606 double childblocks = relblocks[i];
1607
1608 /*
1609 * Report progress. The sampling function will normally report blocks
1610 * done/total, but we need to reset them to 0 here, so that they don't
1611 * show an old value until that.
1612 */
1613 {
1614 const int progress_index[] = {
1618 };
1619 const int64 progress_vals[] = {
1621 0,
1622 0,
1623 };
1624
1626 }
1627
1628 if (childblocks > 0)
1629 {
1630 int childtargrows;
1631
1632 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1633 /* Make sure we don't overrun due to roundoff error */
1634 childtargrows = Min(childtargrows, targrows - numrows);
1635 if (childtargrows > 0)
1636 {
1637 int childrows;
1638 double trows,
1639 tdrows;
1640
1641 /* Fetch a random sample of the child's rows */
1642 childrows = (*acquirefunc) (childrel, elevel,
1643 rows + numrows, childtargrows,
1644 &trows, &tdrows);
1645
1646 /* We may need to convert from child's rowtype to parent's */
1647 if (childrows > 0 &&
1650 {
1651 TupleConversionMap *map;
1652
1655 if (map != NULL)
1656 {
1657 int j;
1658
1659 for (j = 0; j < childrows; j++)
1660 {
1662
1663 newtup = execute_attr_map_tuple(rows[numrows + j], map);
1664 heap_freetuple(rows[numrows + j]);
1665 rows[numrows + j] = newtup;
1666 }
1668 }
1669 }
1670
1671 /* And add to counts */
1672 numrows += childrows;
1673 *totalrows += trows;
1675 }
1676 }
1677
1678 /*
1679 * Note: we cannot release the child-table locks, since we may have
1680 * pointers to their TOAST tables in the sampled rows.
1681 */
1684 i + 1);
1685 }
1686
1687 return numrows;
1688}
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:309
#define Min(x, y)
Definition c.h:1091
#define Assert(condition)
Definition c.h:943
int64_t int64
Definition c.h:621
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition analyze.c:1262
#define ereport(elevel,...)
Definition elog.h:152
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:474
struct RelationData * Relation
Definition genam.h:30
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
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:3588
void * palloc(Size size)
Definition mcxt.c:1387
static char * errmsg
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
static int list_length(const List *l)
Definition pg_list.h:152
#define lfirst_oid(lc)
Definition pg_list.h:174
unsigned int Oid
static int fb(int x)
#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:516
#define RelationGetDescr(relation)
Definition rel.h:542
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:669
#define RelationGetNamespace(relation)
Definition rel.h:557
AnalyzeForeignTable_function AnalyzeForeignTable
Definition fdwapi.h:261
Definition pg_list.h:54
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:3678
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:835
void CommandCounterIncrement(void)
Definition xact.c:1130

References AccessShareLock, acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, Assert, CommandCounterIncrement(), convert_tuples_by_name(), equalRowTypes(), ereport, errmsg, execute_attr_map_tuple(), fb(), 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, 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 1262 of file analyze.c.

1265{
1266 int numrows = 0; /* # rows now in reservoir */
1267 double samplerows = 0; /* total # rows collected */
1268 double liverows = 0; /* # live rows seen */
1269 double deadrows = 0; /* # dead rows seen */
1270 double rowstoskip = -1; /* -1 means not set yet */
1271 uint32 randseed; /* Seed for block sampler(s) */
1274 ReservoirStateData rstate;
1275 TupleTableSlot *slot;
1276 TableScanDesc scan;
1277 BlockNumber nblocks;
1279 ReadStream *stream;
1280
1281 Assert(targrows > 0);
1282
1284
1285 /* Prepare for sampling block numbers */
1287 nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1288
1289 /* Report sampling block numbers */
1291 nblocks);
1292
1293 /* Prepare for sampling rows */
1294 reservoir_init_selection_state(&rstate, targrows);
1295
1297 slot = table_slot_create(onerel, NULL);
1298
1299 /*
1300 * It is safe to use batching, as block_sampling_read_stream_next never
1301 * blocks.
1302 */
1306 scan->rs_rd,
1309 &bs,
1310 0);
1311
1312 /* Outer loop over blocks to sample */
1313 while (table_scan_analyze_next_block(scan, stream))
1314 {
1315 vacuum_delay_point(true);
1316
1317 while (table_scan_analyze_next_tuple(scan, &liverows, &deadrows, slot))
1318 {
1319 /*
1320 * The first targrows sample rows are simply copied into the
1321 * reservoir. Then we start replacing tuples in the sample until
1322 * we reach the end of the relation. This algorithm is from Jeff
1323 * Vitter's paper (see full citation in utils/misc/sampling.c). It
1324 * works by repeatedly computing the number of tuples to skip
1325 * before selecting a tuple, which replaces a randomly chosen
1326 * element of the reservoir (current set of tuples). At all times
1327 * the reservoir is a true random sample of the tuples we've
1328 * passed over so far, so when we fall off the end of the relation
1329 * we're done.
1330 */
1331 if (numrows < targrows)
1332 rows[numrows++] = ExecCopySlotHeapTuple(slot);
1333 else
1334 {
1335 /*
1336 * t in Vitter's paper is the number of records already
1337 * processed. If we need to compute a new S value, we must
1338 * use the not-yet-incremented value of samplerows as t.
1339 */
1340 if (rowstoskip < 0)
1341 rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1342
1343 if (rowstoskip <= 0)
1344 {
1345 /*
1346 * Found a suitable tuple, so save it, replacing one old
1347 * tuple at random
1348 */
1349 int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1350
1351 Assert(k >= 0 && k < targrows);
1352 heap_freetuple(rows[k]);
1353 rows[k] = ExecCopySlotHeapTuple(slot);
1354 }
1355
1356 rowstoskip -= 1;
1357 }
1358
1359 samplerows += 1;
1360 }
1361
1363 ++blksdone);
1364 }
1365
1366 read_stream_end(stream);
1367
1369 table_endscan(scan);
1370
1371 /*
1372 * If we didn't find as many tuples as we wanted then we're done. No sort
1373 * is needed, since they're already in order.
1374 *
1375 * Otherwise we need to sort the collected tuples by position
1376 * (itempointer). It's not worth worrying about corner cases where the
1377 * tuples are already sorted.
1378 */
1379 if (numrows == targrows)
1380 qsort_interruptible(rows, numrows, sizeof(HeapTuple),
1382
1383 /*
1384 * Estimate total numbers of live and dead rows in relation, extrapolating
1385 * on the assumption that the average tuple density in pages we didn't
1386 * scan is the same as in the pages we did scan. Since what we scanned is
1387 * a random sample of the pages in the relation, this should be a good
1388 * assumption.
1389 */
1390 if (bs.m > 0)
1391 {
1392 *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1393 *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1394 }
1395 else
1396 {
1397 *totalrows = 0.0;
1398 *totaldeadrows = 0.0;
1399 }
1400
1401 /*
1402 * Emit some interesting relation info
1403 */
1404 ereport(elevel,
1405 (errmsg("\"%s\": scanned %d of %u pages, "
1406 "containing %.0f live rows and %.0f dead rows; "
1407 "%d rows in sample, %.0f estimated total rows",
1409 bs.m, totalblocks,
1411 numrows, *totalrows)));
1412
1413 return numrows;
1414}
uint32_t uint32
Definition c.h:624
static BufferAccessStrategy vac_strategy
Definition analyze.c:75
static BlockNumber block_sampling_read_stream_next(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition analyze.c:1219
static int compare_rows(const void *a, const void *b, void *arg)
Definition analyze.c:1420
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
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)
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)
void read_stream_end(ReadStream *stream)
#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:1061
static bool table_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
Definition tableam.h:1794
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition tableam.h:1049
static bool table_scan_analyze_next_tuple(TableScanDesc scan, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition tableam.h:1810
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition tuptable.h:503
void vacuum_delay_point(bool is_analyze)
Definition vacuum.c:2433

References Assert, block_sampling_read_stream_next(), BlockSampler_Init(), compare_rows(), ereport, errmsg, ExecCopySlotHeapTuple(), ExecDropSingleTupleTableSlot(), fb(), heap_freetuple(), 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 3038 of file analyze.c.

3044{
3045 double ndistinct_table;
3046 double sumcount;
3047 int i;
3048
3049 /*
3050 * If the entire table was sampled, keep the whole list. This also
3051 * protects us against division by zero in the code below.
3052 */
3053 if (samplerows == totalrows || totalrows <= 1.0)
3054 return num_mcv;
3055
3056 /* Re-extract the estimated number of distinct nonnull values in table */
3057 ndistinct_table = stadistinct;
3058 if (ndistinct_table < 0)
3060
3061 /*
3062 * Exclude the least common values from the MCV list, if they are not
3063 * significantly more common than the estimated selectivity they would
3064 * have if they weren't in the list. All non-MCV values are assumed to be
3065 * equally common, after taking into account the frequencies of all the
3066 * values in the MCV list and the number of nulls (c.f. eqsel()).
3067 *
3068 * Here sumcount tracks the total count of all but the last (least common)
3069 * value in the MCV list, allowing us to determine the effect of excluding
3070 * that value from the list.
3071 *
3072 * Note that we deliberately do this by removing values from the full
3073 * list, rather than starting with an empty list and adding values,
3074 * because the latter approach can fail to add any values if all the most
3075 * common values have around the same frequency and make up the majority
3076 * of the table, so that the overall average frequency of all values is
3077 * roughly the same as that of the common values. This would lead to any
3078 * uncommon values being significantly overestimated.
3079 */
3080 sumcount = 0.0;
3081 for (i = 0; i < num_mcv - 1; i++)
3082 sumcount += mcv_counts[i];
3083
3084 while (num_mcv > 0)
3085 {
3086 double selec,
3088 N,
3089 n,
3090 K,
3091 variance,
3092 stddev;
3093
3094 /*
3095 * Estimated selectivity the least common value would have if it
3096 * wasn't in the MCV list (c.f. eqsel()).
3097 */
3098 selec = 1.0 - sumcount / samplerows - stanullfrac;
3099 if (selec < 0.0)
3100 selec = 0.0;
3101 if (selec > 1.0)
3102 selec = 1.0;
3104 if (otherdistinct > 1)
3106
3107 /*
3108 * If the value is kept in the MCV list, its population frequency is
3109 * assumed to equal its sample frequency. We use the lower end of a
3110 * textbook continuity-corrected Wald-type confidence interval to
3111 * determine if that is significantly more common than the non-MCV
3112 * frequency --- specifically we assume the population frequency is
3113 * highly likely to be within around 2 standard errors of the sample
3114 * frequency, which equates to an interval of 2 standard deviations
3115 * either side of the sample count, plus an additional 0.5 for the
3116 * continuity correction. Since we are sampling without replacement,
3117 * this is a hypergeometric distribution.
3118 *
3119 * XXX: Empirically, this approach seems to work quite well, but it
3120 * may be worth considering more advanced techniques for estimating
3121 * the confidence interval of the hypergeometric distribution.
3122 */
3123 N = totalrows;
3124 n = samplerows;
3125 K = N * mcv_counts[num_mcv - 1] / n;
3126 variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
3127 stddev = sqrt(variance);
3128
3129 if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
3130 {
3131 /*
3132 * The value is significantly more common than the non-MCV
3133 * selectivity would suggest. Keep it, and all the other more
3134 * common values in the list.
3135 */
3136 break;
3137 }
3138 else
3139 {
3140 /* Discard this value and consider the next least common value */
3141 num_mcv--;
3142 if (num_mcv == 0)
3143 break;
3144 sumcount -= mcv_counts[num_mcv - 1];
3145 }
3146 }
3147 return num_mcv;
3148}
#define K(t)
Definition sha1.c:66

References fb(), 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 110 of file analyze.c.

113{
115 int elevel;
117 BlockNumber relpages = 0;
118 bool stats_imported = false;
119
120 /* Select logging level */
121 if (params->options & VACOPT_VERBOSE)
122 elevel = INFO;
123 else
124 elevel = DEBUG2;
125
126 /* Set up static variables */
127 vac_strategy = bstrategy;
128
129 /*
130 * Check for user-requested abort.
131 */
133
134 /*
135 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
136 * ANALYZEs don't run on it concurrently. (This also locks out a
137 * concurrent VACUUM, which doesn't matter much at the moment but might
138 * matter if we ever try to accumulate stats on dead tuples.) If the rel
139 * has been dropped since we last saw it, we don't need to process it.
140 *
141 * Make sure to generate only logs for ANALYZE in this case.
142 */
143 onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
144 params->log_analyze_min_duration >= 0,
146
147 /* leave if relation could not be opened or locked */
148 if (!onerel)
149 return;
150
151 /*
152 * Check if relation needs to be skipped based on privileges. This check
153 * happens also when building the relation list to analyze for a manual
154 * operation, and needs to be done additionally here as ANALYZE could
155 * happen across multiple transactions where privileges could have changed
156 * in-between. Make sure to generate only logs for ANALYZE in this case.
157 */
159 onerel->rd_rel,
160 params->options & ~VACOPT_VACUUM))
161 {
163 return;
164 }
165
166 /*
167 * Silently ignore tables that are temp tables of other backends ---
168 * trying to analyze these is rather pointless, since their contents are
169 * probably not up-to-date on disk. (We don't throw a warning here; it
170 * would just lead to chatter during a database-wide ANALYZE.)
171 */
173 {
175 return;
176 }
177
178 /*
179 * We can ANALYZE any table except pg_statistic. See update_attstats
180 */
182 {
184 return;
185 }
186
187 /*
188 * Check the given list of columns
189 */
190 if (va_cols != NIL)
192
193 /*
194 * Initialize progress reporting before setup for regular/foreign tables.
195 * (For the former, the time spent on it would be negligible, but for the
196 * latter, if FDWs support statistics import or analysis, they'd do some
197 * work that needs the remote access, so the time might be
198 * non-negligible.)
199 */
205 else
208
209 /*
210 * Check that it's of an analyzable relkind, and set up appropriately.
211 */
212 if (onerel->rd_rel->relkind == RELKIND_RELATION ||
213 onerel->rd_rel->relkind == RELKIND_MATVIEW)
214 {
215 /* Regular table, so we'll use the regular row acquisition function */
217 /* Also get regular table's size */
219 }
220 else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
221 {
222 /*
223 * For a foreign table, call the FDW's hook functions to see whether
224 * it supports statistics import or analysis.
225 */
226 FdwRoutine *fdwroutine;
227
228 fdwroutine = GetFdwRoutineForRelation(onerel, false);
229
230 if (fdwroutine->ImportForeignStatistics != NULL &&
231 fdwroutine->ImportForeignStatistics(onerel, va_cols, elevel))
232 stats_imported = true;
233 else
234 {
235 bool ok = false;
236
237 if (fdwroutine->AnalyzeForeignTable != NULL)
238 ok = fdwroutine->AnalyzeForeignTable(onerel,
240 &relpages);
241
242 if (!ok)
243 {
245 errmsg("skipping \"%s\" -- cannot analyze this foreign table.",
248 goto out;
249 }
250 }
251 }
252 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
253 {
254 /*
255 * For partitioned tables, we want to do the recursive ANALYZE below.
256 */
257 }
258 else
259 {
260 /* No need for a WARNING if we already complained during VACUUM */
261 if (!(params->options & VACOPT_VACUUM))
263 (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
266 goto out;
267 }
268
269 /*
270 * Do the normal non-recursive ANALYZE. We can skip this for partitioned
271 * tables, which don't contain any rows, and foreign tables that
272 * successfully imported statistics.
273 */
274 if ((onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
275 && !stats_imported)
276 do_analyze_rel(onerel, params, va_cols, acquirefunc,
277 relpages, false, in_outer_xact, elevel);
278
279 /*
280 * If there are child tables, do recursive ANALYZE.
281 */
282 if (onerel->rd_rel->relhassubclass)
283 do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
284 true, in_outer_xact, elevel);
285
286 /*
287 * Close source relation now, but keep lock so that no one deletes it
288 * before we commit. (If someone did, they'd fail to clean up the entries
289 * we made in pg_statistic. Also, releasing the lock before commit would
290 * expose us to concurrent-update failures in update_attstats.)
291 */
293
294out:
296}
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:306
static void validate_va_cols_list(Relation onerel, List *va_cols)
Definition analyze.c:1047
#define WARNING
Definition elog.h:37
#define DEBUG2
Definition elog.h:30
#define INFO
Definition elog.h:35
#define ShareUpdateExclusiveLock
Definition lockdefs.h:39
#define AmAutoVacuumWorkerProcess()
Definition miscadmin.h:398
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define NIL
Definition pg_list.h:68
#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:206
ImportForeignStatistics_function ImportForeignStatistics
Definition fdwapi.h:262
uint32 options
Definition vacuum.h:218
int log_analyze_min_duration
Definition vacuum.h:230
bool vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple, uint32 options)
Definition vacuum.c:720
Relation vacuum_open_relation(Oid relid, RangeVar *relation, uint32 options, bool verbose, LOCKMODE lmode)
Definition vacuum.c:772
#define VACOPT_VACUUM
Definition vacuum.h:179
#define VACOPT_VERBOSE
Definition vacuum.h:181

References acquire_sample_rows(), AmAutoVacuumWorkerProcess, FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), ereport, errmsg, fb(), GetFdwRoutineForRelation(), FdwRoutine::ImportForeignStatistics, INFO, VacuumParams::log_analyze_min_duration, NIL, 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, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, ShareUpdateExclusiveLock, vac_strategy, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_permitted_for_relation(), vacuum_open_relation(), validate_va_cols_list(), and WARNING.

Referenced by process_single_relation(), and vacuum().

◆ attribute_is_analyzable()

bool attribute_is_analyzable ( Relation  onerel,
int  attnum,
Form_pg_attribute  attr,
int p_attstattarget 
)

Definition at line 1176 of file analyze.c.

1178{
1179 int attstattarget;
1181 Datum dat;
1182 bool isnull;
1183
1184 /* Never analyze dropped columns */
1185 if (attr->attisdropped)
1186 return false;
1187
1188 /* Don't analyze virtual generated columns */
1189 if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
1190 return false;
1191
1192 /*
1193 * Get attstattarget value. Set to -1 if null. (Analyze functions expect
1194 * -1 to mean use default_statistics_target; see for example
1195 * std_typanalyze.)
1196 */
1199 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1202 attstattarget = isnull ? -1 : DatumGetInt16(dat);
1204
1205 /* Don't analyze column if user has specified not to */
1206 if (attstattarget == 0)
1207 return false;
1208
1209 if (p_attstattarget)
1210 *p_attstattarget = attstattarget;
1211 return true;
1212}
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define HeapTupleIsValid(tuple)
Definition htup.h:78
int16 attnum
static Datum Int16GetDatum(int16 X)
Definition postgres.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static int16 DatumGetInt16(Datum X)
Definition postgres.h:162
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:231
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596

References attnum, DatumGetInt16(), elog, ERROR, fb(), HeapTupleIsValid, Int16GetDatum(), ObjectIdGetDatum(), RelationGetRelid, ReleaseSysCache(), SearchSysCache2(), and SysCacheGetAttr().

Referenced by build_remattrmap(), and examine_attribute().

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

1222{
1223 BlockSamplerData *bs = callback_private_data;
1224
1226}
#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(), fb(), 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 3020 of file analyze.c.

3021{
3022 int da = ((const ScalarMCVItem *) a)->first;
3023 int db = ((const ScalarMCVItem *) b)->first;
3024
3025 return da - db;
3026}
int b
Definition isn.c:74
int a
Definition isn.c:73

References a, b, and fb().

Referenced by compute_scalar_stats().

◆ compare_rows()

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

Definition at line 1420 of file analyze.c.

1421{
1422 HeapTuple ha = *(const HeapTuple *) a;
1423 HeapTuple hb = *(const HeapTuple *) b;
1428
1429 if (ba < bb)
1430 return -1;
1431 if (ba > bb)
1432 return 1;
1433 if (oa < ob)
1434 return -1;
1435 if (oa > ob)
1436 return 1;
1437 return 0;
1438}
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

References a, b, fb(), ItemPointerGetBlockNumber(), and ItemPointerGetOffsetNumber().

Referenced by acquire_sample_rows().

◆ compare_scalars()

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

Definition at line 2989 of file analyze.c.

2990{
2991 Datum da = ((const ScalarItem *) a)->value;
2992 int ta = ((const ScalarItem *) a)->tupno;
2993 Datum db = ((const ScalarItem *) b)->value;
2994 int tb = ((const ScalarItem *) b)->tupno;
2996 int compare;
2997
2998 compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2999 if (compare != 0)
3000 return compare;
3001
3002 /*
3003 * The two datums are equal, so update cxt->tupnoLink[].
3004 */
3005 if (cxt->tupnoLink[ta] < tb)
3006 cxt->tupnoLink[ta] = tb;
3007 if (cxt->tupnoLink[tb] < ta)
3008 cxt->tupnoLink[tb] = ta;
3009
3010 /*
3011 * For equal datums, sort by tupno
3012 */
3013 return ta - tb;
3014}
Datum arg
Definition elog.c:1322
static int compare(const void *arg1, const void *arg2)
Definition geqo_pool.c:144
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)

References a, ApplySortComparator(), arg, b, compare(), fb(), 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 2117 of file analyze.c.

2121{
2122 int i;
2123 int null_cnt = 0;
2124 int nonnull_cnt = 0;
2125 int toowide_cnt = 0;
2126 double total_width = 0;
2127 bool is_varlena = (!stats->attrtype->typbyval &&
2128 stats->attrtype->typlen == -1);
2129 bool is_varwidth = (!stats->attrtype->typbyval &&
2130 stats->attrtype->typlen < 0);
2132 typedef struct
2133 {
2134 Datum value;
2135 int count;
2136 } TrackItem;
2138 int track_cnt,
2139 track_max;
2140 int num_mcv = stats->attstattarget;
2142
2143 /*
2144 * We track up to 2*n values for an n-element MCV list; but at least 10
2145 */
2146 track_max = 2 * num_mcv;
2147 if (track_max < 10)
2148 track_max = 10;
2149 track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
2150 track_cnt = 0;
2151
2152 fmgr_info(mystats->eqfunc, &f_cmpeq);
2153
2154 for (i = 0; i < samplerows; i++)
2155 {
2156 Datum value;
2157 bool isnull;
2158 bool match;
2159 int firstcount1,
2160 j;
2161
2162 vacuum_delay_point(true);
2163
2164 value = fetchfunc(stats, i, &isnull);
2165
2166 /* Check for null/nonnull */
2167 if (isnull)
2168 {
2169 null_cnt++;
2170 continue;
2171 }
2172 nonnull_cnt++;
2173
2174 /*
2175 * If it's a variable-width field, add up widths for average width
2176 * calculation. Note that if the value is toasted, we use the toasted
2177 * width. We don't bother with this calculation if it's a fixed-width
2178 * type.
2179 */
2180 if (is_varlena)
2181 {
2183
2184 /*
2185 * If the value is toasted, we want to detoast it just once to
2186 * avoid repeated detoastings and resultant excess memory usage
2187 * during the comparisons. Also, check to see if the value is
2188 * excessively wide, and if so don't detoast at all --- just
2189 * ignore the value.
2190 */
2192 {
2193 toowide_cnt++;
2194 continue;
2195 }
2197 }
2198 else if (is_varwidth)
2199 {
2200 /* must be cstring */
2202 }
2203
2204 /*
2205 * See if the value matches anything we're already tracking.
2206 */
2207 match = false;
2209 for (j = 0; j < track_cnt; j++)
2210 {
2212 stats->attrcollid,
2213 value, track[j].value)))
2214 {
2215 match = true;
2216 break;
2217 }
2218 if (j < firstcount1 && track[j].count == 1)
2219 firstcount1 = j;
2220 }
2221
2222 if (match)
2223 {
2224 /* Found a match */
2225 track[j].count++;
2226 /* This value may now need to "bubble up" in the track list */
2227 while (j > 0 && track[j].count > track[j - 1].count)
2228 {
2229 swapDatum(track[j].value, track[j - 1].value);
2230 swapInt(track[j].count, track[j - 1].count);
2231 j--;
2232 }
2233 }
2234 else
2235 {
2236 /* No match. Insert at head of count-1 list */
2237 if (track_cnt < track_max)
2238 track_cnt++;
2239 for (j = track_cnt - 1; j > firstcount1; j--)
2240 {
2241 track[j].value = track[j - 1].value;
2242 track[j].count = track[j - 1].count;
2243 }
2244 if (firstcount1 < track_cnt)
2245 {
2246 track[firstcount1].value = value;
2247 track[firstcount1].count = 1;
2248 }
2249 }
2250 }
2251
2252 /* We can only compute real stats if we found some non-null values. */
2253 if (nonnull_cnt > 0)
2254 {
2255 int nmultiple,
2257
2258 stats->stats_valid = true;
2259 /* Do the simple null-frac and width stats */
2260 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2261 if (is_varwidth)
2263 else
2264 stats->stawidth = stats->attrtype->typlen;
2265
2266 /* Count the number of values we found multiple times */
2267 summultiple = 0;
2268 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2269 {
2270 if (track[nmultiple].count == 1)
2271 break;
2272 summultiple += track[nmultiple].count;
2273 }
2274
2275 if (nmultiple == 0)
2276 {
2277 /*
2278 * If we found no repeated non-null values, assume it's a unique
2279 * column; but be sure to discount for any nulls we found.
2280 */
2281 stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2282 }
2283 else if (track_cnt < track_max && toowide_cnt == 0 &&
2285 {
2286 /*
2287 * Our track list includes every value in the sample, and every
2288 * value appeared more than once. Assume the column has just
2289 * these values. (This case is meant to address columns with
2290 * small, fixed sets of possible values, such as boolean or enum
2291 * columns. If there are any values that appear just once in the
2292 * sample, including too-wide values, we should assume that that's
2293 * not what we're dealing with.)
2294 */
2295 stats->stadistinct = track_cnt;
2296 }
2297 else
2298 {
2299 /*----------
2300 * Estimate the number of distinct values using the estimator
2301 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2302 * n*d / (n - f1 + f1*n/N)
2303 * where f1 is the number of distinct values that occurred
2304 * exactly once in our sample of n rows (from a total of N),
2305 * and d is the total number of distinct values in the sample.
2306 * This is their Duj1 estimator; the other estimators they
2307 * recommend are considerably more complex, and are numerically
2308 * very unstable when n is much smaller than N.
2309 *
2310 * In this calculation, we consider only non-nulls. We used to
2311 * include rows with null values in the n and N counts, but that
2312 * leads to inaccurate answers in columns with many nulls, and
2313 * it's intuitively bogus anyway considering the desired result is
2314 * the number of distinct non-null values.
2315 *
2316 * We assume (not very reliably!) that all the multiply-occurring
2317 * values are reflected in the final track[] list, and the other
2318 * nonnull values all appeared but once. (XXX this usually
2319 * results in a drastic overestimate of ndistinct. Can we do
2320 * any better?)
2321 *----------
2322 */
2323 int f1 = nonnull_cnt - summultiple;
2324 int d = f1 + nmultiple;
2325 double n = samplerows - null_cnt;
2326 double N = totalrows * (1.0 - stats->stanullfrac);
2327 double stadistinct;
2328
2329 /* N == 0 shouldn't happen, but just in case ... */
2330 if (N > 0)
2331 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2332 else
2333 stadistinct = 0;
2334
2335 /* Clamp to sane range in case of roundoff error */
2336 if (stadistinct < d)
2337 stadistinct = d;
2338 if (stadistinct > N)
2339 stadistinct = N;
2340 /* And round to integer */
2341 stats->stadistinct = floor(stadistinct + 0.5);
2342 }
2343
2344 /*
2345 * If we estimated the number of distinct values at more than 10% of
2346 * the total row count (a very arbitrary limit), then assume that
2347 * stadistinct should scale with the row count rather than be a fixed
2348 * value.
2349 */
2350 if (stats->stadistinct > 0.1 * totalrows)
2351 stats->stadistinct = -(stats->stadistinct / totalrows);
2352
2353 /*
2354 * Decide how many values are worth storing as most-common values. If
2355 * we are able to generate a complete MCV list (all the values in the
2356 * sample will fit, and we think these are all the ones in the table),
2357 * then do so. Otherwise, store only those values that are
2358 * significantly more common than the values not in the list.
2359 *
2360 * Note: the first of these cases is meant to address columns with
2361 * small, fixed sets of possible values, such as boolean or enum
2362 * columns. If we can *completely* represent the column population by
2363 * an MCV list that will fit into the stats target, then we should do
2364 * so and thus provide the planner with complete information. But if
2365 * the MCV list is not complete, it's generally worth being more
2366 * selective, and not just filling it all the way up to the stats
2367 * target.
2368 */
2369 if (track_cnt < track_max && toowide_cnt == 0 &&
2370 stats->stadistinct > 0 &&
2371 track_cnt <= num_mcv)
2372 {
2373 /* Track list includes all values seen, and all will fit */
2375 }
2376 else
2377 {
2378 int *mcv_counts;
2379
2380 /* Incomplete list; decide how many values are worth keeping */
2381 if (num_mcv > track_cnt)
2383
2384 if (num_mcv > 0)
2385 {
2386 mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2387 for (i = 0; i < num_mcv; i++)
2388 mcv_counts[i] = track[i].count;
2389
2391 stats->stadistinct,
2392 stats->stanullfrac,
2393 samplerows, totalrows);
2394 }
2395 }
2396
2397 /* Generate MCV slot entry */
2398 if (num_mcv > 0)
2399 {
2403
2404 /* Must copy the target values into anl_context */
2406 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2407 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2408 for (i = 0; i < num_mcv; i++)
2409 {
2411 stats->attrtype->typbyval,
2412 stats->attrtype->typlen);
2413 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2414 }
2416
2417 stats->stakind[0] = STATISTIC_KIND_MCV;
2418 stats->staop[0] = mystats->eqopr;
2419 stats->stacoll[0] = stats->attrcollid;
2420 stats->stanumbers[0] = mcv_freqs;
2421 stats->numnumbers[0] = num_mcv;
2422 stats->stavalues[0] = mcv_values;
2423 stats->numvalues[0] = num_mcv;
2424
2425 /*
2426 * Accept the defaults for stats->statypid and others. They have
2427 * been set before we were called (see vacuum.h)
2428 */
2429 }
2430 }
2431 else if (null_cnt > 0)
2432 {
2433 /* We found only nulls; assume the column is entirely null */
2434 stats->stats_valid = true;
2435 stats->stanullfrac = 1.0;
2436 if (is_varwidth)
2437 stats->stawidth = 0; /* "unknown" */
2438 else
2439 stats->stawidth = stats->attrtype->typlen;
2440 stats->stadistinct = 0.0; /* "unknown" */
2441 }
2442
2443 /* We don't need to bother cleaning up any of our temporary palloc's */
2444}
float float4
Definition c.h:713
#define swapInt(a, b)
Definition analyze.c:1904
#define swapDatum(a, b)
Definition analyze.c:1905
#define WIDTH_THRESHOLD
Definition analyze.c:1902
static int analyze_mcv_list(int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
Definition analyze.c:3038
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:1151
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition fmgr.c:129
#define PG_DETOAST_DATUM(datum)
Definition fmgr.h:240
static struct @177 value
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:342
static char * DatumGetCString(Datum X)
Definition postgres.h:355
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
int f1[ARRAY_SIZE]
bool stats_valid
Definition vacuum.h:143
float4 stanullfrac
Definition vacuum.h:144
Form_pg_type attrtype
Definition vacuum.h:127
int16 stakind[STATISTIC_NUM_SLOTS]
Definition vacuum.h:147
MemoryContext anl_context
Definition vacuum.h:129
Oid staop[STATISTIC_NUM_SLOTS]
Definition vacuum.h:148
Oid stacoll[STATISTIC_NUM_SLOTS]
Definition vacuum.h:149
float4 * stanumbers[STATISTIC_NUM_SLOTS]
Definition vacuum.h:151
int attstattarget
Definition vacuum.h:124
int32 stawidth
Definition vacuum.h:145
void * extra_data
Definition vacuum.h:137
int numvalues[STATISTIC_NUM_SLOTS]
Definition vacuum.h:152
Datum * stavalues[STATISTIC_NUM_SLOTS]
Definition vacuum.h:153
float4 stadistinct
Definition vacuum.h:146
int numnumbers[STATISTIC_NUM_SLOTS]
Definition vacuum.h:150
Oid attrcollid
Definition vacuum.h:128
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(), VacAttrStats::extra_data, f1, fb(), fmgr_info(), FunctionCall2Coll(), i, 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 877 of file analyze.c.

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

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, anl_context, attnum, VacAttrStats::attrtype, VacAttrStats::compute_stats, CreateExecutorState(), datumCopy(), ExprContext::ecxt_scantuple, ExecDropSingleTupleTableSlot(), ExecPrepareQual(), ExecQual(), ExecStoreHeapTuple(), VacAttrStats::exprnulls, VacAttrStats::exprvals, fb(), FormIndexDatum(), FreeExecutorState(), GetPerTupleExprContext, i, IndexInfo::ii_Predicate, ind_fetch_func(), INDEX_MAX_KEYS, MakeSingleTupleTableSlot(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), NIL, palloc(), RelationGetDescr, ResetExprContext, VacAttrStats::rowstride, TTSOpsHeapTuple, VacAttrStats::tupattnum, 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 2460 of file analyze.c.

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

References SortSupportData::abbreviate, analyze_mcv_list(), VacAttrStats::anl_context, Assert, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attstattarget, compare_mcvs(), compare_scalars(), CurrentMemoryContext, datumCopy(), DatumGetCString(), DatumGetPointer(), VacAttrStats::extra_data, f1, fb(), i, j, 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 2027 of file analyze.c.

2031{
2032 int i;
2033 int null_cnt = 0;
2034 int nonnull_cnt = 0;
2035 double total_width = 0;
2036 bool is_varlena = (!stats->attrtype->typbyval &&
2037 stats->attrtype->typlen == -1);
2038 bool is_varwidth = (!stats->attrtype->typbyval &&
2039 stats->attrtype->typlen < 0);
2040
2041 for (i = 0; i < samplerows; i++)
2042 {
2043 Datum value;
2044 bool isnull;
2045
2046 vacuum_delay_point(true);
2047
2048 value = fetchfunc(stats, i, &isnull);
2049
2050 /* Check for null/nonnull */
2051 if (isnull)
2052 {
2053 null_cnt++;
2054 continue;
2055 }
2056 nonnull_cnt++;
2057
2058 /*
2059 * If it's a variable-width field, add up widths for average width
2060 * calculation. Note that if the value is toasted, we use the toasted
2061 * width. We don't bother with this calculation if it's a fixed-width
2062 * type.
2063 */
2064 if (is_varlena)
2065 {
2067 }
2068 else if (is_varwidth)
2069 {
2070 /* must be cstring */
2072 }
2073 }
2074
2075 /* We can only compute average width if we found some non-null values. */
2076 if (nonnull_cnt > 0)
2077 {
2078 stats->stats_valid = true;
2079 /* Do the simple null-frac and width stats */
2080 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2081 if (is_varwidth)
2083 else
2084 stats->stawidth = stats->attrtype->typlen;
2085 stats->stadistinct = 0.0; /* "unknown" */
2086 }
2087 else if (null_cnt > 0)
2088 {
2089 /* We found only nulls; assume the column is entirely null */
2090 stats->stats_valid = true;
2091 stats->stanullfrac = 1.0;
2092 if (is_varwidth)
2093 stats->stawidth = 0; /* "unknown" */
2094 else
2095 stats->stawidth = stats->attrtype->typlen;
2096 stats->stadistinct = 0.0; /* "unknown" */
2097 }
2098}

References VacAttrStats::attrtype, DatumGetCString(), DatumGetPointer(), fb(), 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 306 of file analyze.c.

310{
311 int attr_cnt,
312 tcnt,
313 i,
314 ind;
315 Relation *Irel;
316 int nindexes;
317 bool verbose,
318 instrument,
319 hasindex;
320 VacAttrStats **vacattrstats;
322 int targrows,
323 numrows,
324 minrows;
325 double totalrows,
327 HeapTuple *rows;
329 TimestampTz starttime = 0;
331 Oid save_userid;
332 int save_sec_context;
333 int save_nestlevel;
336 BufferUsage bufferusage;
339
340 verbose = (params->options & VACOPT_VERBOSE) != 0;
341 instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
342 params->log_analyze_min_duration >= 0));
343 if (inh)
344 ereport(elevel,
345 (errmsg("analyzing \"%s.%s\" inheritance tree",
348 else
349 ereport(elevel,
350 (errmsg("analyzing \"%s.%s\"",
353
354 /*
355 * Set up a working context so that we can easily free whatever junk gets
356 * created.
357 */
359 "Analyze",
362
363 /*
364 * Switch to the table owner's userid, so that any index functions are run
365 * as that user. Also lock down security-restricted operations and
366 * arrange to make GUC variable changes local to this command.
367 */
368 GetUserIdAndSecContext(&save_userid, &save_sec_context);
369 SetUserIdAndSecContext(onerel->rd_rel->relowner,
370 save_sec_context | SECURITY_RESTRICTED_OPERATION);
371 save_nestlevel = NewGUCNestLevel();
373
374 /*
375 * When verbose or autovacuum logging is used, initialize a resource usage
376 * snapshot and optionally track I/O timing.
377 */
378 if (instrument)
379 {
380 if (track_io_timing)
381 {
384 }
385
387 }
388
389 /* Used for instrumentation and stats report */
390 starttime = GetCurrentTimestamp();
391
392 /*
393 * Determine which columns to analyze.
394 */
395 if (va_cols != NIL)
396 {
397 ListCell *le;
398
399 vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
400 sizeof(VacAttrStats *));
401 tcnt = 0;
402 foreach(le, va_cols)
403 {
404 char *col = strVal(lfirst(le));
405
406 i = attnameAttNum(onerel, col, false);
408 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
409 if (vacattrstats[tcnt] != NULL)
410 tcnt++;
411 }
412 attr_cnt = tcnt;
413 }
414 else
415 {
416 attr_cnt = onerel->rd_att->natts;
417 vacattrstats = (VacAttrStats **)
418 palloc(attr_cnt * sizeof(VacAttrStats *));
419 tcnt = 0;
420 for (i = 1; i <= attr_cnt; i++)
421 {
422 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
423 if (vacattrstats[tcnt] != NULL)
424 tcnt++;
425 }
426 attr_cnt = tcnt;
427 }
428
429 /*
430 * Open all indexes of the relation, and see if there are any analyzable
431 * columns in the indexes. We do not analyze index columns if there was
432 * an explicit column list in the ANALYZE command, however.
433 *
434 * If we are doing a recursive scan, we don't want to touch the parent's
435 * indexes at all. If we're processing a partitioned table, we need to
436 * know if there are any indexes, but we don't want to process them.
437 */
438 if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
439 {
441
442 Irel = NULL;
443 nindexes = 0;
444 hasindex = idxs != NIL;
446 }
447 else if (!inh)
448 {
450 hasindex = nindexes > 0;
451 }
452 else
453 {
454 Irel = NULL;
455 nindexes = 0;
456 hasindex = false;
457 }
458 indexdata = NULL;
459 if (nindexes > 0)
460 {
461 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
462 for (ind = 0; ind < nindexes; ind++)
463 {
465 IndexInfo *indexInfo;
466
467 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
468 thisdata->tupleFract = 1.0; /* fix later if partial */
469 if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
470 {
472
473 thisdata->vacattrstats = (VacAttrStats **)
474 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
475 tcnt = 0;
476 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
477 {
478 int keycol = indexInfo->ii_IndexAttrNumbers[i];
479
480 if (keycol == 0)
481 {
482 /* Found an index expression */
483 Node *indexkey;
484
485 if (indexpr_item == NULL) /* shouldn't happen */
486 elog(ERROR, "too few entries in indexprs list");
488 indexpr_item = lnext(indexInfo->ii_Expressions,
490 thisdata->vacattrstats[tcnt] =
492 if (thisdata->vacattrstats[tcnt] != NULL)
493 tcnt++;
494 }
495 }
496 thisdata->attr_cnt = tcnt;
497 }
498 }
499 }
500
501 /*
502 * Determine how many rows we need to sample, using the worst case from
503 * all analyzable columns. We use a lower bound of 100 rows to avoid
504 * possible overflow in Vitter's algorithm. (Note: that will also be the
505 * target in the corner case where there are no analyzable columns.)
506 */
507 targrows = 100;
508 for (i = 0; i < attr_cnt; i++)
509 {
510 if (targrows < vacattrstats[i]->minrows)
511 targrows = vacattrstats[i]->minrows;
512 }
513 for (ind = 0; ind < nindexes; ind++)
514 {
516
517 for (i = 0; i < thisdata->attr_cnt; i++)
518 {
519 if (targrows < thisdata->vacattrstats[i]->minrows)
520 targrows = thisdata->vacattrstats[i]->minrows;
521 }
522 }
523
524 /*
525 * Look at extended statistics objects too, as those may define custom
526 * statistics target. So we may need to sample more rows and then build
527 * the statistics with enough detail.
528 */
529 minrows = ComputeExtStatisticsRows(onerel, attr_cnt, vacattrstats);
530
531 if (targrows < minrows)
532 targrows = minrows;
533
534 /*
535 * Acquire the sample rows
536 */
537 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
541 if (inh)
542 numrows = acquire_inherited_sample_rows(onerel, elevel,
543 rows, targrows,
545 else
546 numrows = (*acquirefunc) (onerel, elevel,
547 rows, targrows,
549
550 /*
551 * Compute the statistics. Temporary results during the calculations for
552 * each column are stored in a child context. The calc routines are
553 * responsible to make sure that whatever they store into the VacAttrStats
554 * structure is allocated in anl_context.
555 */
556 if (numrows > 0)
557 {
560
563
565 "Analyze Column",
568
569 for (i = 0; i < attr_cnt; i++)
570 {
571 VacAttrStats *stats = vacattrstats[i];
573
574 stats->rows = rows;
575 stats->tupDesc = onerel->rd_att;
576 stats->compute_stats(stats,
578 numrows,
579 totalrows);
580
581 /*
582 * If the appropriate flavor of the n_distinct option is
583 * specified, override with the corresponding value.
584 */
585 aopt = get_attribute_options(onerel->rd_id, stats->tupattnum);
586 if (aopt != NULL)
587 {
588 float8 n_distinct;
589
590 n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
591 if (n_distinct != 0.0)
592 stats->stadistinct = n_distinct;
593 }
594
596 }
597
598 if (nindexes > 0)
600 indexdata, nindexes,
601 rows, numrows,
603
606
607 /*
608 * Emit the completed stats rows into pg_statistic, replacing any
609 * previous statistics for the target columns. (If there are stats in
610 * pg_statistic for columns we didn't process, we leave them alone.)
611 */
613 attr_cnt, vacattrstats);
614
615 for (ind = 0; ind < nindexes; ind++)
616 {
618
620 thisdata->attr_cnt, thisdata->vacattrstats);
621 }
622
623 /* Build extended statistics (if there are any). */
624 BuildRelationExtStatistics(onerel, inh, totalrows, numrows, rows,
625 attr_cnt, vacattrstats);
626 }
627
630
631 /*
632 * Update pages/tuples stats in pg_class ... but not if we're doing
633 * inherited stats.
634 *
635 * We assume that VACUUM hasn't set pg_class.reltuples already, even
636 * during a VACUUM ANALYZE. Although VACUUM often updates pg_class,
637 * exceptions exist. A "VACUUM (ANALYZE, INDEX_CLEANUP OFF)" command will
638 * never update pg_class entries for index relations. It's also possible
639 * that an individual index's pg_class entry won't be updated during
640 * VACUUM if the index AM returns NULL from its amvacuumcleanup() routine.
641 */
642 if (!inh)
643 {
644 BlockNumber relallvisible = 0;
645 BlockNumber relallfrozen = 0;
646
647 if (RELKIND_HAS_STORAGE(onerel->rd_rel->relkind))
648 visibilitymap_count(onerel, &relallvisible, &relallfrozen);
649
650 /*
651 * Update pg_class for table relation. CCI first, in case acquirefunc
652 * updated pg_class.
653 */
656 relpages,
657 totalrows,
658 relallvisible,
659 relallfrozen,
660 hasindex,
663 NULL, NULL,
665
666 /* Same for indexes */
667 for (ind = 0; ind < nindexes; ind++)
668 {
670 double totalindexrows;
671
672 totalindexrows = ceil(thisdata->tupleFract * totalrows);
676 0, 0,
677 false,
680 NULL, NULL,
682 }
683 }
684 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
685 {
686 /*
687 * Partitioned tables don't have storage, so we don't set any fields
688 * in their pg_class entries except for reltuples and relhasindex.
689 */
692 0, 0, hasindex, InvalidTransactionId,
694 NULL, NULL,
696 }
697
698 /*
699 * Now report ANALYZE to the cumulative stats system. For regular tables,
700 * we do it only if not doing inherited stats. For partitioned tables, we
701 * only do it for inherited stats. (We're never called for not-inherited
702 * stats on partitioned tables anyway.)
703 *
704 * Reset the mod_since_analyze counter only if we analyzed all columns;
705 * otherwise, there is still work for auto-analyze to do.
706 */
707 if (!inh)
709 (va_cols == NIL), starttime);
710 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
711 pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL), starttime);
712
713 /*
714 * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
715 *
716 * Note that most index AMs perform a no-op as a matter of policy for
717 * amvacuumcleanup() when called in ANALYZE-only mode. The only exception
718 * among core index AMs is GIN/ginvacuumcleanup().
719 */
720 if (!(params->options & VACOPT_VACUUM))
721 {
722 for (ind = 0; ind < nindexes; ind++)
723 {
726
727 ivinfo.index = Irel[ind];
728 ivinfo.heaprel = onerel;
729 ivinfo.analyze_only = true;
730 ivinfo.estimated_count = true;
731 ivinfo.message_level = elevel;
732 ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
733 ivinfo.strategy = vac_strategy;
734
736
737 if (stats)
738 pfree(stats);
739 }
740 }
741
742 /* Done with indexes */
743 vac_close_indexes(nindexes, Irel, NoLock);
744
745 /* Log the action if appropriate */
746 if (instrument)
747 {
749
750 if (verbose || params->log_analyze_min_duration == 0 ||
753 {
754 long delay_in_ms;
755 WalUsage walusage;
756 double read_rate = 0;
757 double write_rate = 0;
758 char *msgfmt;
763
764 memset(&bufferusage, 0, sizeof(BufferUsage));
766 memset(&walusage, 0, sizeof(WalUsage));
768
769 total_blks_hit = bufferusage.shared_blks_hit +
770 bufferusage.local_blks_hit;
771 total_blks_read = bufferusage.shared_blks_read +
772 bufferusage.local_blks_read;
774 bufferusage.local_blks_dirtied;
775
776 /*
777 * We do not expect an analyze to take > 25 days and it simplifies
778 * things a bit to use TimestampDifferenceMilliseconds.
779 */
781
782 /*
783 * Note that we are reporting these read/write rates in the same
784 * manner as VACUUM does, which means that while the 'average read
785 * rate' here actually corresponds to page misses and resulting
786 * reads which are also picked up by track_io_timing, if enabled,
787 * the 'average write rate' is actually talking about the rate of
788 * pages being dirtied, not being written out, so it's typical to
789 * have a non-zero 'avg write rate' while I/O timings only reports
790 * reads.
791 *
792 * It's not clear that an ANALYZE will ever result in
793 * FlushBuffer() being called, but we track and support reporting
794 * on I/O write time in case that changes as it's practically free
795 * to do so anyway.
796 */
797
798 if (delay_in_ms > 0)
799 {
801 (1024 * 1024) / (delay_in_ms / 1000.0);
803 (1024 * 1024) / (delay_in_ms / 1000.0);
804 }
805
806 /*
807 * We split this up so we don't emit empty I/O timing values when
808 * track_io_timing isn't enabled.
809 */
810
812
814 msgfmt = _("automatic analyze of table \"%s.%s.%s\"\n");
815 else
816 msgfmt = _("finished analyzing table \"%s.%s.%s\"\n");
817
823 {
824 /*
825 * We bypass the changecount mechanism because this value is
826 * only updated by the calling process.
827 */
828 appendStringInfo(&buf, _("delay time: %.3f ms\n"),
830 }
831 if (track_io_timing)
832 {
833 double read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
835
836 appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
838 }
839 appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
841 appendStringInfo(&buf, _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
846 _("WAL usage: %" PRId64 " records, %" PRId64 " full page images, %" PRIu64 " bytes, %" PRIu64 " full page image bytes, %" PRId64 " buffers full\n"),
847 walusage.wal_records,
848 walusage.wal_fpi,
849 walusage.wal_bytes,
850 walusage.wal_fpi_bytes,
851 walusage.wal_buffers_full);
852 appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
853
855 (errmsg_internal("%s", buf.data)));
856
857 pfree(buf.data);
858 }
859 }
860
861 /* Roll back any GUC changes executed by index functions */
862 AtEOXact_GUC(false, save_nestlevel);
863
864 /* Restore userid and security context */
865 SetUserIdAndSecContext(save_userid, save_sec_context);
866
867 /* Restore current context and release memory */
871}
#define InvalidAttrNumber
Definition attnum.h:23
AttributeOpts * get_attribute_options(Oid attrelid, int attnum)
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.c:1751
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1775
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
PgBackendStatus * MyBEEntry
bool track_io_timing
Definition bufmgr.c:192
double float8
Definition c.h:714
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
Definition analyze.c:1856
static void update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
Definition analyze.c:1714
static int acquire_inherited_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition analyze.c:1450
static VacAttrStats * examine_attribute(Relation onerel, int attnum, Node *index_expr)
Definition analyze.c:1082
static void compute_index_stats(Relation onerel, double totalrows, AnlIndexData *indexdata, int nindexes, HeapTuple *rows, int numrows, MemoryContext col_context)
Definition analyze.c:877
int64 TimestampTz
Definition timestamp.h:39
#define _(x)
Definition elog.c:95
#define LOG
Definition elog.h:32
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
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:96
int NewGUCNestLevel(void)
Definition guc.c:2142
void RestrictSearchPath(void)
Definition guc.c:2153
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition guc.c:2169
IndexInfo * BuildIndexInfo(Relation index)
Definition index.c:2446
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition indexam.c:794
WalUsage pgWalUsage
Definition instrument.c:27
void WalUsageAccumDiff(WalUsage *dst, const WalUsage *add, const WalUsage *sub)
Definition instrument.c:367
BufferUsage pgBufferUsage
Definition instrument.c:25
void BufferUsageAccumDiff(BufferUsage *dst, const BufferUsage *add, const BufferUsage *sub)
Definition instrument.c:327
void list_free(List *list)
Definition list.c:1546
char * get_database_name(Oid dbid)
Definition lsyscache.c:1312
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
#define SECURITY_RESTRICTED_OPERATION
Definition miscadmin.h:331
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition miscinit.c:613
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition miscinit.c:620
#define InvalidMultiXactId
Definition multixact.h:25
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
static int verbose
const void * data
#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:375
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]
int64 PgStat_Counter
Definition pgstat.h:71
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:4827
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
VacAttrStats ** vacattrstats
Definition analyze.c:65
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:181
List * ii_Expressions
Definition execnodes.h:192
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition execnodes.h:189
Relation index
Definition genam.h:54
Definition nodes.h:135
int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM]
Form_pg_class rd_rel
Definition rel.h:111
HeapTuple * rows
Definition vacuum.h:171
int minrows
Definition vacuum.h:136
TupleDesc tupDesc
Definition vacuum.h:172
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:83
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition vacuum.c:2369
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition vacuum.c:2412
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:1427
#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, anl_context, appendStringInfo(), Assert, AtEOXact_GUC(), attnameAttNum(), buf, BufferUsageAccumDiff(), BuildIndexInfo(), BuildRelationExtStatistics(), CommandCounterIncrement(), compute_index_stats(), VacAttrStats::compute_stats, ComputeExtStatisticsRows(), CurrentMemoryContext, elog, ereport, errmsg, errmsg_internal(), ERROR, examine_attribute(), fb(), get_attribute_options(), get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GetUserIdAndSecContext(), i, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, IndexInfo::ii_NumIndexAttrs, IndexVacuumInfo::index, index_vacuum_cleanup(), 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(), VacAttrStats::minrows, MyBEEntry, MyDatabaseId, NewGUCNestLevel(), NIL, NoLock, 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_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(), strVal, TimestampDifferenceExceeds(), TimestampDifferenceMilliseconds(), track_cost_delay_timing, track_io_timing, VacAttrStats::tupattnum, VacAttrStats::tupDesc, 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 1082 of file analyze.c.

1083{
1084 Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1085 int attstattarget;
1087 VacAttrStats *stats;
1088 int i;
1089 bool ok;
1090
1091 /*
1092 * Check if the column is analyzable.
1093 */
1094 if (!attribute_is_analyzable(onerel, attnum, attr, &attstattarget))
1095 return NULL;
1096
1097 /*
1098 * Create the VacAttrStats struct.
1099 */
1101 stats->attstattarget = attstattarget;
1102
1103 /*
1104 * When analyzing an expression index, believe the expression tree's type
1105 * not the column datatype --- the latter might be the opckeytype storage
1106 * type of the opclass, which is not interesting for our purposes. (Note:
1107 * if we did anything with non-expression index columns, we'd need to
1108 * figure out where to get the correct type info from, but for now that's
1109 * not a problem.) It's not clear whether anyone will care about the
1110 * typmod, but we store that too just in case.
1111 */
1112 if (index_expr)
1113 {
1114 stats->attrtypid = exprType(index_expr);
1116
1117 /*
1118 * If a collation has been specified for the index column, use that in
1119 * preference to anything else; but if not, fall back to whatever we
1120 * can get from the expression.
1121 */
1122 if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1123 stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1124 else
1126 }
1127 else
1128 {
1129 stats->attrtypid = attr->atttypid;
1130 stats->attrtypmod = attr->atttypmod;
1131 stats->attrcollid = attr->attcollation;
1132 }
1133
1135 ObjectIdGetDatum(stats->attrtypid));
1137 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1139 stats->anl_context = anl_context;
1140 stats->tupattnum = attnum;
1141
1142 /*
1143 * The fields describing the stats->stavalues[n] element types default to
1144 * the type of the data being analyzed, but the type-specific typanalyze
1145 * function can change them if it wants to store something else.
1146 */
1147 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1148 {
1149 stats->statypid[i] = stats->attrtypid;
1150 stats->statyplen[i] = stats->attrtype->typlen;
1151 stats->statypbyval[i] = stats->attrtype->typbyval;
1152 stats->statypalign[i] = stats->attrtype->typalign;
1153 }
1154
1155 /*
1156 * Call the type-specific typanalyze function. If none is specified, use
1157 * std_typanalyze().
1158 */
1159 if (OidIsValid(stats->attrtype->typanalyze))
1160 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1161 PointerGetDatum(stats)));
1162 else
1163 ok = std_typanalyze(stats);
1164
1165 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1166 {
1168 pfree(stats);
1169 return NULL;
1170 }
1171
1172 return stats;
1173}
#define OidIsValid(objectId)
Definition c.h:858
bool attribute_is_analyzable(Relation onerel, int attnum, Form_pg_attribute attr, int *p_attstattarget)
Definition analyze.c:1176
bool std_typanalyze(VacAttrStats *stats)
Definition analyze.c:1949
#define palloc0_object(type)
Definition fe_memutils.h:75
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:722
static void * GETSTRUCT(const HeapTupleData *tuple)
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
FormData_pg_attribute * Form_pg_attribute
#define STATISTIC_NUM_SLOTS
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
int32 attrtypmod
Definition vacuum.h:126
Oid statypid[STATISTIC_NUM_SLOTS]
Definition vacuum.h:161
char statypalign[STATISTIC_NUM_SLOTS]
Definition vacuum.h:164
Oid attrtypid
Definition vacuum.h:125
bool statypbyval[STATISTIC_NUM_SLOTS]
Definition vacuum.h:163
int16 statyplen[STATISTIC_NUM_SLOTS]
Definition vacuum.h:162
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References anl_context, VacAttrStats::anl_context, attnum, VacAttrStats::attrcollid, attribute_is_analyzable(), VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::attstattarget, VacAttrStats::compute_stats, DatumGetBool(), elog, ERROR, exprCollation(), exprType(), exprTypmod(), fb(), Form_pg_type, GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, i, VacAttrStats::minrows, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, palloc0_object, pfree(), PointerGetDatum(), SearchSysCacheCopy1, STATISTIC_NUM_SLOTS, VacAttrStats::statypalign, VacAttrStats::statypbyval, VacAttrStats::statypid, VacAttrStats::statyplen, std_typanalyze(), 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 1872 of file analyze.c.

1873{
1874 int i;
1875
1876 /* exprvals and exprnulls are already offset for proper column */
1877 i = rownum * stats->rowstride;
1878 *isNull = stats->exprnulls[i];
1879 return stats->exprvals[i];
1880}

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

1857{
1858 int attnum = stats->tupattnum;
1859 HeapTuple tuple = stats->rows[rownum];
1860 TupleDesc tupDesc = stats->tupDesc;
1861
1862 return heap_getattr(tuple, attnum, tupDesc, isNull);
1863}
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)

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

1950{
1951 Oid ltopr;
1952 Oid eqopr;
1954
1955 /* If the attstattarget column is negative, use the default value */
1956 if (stats->attstattarget < 0)
1958
1959 /* Look for default "<" and "=" operators for column's type */
1961 false, false, false,
1962 &ltopr, &eqopr, NULL,
1963 NULL);
1964
1965 /* Save the operator info for compute_stats routines */
1967 mystats->eqopr = eqopr;
1968 mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1969 mystats->ltopr = ltopr;
1970 stats->extra_data = mystats;
1971
1972 /*
1973 * Determine which standard statistics algorithm to use
1974 */
1975 if (OidIsValid(eqopr) && OidIsValid(ltopr))
1976 {
1977 /* Seems to be a scalar datatype */
1979 /*--------------------
1980 * The following choice of minrows is based on the paper
1981 * "Random sampling for histogram construction: how much is enough?"
1982 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1983 * Proceedings of ACM SIGMOD International Conference on Management
1984 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1985 * says that for table size n, histogram size k, maximum relative
1986 * error in bin size f, and error probability gamma, the minimum
1987 * random sample size is
1988 * r = 4 * k * ln(2*n/gamma) / f^2
1989 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1990 * r = 305.82 * k
1991 * Note that because of the log function, the dependence on n is
1992 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1993 * bin size error with probability 0.99. So there's no real need to
1994 * scale for n, which is a good thing because we don't necessarily
1995 * know it at this point.
1996 *--------------------
1997 */
1998 stats->minrows = 300 * stats->attstattarget;
1999 }
2000 else if (OidIsValid(eqopr))
2001 {
2002 /* We can still recognize distinct values */
2004 /* Might as well use the same minrows as above */
2005 stats->minrows = 300 * stats->attstattarget;
2006 }
2007 else
2008 {
2009 /* Can't do much but the trivial stuff */
2011 /* Might as well use the same minrows as above */
2012 stats->minrows = 300 * stats->attstattarget;
2013 }
2014
2015 return true;
2016}
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition analyze.c:2460
int default_statistics_target
Definition analyze.c:71
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition analyze.c:2117
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition analyze.c:2027
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1505
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:183
#define InvalidOid

References VacAttrStats::attrtypid, VacAttrStats::attstattarget, compute_distinct_stats(), compute_scalar_stats(), VacAttrStats::compute_stats, compute_trivial_stats(), default_statistics_target, VacAttrStats::extra_data, fb(), get_opcode(), get_sort_group_operators(), InvalidOid, VacAttrStats::minrows, OidIsValid, and palloc_object.

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

◆ update_attstats()

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

Definition at line 1714 of file analyze.c.

1715{
1716 Relation sd;
1717 int attno;
1719
1720 if (natts <= 0)
1721 return; /* nothing to do */
1722
1724
1725 for (attno = 0; attno < natts; attno++)
1726 {
1727 VacAttrStats *stats = vacattrstats[attno];
1729 oldtup;
1730 int i,
1731 k,
1732 n;
1734 bool nulls[Natts_pg_statistic];
1736
1737 /* Ignore attr if we weren't able to collect stats */
1738 if (!stats->stats_valid)
1739 continue;
1740
1741 /*
1742 * Construct a new pg_statistic tuple
1743 */
1744 for (i = 0; i < Natts_pg_statistic; ++i)
1745 {
1746 nulls[i] = false;
1747 replaces[i] = true;
1748 }
1749
1757 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1758 {
1759 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1760 }
1762 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1763 {
1764 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1765 }
1767 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1768 {
1769 values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1770 }
1772 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1773 {
1774 if (stats->stanumbers[k] != NULL)
1775 {
1776 int nnum = stats->numnumbers[k];
1777 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1778 ArrayType *arry;
1779
1780 for (n = 0; n < nnum; n++)
1781 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1783 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1784 }
1785 else
1786 {
1787 nulls[i] = true;
1788 values[i++] = (Datum) 0;
1789 }
1790 }
1792 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1793 {
1794 if (stats->stavalues[k] != NULL)
1795 {
1796 ArrayType *arry;
1797
1798 arry = construct_array(stats->stavalues[k],
1799 stats->numvalues[k],
1800 stats->statypid[k],
1801 stats->statyplen[k],
1802 stats->statypbyval[k],
1803 stats->statypalign[k]);
1804 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1805 }
1806 else
1807 {
1808 nulls[i] = true;
1809 values[i++] = (Datum) 0;
1810 }
1811 }
1812
1813 /* Is there already a pg_statistic tuple for this attribute? */
1815 ObjectIdGetDatum(relid),
1816 Int16GetDatum(stats->tupattnum),
1817 BoolGetDatum(inh));
1818
1819 /* Open index information when we know we need it */
1820 if (indstate == NULL)
1822
1824 {
1825 /* Yes, replace it */
1828 values,
1829 nulls,
1830 replaces);
1833 }
1834 else
1835 {
1836 /* No, insert new tuple */
1839 }
1840
1842 }
1843
1844 if (indstate != NULL)
1847}
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1025
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:468
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
HeapTuple SearchSysCache3(SysCacheIdentifier cacheId, Datum key1, Datum key2, Datum key3)
Definition syscache.c:241

References BoolGetDatum(), CatalogCloseIndexes(), CatalogOpenIndexes(), CatalogTupleInsertWithInfo(), CatalogTupleUpdateWithInfo(), construct_array(), construct_array_builtin(), fb(), 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, table_close(), table_open(), VacAttrStats::tupattnum, and values.

Referenced by do_analyze_rel().

◆ validate_va_cols_list()

static void validate_va_cols_list ( Relation  onerel,
List va_cols 
)
static

Definition at line 1047 of file analyze.c.

1048{
1050 ListCell *le;
1051
1052 Assert(va_cols != NIL);
1053 foreach(le, va_cols)
1054 {
1055 char *col = strVal(lfirst(le));
1056 int i = attnameAttNum(onerel, col, false);
1057
1058 if (i == InvalidAttrNumber)
1059 ereport(ERROR,
1061 errmsg("column \"%s\" of relation \"%s\" does not exist",
1064 ereport(ERROR,
1066 errmsg("column \"%s\" of relation \"%s\" appears more than once",
1069 }
1070}
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
int errcode(int sqlerrcode)
Definition elog.c:874

References Assert, attnameAttNum(), bms_add_member(), bms_is_member(), ereport, errcode(), errmsg, ERROR, fb(), i, InvalidAttrNumber, lfirst, NIL, RelationGetRelationName, and strVal.

Referenced by analyze_rel().

Variable Documentation

◆ anl_context

MemoryContext anl_context = NULL
static

Definition at line 74 of file analyze.c.

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

◆ default_statistics_target

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 75 of file analyze.c.

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