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 VacAttrStatsexamine_attribute (Relation onerel, int attnum, Node *index_expr)
 
static int acquire_sample_rows (Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
 
static int compare_rows (const void *a, const void *b, void *arg)
 
static int acquire_inherited_sample_rows (Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
 
static void update_attstats (Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
 
static Datum std_fetch_func (VacAttrStatsP stats, int rownum, bool *isNull)
 
static Datum ind_fetch_func (VacAttrStatsP stats, int rownum, bool *isNull)
 
void analyze_rel (Oid relid, RangeVar *relation, const VacuumParams params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
 
static BlockNumber block_sampling_read_stream_next (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static void compute_trivial_stats (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static void compute_distinct_stats (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static void compute_scalar_stats (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
static int compare_scalars (const void *a, const void *b, void *arg)
 
static int compare_mcvs (const void *a, const void *b, void *arg)
 
static int analyze_mcv_list (int *mcv_counts, int num_mcv, double stadistinct, double stanullfrac, int samplerows, double totalrows)
 
bool std_typanalyze (VacAttrStats *stats)
 

Variables

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

Macro Definition Documentation

◆ swapDatum

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

Definition at line 1849 of file analyze.c.

◆ swapInt

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

Definition at line 1848 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

1397{
1398 List *tableOIDs;
1399 Relation *rels;
1401 double *relblocks;
1402 double totalblocks;
1403 int numrows,
1404 nrels,
1405 i;
1406 ListCell *lc;
1407 bool has_child;
1408
1409 /* Initialize output parameters to zero now, in case we exit early */
1410 *totalrows = 0;
1411 *totaldeadrows = 0;
1412
1413 /*
1414 * Find all members of inheritance set. We only need AccessShareLock on
1415 * the children.
1416 */
1417 tableOIDs =
1419
1420 /*
1421 * Check that there's at least one descendant, else fail. This could
1422 * happen despite analyze_rel's relhassubclass check, if table once had a
1423 * child but no longer does. In that case, we can clear the
1424 * relhassubclass field so as not to make the same mistake again later.
1425 * (This is safe because we hold ShareUpdateExclusiveLock.)
1426 */
1427 if (list_length(tableOIDs) < 2)
1428 {
1429 /* CCI because we already updated the pg_class row in this command */
1432 ereport(elevel,
1433 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1436 return 0;
1437 }
1438
1439 /*
1440 * Identify acquirefuncs to use, and count blocks in all the relations.
1441 * The result could overflow BlockNumber, so we use double arithmetic.
1442 */
1443 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1446 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1447 totalblocks = 0;
1448 nrels = 0;
1449 has_child = false;
1450 foreach(lc, tableOIDs)
1451 {
1455 BlockNumber relpages = 0;
1456
1457 /* We already got the needed lock */
1459
1460 /* Ignore if temp table of another backend */
1462 {
1463 /* ... but release the lock on it */
1466 continue;
1467 }
1468
1469 /* Check table type (MATVIEW can't happen, but might as well allow) */
1470 if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1471 childrel->rd_rel->relkind == RELKIND_MATVIEW)
1472 {
1473 /* Regular table, so use the regular row acquisition function */
1476 }
1477 else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1478 {
1479 /*
1480 * For a foreign table, call the FDW's hook function to see
1481 * whether it supports analysis.
1482 */
1483 FdwRoutine *fdwroutine;
1484 bool ok = false;
1485
1486 fdwroutine = GetFdwRoutineForRelation(childrel, false);
1487
1488 if (fdwroutine->AnalyzeForeignTable != NULL)
1489 ok = fdwroutine->AnalyzeForeignTable(childrel,
1490 &acquirefunc,
1491 &relpages);
1492
1493 if (!ok)
1494 {
1495 /* ignore, but release the lock on it */
1498 continue;
1499 }
1500 }
1501 else
1502 {
1503 /*
1504 * ignore, but release the lock on it. don't try to unlock the
1505 * passed-in relation
1506 */
1507 Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1508 if (childrel != onerel)
1510 else
1512 continue;
1513 }
1514
1515 /* OK, we'll process this child */
1516 has_child = true;
1517 rels[nrels] = childrel;
1518 acquirefuncs[nrels] = acquirefunc;
1519 relblocks[nrels] = (double) relpages;
1520 totalblocks += (double) relpages;
1521 nrels++;
1522 }
1523
1524 /*
1525 * If we don't have at least one child table to consider, fail. If the
1526 * relation is a partitioned table, it's not counted as a child table.
1527 */
1528 if (!has_child)
1529 {
1530 ereport(elevel,
1531 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1534 return 0;
1535 }
1536
1537 /*
1538 * Now sample rows from each relation, proportionally to its fraction of
1539 * the total block count. (This might be less than desirable if the child
1540 * rels have radically different free-space percentages, but it's not
1541 * clear that it's worth working harder.)
1542 */
1544 nrels);
1545 numrows = 0;
1546 for (i = 0; i < nrels; i++)
1547 {
1548 Relation childrel = rels[i];
1550 double childblocks = relblocks[i];
1551
1552 /*
1553 * Report progress. The sampling function will normally report blocks
1554 * done/total, but we need to reset them to 0 here, so that they don't
1555 * show an old value until that.
1556 */
1557 {
1558 const int progress_index[] = {
1562 };
1563 const int64 progress_vals[] = {
1565 0,
1566 0,
1567 };
1568
1570 }
1571
1572 if (childblocks > 0)
1573 {
1574 int childtargrows;
1575
1576 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1577 /* Make sure we don't overrun due to roundoff error */
1578 childtargrows = Min(childtargrows, targrows - numrows);
1579 if (childtargrows > 0)
1580 {
1581 int childrows;
1582 double trows,
1583 tdrows;
1584
1585 /* Fetch a random sample of the child's rows */
1586 childrows = (*acquirefunc) (childrel, elevel,
1587 rows + numrows, childtargrows,
1588 &trows, &tdrows);
1589
1590 /* We may need to convert from child's rowtype to parent's */
1591 if (childrows > 0 &&
1594 {
1595 TupleConversionMap *map;
1596
1599 if (map != NULL)
1600 {
1601 int j;
1602
1603 for (j = 0; j < childrows; j++)
1604 {
1606
1607 newtup = execute_attr_map_tuple(rows[numrows + j], map);
1608 heap_freetuple(rows[numrows + j]);
1609 rows[numrows + j] = newtup;
1610 }
1612 }
1613 }
1614
1615 /* And add to counts */
1616 numrows += childrows;
1617 *totalrows += trows;
1619 }
1620 }
1621
1622 /*
1623 * Note: we cannot release the child-table locks, since we may have
1624 * pointers to their TOAST tables in the sampled rows.
1625 */
1628 i + 1);
1629 }
1630
1631 return numrows;
1632}
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:307
#define Min(x, y)
Definition c.h:1093
#define Assert(condition)
Definition c.h:945
int64_t int64
Definition c.h:615
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition analyze.c:1206
#define ereport(elevel,...)
Definition elog.h:150
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition fdwapi.h:151
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition foreign.c:531
struct RelationData * Relation
Definition genam.h:30
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1384
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:514
#define RelationGetDescr(relation)
Definition rel.h:540
#define RelationGetRelationName(relation)
Definition rel.h:548
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:667
#define RelationGetNamespace(relation)
Definition rel.h:555
AnalyzeForeignTable_function AnalyzeForeignTable
Definition fdwapi.h:257
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:832
void CommandCounterIncrement(void)
Definition xact.c:1102

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

1209{
1210 int numrows = 0; /* # rows now in reservoir */
1211 double samplerows = 0; /* total # rows collected */
1212 double liverows = 0; /* # live rows seen */
1213 double deadrows = 0; /* # dead rows seen */
1214 double rowstoskip = -1; /* -1 means not set yet */
1215 uint32 randseed; /* Seed for block sampler(s) */
1218 ReservoirStateData rstate;
1219 TupleTableSlot *slot;
1220 TableScanDesc scan;
1221 BlockNumber nblocks;
1223 ReadStream *stream;
1224
1225 Assert(targrows > 0);
1226
1228
1229 /* Prepare for sampling block numbers */
1231 nblocks = BlockSampler_Init(&bs, totalblocks, targrows, randseed);
1232
1233 /* Report sampling block numbers */
1235 nblocks);
1236
1237 /* Prepare for sampling rows */
1238 reservoir_init_selection_state(&rstate, targrows);
1239
1241 slot = table_slot_create(onerel, NULL);
1242
1243 /*
1244 * It is safe to use batching, as block_sampling_read_stream_next never
1245 * blocks.
1246 */
1250 scan->rs_rd,
1253 &bs,
1254 0);
1255
1256 /* Outer loop over blocks to sample */
1257 while (table_scan_analyze_next_block(scan, stream))
1258 {
1259 vacuum_delay_point(true);
1260
1261 while (table_scan_analyze_next_tuple(scan, &liverows, &deadrows, slot))
1262 {
1263 /*
1264 * The first targrows sample rows are simply copied into the
1265 * reservoir. Then we start replacing tuples in the sample until
1266 * we reach the end of the relation. This algorithm is from Jeff
1267 * Vitter's paper (see full citation in utils/misc/sampling.c). It
1268 * works by repeatedly computing the number of tuples to skip
1269 * before selecting a tuple, which replaces a randomly chosen
1270 * element of the reservoir (current set of tuples). At all times
1271 * the reservoir is a true random sample of the tuples we've
1272 * passed over so far, so when we fall off the end of the relation
1273 * we're done.
1274 */
1275 if (numrows < targrows)
1276 rows[numrows++] = ExecCopySlotHeapTuple(slot);
1277 else
1278 {
1279 /*
1280 * t in Vitter's paper is the number of records already
1281 * processed. If we need to compute a new S value, we must
1282 * use the not-yet-incremented value of samplerows as t.
1283 */
1284 if (rowstoskip < 0)
1285 rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1286
1287 if (rowstoskip <= 0)
1288 {
1289 /*
1290 * Found a suitable tuple, so save it, replacing one old
1291 * tuple at random
1292 */
1293 int k = (int) (targrows * sampler_random_fract(&rstate.randstate));
1294
1295 Assert(k >= 0 && k < targrows);
1296 heap_freetuple(rows[k]);
1297 rows[k] = ExecCopySlotHeapTuple(slot);
1298 }
1299
1300 rowstoskip -= 1;
1301 }
1302
1303 samplerows += 1;
1304 }
1305
1307 ++blksdone);
1308 }
1309
1310 read_stream_end(stream);
1311
1313 table_endscan(scan);
1314
1315 /*
1316 * If we didn't find as many tuples as we wanted then we're done. No sort
1317 * is needed, since they're already in order.
1318 *
1319 * Otherwise we need to sort the collected tuples by position
1320 * (itempointer). It's not worth worrying about corner cases where the
1321 * tuples are already sorted.
1322 */
1323 if (numrows == targrows)
1324 qsort_interruptible(rows, numrows, sizeof(HeapTuple),
1326
1327 /*
1328 * Estimate total numbers of live and dead rows in relation, extrapolating
1329 * on the assumption that the average tuple density in pages we didn't
1330 * scan is the same as in the pages we did scan. Since what we scanned is
1331 * a random sample of the pages in the relation, this should be a good
1332 * assumption.
1333 */
1334 if (bs.m > 0)
1335 {
1336 *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1337 *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1338 }
1339 else
1340 {
1341 *totalrows = 0.0;
1342 *totaldeadrows = 0.0;
1343 }
1344
1345 /*
1346 * Emit some interesting relation info
1347 */
1348 ereport(elevel,
1349 (errmsg("\"%s\": scanned %d of %u pages, "
1350 "containing %.0f live rows and %.0f dead rows; "
1351 "%d rows in sample, %.0f estimated total rows",
1353 bs.m, totalblocks,
1355 numrows, *totalrows)));
1356
1357 return numrows;
1358}
uint32_t uint32
Definition c.h:618
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:1163
static int compare_rows(const void *a, const void *b, void *arg)
Definition analyze.c:1364
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:35
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition tableam.c:92
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1004
static bool table_scan_analyze_next_block(TableScanDesc scan, ReadStream *stream)
Definition tableam.h:1712
static TableScanDesc table_beginscan_analyze(Relation rel)
Definition tableam.h:993
static bool table_scan_analyze_next_tuple(TableScanDesc scan, double *liverows, double *deadrows, TupleTableSlot *slot)
Definition tableam.h:1728
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition tuptable.h:503
void vacuum_delay_point(bool is_analyze)
Definition vacuum.c:2431

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

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

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

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

Referenced by process_single_relation(), and vacuum().

◆ block_sampling_read_stream_next()

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

Definition at line 1163 of file analyze.c.

1166{
1167 BlockSamplerData *bs = callback_private_data;
1168
1170}
#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 2964 of file analyze.c.

2965{
2966 int da = ((const ScalarMCVItem *) a)->first;
2967 int db = ((const ScalarMCVItem *) b)->first;
2968
2969 return da - db;
2970}
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 1364 of file analyze.c.

1365{
1366 HeapTuple ha = *(const HeapTuple *) a;
1367 HeapTuple hb = *(const HeapTuple *) b;
1372
1373 if (ba < bb)
1374 return -1;
1375 if (ba > bb)
1376 return 1;
1377 if (oa < ob)
1378 return -1;
1379 if (oa > ob)
1380 return 1;
1381 return 0;
1382}
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 2933 of file analyze.c.

2934{
2935 Datum da = ((const ScalarItem *) a)->value;
2936 int ta = ((const ScalarItem *) a)->tupno;
2937 Datum db = ((const ScalarItem *) b)->value;
2938 int tb = ((const ScalarItem *) b)->tupno;
2940 int compare;
2941
2942 compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2943 if (compare != 0)
2944 return compare;
2945
2946 /*
2947 * The two datums are equal, so update cxt->tupnoLink[].
2948 */
2949 if (cxt->tupnoLink[ta] < tb)
2950 cxt->tupnoLink[ta] = tb;
2951 if (cxt->tupnoLink[tb] < ta)
2952 cxt->tupnoLink[tb] = ta;
2953
2954 /*
2955 * For equal datums, sort by tupno
2956 */
2957 return ta - tb;
2958}
Datum arg
Definition elog.c:1322
static int compare(const void *arg1, const void *arg2)
Definition geqo_pool.c:144
uint64_t Datum
Definition postgres.h:70
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 2061 of file analyze.c.

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

References analyze_mcv_list(), VacAttrStats::anl_context, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attstattarget, datumCopy(), DatumGetBool(), DatumGetCString(), DatumGetPointer(), 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 872 of file analyze.c.

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

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, anl_context, attnum, 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 2404 of file analyze.c.

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

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

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

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

References _, AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AmAutoVacuumWorkerProcess, anl_context, appendStringInfo(), AtEOXact_GUC(), attnameAttNum(), bms_add_member(), bms_is_member(), buf, BufferUsageAccumDiff(), BuildIndexInfo(), BuildRelationExtStatistics(), CommandCounterIncrement(), compute_index_stats(), VacAttrStats::compute_stats, ComputeExtStatisticsRows(), CurrentMemoryContext, elog, ereport, errcode(), errmsg, errmsg_internal(), ERROR, 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 1043 of file analyze.c.

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

Referenced by do_analyze_rel().

◆ ind_fetch_func()

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

Definition at line 1816 of file analyze.c.

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

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

1801{
1802 int attnum = stats->tupattnum;
1803 HeapTuple tuple = stats->rows[rownum];
1804 TupleDesc tupDesc = stats->tupDesc;
1805
1806 return heap_getattr(tuple, attnum, tupDesc, isNull);
1807}
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 1893 of file analyze.c.

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

1659{
1660 Relation sd;
1661 int attno;
1663
1664 if (natts <= 0)
1665 return; /* nothing to do */
1666
1668
1669 for (attno = 0; attno < natts; attno++)
1670 {
1671 VacAttrStats *stats = vacattrstats[attno];
1673 oldtup;
1674 int i,
1675 k,
1676 n;
1678 bool nulls[Natts_pg_statistic];
1680
1681 /* Ignore attr if we weren't able to collect stats */
1682 if (!stats->stats_valid)
1683 continue;
1684
1685 /*
1686 * Construct a new pg_statistic tuple
1687 */
1688 for (i = 0; i < Natts_pg_statistic; ++i)
1689 {
1690 nulls[i] = false;
1691 replaces[i] = true;
1692 }
1693
1701 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1702 {
1703 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1704 }
1706 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1707 {
1708 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1709 }
1711 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1712 {
1713 values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1714 }
1716 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1717 {
1718 if (stats->stanumbers[k] != NULL)
1719 {
1720 int nnum = stats->numnumbers[k];
1721 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1722 ArrayType *arry;
1723
1724 for (n = 0; n < nnum; n++)
1725 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1727 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1728 }
1729 else
1730 {
1731 nulls[i] = true;
1732 values[i++] = (Datum) 0;
1733 }
1734 }
1736 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1737 {
1738 if (stats->stavalues[k] != NULL)
1739 {
1740 ArrayType *arry;
1741
1742 arry = construct_array(stats->stavalues[k],
1743 stats->numvalues[k],
1744 stats->statypid[k],
1745 stats->statyplen[k],
1746 stats->statypbyval[k],
1747 stats->statypalign[k]);
1748 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1749 }
1750 else
1751 {
1752 nulls[i] = true;
1753 values[i++] = (Datum) 0;
1754 }
1755 }
1756
1757 /* Is there already a pg_statistic tuple for this attribute? */
1759 ObjectIdGetDatum(relid),
1760 Int16GetDatum(stats->tupattnum),
1761 BoolGetDatum(inh));
1762
1763 /* Open index information when we know we need it */
1764 if (indstate == NULL)
1766
1768 {
1769 /* Yes, replace it */
1772 values,
1773 nulls,
1774 replaces);
1777 }
1778 else
1779 {
1780 /* No, insert new tuple */
1783 }
1784
1786 }
1787
1788 if (indstate != NULL)
1791}
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:1130
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1037
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:240

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

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