1 /*-------------------------------------------------------------------------
4 * the Postgres statistics generator
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.128 2008/11/10 00:49:37 tgl Exp $
13 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "access/transam.h"
21 #include "access/tuptoaster.h"
22 #include "access/xact.h"
23 #include "catalog/index.h"
24 #include "catalog/indexing.h"
25 #include "catalog/namespace.h"
26 #include "catalog/pg_namespace.h"
27 #include "commands/dbcommands.h"
28 #include "commands/vacuum.h"
29 #include "executor/executor.h"
30 #include "miscadmin.h"
31 #include "nodes/nodeFuncs.h"
32 #include "parser/parse_oper.h"
33 #include "parser/parse_relation.h"
35 #include "postmaster/autovacuum.h"
36 #include "storage/bufmgr.h"
37 #include "storage/proc.h"
38 #include "storage/procarray.h"
39 #include "utils/acl.h"
40 #include "utils/datum.h"
41 #include "utils/lsyscache.h"
42 #include "utils/memutils.h"
43 #include "utils/pg_rusage.h"
44 #include "utils/syscache.h"
45 #include "utils/tuplesort.h"
46 #include "utils/tqual.h"
49 /* Data structure for Algorithm S from Knuth 3.4.2 */
52 BlockNumber N; /* number of blocks, known in advance */
53 int n; /* desired sample size */
54 BlockNumber t; /* current block number */
55 int m; /* blocks selected so far */
57 typedef BlockSamplerData *BlockSampler;
59 /* Per-index data for ANALYZE */
60 typedef struct AnlIndexData
62 IndexInfo *indexInfo; /* BuildIndexInfo result */
63 double tupleFract; /* fraction of rows for partial index */
64 VacAttrStats **vacattrstats; /* index attrs to analyze */
69 /* Default statistics target (GUC parameter) */
70 int default_statistics_target = 10;
72 /* A few variables that don't seem worth passing around as parameters */
73 static int elevel = -1;
75 static MemoryContext anl_context = NULL;
77 static BufferAccessStrategy vac_strategy;
80 static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
82 static bool BlockSampler_HasMore(BlockSampler bs);
83 static BlockNumber BlockSampler_Next(BlockSampler bs);
84 static void compute_index_stats(Relation onerel, double totalrows,
85 AnlIndexData *indexdata, int nindexes,
86 HeapTuple *rows, int numrows,
87 MemoryContext col_context);
88 static VacAttrStats *examine_attribute(Relation onerel, int attnum);
89 static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
90 int targrows, double *totalrows, double *totaldeadrows);
91 static double random_fract(void);
92 static double init_selection_state(int n);
93 static double get_next_S(double t, int n, double *stateptr);
94 static int compare_rows(const void *a, const void *b);
95 static void update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats);
96 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
97 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
99 static bool std_typanalyze(VacAttrStats *stats);
103 * analyze_rel() -- analyze one relation
106 analyze_rel(Oid relid, VacuumStmt *vacstmt,
107 BufferAccessStrategy bstrategy)
117 bool analyzableindex;
118 VacAttrStats **vacattrstats;
119 AnlIndexData *indexdata;
126 TimestampTz starttime = 0;
130 if (vacstmt->verbose)
135 vac_strategy = bstrategy;
138 * Use the current context for storing analysis info. vacuum.c ensures
139 * that this context will be cleared when I return, thus releasing the
140 * memory allocated here.
142 anl_context = CurrentMemoryContext;
145 * Check for user-requested abort. Note we want this to be inside a
146 * transaction, so xact.c doesn't issue useless WARNING.
148 CHECK_FOR_INTERRUPTS();
151 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
152 * ANALYZEs don't run on it concurrently. (This also locks out a
153 * concurrent VACUUM, which doesn't matter much at the moment but might
154 * matter if we ever try to accumulate stats on dead tuples.) If the rel
155 * has been dropped since we last saw it, we don't need to process it.
157 onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
162 * Check permissions --- this should match vacuum's check!
164 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
165 (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
167 /* No need for a WARNING if we already complained during VACUUM */
168 if (!vacstmt->vacuum)
170 if (onerel->rd_rel->relisshared)
172 (errmsg("skipping \"%s\" --- only superuser can analyze it",
173 RelationGetRelationName(onerel))));
174 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
176 (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
177 RelationGetRelationName(onerel))));
180 (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
181 RelationGetRelationName(onerel))));
183 relation_close(onerel, ShareUpdateExclusiveLock);
188 * Check that it's a plain table; we used to do this in get_rel_oids() but
189 * seems safer to check after we've locked the relation.
191 if (onerel->rd_rel->relkind != RELKIND_RELATION)
193 /* No need for a WARNING if we already complained during VACUUM */
194 if (!vacstmt->vacuum)
196 (errmsg("skipping \"%s\" --- cannot analyze indexes, views, or special system tables",
197 RelationGetRelationName(onerel))));
198 relation_close(onerel, ShareUpdateExclusiveLock);
203 * Silently ignore tables that are temp tables of other backends ---
204 * trying to analyze these is rather pointless, since their contents are
205 * probably not up-to-date on disk. (We don't throw a warning here; it
206 * would just lead to chatter during a database-wide ANALYZE.)
208 if (isOtherTempNamespace(RelationGetNamespace(onerel)))
210 relation_close(onerel, ShareUpdateExclusiveLock);
215 * We can ANALYZE any table except pg_statistic. See update_attstats
217 if (RelationGetRelid(onerel) == StatisticRelationId)
219 relation_close(onerel, ShareUpdateExclusiveLock);
224 (errmsg("analyzing \"%s.%s\"",
225 get_namespace_name(RelationGetNamespace(onerel)),
226 RelationGetRelationName(onerel))));
229 * Switch to the table owner's userid, so that any index functions are
232 GetUserIdAndContext(&save_userid, &save_secdefcxt);
233 SetUserIdAndContext(onerel->rd_rel->relowner, true);
235 /* let others know what I'm doing */
236 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
237 MyProc->vacuumFlags |= PROC_IN_ANALYZE;
238 LWLockRelease(ProcArrayLock);
240 /* measure elapsed time iff autovacuum logging requires it */
241 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
243 pg_rusage_init(&ru0);
244 if (Log_autovacuum_min_duration > 0)
245 starttime = GetCurrentTimestamp();
249 * Determine which columns to analyze
251 * Note that system attributes are never analyzed.
253 if (vacstmt->va_cols != NIL)
257 vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
258 sizeof(VacAttrStats *));
260 foreach(le, vacstmt->va_cols)
262 char *col = strVal(lfirst(le));
264 i = attnameAttNum(onerel, col, false);
265 if (i == InvalidAttrNumber)
267 (errcode(ERRCODE_UNDEFINED_COLUMN),
268 errmsg("column \"%s\" of relation \"%s\" does not exist",
269 col, RelationGetRelationName(onerel))));
270 vacattrstats[tcnt] = examine_attribute(onerel, i);
271 if (vacattrstats[tcnt] != NULL)
278 attr_cnt = onerel->rd_att->natts;
279 vacattrstats = (VacAttrStats **)
280 palloc(attr_cnt * sizeof(VacAttrStats *));
282 for (i = 1; i <= attr_cnt; i++)
284 vacattrstats[tcnt] = examine_attribute(onerel, i);
285 if (vacattrstats[tcnt] != NULL)
292 * Open all indexes of the relation, and see if there are any analyzable
293 * columns in the indexes. We do not analyze index columns if there was
294 * an explicit column list in the ANALYZE command, however.
296 vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
297 hasindex = (nindexes > 0);
299 analyzableindex = false;
302 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
303 for (ind = 0; ind < nindexes; ind++)
305 AnlIndexData *thisdata = &indexdata[ind];
306 IndexInfo *indexInfo;
308 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
309 thisdata->tupleFract = 1.0; /* fix later if partial */
310 if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
312 ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
314 thisdata->vacattrstats = (VacAttrStats **)
315 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
317 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
319 int keycol = indexInfo->ii_KeyAttrNumbers[i];
323 /* Found an index expression */
326 if (indexpr_item == NULL) /* shouldn't happen */
327 elog(ERROR, "too few entries in indexprs list");
328 indexkey = (Node *) lfirst(indexpr_item);
329 indexpr_item = lnext(indexpr_item);
332 * Can't analyze if the opclass uses a storage type
333 * different from the expression result type. We'd get
334 * confused because the type shown in pg_attribute for
335 * the index column doesn't match what we are getting
336 * from the expression. Perhaps this can be fixed
337 * someday, but for now, punt.
339 if (exprType(indexkey) !=
340 Irel[ind]->rd_att->attrs[i]->atttypid)
343 thisdata->vacattrstats[tcnt] =
344 examine_attribute(Irel[ind], i + 1);
345 if (thisdata->vacattrstats[tcnt] != NULL)
348 analyzableindex = true;
352 thisdata->attr_cnt = tcnt;
358 * Quit if no analyzable columns
360 if (attr_cnt <= 0 && !analyzableindex)
363 * We report that the table is empty; this is just so that the
364 * autovacuum code doesn't go nuts trying to get stats about a
367 if (!vacstmt->vacuum)
368 pgstat_report_analyze(onerel, 0, 0);
373 * Determine how many rows we need to sample, using the worst case from
374 * all analyzable columns. We use a lower bound of 100 rows to avoid
375 * possible overflow in Vitter's algorithm.
378 for (i = 0; i < attr_cnt; i++)
380 if (targrows < vacattrstats[i]->minrows)
381 targrows = vacattrstats[i]->minrows;
383 for (ind = 0; ind < nindexes; ind++)
385 AnlIndexData *thisdata = &indexdata[ind];
387 for (i = 0; i < thisdata->attr_cnt; i++)
389 if (targrows < thisdata->vacattrstats[i]->minrows)
390 targrows = thisdata->vacattrstats[i]->minrows;
395 * Acquire the sample rows
397 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
398 numrows = acquire_sample_rows(onerel, rows, targrows,
399 &totalrows, &totaldeadrows);
402 * Compute the statistics. Temporary results during the calculations for
403 * each column are stored in a child context. The calc routines are
404 * responsible to make sure that whatever they store into the VacAttrStats
405 * structure is allocated in anl_context.
409 MemoryContext col_context,
412 col_context = AllocSetContextCreate(anl_context,
414 ALLOCSET_DEFAULT_MINSIZE,
415 ALLOCSET_DEFAULT_INITSIZE,
416 ALLOCSET_DEFAULT_MAXSIZE);
417 old_context = MemoryContextSwitchTo(col_context);
419 for (i = 0; i < attr_cnt; i++)
421 VacAttrStats *stats = vacattrstats[i];
424 stats->tupDesc = onerel->rd_att;
425 (*stats->compute_stats) (stats,
429 MemoryContextResetAndDeleteChildren(col_context);
433 compute_index_stats(onerel, totalrows,
438 MemoryContextSwitchTo(old_context);
439 MemoryContextDelete(col_context);
442 * Emit the completed stats rows into pg_statistic, replacing any
443 * previous statistics for the target columns. (If there are stats in
444 * pg_statistic for columns we didn't process, we leave them alone.)
446 update_attstats(relid, attr_cnt, vacattrstats);
448 for (ind = 0; ind < nindexes; ind++)
450 AnlIndexData *thisdata = &indexdata[ind];
452 update_attstats(RelationGetRelid(Irel[ind]),
453 thisdata->attr_cnt, thisdata->vacattrstats);
458 * If we are running a standalone ANALYZE, update pages/tuples stats in
459 * pg_class. We know the accurate page count from the smgr, but only an
460 * approximate number of tuples; therefore, if we are part of VACUUM
461 * ANALYZE do *not* overwrite the accurate count already inserted by
462 * VACUUM. The same consideration applies to indexes.
464 if (!vacstmt->vacuum)
466 vac_update_relstats(onerel,
467 RelationGetNumberOfBlocks(onerel),
468 totalrows, hasindex, InvalidTransactionId);
470 for (ind = 0; ind < nindexes; ind++)
472 AnlIndexData *thisdata = &indexdata[ind];
473 double totalindexrows;
475 totalindexrows = ceil(thisdata->tupleFract * totalrows);
476 vac_update_relstats(Irel[ind],
477 RelationGetNumberOfBlocks(Irel[ind]),
478 totalindexrows, false, InvalidTransactionId);
481 /* report results to the stats collector, too */
482 pgstat_report_analyze(onerel, totalrows, totaldeadrows);
485 /* We skip to here if there were no analyzable columns */
488 /* Done with indexes */
489 vac_close_indexes(nindexes, Irel, NoLock);
492 * Close source relation now, but keep lock so that no one deletes it
493 * before we commit. (If someone did, they'd fail to clean up the entries
494 * we made in pg_statistic. Also, releasing the lock before commit would
495 * expose us to concurrent-update failures in update_attstats.)
497 relation_close(onerel, NoLock);
499 /* Log the action if appropriate */
500 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
502 if (Log_autovacuum_min_duration == 0 ||
503 TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
504 Log_autovacuum_min_duration))
506 (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
507 get_database_name(MyDatabaseId),
508 get_namespace_name(RelationGetNamespace(onerel)),
509 RelationGetRelationName(onerel),
510 pg_rusage_show(&ru0))));
514 * Reset my PGPROC flag. Note: we need this here, and not in vacuum_rel,
515 * because the vacuum flag is cleared by the end-of-xact code.
517 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
518 MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
519 LWLockRelease(ProcArrayLock);
522 SetUserIdAndContext(save_userid, save_secdefcxt);
526 * Compute statistics about indexes of a relation
529 compute_index_stats(Relation onerel, double totalrows,
530 AnlIndexData *indexdata, int nindexes,
531 HeapTuple *rows, int numrows,
532 MemoryContext col_context)
534 MemoryContext ind_context,
536 Datum values[INDEX_MAX_KEYS];
537 bool isnull[INDEX_MAX_KEYS];
541 ind_context = AllocSetContextCreate(anl_context,
543 ALLOCSET_DEFAULT_MINSIZE,
544 ALLOCSET_DEFAULT_INITSIZE,
545 ALLOCSET_DEFAULT_MAXSIZE);
546 old_context = MemoryContextSwitchTo(ind_context);
548 for (ind = 0; ind < nindexes; ind++)
550 AnlIndexData *thisdata = &indexdata[ind];
551 IndexInfo *indexInfo = thisdata->indexInfo;
552 int attr_cnt = thisdata->attr_cnt;
553 TupleTableSlot *slot;
555 ExprContext *econtext;
562 double totalindexrows;
564 /* Ignore index if no columns to analyze and not partial */
565 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
569 * Need an EState for evaluation of index expressions and
570 * partial-index predicates. Create it in the per-index context to be
571 * sure it gets cleaned up at the bottom of the loop.
573 estate = CreateExecutorState();
574 econtext = GetPerTupleExprContext(estate);
575 /* Need a slot to hold the current heap tuple, too */
576 slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
578 /* Arrange for econtext's scan tuple to be the tuple under test */
579 econtext->ecxt_scantuple = slot;
581 /* Set up execution state for predicate. */
583 ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
586 /* Compute and save index expression values */
587 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
588 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
591 for (rowno = 0; rowno < numrows; rowno++)
593 HeapTuple heapTuple = rows[rowno];
595 /* Set up for predicate or expression evaluation */
596 ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
598 /* If index is partial, check predicate */
599 if (predicate != NIL)
601 if (!ExecQual(predicate, econtext, false))
609 * Evaluate the index row to compute expression values. We
610 * could do this by hand, but FormIndexDatum is convenient.
612 FormIndexDatum(indexInfo,
619 * Save just the columns we care about.
621 for (i = 0; i < attr_cnt; i++)
623 VacAttrStats *stats = thisdata->vacattrstats[i];
624 int attnum = stats->attr->attnum;
626 exprvals[tcnt] = values[attnum - 1];
627 exprnulls[tcnt] = isnull[attnum - 1];
634 * Having counted the number of rows that pass the predicate in the
635 * sample, we can estimate the total number of rows in the index.
637 thisdata->tupleFract = (double) numindexrows / (double) numrows;
638 totalindexrows = ceil(thisdata->tupleFract * totalrows);
641 * Now we can compute the statistics for the expression columns.
643 if (numindexrows > 0)
645 MemoryContextSwitchTo(col_context);
646 for (i = 0; i < attr_cnt; i++)
648 VacAttrStats *stats = thisdata->vacattrstats[i];
650 stats->exprvals = exprvals + i;
651 stats->exprnulls = exprnulls + i;
652 stats->rowstride = attr_cnt;
653 (*stats->compute_stats) (stats,
657 MemoryContextResetAndDeleteChildren(col_context);
662 MemoryContextSwitchTo(ind_context);
664 ExecDropSingleTupleTableSlot(slot);
665 FreeExecutorState(estate);
666 MemoryContextResetAndDeleteChildren(ind_context);
669 MemoryContextSwitchTo(old_context);
670 MemoryContextDelete(ind_context);
674 * examine_attribute -- pre-analysis of a single column
676 * Determine whether the column is analyzable; if so, create and initialize
677 * a VacAttrStats struct for it. If not, return NULL.
679 static VacAttrStats *
680 examine_attribute(Relation onerel, int attnum)
682 Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
688 /* Never analyze dropped columns */
689 if (attr->attisdropped)
692 /* Don't analyze column if user has specified not to */
693 if (attr->attstattarget == 0)
697 * Create the VacAttrStats struct.
699 stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
700 stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_TUPLE_SIZE);
701 memcpy(stats->attr, attr, ATTRIBUTE_TUPLE_SIZE);
702 typtuple = SearchSysCache(TYPEOID,
703 ObjectIdGetDatum(attr->atttypid),
705 if (!HeapTupleIsValid(typtuple))
706 elog(ERROR, "cache lookup failed for type %u", attr->atttypid);
707 stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
708 memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
709 ReleaseSysCache(typtuple);
710 stats->anl_context = anl_context;
711 stats->tupattnum = attnum;
714 * The fields describing the stats->stavalues[n] element types default
715 * to the type of the field being analyzed, but the type-specific
716 * typanalyze function can change them if it wants to store something
719 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
721 stats->statypid[i] = stats->attr->atttypid;
722 stats->statyplen[i] = stats->attrtype->typlen;
723 stats->statypbyval[i] = stats->attrtype->typbyval;
724 stats->statypalign[i] = stats->attrtype->typalign;
728 * Call the type-specific typanalyze function. If none is specified, use
731 if (OidIsValid(stats->attrtype->typanalyze))
732 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
733 PointerGetDatum(stats)));
735 ok = std_typanalyze(stats);
737 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
739 pfree(stats->attrtype);
749 * BlockSampler_Init -- prepare for random sampling of blocknumbers
751 * BlockSampler is used for stage one of our new two-stage tuple
752 * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
753 * "Large DB"). It selects a random sample of samplesize blocks out of
754 * the nblocks blocks in the table. If the table has less than
755 * samplesize blocks, all blocks are selected.
757 * Since we know the total number of blocks in advance, we can use the
758 * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
762 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
764 bs->N = nblocks; /* measured table size */
767 * If we decide to reduce samplesize for tables that have less or not much
768 * more than samplesize blocks, here is the place to do it.
771 bs->t = 0; /* blocks scanned so far */
772 bs->m = 0; /* blocks selected so far */
776 BlockSampler_HasMore(BlockSampler bs)
778 return (bs->t < bs->N) && (bs->m < bs->n);
782 BlockSampler_Next(BlockSampler bs)
784 BlockNumber K = bs->N - bs->t; /* remaining blocks */
785 int k = bs->n - bs->m; /* blocks still to sample */
786 double p; /* probability to skip block */
787 double V; /* random */
789 Assert(BlockSampler_HasMore(bs)); /* hence K > 0 and k > 0 */
791 if ((BlockNumber) k >= K)
793 /* need all the rest */
799 * It is not obvious that this code matches Knuth's Algorithm S.
800 * Knuth says to skip the current block with probability 1 - k/K.
801 * If we are to skip, we should advance t (hence decrease K), and
802 * repeat the same probabilistic test for the next block. The naive
803 * implementation thus requires a random_fract() call for each block
804 * number. But we can reduce this to one random_fract() call per
805 * selected block, by noting that each time the while-test succeeds,
806 * we can reinterpret V as a uniform random number in the range 0 to p.
807 * Therefore, instead of choosing a new V, we just adjust p to be
808 * the appropriate fraction of its former value, and our next loop
809 * makes the appropriate probabilistic test.
811 * We have initially K > k > 0. If the loop reduces K to equal k,
812 * the next while-test must fail since p will become exactly zero
813 * (we assume there will not be roundoff error in the division).
814 * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
815 * to be doubly sure about roundoff error.) Therefore K cannot become
816 * less than k, which means that we cannot fail to select enough blocks.
820 p = 1.0 - (double) k / (double) K;
825 K--; /* keep K == N - t */
827 /* adjust p to be new cutoff point in reduced range */
828 p *= 1.0 - (double) k / (double) K;
837 * acquire_sample_rows -- acquire a random sample of rows from the table
839 * As of May 2004 we use a new two-stage method: Stage one selects up
840 * to targrows random blocks (or all blocks, if there aren't so many).
841 * Stage two scans these blocks and uses the Vitter algorithm to create
842 * a random sample of targrows rows (or less, if there are less in the
843 * sample of blocks). The two stages are executed simultaneously: each
844 * block is processed as soon as stage one returns its number and while
845 * the rows are read stage two controls which ones are to be inserted
848 * Although every row has an equal chance of ending up in the final
849 * sample, this sampling method is not perfect: not every possible
850 * sample has an equal chance of being selected. For large relations
851 * the number of different blocks represented by the sample tends to be
852 * too small. We can live with that for now. Improvements are welcome.
854 * We also estimate the total numbers of live and dead rows in the table,
855 * and return them into *totalrows and *totaldeadrows, respectively.
857 * An important property of this sampling method is that because we do
858 * look at a statistically unbiased set of blocks, we should get
859 * unbiased estimates of the average numbers of live and dead rows per
860 * block. The previous sampling method put too much credence in the row
861 * density near the start of the table.
863 * The returned list of tuples is in order by physical position in the table.
864 * (We will rely on this later to derive correlation estimates.)
867 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
868 double *totalrows, double *totaldeadrows)
870 int numrows = 0; /* # rows now in reservoir */
871 double samplerows = 0; /* total # rows collected */
872 double liverows = 0; /* # live rows seen */
873 double deadrows = 0; /* # dead rows seen */
874 double rowstoskip = -1; /* -1 means not set yet */
875 BlockNumber totalblocks;
876 TransactionId OldestXmin;
880 Assert(targrows > 1);
882 totalblocks = RelationGetNumberOfBlocks(onerel);
884 /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
885 OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
887 /* Prepare for sampling block numbers */
888 BlockSampler_Init(&bs, totalblocks, targrows);
889 /* Prepare for sampling rows */
890 rstate = init_selection_state(targrows);
892 /* Outer loop over blocks to sample */
893 while (BlockSampler_HasMore(&bs))
895 BlockNumber targblock = BlockSampler_Next(&bs);
898 OffsetNumber targoffset,
901 vacuum_delay_point();
904 * We must maintain a pin on the target page's buffer to ensure that
905 * the maxoffset value stays good (else concurrent VACUUM might delete
906 * tuples out from under us). Hence, pin the page until we are done
907 * looking at it. We also choose to hold sharelock on the buffer
908 * throughout --- we could release and re-acquire sharelock for
909 * each tuple, but since we aren't doing much work per tuple, the
910 * extra lock traffic is probably better avoided.
912 targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
913 RBM_NORMAL, vac_strategy);
914 LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
915 targpage = BufferGetPage(targbuffer);
916 maxoffset = PageGetMaxOffsetNumber(targpage);
918 /* Inner loop over all tuples on the selected page */
919 for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
922 HeapTupleData targtuple;
923 bool sample_it = false;
925 itemid = PageGetItemId(targpage, targoffset);
928 * We ignore unused and redirect line pointers. DEAD line
929 * pointers should be counted as dead, because we need vacuum
930 * to run to get rid of them. Note that this rule agrees with
931 * the way that heap_page_prune() counts things.
933 if (!ItemIdIsNormal(itemid))
935 if (ItemIdIsDead(itemid))
940 ItemPointerSet(&targtuple.t_self, targblock, targoffset);
942 targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
943 targtuple.t_len = ItemIdGetLength(itemid);
945 switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
955 case HEAPTUPLE_RECENTLY_DEAD:
956 /* Count dead and recently-dead rows */
960 case HEAPTUPLE_INSERT_IN_PROGRESS:
962 * Insert-in-progress rows are not counted. We assume
963 * that when the inserting transaction commits or aborts,
964 * it will send a stats message to increment the proper
965 * count. This works right only if that transaction ends
966 * after we finish analyzing the table; if things happen
967 * in the other order, its stats update will be
968 * overwritten by ours. However, the error will be
969 * large only if the other transaction runs long enough
970 * to insert many tuples, so assuming it will finish
971 * after us is the safer option.
973 * A special case is that the inserting transaction might
974 * be our own. In this case we should count and sample
975 * the row, to accommodate users who load a table and
976 * analyze it in one transaction. (pgstat_report_analyze
977 * has to adjust the numbers we send to the stats collector
978 * to make this come out right.)
980 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
987 case HEAPTUPLE_DELETE_IN_PROGRESS:
989 * We count delete-in-progress rows as still live, using
990 * the same reasoning given above; but we don't bother to
991 * include them in the sample.
993 * If the delete was done by our own transaction, however,
994 * we must count the row as dead to make
995 * pgstat_report_analyze's stats adjustments come out
996 * right. (Note: this works out properly when the row
997 * was both inserted and deleted in our xact.)
999 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
1006 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1013 * The first targrows sample rows are simply copied into the
1014 * reservoir. Then we start replacing tuples in the sample
1015 * until we reach the end of the relation. This algorithm is
1016 * from Jeff Vitter's paper (see full citation below). It
1017 * works by repeatedly computing the number of tuples to skip
1018 * before selecting a tuple, which replaces a randomly chosen
1019 * element of the reservoir (current set of tuples). At all
1020 * times the reservoir is a true random sample of the tuples
1021 * we've passed over so far, so when we fall off the end of
1022 * the relation we're done.
1024 if (numrows < targrows)
1025 rows[numrows++] = heap_copytuple(&targtuple);
1029 * t in Vitter's paper is the number of records already
1030 * processed. If we need to compute a new S value, we
1031 * must use the not-yet-incremented value of samplerows
1035 rowstoskip = get_next_S(samplerows, targrows, &rstate);
1037 if (rowstoskip <= 0)
1040 * Found a suitable tuple, so save it, replacing one
1041 * old tuple at random
1043 int k = (int) (targrows * random_fract());
1045 Assert(k >= 0 && k < targrows);
1046 heap_freetuple(rows[k]);
1047 rows[k] = heap_copytuple(&targtuple);
1057 /* Now release the lock and pin on the page */
1058 UnlockReleaseBuffer(targbuffer);
1062 * If we didn't find as many tuples as we wanted then we're done. No sort
1063 * is needed, since they're already in order.
1065 * Otherwise we need to sort the collected tuples by position
1066 * (itempointer). It's not worth worrying about corner cases where the
1067 * tuples are already sorted.
1069 if (numrows == targrows)
1070 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1073 * Estimate total numbers of rows in relation.
1077 *totalrows = floor((liverows * totalblocks) / bs.m + 0.5);
1078 *totaldeadrows = floor((deadrows * totalblocks) / bs.m + 0.5);
1083 *totaldeadrows = 0.0;
1087 * Emit some interesting relation info
1090 (errmsg("\"%s\": scanned %d of %u pages, "
1091 "containing %.0f live rows and %.0f dead rows; "
1092 "%d rows in sample, %.0f estimated total rows",
1093 RelationGetRelationName(onerel),
1096 numrows, *totalrows)));
1101 /* Select a random value R uniformly distributed in (0 - 1) */
1105 return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
1109 * These two routines embody Algorithm Z from "Random sampling with a
1110 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1111 * (Mar. 1985), Pages 37-57. Vitter describes his algorithm in terms
1112 * of the count S of records to skip before processing another record.
1113 * It is computed primarily based on t, the number of records already read.
1114 * The only extra state needed between calls is W, a random state variable.
1116 * init_selection_state computes the initial W value.
1118 * Given that we've already read t records (t >= n), get_next_S
1119 * determines the number of records to skip before the next record is
1123 init_selection_state(int n)
1125 /* Initial value of W (for use when Algorithm Z is first applied) */
1126 return exp(-log(random_fract()) / n);
1130 get_next_S(double t, int n, double *stateptr)
1134 /* The magic constant here is T from Vitter's paper */
1135 if (t <= (22.0 * n))
1137 /* Process records using Algorithm X until t is large enough */
1141 V = random_fract(); /* Generate V */
1144 /* Note: "num" in Vitter's code is always equal to t - n */
1145 quot = (t - (double) n) / t;
1146 /* Find min S satisfying (4.1) */
1151 quot *= (t - (double) n) / t;
1156 /* Now apply Algorithm Z */
1157 double W = *stateptr;
1158 double term = t - (double) n + 1;
1172 /* Generate U and X */
1175 S = floor(X); /* S is tentatively set to floor(X) */
1176 /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1177 tmp = (t + 1) / term;
1178 lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
1179 rhs = (((t + X) / (term + S)) * term) / t;
1185 /* Test if U <= f(S)/cg(X) */
1186 y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1190 numer_lim = term + S;
1194 denom = t - (double) n + S;
1197 for (numer = t + S; numer >= numer_lim; numer -= 1)
1202 W = exp(-log(random_fract()) / n); /* Generate W in advance */
1203 if (exp(log(y) / n) <= (t + X) / t)
1212 * qsort comparator for sorting rows[] array
1215 compare_rows(const void *a, const void *b)
1217 HeapTuple ha = *(HeapTuple *) a;
1218 HeapTuple hb = *(HeapTuple *) b;
1219 BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1220 OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1221 BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1222 OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1237 * update_attstats() -- update attribute statistics for one relation
1239 * Statistics are stored in several places: the pg_class row for the
1240 * relation has stats about the whole relation, and there is a
1241 * pg_statistic row for each (non-system) attribute that has ever
1242 * been analyzed. The pg_class values are updated by VACUUM, not here.
1244 * pg_statistic rows are just added or updated normally. This means
1245 * that pg_statistic will probably contain some deleted rows at the
1246 * completion of a vacuum cycle, unless it happens to get vacuumed last.
1248 * To keep things simple, we punt for pg_statistic, and don't try
1249 * to compute or store rows for pg_statistic itself in pg_statistic.
1250 * This could possibly be made to work, but it's not worth the trouble.
1251 * Note analyze_rel() has seen to it that we won't come here when
1252 * vacuuming pg_statistic itself.
1254 * Note: there would be a race condition here if two backends could
1255 * ANALYZE the same table concurrently. Presently, we lock that out
1256 * by taking a self-exclusive lock on the relation in analyze_rel().
1259 update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats)
1265 return; /* nothing to do */
1267 sd = heap_open(StatisticRelationId, RowExclusiveLock);
1269 for (attno = 0; attno < natts; attno++)
1271 VacAttrStats *stats = vacattrstats[attno];
1277 Datum values[Natts_pg_statistic];
1278 bool nulls[Natts_pg_statistic];
1279 bool replaces[Natts_pg_statistic];
1281 /* Ignore attr if we weren't able to collect stats */
1282 if (!stats->stats_valid)
1286 * Construct a new pg_statistic tuple
1288 for (i = 0; i < Natts_pg_statistic; ++i)
1295 values[i++] = ObjectIdGetDatum(relid); /* starelid */
1296 values[i++] = Int16GetDatum(stats->attr->attnum); /* staattnum */
1297 values[i++] = Float4GetDatum(stats->stanullfrac); /* stanullfrac */
1298 values[i++] = Int32GetDatum(stats->stawidth); /* stawidth */
1299 values[i++] = Float4GetDatum(stats->stadistinct); /* stadistinct */
1300 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1302 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1304 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1306 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1308 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1310 int nnum = stats->numnumbers[k];
1314 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1317 for (n = 0; n < nnum; n++)
1318 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1319 /* XXX knows more than it should about type float4: */
1320 arry = construct_array(numdatums, nnum,
1322 sizeof(float4), FLOAT4PASSBYVAL, 'i');
1323 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1328 values[i++] = (Datum) 0;
1331 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1333 if (stats->numvalues[k] > 0)
1337 arry = construct_array(stats->stavalues[k],
1338 stats->numvalues[k],
1340 stats->statyplen[k],
1341 stats->statypbyval[k],
1342 stats->statypalign[k]);
1343 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1348 values[i++] = (Datum) 0;
1352 /* Is there already a pg_statistic tuple for this attribute? */
1353 oldtup = SearchSysCache(STATRELATT,
1354 ObjectIdGetDatum(relid),
1355 Int16GetDatum(stats->attr->attnum),
1358 if (HeapTupleIsValid(oldtup))
1360 /* Yes, replace it */
1361 stup = heap_modify_tuple(oldtup,
1362 RelationGetDescr(sd),
1366 ReleaseSysCache(oldtup);
1367 simple_heap_update(sd, &stup->t_self, stup);
1371 /* No, insert new tuple */
1372 stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1373 simple_heap_insert(sd, stup);
1376 /* update indexes too */
1377 CatalogUpdateIndexes(sd, stup);
1379 heap_freetuple(stup);
1382 heap_close(sd, RowExclusiveLock);
1386 * Standard fetch function for use by compute_stats subroutines.
1388 * This exists to provide some insulation between compute_stats routines
1389 * and the actual storage of the sample data.
1392 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1394 int attnum = stats->tupattnum;
1395 HeapTuple tuple = stats->rows[rownum];
1396 TupleDesc tupDesc = stats->tupDesc;
1398 return heap_getattr(tuple, attnum, tupDesc, isNull);
1402 * Fetch function for analyzing index expressions.
1404 * We have not bothered to construct index tuples, instead the data is
1405 * just in Datum arrays.
1408 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1412 /* exprvals and exprnulls are already offset for proper column */
1413 i = rownum * stats->rowstride;
1414 *isNull = stats->exprnulls[i];
1415 return stats->exprvals[i];
1419 /*==========================================================================
1421 * Code below this point represents the "standard" type-specific statistics
1422 * analysis algorithms. This code can be replaced on a per-data-type basis
1423 * by setting a nonzero value in pg_type.typanalyze.
1425 *==========================================================================
1430 * To avoid consuming too much memory during analysis and/or too much space
1431 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1432 * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1433 * and distinct-value calculations since a wide value is unlikely to be
1434 * duplicated at all, much less be a most-common value. For the same reason,
1435 * ignoring wide values will not affect our estimates of histogram bin
1436 * boundaries very much.
1438 #define WIDTH_THRESHOLD 1024
1440 #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1441 #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1444 * Extra information used by the default analysis routines
1448 Oid eqopr; /* '=' operator for datatype, if any */
1449 Oid eqfunc; /* and associated function */
1450 Oid ltopr; /* '<' operator for datatype, if any */
1455 Datum value; /* a data value */
1456 int tupno; /* position index for tuple it came from */
1461 int count; /* # of duplicates */
1462 int first; /* values[] index of first occurrence */
1470 } CompareScalarsContext;
1473 static void compute_minimal_stats(VacAttrStatsP stats,
1474 AnalyzeAttrFetchFunc fetchfunc,
1477 static void compute_scalar_stats(VacAttrStatsP stats,
1478 AnalyzeAttrFetchFunc fetchfunc,
1481 static int compare_scalars(const void *a, const void *b, void *arg);
1482 static int compare_mcvs(const void *a, const void *b);
1486 * std_typanalyze -- the default type-specific typanalyze function
1489 std_typanalyze(VacAttrStats *stats)
1491 Form_pg_attribute attr = stats->attr;
1494 StdAnalyzeData *mystats;
1496 /* If the attstattarget column is negative, use the default value */
1497 /* NB: it is okay to scribble on stats->attr since it's a copy */
1498 if (attr->attstattarget < 0)
1499 attr->attstattarget = default_statistics_target;
1501 /* Look for default "<" and "=" operators for column's type */
1502 get_sort_group_operators(attr->atttypid,
1503 false, false, false,
1504 <opr, &eqopr, NULL);
1506 /* If column has no "=" operator, we can't do much of anything */
1507 if (!OidIsValid(eqopr))
1510 /* Save the operator info for compute_stats routines */
1511 mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1512 mystats->eqopr = eqopr;
1513 mystats->eqfunc = get_opcode(eqopr);
1514 mystats->ltopr = ltopr;
1515 stats->extra_data = mystats;
1518 * Determine which standard statistics algorithm to use
1520 if (OidIsValid(ltopr))
1522 /* Seems to be a scalar datatype */
1523 stats->compute_stats = compute_scalar_stats;
1524 /*--------------------
1525 * The following choice of minrows is based on the paper
1526 * "Random sampling for histogram construction: how much is enough?"
1527 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1528 * Proceedings of ACM SIGMOD International Conference on Management
1529 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1530 * says that for table size n, histogram size k, maximum relative
1531 * error in bin size f, and error probability gamma, the minimum
1532 * random sample size is
1533 * r = 4 * k * ln(2*n/gamma) / f^2
1534 * Taking f = 0.5, gamma = 0.01, n = 1 million rows, we obtain
1536 * Note that because of the log function, the dependence on n is
1537 * quite weak; even at n = 1 billion, a 300*k sample gives <= 0.59
1538 * bin size error with probability 0.99. So there's no real need to
1539 * scale for n, which is a good thing because we don't necessarily
1540 * know it at this point.
1541 *--------------------
1543 stats->minrows = 300 * attr->attstattarget;
1547 /* Can't do much but the minimal stuff */
1548 stats->compute_stats = compute_minimal_stats;
1549 /* Might as well use the same minrows as above */
1550 stats->minrows = 300 * attr->attstattarget;
1557 * compute_minimal_stats() -- compute minimal column statistics
1559 * We use this when we can find only an "=" operator for the datatype.
1561 * We determine the fraction of non-null rows, the average width, the
1562 * most common values, and the (estimated) number of distinct values.
1564 * The most common values are determined by brute force: we keep a list
1565 * of previously seen values, ordered by number of times seen, as we scan
1566 * the samples. A newly seen value is inserted just after the last
1567 * multiply-seen value, causing the bottommost (oldest) singly-seen value
1568 * to drop off the list. The accuracy of this method, and also its cost,
1569 * depend mainly on the length of the list we are willing to keep.
1572 compute_minimal_stats(VacAttrStatsP stats,
1573 AnalyzeAttrFetchFunc fetchfunc,
1579 int nonnull_cnt = 0;
1580 int toowide_cnt = 0;
1581 double total_width = 0;
1582 bool is_varlena = (!stats->attr->attbyval &&
1583 stats->attr->attlen == -1);
1584 bool is_varwidth = (!stats->attr->attbyval &&
1585 stats->attr->attlen < 0);
1595 int num_mcv = stats->attr->attstattarget;
1596 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1599 * We track up to 2*n values for an n-element MCV list; but at least 10
1601 track_max = 2 * num_mcv;
1604 track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1607 fmgr_info(mystats->eqfunc, &f_cmpeq);
1609 for (i = 0; i < samplerows; i++)
1617 vacuum_delay_point();
1619 value = fetchfunc(stats, i, &isnull);
1621 /* Check for null/nonnull */
1630 * If it's a variable-width field, add up widths for average width
1631 * calculation. Note that if the value is toasted, we use the toasted
1632 * width. We don't bother with this calculation if it's a fixed-width
1637 total_width += VARSIZE_ANY(DatumGetPointer(value));
1640 * If the value is toasted, we want to detoast it just once to
1641 * avoid repeated detoastings and resultant excess memory usage
1642 * during the comparisons. Also, check to see if the value is
1643 * excessively wide, and if so don't detoast at all --- just
1646 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1651 value = PointerGetDatum(PG_DETOAST_DATUM(value));
1653 else if (is_varwidth)
1655 /* must be cstring */
1656 total_width += strlen(DatumGetCString(value)) + 1;
1660 * See if the value matches anything we're already tracking.
1663 firstcount1 = track_cnt;
1664 for (j = 0; j < track_cnt; j++)
1666 if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
1671 if (j < firstcount1 && track[j].count == 1)
1679 /* This value may now need to "bubble up" in the track list */
1680 while (j > 0 && track[j].count > track[j - 1].count)
1682 swapDatum(track[j].value, track[j - 1].value);
1683 swapInt(track[j].count, track[j - 1].count);
1689 /* No match. Insert at head of count-1 list */
1690 if (track_cnt < track_max)
1692 for (j = track_cnt - 1; j > firstcount1; j--)
1694 track[j].value = track[j - 1].value;
1695 track[j].count = track[j - 1].count;
1697 if (firstcount1 < track_cnt)
1699 track[firstcount1].value = value;
1700 track[firstcount1].count = 1;
1705 /* We can only compute real stats if we found some non-null values. */
1706 if (nonnull_cnt > 0)
1711 stats->stats_valid = true;
1712 /* Do the simple null-frac and width stats */
1713 stats->stanullfrac = (double) null_cnt / (double) samplerows;
1715 stats->stawidth = total_width / (double) nonnull_cnt;
1717 stats->stawidth = stats->attrtype->typlen;
1719 /* Count the number of values we found multiple times */
1721 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
1723 if (track[nmultiple].count == 1)
1725 summultiple += track[nmultiple].count;
1730 /* If we found no repeated values, assume it's a unique column */
1731 stats->stadistinct = -1.0;
1733 else if (track_cnt < track_max && toowide_cnt == 0 &&
1734 nmultiple == track_cnt)
1737 * Our track list includes every value in the sample, and every
1738 * value appeared more than once. Assume the column has just
1741 stats->stadistinct = track_cnt;
1746 * Estimate the number of distinct values using the estimator
1747 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
1748 * n*d / (n - f1 + f1*n/N)
1749 * where f1 is the number of distinct values that occurred
1750 * exactly once in our sample of n rows (from a total of N),
1751 * and d is the total number of distinct values in the sample.
1752 * This is their Duj1 estimator; the other estimators they
1753 * recommend are considerably more complex, and are numerically
1754 * very unstable when n is much smaller than N.
1756 * We assume (not very reliably!) that all the multiply-occurring
1757 * values are reflected in the final track[] list, and the other
1758 * nonnull values all appeared but once. (XXX this usually
1759 * results in a drastic overestimate of ndistinct. Can we do
1763 int f1 = nonnull_cnt - summultiple;
1764 int d = f1 + nmultiple;
1769 numer = (double) samplerows *(double) d;
1771 denom = (double) (samplerows - f1) +
1772 (double) f1 *(double) samplerows / totalrows;
1774 stadistinct = numer / denom;
1775 /* Clamp to sane range in case of roundoff error */
1776 if (stadistinct < (double) d)
1777 stadistinct = (double) d;
1778 if (stadistinct > totalrows)
1779 stadistinct = totalrows;
1780 stats->stadistinct = floor(stadistinct + 0.5);
1784 * If we estimated the number of distinct values at more than 10% of
1785 * the total row count (a very arbitrary limit), then assume that
1786 * stadistinct should scale with the row count rather than be a fixed
1789 if (stats->stadistinct > 0.1 * totalrows)
1790 stats->stadistinct = -(stats->stadistinct / totalrows);
1793 * Decide how many values are worth storing as most-common values. If
1794 * we are able to generate a complete MCV list (all the values in the
1795 * sample will fit, and we think these are all the ones in the table),
1796 * then do so. Otherwise, store only those values that are
1797 * significantly more common than the (estimated) average. We set the
1798 * threshold rather arbitrarily at 25% more than average, with at
1799 * least 2 instances in the sample.
1801 if (track_cnt < track_max && toowide_cnt == 0 &&
1802 stats->stadistinct > 0 &&
1803 track_cnt <= num_mcv)
1805 /* Track list includes all values seen, and all will fit */
1806 num_mcv = track_cnt;
1810 double ndistinct = stats->stadistinct;
1815 ndistinct = -ndistinct * totalrows;
1816 /* estimate # of occurrences in sample of a typical value */
1817 avgcount = (double) samplerows / ndistinct;
1818 /* set minimum threshold count to store a value */
1819 mincount = avgcount * 1.25;
1822 if (num_mcv > track_cnt)
1823 num_mcv = track_cnt;
1824 for (i = 0; i < num_mcv; i++)
1826 if (track[i].count < mincount)
1834 /* Generate MCV slot entry */
1837 MemoryContext old_context;
1841 /* Must copy the target values into anl_context */
1842 old_context = MemoryContextSwitchTo(stats->anl_context);
1843 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
1844 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
1845 for (i = 0; i < num_mcv; i++)
1847 mcv_values[i] = datumCopy(track[i].value,
1848 stats->attr->attbyval,
1849 stats->attr->attlen);
1850 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
1852 MemoryContextSwitchTo(old_context);
1854 stats->stakind[0] = STATISTIC_KIND_MCV;
1855 stats->staop[0] = mystats->eqopr;
1856 stats->stanumbers[0] = mcv_freqs;
1857 stats->numnumbers[0] = num_mcv;
1858 stats->stavalues[0] = mcv_values;
1859 stats->numvalues[0] = num_mcv;
1861 * Accept the defaults for stats->statypid and others.
1862 * They have been set before we were called (see vacuum.h)
1866 else if (null_cnt > 0)
1868 /* We found only nulls; assume the column is entirely null */
1869 stats->stats_valid = true;
1870 stats->stanullfrac = 1.0;
1872 stats->stawidth = 0; /* "unknown" */
1874 stats->stawidth = stats->attrtype->typlen;
1875 stats->stadistinct = 0.0; /* "unknown" */
1878 /* We don't need to bother cleaning up any of our temporary palloc's */
1883 * compute_scalar_stats() -- compute column statistics
1885 * We use this when we can find "=" and "<" operators for the datatype.
1887 * We determine the fraction of non-null rows, the average width, the
1888 * most common values, the (estimated) number of distinct values, the
1889 * distribution histogram, and the correlation of physical to logical order.
1891 * The desired stats can be determined fairly easily after sorting the
1892 * data values into order.
1895 compute_scalar_stats(VacAttrStatsP stats,
1896 AnalyzeAttrFetchFunc fetchfunc,
1902 int nonnull_cnt = 0;
1903 int toowide_cnt = 0;
1904 double total_width = 0;
1905 bool is_varlena = (!stats->attr->attbyval &&
1906 stats->attr->attlen == -1);
1907 bool is_varwidth = (!stats->attr->attbyval &&
1908 stats->attr->attlen < 0);
1916 ScalarMCVItem *track;
1918 int num_mcv = stats->attr->attstattarget;
1919 int num_bins = stats->attr->attstattarget;
1920 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1922 values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
1923 tupnoLink = (int *) palloc(samplerows * sizeof(int));
1924 track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
1926 SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
1927 fmgr_info(cmpFn, &f_cmpfn);
1929 /* Initial scan to find sortable values */
1930 for (i = 0; i < samplerows; i++)
1935 vacuum_delay_point();
1937 value = fetchfunc(stats, i, &isnull);
1939 /* Check for null/nonnull */
1948 * If it's a variable-width field, add up widths for average width
1949 * calculation. Note that if the value is toasted, we use the toasted
1950 * width. We don't bother with this calculation if it's a fixed-width
1955 total_width += VARSIZE_ANY(DatumGetPointer(value));
1958 * If the value is toasted, we want to detoast it just once to
1959 * avoid repeated detoastings and resultant excess memory usage
1960 * during the comparisons. Also, check to see if the value is
1961 * excessively wide, and if so don't detoast at all --- just
1964 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1969 value = PointerGetDatum(PG_DETOAST_DATUM(value));
1971 else if (is_varwidth)
1973 /* must be cstring */
1974 total_width += strlen(DatumGetCString(value)) + 1;
1977 /* Add it to the list to be sorted */
1978 values[values_cnt].value = value;
1979 values[values_cnt].tupno = values_cnt;
1980 tupnoLink[values_cnt] = values_cnt;
1984 /* We can only compute real stats if we found some sortable values. */
1987 int ndistinct, /* # distinct values in sample */
1988 nmultiple, /* # that appear multiple times */
1992 CompareScalarsContext cxt;
1994 /* Sort the collected values */
1995 cxt.cmpFn = &f_cmpfn;
1996 cxt.cmpFlags = cmpFlags;
1997 cxt.tupnoLink = tupnoLink;
1998 qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
1999 compare_scalars, (void *) &cxt);
2002 * Now scan the values in order, find the most common ones, and also
2003 * accumulate ordering-correlation statistics.
2005 * To determine which are most common, we first have to count the
2006 * number of duplicates of each value. The duplicates are adjacent in
2007 * the sorted list, so a brute-force approach is to compare successive
2008 * datum values until we find two that are not equal. However, that
2009 * requires N-1 invocations of the datum comparison routine, which are
2010 * completely redundant with work that was done during the sort. (The
2011 * sort algorithm must at some point have compared each pair of items
2012 * that are adjacent in the sorted order; otherwise it could not know
2013 * that it's ordered the pair correctly.) We exploit this by having
2014 * compare_scalars remember the highest tupno index that each
2015 * ScalarItem has been found equal to. At the end of the sort, a
2016 * ScalarItem's tupnoLink will still point to itself if and only if it
2017 * is the last item of its group of duplicates (since the group will
2018 * be ordered by tupno).
2024 for (i = 0; i < values_cnt; i++)
2026 int tupno = values[i].tupno;
2028 corr_xysum += ((double) i) * ((double) tupno);
2030 if (tupnoLink[tupno] == tupno)
2032 /* Reached end of duplicates of this value */
2037 if (track_cnt < num_mcv ||
2038 dups_cnt > track[track_cnt - 1].count)
2041 * Found a new item for the mcv list; find its
2042 * position, bubbling down old items if needed. Loop
2043 * invariant is that j points at an empty/ replaceable
2048 if (track_cnt < num_mcv)
2050 for (j = track_cnt - 1; j > 0; j--)
2052 if (dups_cnt <= track[j - 1].count)
2054 track[j].count = track[j - 1].count;
2055 track[j].first = track[j - 1].first;
2057 track[j].count = dups_cnt;
2058 track[j].first = i + 1 - dups_cnt;
2065 stats->stats_valid = true;
2066 /* Do the simple null-frac and width stats */
2067 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2069 stats->stawidth = total_width / (double) nonnull_cnt;
2071 stats->stawidth = stats->attrtype->typlen;
2075 /* If we found no repeated values, assume it's a unique column */
2076 stats->stadistinct = -1.0;
2078 else if (toowide_cnt == 0 && nmultiple == ndistinct)
2081 * Every value in the sample appeared more than once. Assume the
2082 * column has just these values.
2084 stats->stadistinct = ndistinct;
2089 * Estimate the number of distinct values using the estimator
2090 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2091 * n*d / (n - f1 + f1*n/N)
2092 * where f1 is the number of distinct values that occurred
2093 * exactly once in our sample of n rows (from a total of N),
2094 * and d is the total number of distinct values in the sample.
2095 * This is their Duj1 estimator; the other estimators they
2096 * recommend are considerably more complex, and are numerically
2097 * very unstable when n is much smaller than N.
2099 * Overwidth values are assumed to have been distinct.
2102 int f1 = ndistinct - nmultiple + toowide_cnt;
2103 int d = f1 + nmultiple;
2108 numer = (double) samplerows *(double) d;
2110 denom = (double) (samplerows - f1) +
2111 (double) f1 *(double) samplerows / totalrows;
2113 stadistinct = numer / denom;
2114 /* Clamp to sane range in case of roundoff error */
2115 if (stadistinct < (double) d)
2116 stadistinct = (double) d;
2117 if (stadistinct > totalrows)
2118 stadistinct = totalrows;
2119 stats->stadistinct = floor(stadistinct + 0.5);
2123 * If we estimated the number of distinct values at more than 10% of
2124 * the total row count (a very arbitrary limit), then assume that
2125 * stadistinct should scale with the row count rather than be a fixed
2128 if (stats->stadistinct > 0.1 * totalrows)
2129 stats->stadistinct = -(stats->stadistinct / totalrows);
2132 * Decide how many values are worth storing as most-common values. If
2133 * we are able to generate a complete MCV list (all the values in the
2134 * sample will fit, and we think these are all the ones in the table),
2135 * then do so. Otherwise, store only those values that are
2136 * significantly more common than the (estimated) average. We set the
2137 * threshold rather arbitrarily at 25% more than average, with at
2138 * least 2 instances in the sample. Also, we won't suppress values
2139 * that have a frequency of at least 1/K where K is the intended
2140 * number of histogram bins; such values might otherwise cause us to
2141 * emit duplicate histogram bin boundaries.
2143 if (track_cnt == ndistinct && toowide_cnt == 0 &&
2144 stats->stadistinct > 0 &&
2145 track_cnt <= num_mcv)
2147 /* Track list includes all values seen, and all will fit */
2148 num_mcv = track_cnt;
2152 double ndistinct = stats->stadistinct;
2158 ndistinct = -ndistinct * totalrows;
2159 /* estimate # of occurrences in sample of a typical value */
2160 avgcount = (double) samplerows / ndistinct;
2161 /* set minimum threshold count to store a value */
2162 mincount = avgcount * 1.25;
2165 /* don't let threshold exceed 1/K, however */
2166 maxmincount = (double) samplerows / (double) num_bins;
2167 if (mincount > maxmincount)
2168 mincount = maxmincount;
2169 if (num_mcv > track_cnt)
2170 num_mcv = track_cnt;
2171 for (i = 0; i < num_mcv; i++)
2173 if (track[i].count < mincount)
2181 /* Generate MCV slot entry */
2184 MemoryContext old_context;
2188 /* Must copy the target values into anl_context */
2189 old_context = MemoryContextSwitchTo(stats->anl_context);
2190 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2191 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2192 for (i = 0; i < num_mcv; i++)
2194 mcv_values[i] = datumCopy(values[track[i].first].value,
2195 stats->attr->attbyval,
2196 stats->attr->attlen);
2197 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2199 MemoryContextSwitchTo(old_context);
2201 stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2202 stats->staop[slot_idx] = mystats->eqopr;
2203 stats->stanumbers[slot_idx] = mcv_freqs;
2204 stats->numnumbers[slot_idx] = num_mcv;
2205 stats->stavalues[slot_idx] = mcv_values;
2206 stats->numvalues[slot_idx] = num_mcv;
2208 * Accept the defaults for stats->statypid and others.
2209 * They have been set before we were called (see vacuum.h)
2215 * Generate a histogram slot entry if there are at least two distinct
2216 * values not accounted for in the MCV list. (This ensures the
2217 * histogram won't collapse to empty or a singleton.)
2219 num_hist = ndistinct - num_mcv;
2220 if (num_hist > num_bins)
2221 num_hist = num_bins + 1;
2224 MemoryContext old_context;
2228 /* Sort the MCV items into position order to speed next loop */
2229 qsort((void *) track, num_mcv,
2230 sizeof(ScalarMCVItem), compare_mcvs);
2233 * Collapse out the MCV items from the values[] array.
2235 * Note we destroy the values[] array here... but we don't need it
2236 * for anything more. We do, however, still need values_cnt.
2237 * nvals will be the number of remaining entries in values[].
2246 j = 0; /* index of next interesting MCV item */
2247 while (src < values_cnt)
2253 int first = track[j].first;
2257 /* advance past this MCV item */
2258 src = first + track[j].count;
2262 ncopy = first - src;
2265 ncopy = values_cnt - src;
2266 memmove(&values[dest], &values[src],
2267 ncopy * sizeof(ScalarItem));
2275 Assert(nvals >= num_hist);
2277 /* Must copy the target values into anl_context */
2278 old_context = MemoryContextSwitchTo(stats->anl_context);
2279 hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2280 for (i = 0; i < num_hist; i++)
2284 pos = (i * (nvals - 1)) / (num_hist - 1);
2285 hist_values[i] = datumCopy(values[pos].value,
2286 stats->attr->attbyval,
2287 stats->attr->attlen);
2289 MemoryContextSwitchTo(old_context);
2291 stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2292 stats->staop[slot_idx] = mystats->ltopr;
2293 stats->stavalues[slot_idx] = hist_values;
2294 stats->numvalues[slot_idx] = num_hist;
2296 * Accept the defaults for stats->statypid and others.
2297 * They have been set before we were called (see vacuum.h)
2302 /* Generate a correlation entry if there are multiple values */
2305 MemoryContext old_context;
2310 /* Must copy the target values into anl_context */
2311 old_context = MemoryContextSwitchTo(stats->anl_context);
2312 corrs = (float4 *) palloc(sizeof(float4));
2313 MemoryContextSwitchTo(old_context);
2316 * Since we know the x and y value sets are both
2317 * 0, 1, ..., values_cnt-1
2318 * we have sum(x) = sum(y) =
2319 * (values_cnt-1)*values_cnt / 2
2320 * and sum(x^2) = sum(y^2) =
2321 * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2324 corr_xsum = ((double) (values_cnt - 1)) *
2325 ((double) values_cnt) / 2.0;
2326 corr_x2sum = ((double) (values_cnt - 1)) *
2327 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2329 /* And the correlation coefficient reduces to */
2330 corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2331 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2333 stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2334 stats->staop[slot_idx] = mystats->ltopr;
2335 stats->stanumbers[slot_idx] = corrs;
2336 stats->numnumbers[slot_idx] = 1;
2340 else if (nonnull_cnt == 0 && null_cnt > 0)
2342 /* We found only nulls; assume the column is entirely null */
2343 stats->stats_valid = true;
2344 stats->stanullfrac = 1.0;
2346 stats->stawidth = 0; /* "unknown" */
2348 stats->stawidth = stats->attrtype->typlen;
2349 stats->stadistinct = 0.0; /* "unknown" */
2352 /* We don't need to bother cleaning up any of our temporary palloc's */
2356 * qsort_arg comparator for sorting ScalarItems
2358 * Aside from sorting the items, we update the tupnoLink[] array
2359 * whenever two ScalarItems are found to contain equal datums. The array
2360 * is indexed by tupno; for each ScalarItem, it contains the highest
2361 * tupno that that item's datum has been found to be equal to. This allows
2362 * us to avoid additional comparisons in compute_scalar_stats().
2365 compare_scalars(const void *a, const void *b, void *arg)
2367 Datum da = ((ScalarItem *) a)->value;
2368 int ta = ((ScalarItem *) a)->tupno;
2369 Datum db = ((ScalarItem *) b)->value;
2370 int tb = ((ScalarItem *) b)->tupno;
2371 CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2374 compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2375 da, false, db, false);
2380 * The two datums are equal, so update cxt->tupnoLink[].
2382 if (cxt->tupnoLink[ta] < tb)
2383 cxt->tupnoLink[ta] = tb;
2384 if (cxt->tupnoLink[tb] < ta)
2385 cxt->tupnoLink[tb] = ta;
2388 * For equal datums, sort by tupno
2394 * qsort comparator for sorting ScalarMCVItems by position
2397 compare_mcvs(const void *a, const void *b)
2399 int da = ((ScalarMCVItem *) a)->first;
2400 int db = ((ScalarMCVItem *) b)->first;