1
/*-------------------------------------------------------------------------
4
* the Postgres statistics generator
6
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7
* Portions Copyright (c) 1994, Regents of the University of California
11
* src/backend/commands/analyze.c
13
*-------------------------------------------------------------------------
19
#include "access/heapam.h"
20
#include "access/transam.h"
21
#include "access/tupconvert.h"
22
#include "access/tuptoaster.h"
23
#include "access/xact.h"
24
#include "catalog/index.h"
25
#include "catalog/indexing.h"
26
#include "catalog/namespace.h"
27
#include "catalog/pg_collation.h"
28
#include "catalog/pg_inherits_fn.h"
29
#include "catalog/pg_namespace.h"
30
#include "commands/dbcommands.h"
31
#include "commands/vacuum.h"
32
#include "executor/executor.h"
33
#include "miscadmin.h"
34
#include "nodes/nodeFuncs.h"
35
#include "parser/parse_oper.h"
36
#include "parser/parse_relation.h"
38
#include "postmaster/autovacuum.h"
39
#include "storage/bufmgr.h"
40
#include "storage/lmgr.h"
41
#include "storage/proc.h"
42
#include "storage/procarray.h"
43
#include "utils/acl.h"
44
#include "utils/attoptcache.h"
45
#include "utils/datum.h"
46
#include "utils/guc.h"
47
#include "utils/lsyscache.h"
48
#include "utils/memutils.h"
49
#include "utils/pg_rusage.h"
50
#include "utils/syscache.h"
51
#include "utils/tuplesort.h"
52
#include "utils/tqual.h"
55
/* Data structure for Algorithm S from Knuth 3.4.2 */
58
BlockNumber N; /* number of blocks, known in advance */
59
int n; /* desired sample size */
60
BlockNumber t; /* current block number */
61
int m; /* blocks selected so far */
64
typedef BlockSamplerData *BlockSampler;
66
/* Per-index data for ANALYZE */
67
typedef struct AnlIndexData
69
IndexInfo *indexInfo; /* BuildIndexInfo result */
70
double tupleFract; /* fraction of rows for partial index */
71
VacAttrStats **vacattrstats; /* index attrs to analyze */
76
/* Default statistics target (GUC parameter) */
77
int default_statistics_target = 100;
79
/* A few variables that don't seem worth passing around as parameters */
80
static int elevel = -1;
82
static MemoryContext anl_context = NULL;
84
static BufferAccessStrategy vac_strategy;
87
static void do_analyze_rel(Relation onerel, VacuumStmt *vacstmt,
88
bool update_reltuples, bool inh);
89
static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
91
static bool BlockSampler_HasMore(BlockSampler bs);
92
static BlockNumber BlockSampler_Next(BlockSampler bs);
93
static void compute_index_stats(Relation onerel, double totalrows,
94
AnlIndexData *indexdata, int nindexes,
95
HeapTuple *rows, int numrows,
96
MemoryContext col_context);
97
static VacAttrStats *examine_attribute(Relation onerel, int attnum,
99
static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
100
int targrows, double *totalrows, double *totaldeadrows);
101
static double random_fract(void);
102
static double init_selection_state(int n);
103
static double get_next_S(double t, int n, double *stateptr);
104
static int compare_rows(const void *a, const void *b);
105
static int acquire_inherited_sample_rows(Relation onerel,
106
HeapTuple *rows, int targrows,
107
double *totalrows, double *totaldeadrows);
108
static void update_attstats(Oid relid, bool inh,
109
int natts, VacAttrStats **vacattrstats);
110
static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
111
static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
113
static bool std_typanalyze(VacAttrStats *stats);
117
* analyze_rel() -- analyze one relation
119
* If update_reltuples is true, we update reltuples and relpages columns
120
* in pg_class. Caller should pass false if we're part of VACUUM ANALYZE,
121
* and the VACUUM didn't skip any pages. We only have an approximate count,
122
* so we don't want to overwrite the accurate values already inserted by the
123
* VACUUM in that case. VACUUM always scans all indexes, however, so the
124
* pg_class entries for indexes are never updated if we're part of VACUUM
128
analyze_rel(Oid relid, VacuumStmt *vacstmt,
129
BufferAccessStrategy bstrategy, bool update_reltuples)
133
/* Set up static variables */
134
if (vacstmt->options & VACOPT_VERBOSE)
139
vac_strategy = bstrategy;
142
* Check for user-requested abort.
144
CHECK_FOR_INTERRUPTS();
147
* Open the relation, getting ShareUpdateExclusiveLock to ensure that two
148
* ANALYZEs don't run on it concurrently. (This also locks out a
149
* concurrent VACUUM, which doesn't matter much at the moment but might
150
* matter if we ever try to accumulate stats on dead tuples.) If the rel
151
* has been dropped since we last saw it, we don't need to process it.
153
if (!(vacstmt->options & VACOPT_NOWAIT))
154
onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
155
else if (ConditionalLockRelationOid(relid, ShareUpdateExclusiveLock))
156
onerel = try_relation_open(relid, NoLock);
160
if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
162
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
163
errmsg("skipping analyze of \"%s\" --- lock not available",
164
vacstmt->relation->relname)));
170
* Check permissions --- this should match vacuum's check!
172
if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
173
(pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
175
/* No need for a WARNING if we already complained during VACUUM */
176
if (!(vacstmt->options & VACOPT_VACUUM))
178
if (onerel->rd_rel->relisshared)
180
(errmsg("skipping \"%s\" --- only superuser can analyze it",
181
RelationGetRelationName(onerel))));
182
else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
184
(errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
185
RelationGetRelationName(onerel))));
188
(errmsg("skipping \"%s\" --- only table or database owner can analyze it",
189
RelationGetRelationName(onerel))));
191
relation_close(onerel, ShareUpdateExclusiveLock);
196
* Check that it's a plain table; we used to do this in get_rel_oids() but
197
* seems safer to check after we've locked the relation.
199
if (onerel->rd_rel->relkind != RELKIND_RELATION)
201
/* No need for a WARNING if we already complained during VACUUM */
202
if (!(vacstmt->options & VACOPT_VACUUM))
204
(errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
205
RelationGetRelationName(onerel))));
206
relation_close(onerel, ShareUpdateExclusiveLock);
211
* Silently ignore tables that are temp tables of other backends ---
212
* trying to analyze these is rather pointless, since their contents are
213
* probably not up-to-date on disk. (We don't throw a warning here; it
214
* would just lead to chatter during a database-wide ANALYZE.)
216
if (RELATION_IS_OTHER_TEMP(onerel))
218
relation_close(onerel, ShareUpdateExclusiveLock);
223
* We can ANALYZE any table except pg_statistic. See update_attstats
225
if (RelationGetRelid(onerel) == StatisticRelationId)
227
relation_close(onerel, ShareUpdateExclusiveLock);
232
* OK, let's do it. First let other backends know I'm in ANALYZE.
234
LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
235
MyProc->vacuumFlags |= PROC_IN_ANALYZE;
236
LWLockRelease(ProcArrayLock);
239
* Do the normal non-recursive ANALYZE.
241
do_analyze_rel(onerel, vacstmt, update_reltuples, false);
244
* If there are child tables, do recursive ANALYZE.
246
if (onerel->rd_rel->relhassubclass)
247
do_analyze_rel(onerel, vacstmt, false, true);
250
* Close source relation now, but keep lock so that no one deletes it
251
* before we commit. (If someone did, they'd fail to clean up the entries
252
* we made in pg_statistic. Also, releasing the lock before commit would
253
* expose us to concurrent-update failures in update_attstats.)
255
relation_close(onerel, NoLock);
258
* Reset my PGPROC flag. Note: we need this here, and not in vacuum_rel,
259
* because the vacuum flag is cleared by the end-of-xact code.
261
LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
262
MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
263
LWLockRelease(ProcArrayLock);
267
* do_analyze_rel() -- analyze one relation, recursively or not
270
do_analyze_rel(Relation onerel, VacuumStmt *vacstmt,
271
bool update_reltuples, bool inh)
280
bool analyzableindex;
281
VacAttrStats **vacattrstats;
282
AnlIndexData *indexdata;
289
TimestampTz starttime = 0;
290
MemoryContext caller_context;
292
int save_sec_context;
297
(errmsg("analyzing \"%s.%s\" inheritance tree",
298
get_namespace_name(RelationGetNamespace(onerel)),
299
RelationGetRelationName(onerel))));
302
(errmsg("analyzing \"%s.%s\"",
303
get_namespace_name(RelationGetNamespace(onerel)),
304
RelationGetRelationName(onerel))));
307
* Set up a working context so that we can easily free whatever junk gets
310
anl_context = AllocSetContextCreate(CurrentMemoryContext,
312
ALLOCSET_DEFAULT_MINSIZE,
313
ALLOCSET_DEFAULT_INITSIZE,
314
ALLOCSET_DEFAULT_MAXSIZE);
315
caller_context = MemoryContextSwitchTo(anl_context);
318
* Switch to the table owner's userid, so that any index functions are run
319
* as that user. Also lock down security-restricted operations and
320
* arrange to make GUC variable changes local to this command.
322
GetUserIdAndSecContext(&save_userid, &save_sec_context);
323
SetUserIdAndSecContext(onerel->rd_rel->relowner,
324
save_sec_context | SECURITY_RESTRICTED_OPERATION);
325
save_nestlevel = NewGUCNestLevel();
327
/* measure elapsed time iff autovacuum logging requires it */
328
if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
330
pg_rusage_init(&ru0);
331
if (Log_autovacuum_min_duration > 0)
332
starttime = GetCurrentTimestamp();
336
* Determine which columns to analyze
338
* Note that system attributes are never analyzed.
340
if (vacstmt->va_cols != NIL)
344
vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
345
sizeof(VacAttrStats *));
347
foreach(le, vacstmt->va_cols)
349
char *col = strVal(lfirst(le));
351
i = attnameAttNum(onerel, col, false);
352
if (i == InvalidAttrNumber)
354
(errcode(ERRCODE_UNDEFINED_COLUMN),
355
errmsg("column \"%s\" of relation \"%s\" does not exist",
356
col, RelationGetRelationName(onerel))));
357
vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
358
if (vacattrstats[tcnt] != NULL)
365
attr_cnt = onerel->rd_att->natts;
366
vacattrstats = (VacAttrStats **)
367
palloc(attr_cnt * sizeof(VacAttrStats *));
369
for (i = 1; i <= attr_cnt; i++)
371
vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
372
if (vacattrstats[tcnt] != NULL)
379
* Open all indexes of the relation, and see if there are any analyzable
380
* columns in the indexes. We do not analyze index columns if there was
381
* an explicit column list in the ANALYZE command, however. If we are
382
* doing a recursive scan, we don't want to touch the parent's indexes at
386
vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
392
hasindex = (nindexes > 0);
394
analyzableindex = false;
397
indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
398
for (ind = 0; ind < nindexes; ind++)
400
AnlIndexData *thisdata = &indexdata[ind];
401
IndexInfo *indexInfo;
403
thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
404
thisdata->tupleFract = 1.0; /* fix later if partial */
405
if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
407
ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
409
thisdata->vacattrstats = (VacAttrStats **)
410
palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
412
for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
414
int keycol = indexInfo->ii_KeyAttrNumbers[i];
418
/* Found an index expression */
421
if (indexpr_item == NULL) /* shouldn't happen */
422
elog(ERROR, "too few entries in indexprs list");
423
indexkey = (Node *) lfirst(indexpr_item);
424
indexpr_item = lnext(indexpr_item);
425
thisdata->vacattrstats[tcnt] =
426
examine_attribute(Irel[ind], i + 1, indexkey);
427
if (thisdata->vacattrstats[tcnt] != NULL)
430
analyzableindex = true;
434
thisdata->attr_cnt = tcnt;
440
* Quit if no analyzable columns and no pg_class update needed.
442
if (attr_cnt <= 0 && !analyzableindex && !update_reltuples)
446
* Determine how many rows we need to sample, using the worst case from
447
* all analyzable columns. We use a lower bound of 100 rows to avoid
448
* possible overflow in Vitter's algorithm.
451
for (i = 0; i < attr_cnt; i++)
453
if (targrows < vacattrstats[i]->minrows)
454
targrows = vacattrstats[i]->minrows;
456
for (ind = 0; ind < nindexes; ind++)
458
AnlIndexData *thisdata = &indexdata[ind];
460
for (i = 0; i < thisdata->attr_cnt; i++)
462
if (targrows < thisdata->vacattrstats[i]->minrows)
463
targrows = thisdata->vacattrstats[i]->minrows;
468
* Acquire the sample rows
470
rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
472
numrows = acquire_inherited_sample_rows(onerel, rows, targrows,
473
&totalrows, &totaldeadrows);
475
numrows = acquire_sample_rows(onerel, rows, targrows,
476
&totalrows, &totaldeadrows);
479
* Compute the statistics. Temporary results during the calculations for
480
* each column are stored in a child context. The calc routines are
481
* responsible to make sure that whatever they store into the VacAttrStats
482
* structure is allocated in anl_context.
486
MemoryContext col_context,
489
col_context = AllocSetContextCreate(anl_context,
491
ALLOCSET_DEFAULT_MINSIZE,
492
ALLOCSET_DEFAULT_INITSIZE,
493
ALLOCSET_DEFAULT_MAXSIZE);
494
old_context = MemoryContextSwitchTo(col_context);
496
for (i = 0; i < attr_cnt; i++)
498
VacAttrStats *stats = vacattrstats[i];
499
AttributeOpts *aopt =
500
get_attribute_options(onerel->rd_id, stats->attr->attnum);
503
stats->tupDesc = onerel->rd_att;
504
(*stats->compute_stats) (stats,
510
* If the appropriate flavor of the n_distinct option is
511
* specified, override with the corresponding value.
516
inh ? aopt->n_distinct_inherited : aopt->n_distinct;
518
if (n_distinct != 0.0)
519
stats->stadistinct = n_distinct;
522
MemoryContextResetAndDeleteChildren(col_context);
526
compute_index_stats(onerel, totalrows,
531
MemoryContextSwitchTo(old_context);
532
MemoryContextDelete(col_context);
535
* Emit the completed stats rows into pg_statistic, replacing any
536
* previous statistics for the target columns. (If there are stats in
537
* pg_statistic for columns we didn't process, we leave them alone.)
539
update_attstats(RelationGetRelid(onerel), inh,
540
attr_cnt, vacattrstats);
542
for (ind = 0; ind < nindexes; ind++)
544
AnlIndexData *thisdata = &indexdata[ind];
546
update_attstats(RelationGetRelid(Irel[ind]), false,
547
thisdata->attr_cnt, thisdata->vacattrstats);
552
* Update pages/tuples stats in pg_class, but not if we're inside a VACUUM
553
* that got a more precise number.
555
if (update_reltuples)
556
vac_update_relstats(onerel,
557
RelationGetNumberOfBlocks(onerel),
558
totalrows, hasindex, InvalidTransactionId);
561
* Same for indexes. Vacuum always scans all indexes, so if we're part of
562
* VACUUM ANALYZE, don't overwrite the accurate count already inserted by
565
if (!(vacstmt->options & VACOPT_VACUUM))
567
for (ind = 0; ind < nindexes; ind++)
569
AnlIndexData *thisdata = &indexdata[ind];
570
double totalindexrows;
572
totalindexrows = ceil(thisdata->tupleFract * totalrows);
573
vac_update_relstats(Irel[ind],
574
RelationGetNumberOfBlocks(Irel[ind]),
575
totalindexrows, false, InvalidTransactionId);
580
* Report ANALYZE to the stats collector, too; likewise, tell it to adopt
581
* these numbers only if we're not inside a VACUUM that got a better
582
* number. However, a call with inh = true shouldn't reset the stats.
585
pgstat_report_analyze(onerel, update_reltuples,
586
totalrows, totaldeadrows);
588
/* We skip to here if there were no analyzable columns */
591
/* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
592
if (!(vacstmt->options & VACOPT_VACUUM))
594
for (ind = 0; ind < nindexes; ind++)
596
IndexBulkDeleteResult *stats;
597
IndexVacuumInfo ivinfo;
599
ivinfo.index = Irel[ind];
600
ivinfo.analyze_only = true;
601
ivinfo.estimated_count = true;
602
ivinfo.message_level = elevel;
603
ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
604
ivinfo.strategy = vac_strategy;
606
stats = index_vacuum_cleanup(&ivinfo, NULL);
613
/* Done with indexes */
614
vac_close_indexes(nindexes, Irel, NoLock);
616
/* Log the action if appropriate */
617
if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
619
if (Log_autovacuum_min_duration == 0 ||
620
TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
621
Log_autovacuum_min_duration))
623
(errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
624
get_database_name(MyDatabaseId),
625
get_namespace_name(RelationGetNamespace(onerel)),
626
RelationGetRelationName(onerel),
627
pg_rusage_show(&ru0))));
630
/* Roll back any GUC changes executed by index functions */
631
AtEOXact_GUC(false, save_nestlevel);
633
/* Restore userid and security context */
634
SetUserIdAndSecContext(save_userid, save_sec_context);
636
/* Restore current context and release memory */
637
MemoryContextSwitchTo(caller_context);
638
MemoryContextDelete(anl_context);
643
* Compute statistics about indexes of a relation
646
compute_index_stats(Relation onerel, double totalrows,
647
AnlIndexData *indexdata, int nindexes,
648
HeapTuple *rows, int numrows,
649
MemoryContext col_context)
651
MemoryContext ind_context,
653
Datum values[INDEX_MAX_KEYS];
654
bool isnull[INDEX_MAX_KEYS];
658
ind_context = AllocSetContextCreate(anl_context,
660
ALLOCSET_DEFAULT_MINSIZE,
661
ALLOCSET_DEFAULT_INITSIZE,
662
ALLOCSET_DEFAULT_MAXSIZE);
663
old_context = MemoryContextSwitchTo(ind_context);
665
for (ind = 0; ind < nindexes; ind++)
667
AnlIndexData *thisdata = &indexdata[ind];
668
IndexInfo *indexInfo = thisdata->indexInfo;
669
int attr_cnt = thisdata->attr_cnt;
670
TupleTableSlot *slot;
672
ExprContext *econtext;
679
double totalindexrows;
681
/* Ignore index if no columns to analyze and not partial */
682
if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
686
* Need an EState for evaluation of index expressions and
687
* partial-index predicates. Create it in the per-index context to be
688
* sure it gets cleaned up at the bottom of the loop.
690
estate = CreateExecutorState();
691
econtext = GetPerTupleExprContext(estate);
692
/* Need a slot to hold the current heap tuple, too */
693
slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
695
/* Arrange for econtext's scan tuple to be the tuple under test */
696
econtext->ecxt_scantuple = slot;
698
/* Set up execution state for predicate. */
700
ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
703
/* Compute and save index expression values */
704
exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
705
exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
708
for (rowno = 0; rowno < numrows; rowno++)
710
HeapTuple heapTuple = rows[rowno];
713
* Reset the per-tuple context each time, to reclaim any cruft
714
* left behind by evaluating the predicate or index expressions.
716
ResetExprContext(econtext);
718
/* Set up for predicate or expression evaluation */
719
ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
721
/* If index is partial, check predicate */
722
if (predicate != NIL)
724
if (!ExecQual(predicate, econtext, false))
732
* Evaluate the index row to compute expression values. We
733
* could do this by hand, but FormIndexDatum is convenient.
735
FormIndexDatum(indexInfo,
742
* Save just the columns we care about. We copy the values
743
* into ind_context from the estate's per-tuple context.
745
for (i = 0; i < attr_cnt; i++)
747
VacAttrStats *stats = thisdata->vacattrstats[i];
748
int attnum = stats->attr->attnum;
750
if (isnull[attnum - 1])
752
exprvals[tcnt] = (Datum) 0;
753
exprnulls[tcnt] = true;
757
exprvals[tcnt] = datumCopy(values[attnum - 1],
758
stats->attrtype->typbyval,
759
stats->attrtype->typlen);
760
exprnulls[tcnt] = false;
768
* Having counted the number of rows that pass the predicate in the
769
* sample, we can estimate the total number of rows in the index.
771
thisdata->tupleFract = (double) numindexrows / (double) numrows;
772
totalindexrows = ceil(thisdata->tupleFract * totalrows);
775
* Now we can compute the statistics for the expression columns.
777
if (numindexrows > 0)
779
MemoryContextSwitchTo(col_context);
780
for (i = 0; i < attr_cnt; i++)
782
VacAttrStats *stats = thisdata->vacattrstats[i];
783
AttributeOpts *aopt =
784
get_attribute_options(stats->attr->attrelid,
785
stats->attr->attnum);
787
stats->exprvals = exprvals + i;
788
stats->exprnulls = exprnulls + i;
789
stats->rowstride = attr_cnt;
790
(*stats->compute_stats) (stats,
796
* If the n_distinct option is specified, it overrides the
797
* above computation. For indices, we always use just
798
* n_distinct, not n_distinct_inherited.
800
if (aopt != NULL && aopt->n_distinct != 0.0)
801
stats->stadistinct = aopt->n_distinct;
803
MemoryContextResetAndDeleteChildren(col_context);
808
MemoryContextSwitchTo(ind_context);
810
ExecDropSingleTupleTableSlot(slot);
811
FreeExecutorState(estate);
812
MemoryContextResetAndDeleteChildren(ind_context);
815
MemoryContextSwitchTo(old_context);
816
MemoryContextDelete(ind_context);
820
* examine_attribute -- pre-analysis of a single column
822
* Determine whether the column is analyzable; if so, create and initialize
823
* a VacAttrStats struct for it. If not, return NULL.
825
* If index_expr isn't NULL, then we're trying to analyze an expression index,
826
* and index_expr is the expression tree representing the column's data.
828
static VacAttrStats *
829
examine_attribute(Relation onerel, int attnum, Node *index_expr)
831
Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
837
/* Never analyze dropped columns */
838
if (attr->attisdropped)
841
/* Don't analyze column if user has specified not to */
842
if (attr->attstattarget == 0)
846
* Create the VacAttrStats struct. Note that we only have a copy of the
847
* fixed fields of the pg_attribute tuple.
849
stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
850
stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
851
memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
854
* When analyzing an expression index, believe the expression tree's type
855
* not the column datatype --- the latter might be the opckeytype storage
856
* type of the opclass, which is not interesting for our purposes. (Note:
857
* if we did anything with non-expression index columns, we'd need to
858
* figure out where to get the correct type info from, but for now that's
859
* not a problem.) It's not clear whether anyone will care about the
860
* typmod, but we store that too just in case.
864
stats->attrtypid = exprType(index_expr);
865
stats->attrtypmod = exprTypmod(index_expr);
869
stats->attrtypid = attr->atttypid;
870
stats->attrtypmod = attr->atttypmod;
873
typtuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(stats->attrtypid));
874
if (!HeapTupleIsValid(typtuple))
875
elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
876
stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
877
memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
878
ReleaseSysCache(typtuple);
879
stats->anl_context = anl_context;
880
stats->tupattnum = attnum;
883
* The fields describing the stats->stavalues[n] element types default to
884
* the type of the data being analyzed, but the type-specific typanalyze
885
* function can change them if it wants to store something else.
887
for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
889
stats->statypid[i] = stats->attrtypid;
890
stats->statyplen[i] = stats->attrtype->typlen;
891
stats->statypbyval[i] = stats->attrtype->typbyval;
892
stats->statypalign[i] = stats->attrtype->typalign;
896
* Call the type-specific typanalyze function. If none is specified, use
899
if (OidIsValid(stats->attrtype->typanalyze))
900
ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
901
PointerGetDatum(stats)));
903
ok = std_typanalyze(stats);
905
if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
907
pfree(stats->attrtype);
917
* BlockSampler_Init -- prepare for random sampling of blocknumbers
919
* BlockSampler is used for stage one of our new two-stage tuple
920
* sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
921
* "Large DB"). It selects a random sample of samplesize blocks out of
922
* the nblocks blocks in the table. If the table has less than
923
* samplesize blocks, all blocks are selected.
925
* Since we know the total number of blocks in advance, we can use the
926
* straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
930
BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
932
bs->N = nblocks; /* measured table size */
935
* If we decide to reduce samplesize for tables that have less or not much
936
* more than samplesize blocks, here is the place to do it.
939
bs->t = 0; /* blocks scanned so far */
940
bs->m = 0; /* blocks selected so far */
944
BlockSampler_HasMore(BlockSampler bs)
946
return (bs->t < bs->N) && (bs->m < bs->n);
950
BlockSampler_Next(BlockSampler bs)
952
BlockNumber K = bs->N - bs->t; /* remaining blocks */
953
int k = bs->n - bs->m; /* blocks still to sample */
954
double p; /* probability to skip block */
955
double V; /* random */
957
Assert(BlockSampler_HasMore(bs)); /* hence K > 0 and k > 0 */
959
if ((BlockNumber) k >= K)
961
/* need all the rest */
967
* It is not obvious that this code matches Knuth's Algorithm S.
968
* Knuth says to skip the current block with probability 1 - k/K.
969
* If we are to skip, we should advance t (hence decrease K), and
970
* repeat the same probabilistic test for the next block. The naive
971
* implementation thus requires a random_fract() call for each block
972
* number. But we can reduce this to one random_fract() call per
973
* selected block, by noting that each time the while-test succeeds,
974
* we can reinterpret V as a uniform random number in the range 0 to p.
975
* Therefore, instead of choosing a new V, we just adjust p to be
976
* the appropriate fraction of its former value, and our next loop
977
* makes the appropriate probabilistic test.
979
* We have initially K > k > 0. If the loop reduces K to equal k,
980
* the next while-test must fail since p will become exactly zero
981
* (we assume there will not be roundoff error in the division).
982
* (Note: Knuth suggests a "<=" loop condition, but we use "<" just
983
* to be doubly sure about roundoff error.) Therefore K cannot become
984
* less than k, which means that we cannot fail to select enough blocks.
988
p = 1.0 - (double) k / (double) K;
993
K--; /* keep K == N - t */
995
/* adjust p to be new cutoff point in reduced range */
996
p *= 1.0 - (double) k / (double) K;
1005
* acquire_sample_rows -- acquire a random sample of rows from the table
1007
* Selected rows are returned in the caller-allocated array rows[], which
1008
* must have at least targrows entries.
1009
* The actual number of rows selected is returned as the function result.
1010
* We also estimate the total numbers of live and dead rows in the table,
1011
* and return them into *totalrows and *totaldeadrows, respectively.
1013
* The returned list of tuples is in order by physical position in the table.
1014
* (We will rely on this later to derive correlation estimates.)
1016
* As of May 2004 we use a new two-stage method: Stage one selects up
1017
* to targrows random blocks (or all blocks, if there aren't so many).
1018
* Stage two scans these blocks and uses the Vitter algorithm to create
1019
* a random sample of targrows rows (or less, if there are less in the
1020
* sample of blocks). The two stages are executed simultaneously: each
1021
* block is processed as soon as stage one returns its number and while
1022
* the rows are read stage two controls which ones are to be inserted
1025
* Although every row has an equal chance of ending up in the final
1026
* sample, this sampling method is not perfect: not every possible
1027
* sample has an equal chance of being selected. For large relations
1028
* the number of different blocks represented by the sample tends to be
1029
* too small. We can live with that for now. Improvements are welcome.
1031
* An important property of this sampling method is that because we do
1032
* look at a statistically unbiased set of blocks, we should get
1033
* unbiased estimates of the average numbers of live and dead rows per
1034
* block. The previous sampling method put too much credence in the row
1035
* density near the start of the table.
1038
acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1039
double *totalrows, double *totaldeadrows)
1041
int numrows = 0; /* # rows now in reservoir */
1042
double samplerows = 0; /* total # rows collected */
1043
double liverows = 0; /* # live rows seen */
1044
double deadrows = 0; /* # dead rows seen */
1045
double rowstoskip = -1; /* -1 means not set yet */
1046
BlockNumber totalblocks;
1047
TransactionId OldestXmin;
1048
BlockSamplerData bs;
1051
Assert(targrows > 0);
1053
totalblocks = RelationGetNumberOfBlocks(onerel);
1055
/* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1056
OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
1058
/* Prepare for sampling block numbers */
1059
BlockSampler_Init(&bs, totalblocks, targrows);
1060
/* Prepare for sampling rows */
1061
rstate = init_selection_state(targrows);
1063
/* Outer loop over blocks to sample */
1064
while (BlockSampler_HasMore(&bs))
1066
BlockNumber targblock = BlockSampler_Next(&bs);
1069
OffsetNumber targoffset,
1072
vacuum_delay_point();
1075
* We must maintain a pin on the target page's buffer to ensure that
1076
* the maxoffset value stays good (else concurrent VACUUM might delete
1077
* tuples out from under us). Hence, pin the page until we are done
1078
* looking at it. We also choose to hold sharelock on the buffer
1079
* throughout --- we could release and re-acquire sharelock for each
1080
* tuple, but since we aren't doing much work per tuple, the extra
1081
* lock traffic is probably better avoided.
1083
targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1084
RBM_NORMAL, vac_strategy);
1085
LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1086
targpage = BufferGetPage(targbuffer);
1087
maxoffset = PageGetMaxOffsetNumber(targpage);
1089
/* Inner loop over all tuples on the selected page */
1090
for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1093
HeapTupleData targtuple;
1094
bool sample_it = false;
1096
itemid = PageGetItemId(targpage, targoffset);
1099
* We ignore unused and redirect line pointers. DEAD line
1100
* pointers should be counted as dead, because we need vacuum to
1101
* run to get rid of them. Note that this rule agrees with the
1102
* way that heap_page_prune() counts things.
1104
if (!ItemIdIsNormal(itemid))
1106
if (ItemIdIsDead(itemid))
1111
ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1113
targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1114
targtuple.t_len = ItemIdGetLength(itemid);
1116
switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
1120
case HEAPTUPLE_LIVE:
1125
case HEAPTUPLE_DEAD:
1126
case HEAPTUPLE_RECENTLY_DEAD:
1127
/* Count dead and recently-dead rows */
1131
case HEAPTUPLE_INSERT_IN_PROGRESS:
1134
* Insert-in-progress rows are not counted. We assume
1135
* that when the inserting transaction commits or aborts,
1136
* it will send a stats message to increment the proper
1137
* count. This works right only if that transaction ends
1138
* after we finish analyzing the table; if things happen
1139
* in the other order, its stats update will be
1140
* overwritten by ours. However, the error will be large
1141
* only if the other transaction runs long enough to
1142
* insert many tuples, so assuming it will finish after us
1143
* is the safer option.
1145
* A special case is that the inserting transaction might
1146
* be our own. In this case we should count and sample
1147
* the row, to accommodate users who load a table and
1148
* analyze it in one transaction. (pgstat_report_analyze
1149
* has to adjust the numbers we send to the stats
1150
* collector to make this come out right.)
1152
if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
1159
case HEAPTUPLE_DELETE_IN_PROGRESS:
1162
* We count delete-in-progress rows as still live, using
1163
* the same reasoning given above; but we don't bother to
1164
* include them in the sample.
1166
* If the delete was done by our own transaction, however,
1167
* we must count the row as dead to make
1168
* pgstat_report_analyze's stats adjustments come out
1169
* right. (Note: this works out properly when the row was
1170
* both inserted and deleted in our xact.)
1172
if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
1179
elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1186
* The first targrows sample rows are simply copied into the
1187
* reservoir. Then we start replacing tuples in the sample
1188
* until we reach the end of the relation. This algorithm is
1189
* from Jeff Vitter's paper (see full citation below). It
1190
* works by repeatedly computing the number of tuples to skip
1191
* before selecting a tuple, which replaces a randomly chosen
1192
* element of the reservoir (current set of tuples). At all
1193
* times the reservoir is a true random sample of the tuples
1194
* we've passed over so far, so when we fall off the end of
1195
* the relation we're done.
1197
if (numrows < targrows)
1198
rows[numrows++] = heap_copytuple(&targtuple);
1202
* t in Vitter's paper is the number of records already
1203
* processed. If we need to compute a new S value, we
1204
* must use the not-yet-incremented value of samplerows as
1208
rowstoskip = get_next_S(samplerows, targrows, &rstate);
1210
if (rowstoskip <= 0)
1213
* Found a suitable tuple, so save it, replacing one
1214
* old tuple at random
1216
int k = (int) (targrows * random_fract());
1218
Assert(k >= 0 && k < targrows);
1219
heap_freetuple(rows[k]);
1220
rows[k] = heap_copytuple(&targtuple);
1230
/* Now release the lock and pin on the page */
1231
UnlockReleaseBuffer(targbuffer);
1235
* If we didn't find as many tuples as we wanted then we're done. No sort
1236
* is needed, since they're already in order.
1238
* Otherwise we need to sort the collected tuples by position
1239
* (itempointer). It's not worth worrying about corner cases where the
1240
* tuples are already sorted.
1242
if (numrows == targrows)
1243
qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1246
* Estimate total numbers of rows in relation.
1250
*totalrows = floor((liverows * totalblocks) / bs.m + 0.5);
1251
*totaldeadrows = floor((deadrows * totalblocks) / bs.m + 0.5);
1256
*totaldeadrows = 0.0;
1260
* Emit some interesting relation info
1263
(errmsg("\"%s\": scanned %d of %u pages, "
1264
"containing %.0f live rows and %.0f dead rows; "
1265
"%d rows in sample, %.0f estimated total rows",
1266
RelationGetRelationName(onerel),
1269
numrows, *totalrows)));
1274
/* Select a random value R uniformly distributed in (0 - 1) */
1278
return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
1282
* These two routines embody Algorithm Z from "Random sampling with a
1283
* reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1284
* (Mar. 1985), Pages 37-57. Vitter describes his algorithm in terms
1285
* of the count S of records to skip before processing another record.
1286
* It is computed primarily based on t, the number of records already read.
1287
* The only extra state needed between calls is W, a random state variable.
1289
* init_selection_state computes the initial W value.
1291
* Given that we've already read t records (t >= n), get_next_S
1292
* determines the number of records to skip before the next record is
1296
init_selection_state(int n)
1298
/* Initial value of W (for use when Algorithm Z is first applied) */
1299
return exp(-log(random_fract()) / n);
1303
get_next_S(double t, int n, double *stateptr)
1307
/* The magic constant here is T from Vitter's paper */
1308
if (t <= (22.0 * n))
1310
/* Process records using Algorithm X until t is large enough */
1314
V = random_fract(); /* Generate V */
1317
/* Note: "num" in Vitter's code is always equal to t - n */
1318
quot = (t - (double) n) / t;
1319
/* Find min S satisfying (4.1) */
1324
quot *= (t - (double) n) / t;
1329
/* Now apply Algorithm Z */
1330
double W = *stateptr;
1331
double term = t - (double) n + 1;
1345
/* Generate U and X */
1348
S = floor(X); /* S is tentatively set to floor(X) */
1349
/* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1350
tmp = (t + 1) / term;
1351
lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
1352
rhs = (((t + X) / (term + S)) * term) / t;
1358
/* Test if U <= f(S)/cg(X) */
1359
y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1363
numer_lim = term + S;
1367
denom = t - (double) n + S;
1370
for (numer = t + S; numer >= numer_lim; numer -= 1)
1375
W = exp(-log(random_fract()) / n); /* Generate W in advance */
1376
if (exp(log(y) / n) <= (t + X) / t)
1385
* qsort comparator for sorting rows[] array
1388
compare_rows(const void *a, const void *b)
1390
HeapTuple ha = *(HeapTuple *) a;
1391
HeapTuple hb = *(HeapTuple *) b;
1392
BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1393
OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1394
BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1395
OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1410
* acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1412
* This has the same API as acquire_sample_rows, except that rows are
1413
* collected from all inheritance children as well as the specified table.
1414
* We fail and return zero if there are no inheritance children.
1417
acquire_inherited_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1418
double *totalrows, double *totaldeadrows)
1430
* Find all members of inheritance set. We only need AccessShareLock on
1434
find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
1437
* Check that there's at least one descendant, else fail. This could
1438
* happen despite analyze_rel's relhassubclass check, if table once had a
1439
* child but no longer does.
1441
if (list_length(tableOIDs) < 2)
1444
* XXX It would be desirable to clear relhassubclass here, but we
1445
* don't have adequate lock to do that safely.
1451
* Count the blocks in all the relations. The result could overflow
1452
* BlockNumber, so we use double arithmetic.
1454
rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1455
relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1458
foreach(lc, tableOIDs)
1460
Oid childOID = lfirst_oid(lc);
1463
/* We already got the needed lock */
1464
childrel = heap_open(childOID, NoLock);
1466
/* Ignore if temp table of another backend */
1467
if (RELATION_IS_OTHER_TEMP(childrel))
1469
/* ... but release the lock on it */
1470
Assert(childrel != onerel);
1471
heap_close(childrel, AccessShareLock);
1475
rels[nrels] = childrel;
1476
relblocks[nrels] = (double) RelationGetNumberOfBlocks(childrel);
1477
totalblocks += relblocks[nrels];
1482
* Now sample rows from each relation, proportionally to its fraction of
1483
* the total block count. (This might be less than desirable if the child
1484
* rels have radically different free-space percentages, but it's not
1485
* clear that it's worth working harder.)
1490
for (i = 0; i < nrels; i++)
1492
Relation childrel = rels[i];
1493
double childblocks = relblocks[i];
1495
if (childblocks > 0)
1499
childtargrows = (int) rint(targrows * childblocks / totalblocks);
1500
/* Make sure we don't overrun due to roundoff error */
1501
childtargrows = Min(childtargrows, targrows - numrows);
1502
if (childtargrows > 0)
1508
/* Fetch a random sample of the child's rows */
1509
childrows = acquire_sample_rows(childrel,
1515
/* We may need to convert from child's rowtype to parent's */
1516
if (childrows > 0 &&
1517
!equalTupleDescs(RelationGetDescr(childrel),
1518
RelationGetDescr(onerel)))
1520
TupleConversionMap *map;
1522
map = convert_tuples_by_name(RelationGetDescr(childrel),
1523
RelationGetDescr(onerel),
1524
gettext_noop("could not convert row type"));
1529
for (j = 0; j < childrows; j++)
1533
newtup = do_convert_tuple(rows[numrows + j], map);
1534
heap_freetuple(rows[numrows + j]);
1535
rows[numrows + j] = newtup;
1537
free_conversion_map(map);
1541
/* And add to counts */
1542
numrows += childrows;
1543
*totalrows += trows;
1544
*totaldeadrows += tdrows;
1549
* Note: we cannot release the child-table locks, since we may have
1550
* pointers to their TOAST tables in the sampled rows.
1552
heap_close(childrel, NoLock);
1560
* update_attstats() -- update attribute statistics for one relation
1562
* Statistics are stored in several places: the pg_class row for the
1563
* relation has stats about the whole relation, and there is a
1564
* pg_statistic row for each (non-system) attribute that has ever
1565
* been analyzed. The pg_class values are updated by VACUUM, not here.
1567
* pg_statistic rows are just added or updated normally. This means
1568
* that pg_statistic will probably contain some deleted rows at the
1569
* completion of a vacuum cycle, unless it happens to get vacuumed last.
1571
* To keep things simple, we punt for pg_statistic, and don't try
1572
* to compute or store rows for pg_statistic itself in pg_statistic.
1573
* This could possibly be made to work, but it's not worth the trouble.
1574
* Note analyze_rel() has seen to it that we won't come here when
1575
* vacuuming pg_statistic itself.
1577
* Note: there would be a race condition here if two backends could
1578
* ANALYZE the same table concurrently. Presently, we lock that out
1579
* by taking a self-exclusive lock on the relation in analyze_rel().
1582
update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1588
return; /* nothing to do */
1590
sd = heap_open(StatisticRelationId, RowExclusiveLock);
1592
for (attno = 0; attno < natts; attno++)
1594
VacAttrStats *stats = vacattrstats[attno];
1600
Datum values[Natts_pg_statistic];
1601
bool nulls[Natts_pg_statistic];
1602
bool replaces[Natts_pg_statistic];
1604
/* Ignore attr if we weren't able to collect stats */
1605
if (!stats->stats_valid)
1609
* Construct a new pg_statistic tuple
1611
for (i = 0; i < Natts_pg_statistic; ++i)
1618
values[i++] = ObjectIdGetDatum(relid); /* starelid */
1619
values[i++] = Int16GetDatum(stats->attr->attnum); /* staattnum */
1620
values[i++] = BoolGetDatum(inh); /* stainherit */
1621
values[i++] = Float4GetDatum(stats->stanullfrac); /* stanullfrac */
1622
values[i++] = Int32GetDatum(stats->stawidth); /* stawidth */
1623
values[i++] = Float4GetDatum(stats->stadistinct); /* stadistinct */
1624
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1626
values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1628
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1630
values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1632
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1634
int nnum = stats->numnumbers[k];
1638
Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1641
for (n = 0; n < nnum; n++)
1642
numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1643
/* XXX knows more than it should about type float4: */
1644
arry = construct_array(numdatums, nnum,
1646
sizeof(float4), FLOAT4PASSBYVAL, 'i');
1647
values[i++] = PointerGetDatum(arry); /* stanumbersN */
1652
values[i++] = (Datum) 0;
1655
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1657
if (stats->numvalues[k] > 0)
1661
arry = construct_array(stats->stavalues[k],
1662
stats->numvalues[k],
1664
stats->statyplen[k],
1665
stats->statypbyval[k],
1666
stats->statypalign[k]);
1667
values[i++] = PointerGetDatum(arry); /* stavaluesN */
1672
values[i++] = (Datum) 0;
1676
/* Is there already a pg_statistic tuple for this attribute? */
1677
oldtup = SearchSysCache3(STATRELATTINH,
1678
ObjectIdGetDatum(relid),
1679
Int16GetDatum(stats->attr->attnum),
1682
if (HeapTupleIsValid(oldtup))
1684
/* Yes, replace it */
1685
stup = heap_modify_tuple(oldtup,
1686
RelationGetDescr(sd),
1690
ReleaseSysCache(oldtup);
1691
simple_heap_update(sd, &stup->t_self, stup);
1695
/* No, insert new tuple */
1696
stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1697
simple_heap_insert(sd, stup);
1700
/* update indexes too */
1701
CatalogUpdateIndexes(sd, stup);
1703
heap_freetuple(stup);
1706
heap_close(sd, RowExclusiveLock);
1710
* Standard fetch function for use by compute_stats subroutines.
1712
* This exists to provide some insulation between compute_stats routines
1713
* and the actual storage of the sample data.
1716
std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1718
int attnum = stats->tupattnum;
1719
HeapTuple tuple = stats->rows[rownum];
1720
TupleDesc tupDesc = stats->tupDesc;
1722
return heap_getattr(tuple, attnum, tupDesc, isNull);
1726
* Fetch function for analyzing index expressions.
1728
* We have not bothered to construct index tuples, instead the data is
1729
* just in Datum arrays.
1732
ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1736
/* exprvals and exprnulls are already offset for proper column */
1737
i = rownum * stats->rowstride;
1738
*isNull = stats->exprnulls[i];
1739
return stats->exprvals[i];
1743
/*==========================================================================
1745
* Code below this point represents the "standard" type-specific statistics
1746
* analysis algorithms. This code can be replaced on a per-data-type basis
1747
* by setting a nonzero value in pg_type.typanalyze.
1749
*==========================================================================
1754
* To avoid consuming too much memory during analysis and/or too much space
1755
* in the resulting pg_statistic rows, we ignore varlena datums that are wider
1756
* than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1757
* and distinct-value calculations since a wide value is unlikely to be
1758
* duplicated at all, much less be a most-common value. For the same reason,
1759
* ignoring wide values will not affect our estimates of histogram bin
1760
* boundaries very much.
1762
#define WIDTH_THRESHOLD 1024
1764
#define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1765
#define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1768
* Extra information used by the default analysis routines
1772
Oid eqopr; /* '=' operator for datatype, if any */
1773
Oid eqfunc; /* and associated function */
1774
Oid ltopr; /* '<' operator for datatype, if any */
1779
Datum value; /* a data value */
1780
int tupno; /* position index for tuple it came from */
1785
int count; /* # of duplicates */
1786
int first; /* values[] index of first occurrence */
1794
} CompareScalarsContext;
1797
static void compute_minimal_stats(VacAttrStatsP stats,
1798
AnalyzeAttrFetchFunc fetchfunc,
1801
static void compute_scalar_stats(VacAttrStatsP stats,
1802
AnalyzeAttrFetchFunc fetchfunc,
1805
static int compare_scalars(const void *a, const void *b, void *arg);
1806
static int compare_mcvs(const void *a, const void *b);
1810
* std_typanalyze -- the default type-specific typanalyze function
1813
std_typanalyze(VacAttrStats *stats)
1815
Form_pg_attribute attr = stats->attr;
1818
StdAnalyzeData *mystats;
1820
/* If the attstattarget column is negative, use the default value */
1821
/* NB: it is okay to scribble on stats->attr since it's a copy */
1822
if (attr->attstattarget < 0)
1823
attr->attstattarget = default_statistics_target;
1825
/* Look for default "<" and "=" operators for column's type */
1826
get_sort_group_operators(stats->attrtypid,
1827
false, false, false,
1828
<opr, &eqopr, NULL,
1831
/* If column has no "=" operator, we can't do much of anything */
1832
if (!OidIsValid(eqopr))
1835
/* Save the operator info for compute_stats routines */
1836
mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1837
mystats->eqopr = eqopr;
1838
mystats->eqfunc = get_opcode(eqopr);
1839
mystats->ltopr = ltopr;
1840
stats->extra_data = mystats;
1843
* Determine which standard statistics algorithm to use
1845
if (OidIsValid(ltopr))
1847
/* Seems to be a scalar datatype */
1848
stats->compute_stats = compute_scalar_stats;
1849
/*--------------------
1850
* The following choice of minrows is based on the paper
1851
* "Random sampling for histogram construction: how much is enough?"
1852
* by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1853
* Proceedings of ACM SIGMOD International Conference on Management
1854
* of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1855
* says that for table size n, histogram size k, maximum relative
1856
* error in bin size f, and error probability gamma, the minimum
1857
* random sample size is
1858
* r = 4 * k * ln(2*n/gamma) / f^2
1859
* Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1861
* Note that because of the log function, the dependence on n is
1862
* quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1863
* bin size error with probability 0.99. So there's no real need to
1864
* scale for n, which is a good thing because we don't necessarily
1865
* know it at this point.
1866
*--------------------
1868
stats->minrows = 300 * attr->attstattarget;
1872
/* Can't do much but the minimal stuff */
1873
stats->compute_stats = compute_minimal_stats;
1874
/* Might as well use the same minrows as above */
1875
stats->minrows = 300 * attr->attstattarget;
1882
* compute_minimal_stats() -- compute minimal column statistics
1884
* We use this when we can find only an "=" operator for the datatype.
1886
* We determine the fraction of non-null rows, the average width, the
1887
* most common values, and the (estimated) number of distinct values.
1889
* The most common values are determined by brute force: we keep a list
1890
* of previously seen values, ordered by number of times seen, as we scan
1891
* the samples. A newly seen value is inserted just after the last
1892
* multiply-seen value, causing the bottommost (oldest) singly-seen value
1893
* to drop off the list. The accuracy of this method, and also its cost,
1894
* depend mainly on the length of the list we are willing to keep.
1897
compute_minimal_stats(VacAttrStatsP stats,
1898
AnalyzeAttrFetchFunc fetchfunc,
1904
int nonnull_cnt = 0;
1905
int toowide_cnt = 0;
1906
double total_width = 0;
1907
bool is_varlena = (!stats->attrtype->typbyval &&
1908
stats->attrtype->typlen == -1);
1909
bool is_varwidth = (!stats->attrtype->typbyval &&
1910
stats->attrtype->typlen < 0);
1920
int num_mcv = stats->attr->attstattarget;
1921
StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1924
* We track up to 2*n values for an n-element MCV list; but at least 10
1926
track_max = 2 * num_mcv;
1929
track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1932
fmgr_info(mystats->eqfunc, &f_cmpeq);
1934
for (i = 0; i < samplerows; i++)
1942
vacuum_delay_point();
1944
value = fetchfunc(stats, i, &isnull);
1946
/* Check for null/nonnull */
1955
* If it's a variable-width field, add up widths for average width
1956
* calculation. Note that if the value is toasted, we use the toasted
1957
* width. We don't bother with this calculation if it's a fixed-width
1962
total_width += VARSIZE_ANY(DatumGetPointer(value));
1965
* If the value is toasted, we want to detoast it just once to
1966
* avoid repeated detoastings and resultant excess memory usage
1967
* during the comparisons. Also, check to see if the value is
1968
* excessively wide, and if so don't detoast at all --- just
1971
if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1976
value = PointerGetDatum(PG_DETOAST_DATUM(value));
1978
else if (is_varwidth)
1980
/* must be cstring */
1981
total_width += strlen(DatumGetCString(value)) + 1;
1985
* See if the value matches anything we're already tracking.
1988
firstcount1 = track_cnt;
1989
for (j = 0; j < track_cnt; j++)
1991
/* We always use the default collation for statistics */
1992
if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
1993
DEFAULT_COLLATION_OID,
1994
value, track[j].value)))
1999
if (j < firstcount1 && track[j].count == 1)
2007
/* This value may now need to "bubble up" in the track list */
2008
while (j > 0 && track[j].count > track[j - 1].count)
2010
swapDatum(track[j].value, track[j - 1].value);
2011
swapInt(track[j].count, track[j - 1].count);
2017
/* No match. Insert at head of count-1 list */
2018
if (track_cnt < track_max)
2020
for (j = track_cnt - 1; j > firstcount1; j--)
2022
track[j].value = track[j - 1].value;
2023
track[j].count = track[j - 1].count;
2025
if (firstcount1 < track_cnt)
2027
track[firstcount1].value = value;
2028
track[firstcount1].count = 1;
2033
/* We can only compute real stats if we found some non-null values. */
2034
if (nonnull_cnt > 0)
2039
stats->stats_valid = true;
2040
/* Do the simple null-frac and width stats */
2041
stats->stanullfrac = (double) null_cnt / (double) samplerows;
2043
stats->stawidth = total_width / (double) nonnull_cnt;
2045
stats->stawidth = stats->attrtype->typlen;
2047
/* Count the number of values we found multiple times */
2049
for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2051
if (track[nmultiple].count == 1)
2053
summultiple += track[nmultiple].count;
2058
/* If we found no repeated values, assume it's a unique column */
2059
stats->stadistinct = -1.0;
2061
else if (track_cnt < track_max && toowide_cnt == 0 &&
2062
nmultiple == track_cnt)
2065
* Our track list includes every value in the sample, and every
2066
* value appeared more than once. Assume the column has just
2069
stats->stadistinct = track_cnt;
2074
* Estimate the number of distinct values using the estimator
2075
* proposed by Haas and Stokes in IBM Research Report RJ 10025:
2076
* n*d / (n - f1 + f1*n/N)
2077
* where f1 is the number of distinct values that occurred
2078
* exactly once in our sample of n rows (from a total of N),
2079
* and d is the total number of distinct values in the sample.
2080
* This is their Duj1 estimator; the other estimators they
2081
* recommend are considerably more complex, and are numerically
2082
* very unstable when n is much smaller than N.
2084
* We assume (not very reliably!) that all the multiply-occurring
2085
* values are reflected in the final track[] list, and the other
2086
* nonnull values all appeared but once. (XXX this usually
2087
* results in a drastic overestimate of ndistinct. Can we do
2091
int f1 = nonnull_cnt - summultiple;
2092
int d = f1 + nmultiple;
2097
numer = (double) samplerows *(double) d;
2099
denom = (double) (samplerows - f1) +
2100
(double) f1 *(double) samplerows / totalrows;
2102
stadistinct = numer / denom;
2103
/* Clamp to sane range in case of roundoff error */
2104
if (stadistinct < (double) d)
2105
stadistinct = (double) d;
2106
if (stadistinct > totalrows)
2107
stadistinct = totalrows;
2108
stats->stadistinct = floor(stadistinct + 0.5);
2112
* If we estimated the number of distinct values at more than 10% of
2113
* the total row count (a very arbitrary limit), then assume that
2114
* stadistinct should scale with the row count rather than be a fixed
2117
if (stats->stadistinct > 0.1 * totalrows)
2118
stats->stadistinct = -(stats->stadistinct / totalrows);
2121
* Decide how many values are worth storing as most-common values. If
2122
* we are able to generate a complete MCV list (all the values in the
2123
* sample will fit, and we think these are all the ones in the table),
2124
* then do so. Otherwise, store only those values that are
2125
* significantly more common than the (estimated) average. We set the
2126
* threshold rather arbitrarily at 25% more than average, with at
2127
* least 2 instances in the sample.
2129
if (track_cnt < track_max && toowide_cnt == 0 &&
2130
stats->stadistinct > 0 &&
2131
track_cnt <= num_mcv)
2133
/* Track list includes all values seen, and all will fit */
2134
num_mcv = track_cnt;
2138
double ndistinct = stats->stadistinct;
2143
ndistinct = -ndistinct * totalrows;
2144
/* estimate # of occurrences in sample of a typical value */
2145
avgcount = (double) samplerows / ndistinct;
2146
/* set minimum threshold count to store a value */
2147
mincount = avgcount * 1.25;
2150
if (num_mcv > track_cnt)
2151
num_mcv = track_cnt;
2152
for (i = 0; i < num_mcv; i++)
2154
if (track[i].count < mincount)
2162
/* Generate MCV slot entry */
2165
MemoryContext old_context;
2169
/* Must copy the target values into anl_context */
2170
old_context = MemoryContextSwitchTo(stats->anl_context);
2171
mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2172
mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2173
for (i = 0; i < num_mcv; i++)
2175
mcv_values[i] = datumCopy(track[i].value,
2176
stats->attrtype->typbyval,
2177
stats->attrtype->typlen);
2178
mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2180
MemoryContextSwitchTo(old_context);
2182
stats->stakind[0] = STATISTIC_KIND_MCV;
2183
stats->staop[0] = mystats->eqopr;
2184
stats->stanumbers[0] = mcv_freqs;
2185
stats->numnumbers[0] = num_mcv;
2186
stats->stavalues[0] = mcv_values;
2187
stats->numvalues[0] = num_mcv;
2190
* Accept the defaults for stats->statypid and others. They have
2191
* been set before we were called (see vacuum.h)
2195
else if (null_cnt > 0)
2197
/* We found only nulls; assume the column is entirely null */
2198
stats->stats_valid = true;
2199
stats->stanullfrac = 1.0;
2201
stats->stawidth = 0; /* "unknown" */
2203
stats->stawidth = stats->attrtype->typlen;
2204
stats->stadistinct = 0.0; /* "unknown" */
2207
/* We don't need to bother cleaning up any of our temporary palloc's */
2212
* compute_scalar_stats() -- compute column statistics
2214
* We use this when we can find "=" and "<" operators for the datatype.
2216
* We determine the fraction of non-null rows, the average width, the
2217
* most common values, the (estimated) number of distinct values, the
2218
* distribution histogram, and the correlation of physical to logical order.
2220
* The desired stats can be determined fairly easily after sorting the
2221
* data values into order.
2224
compute_scalar_stats(VacAttrStatsP stats,
2225
AnalyzeAttrFetchFunc fetchfunc,
2231
int nonnull_cnt = 0;
2232
int toowide_cnt = 0;
2233
double total_width = 0;
2234
bool is_varlena = (!stats->attrtype->typbyval &&
2235
stats->attrtype->typlen == -1);
2236
bool is_varwidth = (!stats->attrtype->typbyval &&
2237
stats->attrtype->typlen < 0);
2245
ScalarMCVItem *track;
2247
int num_mcv = stats->attr->attstattarget;
2248
int num_bins = stats->attr->attstattarget;
2249
StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2251
values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2252
tupnoLink = (int *) palloc(samplerows * sizeof(int));
2253
track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2255
SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
2256
fmgr_info(cmpFn, &f_cmpfn);
2258
/* Initial scan to find sortable values */
2259
for (i = 0; i < samplerows; i++)
2264
vacuum_delay_point();
2266
value = fetchfunc(stats, i, &isnull);
2268
/* Check for null/nonnull */
2277
* If it's a variable-width field, add up widths for average width
2278
* calculation. Note that if the value is toasted, we use the toasted
2279
* width. We don't bother with this calculation if it's a fixed-width
2284
total_width += VARSIZE_ANY(DatumGetPointer(value));
2287
* If the value is toasted, we want to detoast it just once to
2288
* avoid repeated detoastings and resultant excess memory usage
2289
* during the comparisons. Also, check to see if the value is
2290
* excessively wide, and if so don't detoast at all --- just
2293
if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2298
value = PointerGetDatum(PG_DETOAST_DATUM(value));
2300
else if (is_varwidth)
2302
/* must be cstring */
2303
total_width += strlen(DatumGetCString(value)) + 1;
2306
/* Add it to the list to be sorted */
2307
values[values_cnt].value = value;
2308
values[values_cnt].tupno = values_cnt;
2309
tupnoLink[values_cnt] = values_cnt;
2313
/* We can only compute real stats if we found some sortable values. */
2316
int ndistinct, /* # distinct values in sample */
2317
nmultiple, /* # that appear multiple times */
2321
CompareScalarsContext cxt;
2323
/* Sort the collected values */
2324
cxt.cmpFn = &f_cmpfn;
2325
cxt.cmpFlags = cmpFlags;
2326
cxt.tupnoLink = tupnoLink;
2327
qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2328
compare_scalars, (void *) &cxt);
2331
* Now scan the values in order, find the most common ones, and also
2332
* accumulate ordering-correlation statistics.
2334
* To determine which are most common, we first have to count the
2335
* number of duplicates of each value. The duplicates are adjacent in
2336
* the sorted list, so a brute-force approach is to compare successive
2337
* datum values until we find two that are not equal. However, that
2338
* requires N-1 invocations of the datum comparison routine, which are
2339
* completely redundant with work that was done during the sort. (The
2340
* sort algorithm must at some point have compared each pair of items
2341
* that are adjacent in the sorted order; otherwise it could not know
2342
* that it's ordered the pair correctly.) We exploit this by having
2343
* compare_scalars remember the highest tupno index that each
2344
* ScalarItem has been found equal to. At the end of the sort, a
2345
* ScalarItem's tupnoLink will still point to itself if and only if it
2346
* is the last item of its group of duplicates (since the group will
2347
* be ordered by tupno).
2353
for (i = 0; i < values_cnt; i++)
2355
int tupno = values[i].tupno;
2357
corr_xysum += ((double) i) * ((double) tupno);
2359
if (tupnoLink[tupno] == tupno)
2361
/* Reached end of duplicates of this value */
2366
if (track_cnt < num_mcv ||
2367
dups_cnt > track[track_cnt - 1].count)
2370
* Found a new item for the mcv list; find its
2371
* position, bubbling down old items if needed. Loop
2372
* invariant is that j points at an empty/ replaceable
2377
if (track_cnt < num_mcv)
2379
for (j = track_cnt - 1; j > 0; j--)
2381
if (dups_cnt <= track[j - 1].count)
2383
track[j].count = track[j - 1].count;
2384
track[j].first = track[j - 1].first;
2386
track[j].count = dups_cnt;
2387
track[j].first = i + 1 - dups_cnt;
2394
stats->stats_valid = true;
2395
/* Do the simple null-frac and width stats */
2396
stats->stanullfrac = (double) null_cnt / (double) samplerows;
2398
stats->stawidth = total_width / (double) nonnull_cnt;
2400
stats->stawidth = stats->attrtype->typlen;
2404
/* If we found no repeated values, assume it's a unique column */
2405
stats->stadistinct = -1.0;
2407
else if (toowide_cnt == 0 && nmultiple == ndistinct)
2410
* Every value in the sample appeared more than once. Assume the
2411
* column has just these values.
2413
stats->stadistinct = ndistinct;
2418
* Estimate the number of distinct values using the estimator
2419
* proposed by Haas and Stokes in IBM Research Report RJ 10025:
2420
* n*d / (n - f1 + f1*n/N)
2421
* where f1 is the number of distinct values that occurred
2422
* exactly once in our sample of n rows (from a total of N),
2423
* and d is the total number of distinct values in the sample.
2424
* This is their Duj1 estimator; the other estimators they
2425
* recommend are considerably more complex, and are numerically
2426
* very unstable when n is much smaller than N.
2428
* Overwidth values are assumed to have been distinct.
2431
int f1 = ndistinct - nmultiple + toowide_cnt;
2432
int d = f1 + nmultiple;
2437
numer = (double) samplerows *(double) d;
2439
denom = (double) (samplerows - f1) +
2440
(double) f1 *(double) samplerows / totalrows;
2442
stadistinct = numer / denom;
2443
/* Clamp to sane range in case of roundoff error */
2444
if (stadistinct < (double) d)
2445
stadistinct = (double) d;
2446
if (stadistinct > totalrows)
2447
stadistinct = totalrows;
2448
stats->stadistinct = floor(stadistinct + 0.5);
2452
* If we estimated the number of distinct values at more than 10% of
2453
* the total row count (a very arbitrary limit), then assume that
2454
* stadistinct should scale with the row count rather than be a fixed
2457
if (stats->stadistinct > 0.1 * totalrows)
2458
stats->stadistinct = -(stats->stadistinct / totalrows);
2461
* Decide how many values are worth storing as most-common values. If
2462
* we are able to generate a complete MCV list (all the values in the
2463
* sample will fit, and we think these are all the ones in the table),
2464
* then do so. Otherwise, store only those values that are
2465
* significantly more common than the (estimated) average. We set the
2466
* threshold rather arbitrarily at 25% more than average, with at
2467
* least 2 instances in the sample. Also, we won't suppress values
2468
* that have a frequency of at least 1/K where K is the intended
2469
* number of histogram bins; such values might otherwise cause us to
2470
* emit duplicate histogram bin boundaries. (We might end up with
2471
* duplicate histogram entries anyway, if the distribution is skewed;
2472
* but we prefer to treat such values as MCVs if at all possible.)
2474
if (track_cnt == ndistinct && toowide_cnt == 0 &&
2475
stats->stadistinct > 0 &&
2476
track_cnt <= num_mcv)
2478
/* Track list includes all values seen, and all will fit */
2479
num_mcv = track_cnt;
2483
double ndistinct = stats->stadistinct;
2489
ndistinct = -ndistinct * totalrows;
2490
/* estimate # of occurrences in sample of a typical value */
2491
avgcount = (double) samplerows / ndistinct;
2492
/* set minimum threshold count to store a value */
2493
mincount = avgcount * 1.25;
2496
/* don't let threshold exceed 1/K, however */
2497
maxmincount = (double) samplerows / (double) num_bins;
2498
if (mincount > maxmincount)
2499
mincount = maxmincount;
2500
if (num_mcv > track_cnt)
2501
num_mcv = track_cnt;
2502
for (i = 0; i < num_mcv; i++)
2504
if (track[i].count < mincount)
2512
/* Generate MCV slot entry */
2515
MemoryContext old_context;
2519
/* Must copy the target values into anl_context */
2520
old_context = MemoryContextSwitchTo(stats->anl_context);
2521
mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2522
mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2523
for (i = 0; i < num_mcv; i++)
2525
mcv_values[i] = datumCopy(values[track[i].first].value,
2526
stats->attrtype->typbyval,
2527
stats->attrtype->typlen);
2528
mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2530
MemoryContextSwitchTo(old_context);
2532
stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2533
stats->staop[slot_idx] = mystats->eqopr;
2534
stats->stanumbers[slot_idx] = mcv_freqs;
2535
stats->numnumbers[slot_idx] = num_mcv;
2536
stats->stavalues[slot_idx] = mcv_values;
2537
stats->numvalues[slot_idx] = num_mcv;
2540
* Accept the defaults for stats->statypid and others. They have
2541
* been set before we were called (see vacuum.h)
2547
* Generate a histogram slot entry if there are at least two distinct
2548
* values not accounted for in the MCV list. (This ensures the
2549
* histogram won't collapse to empty or a singleton.)
2551
num_hist = ndistinct - num_mcv;
2552
if (num_hist > num_bins)
2553
num_hist = num_bins + 1;
2556
MemoryContext old_context;
2564
/* Sort the MCV items into position order to speed next loop */
2565
qsort((void *) track, num_mcv,
2566
sizeof(ScalarMCVItem), compare_mcvs);
2569
* Collapse out the MCV items from the values[] array.
2571
* Note we destroy the values[] array here... but we don't need it
2572
* for anything more. We do, however, still need values_cnt.
2573
* nvals will be the number of remaining entries in values[].
2582
j = 0; /* index of next interesting MCV item */
2583
while (src < values_cnt)
2589
int first = track[j].first;
2593
/* advance past this MCV item */
2594
src = first + track[j].count;
2598
ncopy = first - src;
2601
ncopy = values_cnt - src;
2602
memmove(&values[dest], &values[src],
2603
ncopy * sizeof(ScalarItem));
2611
Assert(nvals >= num_hist);
2613
/* Must copy the target values into anl_context */
2614
old_context = MemoryContextSwitchTo(stats->anl_context);
2615
hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2618
* The object of this loop is to copy the first and last values[]
2619
* entries along with evenly-spaced values in between. So the
2620
* i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2621
* computing that subscript directly risks integer overflow when
2622
* the stats target is more than a couple thousand. Instead we
2623
* add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2624
* the integral and fractional parts of the sum separately.
2626
delta = (nvals - 1) / (num_hist - 1);
2627
deltafrac = (nvals - 1) % (num_hist - 1);
2630
for (i = 0; i < num_hist; i++)
2632
hist_values[i] = datumCopy(values[pos].value,
2633
stats->attrtype->typbyval,
2634
stats->attrtype->typlen);
2636
posfrac += deltafrac;
2637
if (posfrac >= (num_hist - 1))
2639
/* fractional part exceeds 1, carry to integer part */
2641
posfrac -= (num_hist - 1);
2645
MemoryContextSwitchTo(old_context);
2647
stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2648
stats->staop[slot_idx] = mystats->ltopr;
2649
stats->stavalues[slot_idx] = hist_values;
2650
stats->numvalues[slot_idx] = num_hist;
2653
* Accept the defaults for stats->statypid and others. They have
2654
* been set before we were called (see vacuum.h)
2659
/* Generate a correlation entry if there are multiple values */
2662
MemoryContext old_context;
2667
/* Must copy the target values into anl_context */
2668
old_context = MemoryContextSwitchTo(stats->anl_context);
2669
corrs = (float4 *) palloc(sizeof(float4));
2670
MemoryContextSwitchTo(old_context);
2673
* Since we know the x and y value sets are both
2674
* 0, 1, ..., values_cnt-1
2675
* we have sum(x) = sum(y) =
2676
* (values_cnt-1)*values_cnt / 2
2677
* and sum(x^2) = sum(y^2) =
2678
* (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2681
corr_xsum = ((double) (values_cnt - 1)) *
2682
((double) values_cnt) / 2.0;
2683
corr_x2sum = ((double) (values_cnt - 1)) *
2684
((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2686
/* And the correlation coefficient reduces to */
2687
corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2688
(values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2690
stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2691
stats->staop[slot_idx] = mystats->ltopr;
2692
stats->stanumbers[slot_idx] = corrs;
2693
stats->numnumbers[slot_idx] = 1;
2697
else if (nonnull_cnt == 0 && null_cnt > 0)
2699
/* We found only nulls; assume the column is entirely null */
2700
stats->stats_valid = true;
2701
stats->stanullfrac = 1.0;
2703
stats->stawidth = 0; /* "unknown" */
2705
stats->stawidth = stats->attrtype->typlen;
2706
stats->stadistinct = 0.0; /* "unknown" */
2709
/* We don't need to bother cleaning up any of our temporary palloc's */
2713
* qsort_arg comparator for sorting ScalarItems
2715
* Aside from sorting the items, we update the tupnoLink[] array
2716
* whenever two ScalarItems are found to contain equal datums. The array
2717
* is indexed by tupno; for each ScalarItem, it contains the highest
2718
* tupno that that item's datum has been found to be equal to. This allows
2719
* us to avoid additional comparisons in compute_scalar_stats().
2722
compare_scalars(const void *a, const void *b, void *arg)
2724
Datum da = ((ScalarItem *) a)->value;
2725
int ta = ((ScalarItem *) a)->tupno;
2726
Datum db = ((ScalarItem *) b)->value;
2727
int tb = ((ScalarItem *) b)->tupno;
2728
CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2731
/* We always use the default collation for statistics */
2732
compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2733
DEFAULT_COLLATION_OID,
2734
da, false, db, false);
2739
* The two datums are equal, so update cxt->tupnoLink[].
2741
if (cxt->tupnoLink[ta] < tb)
2742
cxt->tupnoLink[ta] = tb;
2743
if (cxt->tupnoLink[tb] < ta)
2744
cxt->tupnoLink[tb] = ta;
2747
* For equal datums, sort by tupno
2753
* qsort comparator for sorting ScalarMCVItems by position
2756
compare_mcvs(const void *a, const void *b)
2758
int da = ((ScalarMCVItem *) a)->first;
2759
int db = ((ScalarMCVItem *) b)->first;