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

◆ swapInt

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

Definition at line 1847 of file analyze.c.

◆ WIDTH_THRESHOLD

#define WIDTH_THRESHOLD   1024

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

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

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

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

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

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

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

References acquire_sample_rows(), AmAutoVacuumWorkerProcess, FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), ereport, errmsg(), 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 vacuum().

◆ block_sampling_read_stream_next()

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

Definition at line 1162 of file analyze.c.

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

References BlockSampler_HasMore(), BlockSampler_Next(), 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 2963 of file analyze.c.

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

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

2933{
2934 Datum da = ((const ScalarItem *) a)->value;
2935 int ta = ((const ScalarItem *) a)->tupno;
2936 Datum db = ((const ScalarItem *) b)->value;
2937 int tb = ((const ScalarItem *) b)->tupno;
2939 int compare;
2940
2941 compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2942 if (compare != 0)
2943 return compare;
2944
2945 /*
2946 * The two datums are equal, so update cxt->tupnoLink[].
2947 */
2948 if (cxt->tupnoLink[ta] < tb)
2949 cxt->tupnoLink[ta] = tb;
2950 if (cxt->tupnoLink[tb] < ta)
2951 cxt->tupnoLink[tb] = ta;
2952
2953 /*
2954 * For equal datums, sort by tupno
2955 */
2956 return ta - tb;
2957}
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 2060 of file analyze.c.

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

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

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

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

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

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

References _, AccessShareLock, acquire_inherited_sample_rows(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AmAutoVacuumWorkerProcess, 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 1042 of file analyze.c.

1043{
1044 Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
1045 int attstattarget;
1047 Datum dat;
1048 bool isnull;
1050 VacAttrStats *stats;
1051 int i;
1052 bool ok;
1053
1054 /* Never analyze dropped columns */
1055 if (attr->attisdropped)
1056 return NULL;
1057
1058 /* Don't analyze virtual generated columns */
1059 if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
1060 return NULL;
1061
1062 /*
1063 * Get attstattarget value. Set to -1 if null. (Analyze functions expect
1064 * -1 to mean use default_statistics_target; see for example
1065 * std_typanalyze.)
1066 */
1069 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1072 attstattarget = isnull ? -1 : DatumGetInt16(dat);
1074
1075 /* Don't analyze column if user has specified not to */
1076 if (attstattarget == 0)
1077 return NULL;
1078
1079 /*
1080 * Create the VacAttrStats struct.
1081 */
1083 stats->attstattarget = attstattarget;
1084
1085 /*
1086 * When analyzing an expression index, believe the expression tree's type
1087 * not the column datatype --- the latter might be the opckeytype storage
1088 * type of the opclass, which is not interesting for our purposes. (Note:
1089 * if we did anything with non-expression index columns, we'd need to
1090 * figure out where to get the correct type info from, but for now that's
1091 * not a problem.) It's not clear whether anyone will care about the
1092 * typmod, but we store that too just in case.
1093 */
1094 if (index_expr)
1095 {
1096 stats->attrtypid = exprType(index_expr);
1098
1099 /*
1100 * If a collation has been specified for the index column, use that in
1101 * preference to anything else; but if not, fall back to whatever we
1102 * can get from the expression.
1103 */
1104 if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
1105 stats->attrcollid = onerel->rd_indcollation[attnum - 1];
1106 else
1108 }
1109 else
1110 {
1111 stats->attrtypid = attr->atttypid;
1112 stats->attrtypmod = attr->atttypmod;
1113 stats->attrcollid = attr->attcollation;
1114 }
1115
1117 ObjectIdGetDatum(stats->attrtypid));
1119 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1121 stats->anl_context = anl_context;
1122 stats->tupattnum = attnum;
1123
1124 /*
1125 * The fields describing the stats->stavalues[n] element types default to
1126 * the type of the data being analyzed, but the type-specific typanalyze
1127 * function can change them if it wants to store something else.
1128 */
1129 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
1130 {
1131 stats->statypid[i] = stats->attrtypid;
1132 stats->statyplen[i] = stats->attrtype->typlen;
1133 stats->statypbyval[i] = stats->attrtype->typbyval;
1134 stats->statypalign[i] = stats->attrtype->typalign;
1135 }
1136
1137 /*
1138 * Call the type-specific typanalyze function. If none is specified, use
1139 * std_typanalyze().
1140 */
1141 if (OidIsValid(stats->attrtype->typanalyze))
1142 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
1143 PointerGetDatum(stats)));
1144 else
1145 ok = std_typanalyze(stats);
1146
1147 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
1148 {
1150 pfree(stats);
1151 return NULL;
1152 }
1153
1154 return stats;
1155}
#define OidIsValid(objectId)
Definition c.h:800
bool std_typanalyze(VacAttrStats *stats)
Definition analyze.c:1892
#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:301
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:821
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:182
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
static int16 DatumGetInt16(Datum X)
Definition postgres.h:172
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:160

References anl_context, VacAttrStats::anl_context, attnum, VacAttrStats::attrcollid, VacAttrStats::attrtype, VacAttrStats::attrtypid, VacAttrStats::attrtypmod, VacAttrStats::attstattarget, VacAttrStats::compute_stats, DatumGetBool(), DatumGetInt16(), elog, ERROR, exprCollation(), exprType(), exprTypmod(), 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 1815 of file analyze.c.

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

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

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

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

1658{
1659 Relation sd;
1660 int attno;
1662
1663 if (natts <= 0)
1664 return; /* nothing to do */
1665
1667
1668 for (attno = 0; attno < natts; attno++)
1669 {
1670 VacAttrStats *stats = vacattrstats[attno];
1672 oldtup;
1673 int i,
1674 k,
1675 n;
1677 bool nulls[Natts_pg_statistic];
1679
1680 /* Ignore attr if we weren't able to collect stats */
1681 if (!stats->stats_valid)
1682 continue;
1683
1684 /*
1685 * Construct a new pg_statistic tuple
1686 */
1687 for (i = 0; i < Natts_pg_statistic; ++i)
1688 {
1689 nulls[i] = false;
1690 replaces[i] = true;
1691 }
1692
1700 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1701 {
1702 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1703 }
1705 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1706 {
1707 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1708 }
1710 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1711 {
1712 values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1713 }
1715 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1716 {
1717 if (stats->stanumbers[k] != NULL)
1718 {
1719 int nnum = stats->numnumbers[k];
1720 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1721 ArrayType *arry;
1722
1723 for (n = 0; n < nnum; n++)
1724 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1726 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1727 }
1728 else
1729 {
1730 nulls[i] = true;
1731 values[i++] = (Datum) 0;
1732 }
1733 }
1735 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1736 {
1737 if (stats->stavalues[k] != NULL)
1738 {
1739 ArrayType *arry;
1740
1741 arry = construct_array(stats->stavalues[k],
1742 stats->numvalues[k],
1743 stats->statypid[k],
1744 stats->statyplen[k],
1745 stats->statypbyval[k],
1746 stats->statypalign[k]);
1747 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1748 }
1749 else
1750 {
1751 nulls[i] = true;
1752 values[i++] = (Datum) 0;
1753 }
1754 }
1755
1756 /* Is there already a pg_statistic tuple for this attribute? */
1758 ObjectIdGetDatum(relid),
1759 Int16GetDatum(stats->tupattnum),
1760 BoolGetDatum(inh));
1761
1762 /* Open index information when we know we need it */
1763 if (indstate == NULL)
1765
1767 {
1768 /* Yes, replace it */
1771 values,
1772 nulls,
1773 replaces);
1776 }
1777 else
1778 {
1779 /* No, insert new tuple */
1782 }
1783
1785 }
1786
1787 if (indstate != NULL)
1790}
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:1210
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1117
void CatalogTupleUpdateWithInfo(Relation heapRel, const ItemPointerData *otid, HeapTuple tup, CatalogIndexState indstate)
Definition indexing.c:337
void CatalogTupleInsertWithInfo(Relation heapRel, HeapTuple tup, CatalogIndexState indstate)
Definition indexing.c:256
void CatalogCloseIndexes(CatalogIndexState indstate)
Definition indexing.c:61
CatalogIndexState CatalogOpenIndexes(Relation heapRel)
Definition indexing.c:43
#define RowExclusiveLock
Definition lockdefs.h:38
static Datum Float4GetDatum(float4 X)
Definition postgres.h:478
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
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 73 of file analyze.c.

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

◆ default_statistics_target

int default_statistics_target = 100

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 74 of file analyze.c.

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