1 /*-------------------------------------------------------------------------
4 * the Postgres statistics generator
6 * Portions Copyright (c) 1996-2019, 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/genam.h"
20 #include "access/multixact.h"
21 #include "access/relation.h"
22 #include "access/sysattr.h"
23 #include "access/table.h"
24 #include "access/transam.h"
25 #include "access/tupconvert.h"
26 #include "access/tuptoaster.h"
27 #include "access/visibilitymap.h"
28 #include "access/xact.h"
29 #include "catalog/catalog.h"
30 #include "catalog/index.h"
31 #include "catalog/indexing.h"
32 #include "catalog/pg_collation.h"
33 #include "catalog/pg_inherits.h"
34 #include "catalog/pg_namespace.h"
35 #include "catalog/pg_statistic_ext.h"
36 #include "commands/dbcommands.h"
37 #include "commands/tablecmds.h"
38 #include "commands/vacuum.h"
39 #include "executor/executor.h"
40 #include "foreign/fdwapi.h"
41 #include "miscadmin.h"
42 #include "nodes/nodeFuncs.h"
43 #include "parser/parse_oper.h"
44 #include "parser/parse_relation.h"
46 #include "postmaster/autovacuum.h"
47 #include "statistics/extended_stats_internal.h"
48 #include "statistics/statistics.h"
49 #include "storage/bufmgr.h"
50 #include "storage/lmgr.h"
51 #include "storage/proc.h"
52 #include "storage/procarray.h"
53 #include "utils/acl.h"
54 #include "utils/attoptcache.h"
55 #include "utils/builtins.h"
56 #include "utils/datum.h"
57 #include "utils/fmgroids.h"
58 #include "utils/guc.h"
59 #include "utils/lsyscache.h"
60 #include "utils/memutils.h"
61 #include "utils/pg_rusage.h"
62 #include "utils/sampling.h"
63 #include "utils/sortsupport.h"
64 #include "utils/syscache.h"
65 #include "utils/timestamp.h"
66 #include "utils/tqual.h"
69 /* Per-index data for ANALYZE */
70 typedef struct AnlIndexData
72 IndexInfo *indexInfo; /* BuildIndexInfo result */
73 double tupleFract; /* fraction of rows for partial index */
74 VacAttrStats **vacattrstats; /* index attrs to analyze */
79 /* Default statistics target (GUC parameter) */
80 int default_statistics_target = 100;
82 /* A few variables that don't seem worth passing around as parameters */
83 static MemoryContext anl_context = NULL;
84 static BufferAccessStrategy vac_strategy;
87 static void do_analyze_rel(Relation onerel, int options,
88 VacuumParams *params, List *va_cols,
89 AcquireSampleRowsFunc acquirefunc, BlockNumber relpages,
90 bool inh, bool in_outer_xact, int elevel);
91 static void compute_index_stats(Relation onerel, double totalrows,
92 AnlIndexData *indexdata, int nindexes,
93 HeapTuple *rows, int numrows,
94 MemoryContext col_context);
95 static VacAttrStats *examine_attribute(Relation onerel, int attnum,
97 static int acquire_sample_rows(Relation onerel, int elevel,
98 HeapTuple *rows, int targrows,
99 double *totalrows, double *totaldeadrows);
100 static int compare_rows(const void *a, const void *b);
101 static int acquire_inherited_sample_rows(Relation onerel, int elevel,
102 HeapTuple *rows, int targrows,
103 double *totalrows, double *totaldeadrows);
104 static void update_attstats(Oid relid, bool inh,
105 int natts, VacAttrStats **vacattrstats);
106 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
107 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
111 * analyze_rel() -- analyze one relation
113 * relid identifies the relation to analyze. If relation is supplied, use
114 * the name therein for reporting any failure to open/lock the rel; do not
115 * use it once we've successfully opened the rel, since it might be stale.
118 analyze_rel(Oid relid, RangeVar *relation, int options,
119 VacuumParams *params, List *va_cols, bool in_outer_xact,
120 BufferAccessStrategy bstrategy)
124 AcquireSampleRowsFunc acquirefunc = NULL;
125 BlockNumber relpages = 0;
127 /* Select logging level */
128 if (options & VACOPT_VERBOSE)
133 /* Set up static variables */
134 vac_strategy = bstrategy;
137 * Check for user-requested abort.
139 CHECK_FOR_INTERRUPTS();
142 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
143 * ANALYZEs don't run on it concurrently. (This also locks out a
144 * concurrent VACUUM, which doesn't matter much at the moment but might
145 * matter if we ever try to accumulate stats on dead tuples.) If the rel
146 * has been dropped since we last saw it, we don't need to process it.
148 * Make sure to generate only logs for ANALYZE in this case.
150 onerel = vacuum_open_relation(relid, relation, params,
151 options & ~(VACOPT_VACUUM),
152 ShareUpdateExclusiveLock);
154 /* leave if relation could not be opened or locked */
159 * Check if relation needs to be skipped based on ownership. This check
160 * happens also when building the relation list to analyze for a manual
161 * operation, and needs to be done additionally here as ANALYZE could
162 * happen across multiple transactions where relation ownership could have
163 * changed in-between. Make sure to generate only logs for ANALYZE in
166 if (!vacuum_is_relation_owner(RelationGetRelid(onerel),
168 options & VACOPT_ANALYZE))
170 relation_close(onerel, ShareUpdateExclusiveLock);
175 * Silently ignore tables that are temp tables of other backends ---
176 * trying to analyze these is rather pointless, since their contents are
177 * probably not up-to-date on disk. (We don't throw a warning here; it
178 * would just lead to chatter during a database-wide ANALYZE.)
180 if (RELATION_IS_OTHER_TEMP(onerel))
182 relation_close(onerel, ShareUpdateExclusiveLock);
187 * We can ANALYZE any table except pg_statistic. See update_attstats
189 if (RelationGetRelid(onerel) == StatisticRelationId)
191 relation_close(onerel, ShareUpdateExclusiveLock);
196 * Check that it's of an analyzable relkind, and set up appropriately.
198 if (onerel->rd_rel->relkind == RELKIND_RELATION ||
199 onerel->rd_rel->relkind == RELKIND_MATVIEW)
201 /* Regular table, so we'll use the regular row acquisition function */
202 acquirefunc = acquire_sample_rows;
203 /* Also get regular table's size */
204 relpages = RelationGetNumberOfBlocks(onerel);
206 else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
209 * For a foreign table, call the FDW's hook function to see whether it
212 FdwRoutine *fdwroutine;
215 fdwroutine = GetFdwRoutineForRelation(onerel, false);
217 if (fdwroutine->AnalyzeForeignTable != NULL)
218 ok = fdwroutine->AnalyzeForeignTable(onerel,
225 (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
226 RelationGetRelationName(onerel))));
227 relation_close(onerel, ShareUpdateExclusiveLock);
231 else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
234 * For partitioned tables, we want to do the recursive ANALYZE below.
239 /* No need for a WARNING if we already complained during VACUUM */
240 if (!(options & VACOPT_VACUUM))
242 (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
243 RelationGetRelationName(onerel))));
244 relation_close(onerel, ShareUpdateExclusiveLock);
249 * OK, let's do it. First let other backends know I'm in ANALYZE.
251 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
252 MyPgXact->vacuumFlags |= PROC_IN_ANALYZE;
253 LWLockRelease(ProcArrayLock);
256 * Do the normal non-recursive ANALYZE. We can skip this for partitioned
257 * tables, which don't contain any rows.
259 if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
260 do_analyze_rel(onerel, options, params, va_cols, acquirefunc,
261 relpages, false, in_outer_xact, elevel);
264 * If there are child tables, do recursive ANALYZE.
266 if (onerel->rd_rel->relhassubclass)
267 do_analyze_rel(onerel, options, params, va_cols, acquirefunc, relpages,
268 true, in_outer_xact, elevel);
271 * Close source relation now, but keep lock so that no one deletes it
272 * before we commit. (If someone did, they'd fail to clean up the entries
273 * we made in pg_statistic. Also, releasing the lock before commit would
274 * expose us to concurrent-update failures in update_attstats.)
276 relation_close(onerel, NoLock);
279 * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
280 * because the vacuum flag is cleared by the end-of-xact code.
282 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
283 MyPgXact->vacuumFlags &= ~PROC_IN_ANALYZE;
284 LWLockRelease(ProcArrayLock);
288 * do_analyze_rel() -- analyze one relation, recursively or not
290 * Note that "acquirefunc" is only relevant for the non-inherited case.
291 * For the inherited case, acquire_inherited_sample_rows() determines the
292 * appropriate acquirefunc for each child table.
295 do_analyze_rel(Relation onerel, int options, VacuumParams *params,
296 List *va_cols, AcquireSampleRowsFunc acquirefunc,
297 BlockNumber relpages, bool inh, bool in_outer_xact,
307 VacAttrStats **vacattrstats;
308 AnlIndexData *indexdata;
315 TimestampTz starttime = 0;
316 MemoryContext caller_context;
318 int save_sec_context;
323 (errmsg("analyzing \"%s.%s\" inheritance tree",
324 get_namespace_name(RelationGetNamespace(onerel)),
325 RelationGetRelationName(onerel))));
328 (errmsg("analyzing \"%s.%s\"",
329 get_namespace_name(RelationGetNamespace(onerel)),
330 RelationGetRelationName(onerel))));
333 * Set up a working context so that we can easily free whatever junk gets
336 anl_context = AllocSetContextCreate(CurrentMemoryContext,
338 ALLOCSET_DEFAULT_SIZES);
339 caller_context = MemoryContextSwitchTo(anl_context);
342 * Switch to the table owner's userid, so that any index functions are run
343 * as that user. Also lock down security-restricted operations and
344 * arrange to make GUC variable changes local to this command.
346 GetUserIdAndSecContext(&save_userid, &save_sec_context);
347 SetUserIdAndSecContext(onerel->rd_rel->relowner,
348 save_sec_context | SECURITY_RESTRICTED_OPERATION);
349 save_nestlevel = NewGUCNestLevel();
351 /* measure elapsed time iff autovacuum logging requires it */
352 if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
354 pg_rusage_init(&ru0);
355 if (params->log_min_duration > 0)
356 starttime = GetCurrentTimestamp();
360 * Determine which columns to analyze
362 * Note that system attributes are never analyzed, so we just reject them
363 * at the lookup stage. We also reject duplicate column mentions. (We
364 * could alternatively ignore duplicates, but analyzing a column twice
365 * won't work; we'd end up making a conflicting update in pg_statistic.)
369 Bitmapset *unique_cols = NULL;
372 vacattrstats = (VacAttrStats **) palloc(list_length(va_cols) *
373 sizeof(VacAttrStats *));
377 char *col = strVal(lfirst(le));
379 i = attnameAttNum(onerel, col, false);
380 if (i == InvalidAttrNumber)
382 (errcode(ERRCODE_UNDEFINED_COLUMN),
383 errmsg("column \"%s\" of relation \"%s\" does not exist",
384 col, RelationGetRelationName(onerel))));
385 if (bms_is_member(i, unique_cols))
387 (errcode(ERRCODE_DUPLICATE_COLUMN),
388 errmsg("column \"%s\" of relation \"%s\" appears more than once",
389 col, RelationGetRelationName(onerel))));
390 unique_cols = bms_add_member(unique_cols, i);
392 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
393 if (vacattrstats[tcnt] != NULL)
400 attr_cnt = onerel->rd_att->natts;
401 vacattrstats = (VacAttrStats **)
402 palloc(attr_cnt * sizeof(VacAttrStats *));
404 for (i = 1; i <= attr_cnt; i++)
406 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
407 if (vacattrstats[tcnt] != NULL)
414 * Open all indexes of the relation, and see if there are any analyzable
415 * columns in the indexes. We do not analyze index columns if there was
416 * an explicit column list in the ANALYZE command, however. If we are
417 * doing a recursive scan, we don't want to touch the parent's indexes at
421 vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
427 hasindex = (nindexes > 0);
431 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
432 for (ind = 0; ind < nindexes; ind++)
434 AnlIndexData *thisdata = &indexdata[ind];
435 IndexInfo *indexInfo;
437 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
438 thisdata->tupleFract = 1.0; /* fix later if partial */
439 if (indexInfo->ii_Expressions != NIL && va_cols == NIL)
441 ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
443 thisdata->vacattrstats = (VacAttrStats **)
444 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
446 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
448 int keycol = indexInfo->ii_IndexAttrNumbers[i];
452 /* Found an index expression */
455 if (indexpr_item == NULL) /* shouldn't happen */
456 elog(ERROR, "too few entries in indexprs list");
457 indexkey = (Node *) lfirst(indexpr_item);
458 indexpr_item = lnext(indexpr_item);
459 thisdata->vacattrstats[tcnt] =
460 examine_attribute(Irel[ind], i + 1, indexkey);
461 if (thisdata->vacattrstats[tcnt] != NULL)
465 thisdata->attr_cnt = tcnt;
471 * Determine how many rows we need to sample, using the worst case from
472 * all analyzable columns. We use a lower bound of 100 rows to avoid
473 * possible overflow in Vitter's algorithm. (Note: that will also be the
474 * target in the corner case where there are no analyzable columns.)
477 for (i = 0; i < attr_cnt; i++)
479 if (targrows < vacattrstats[i]->minrows)
480 targrows = vacattrstats[i]->minrows;
482 for (ind = 0; ind < nindexes; ind++)
484 AnlIndexData *thisdata = &indexdata[ind];
486 for (i = 0; i < thisdata->attr_cnt; i++)
488 if (targrows < thisdata->vacattrstats[i]->minrows)
489 targrows = thisdata->vacattrstats[i]->minrows;
494 * Acquire the sample rows
496 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
498 numrows = acquire_inherited_sample_rows(onerel, elevel,
500 &totalrows, &totaldeadrows);
502 numrows = (*acquirefunc) (onerel, elevel,
504 &totalrows, &totaldeadrows);
507 * Compute the statistics. Temporary results during the calculations for
508 * each column are stored in a child context. The calc routines are
509 * responsible to make sure that whatever they store into the VacAttrStats
510 * structure is allocated in anl_context.
514 MemoryContext col_context,
517 col_context = AllocSetContextCreate(anl_context,
519 ALLOCSET_DEFAULT_SIZES);
520 old_context = MemoryContextSwitchTo(col_context);
522 for (i = 0; i < attr_cnt; i++)
524 VacAttrStats *stats = vacattrstats[i];
528 stats->tupDesc = onerel->rd_att;
529 stats->compute_stats(stats,
535 * If the appropriate flavor of the n_distinct option is
536 * specified, override with the corresponding value.
538 aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
543 n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
544 if (n_distinct != 0.0)
545 stats->stadistinct = n_distinct;
548 MemoryContextResetAndDeleteChildren(col_context);
552 compute_index_stats(onerel, totalrows,
557 MemoryContextSwitchTo(old_context);
558 MemoryContextDelete(col_context);
561 * Emit the completed stats rows into pg_statistic, replacing any
562 * previous statistics for the target columns. (If there are stats in
563 * pg_statistic for columns we didn't process, we leave them alone.)
565 update_attstats(RelationGetRelid(onerel), inh,
566 attr_cnt, vacattrstats);
568 for (ind = 0; ind < nindexes; ind++)
570 AnlIndexData *thisdata = &indexdata[ind];
572 update_attstats(RelationGetRelid(Irel[ind]), false,
573 thisdata->attr_cnt, thisdata->vacattrstats);
576 /* Build extended statistics (if there are any). */
577 BuildRelationExtStatistics(onerel, totalrows, numrows, rows, attr_cnt,
582 * Update pages/tuples stats in pg_class ... but not if we're doing
587 BlockNumber relallvisible;
589 visibilitymap_count(onerel, &relallvisible, NULL);
591 vac_update_relstats(onerel,
596 InvalidTransactionId,
602 * Same for indexes. Vacuum always scans all indexes, so if we're part of
603 * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
606 if (!inh && !(options & VACOPT_VACUUM))
608 for (ind = 0; ind < nindexes; ind++)
610 AnlIndexData *thisdata = &indexdata[ind];
611 double totalindexrows;
613 totalindexrows = ceil(thisdata->tupleFract * totalrows);
614 vac_update_relstats(Irel[ind],
615 RelationGetNumberOfBlocks(Irel[ind]),
619 InvalidTransactionId,
626 * Report ANALYZE to the stats collector, too. However, if doing
627 * inherited stats we shouldn't report, because the stats collector only
628 * tracks per-table stats. Reset the changes_since_analyze counter only
629 * if we analyzed all columns; otherwise, there is still work for
630 * auto-analyze to do.
633 pgstat_report_analyze(onerel, totalrows, totaldeadrows,
636 /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
637 if (!(options & VACOPT_VACUUM))
639 for (ind = 0; ind < nindexes; ind++)
641 IndexBulkDeleteResult *stats;
642 IndexVacuumInfo ivinfo;
644 ivinfo.index = Irel[ind];
645 ivinfo.analyze_only = true;
646 ivinfo.estimated_count = true;
647 ivinfo.message_level = elevel;
648 ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
649 ivinfo.strategy = vac_strategy;
651 stats = index_vacuum_cleanup(&ivinfo, NULL);
658 /* Done with indexes */
659 vac_close_indexes(nindexes, Irel, NoLock);
661 /* Log the action if appropriate */
662 if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
664 if (params->log_min_duration == 0 ||
665 TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
666 params->log_min_duration))
668 (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
669 get_database_name(MyDatabaseId),
670 get_namespace_name(RelationGetNamespace(onerel)),
671 RelationGetRelationName(onerel),
672 pg_rusage_show(&ru0))));
675 /* Roll back any GUC changes executed by index functions */
676 AtEOXact_GUC(false, save_nestlevel);
678 /* Restore userid and security context */
679 SetUserIdAndSecContext(save_userid, save_sec_context);
681 /* Restore current context and release memory */
682 MemoryContextSwitchTo(caller_context);
683 MemoryContextDelete(anl_context);
688 * Compute statistics about indexes of a relation
691 compute_index_stats(Relation onerel, double totalrows,
692 AnlIndexData *indexdata, int nindexes,
693 HeapTuple *rows, int numrows,
694 MemoryContext col_context)
696 MemoryContext ind_context,
698 Datum values[INDEX_MAX_KEYS];
699 bool isnull[INDEX_MAX_KEYS];
703 ind_context = AllocSetContextCreate(anl_context,
705 ALLOCSET_DEFAULT_SIZES);
706 old_context = MemoryContextSwitchTo(ind_context);
708 for (ind = 0; ind < nindexes; ind++)
710 AnlIndexData *thisdata = &indexdata[ind];
711 IndexInfo *indexInfo = thisdata->indexInfo;
712 int attr_cnt = thisdata->attr_cnt;
713 TupleTableSlot *slot;
715 ExprContext *econtext;
716 ExprState *predicate;
722 double totalindexrows;
724 /* Ignore index if no columns to analyze and not partial */
725 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
729 * Need an EState for evaluation of index expressions and
730 * partial-index predicates. Create it in the per-index context to be
731 * sure it gets cleaned up at the bottom of the loop.
733 estate = CreateExecutorState();
734 econtext = GetPerTupleExprContext(estate);
735 /* Need a slot to hold the current heap tuple, too */
736 slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
739 /* Arrange for econtext's scan tuple to be the tuple under test */
740 econtext->ecxt_scantuple = slot;
742 /* Set up execution state for predicate. */
743 predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
745 /* Compute and save index expression values */
746 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
747 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
750 for (rowno = 0; rowno < numrows; rowno++)
752 HeapTuple heapTuple = rows[rowno];
754 vacuum_delay_point();
757 * Reset the per-tuple context each time, to reclaim any cruft
758 * left behind by evaluating the predicate or index expressions.
760 ResetExprContext(econtext);
762 /* Set up for predicate or expression evaluation */
763 ExecStoreHeapTuple(heapTuple, slot, false);
765 /* If index is partial, check predicate */
766 if (predicate != NULL)
768 if (!ExecQual(predicate, econtext))
776 * Evaluate the index row to compute expression values. We
777 * could do this by hand, but FormIndexDatum is convenient.
779 FormIndexDatum(indexInfo,
786 * Save just the columns we care about. We copy the values
787 * into ind_context from the estate's per-tuple context.
789 for (i = 0; i < attr_cnt; i++)
791 VacAttrStats *stats = thisdata->vacattrstats[i];
792 int attnum = stats->attr->attnum;
794 if (isnull[attnum - 1])
796 exprvals[tcnt] = (Datum) 0;
797 exprnulls[tcnt] = true;
801 exprvals[tcnt] = datumCopy(values[attnum - 1],
802 stats->attrtype->typbyval,
803 stats->attrtype->typlen);
804 exprnulls[tcnt] = false;
812 * Having counted the number of rows that pass the predicate in the
813 * sample, we can estimate the total number of rows in the index.
815 thisdata->tupleFract = (double) numindexrows / (double) numrows;
816 totalindexrows = ceil(thisdata->tupleFract * totalrows);
819 * Now we can compute the statistics for the expression columns.
821 if (numindexrows > 0)
823 MemoryContextSwitchTo(col_context);
824 for (i = 0; i < attr_cnt; i++)
826 VacAttrStats *stats = thisdata->vacattrstats[i];
827 AttributeOpts *aopt =
828 get_attribute_options(stats->attr->attrelid,
829 stats->attr->attnum);
831 stats->exprvals = exprvals + i;
832 stats->exprnulls = exprnulls + i;
833 stats->rowstride = attr_cnt;
834 stats->compute_stats(stats,
840 * If the n_distinct option is specified, it overrides the
841 * above computation. For indices, we always use just
842 * n_distinct, not n_distinct_inherited.
844 if (aopt != NULL && aopt->n_distinct != 0.0)
845 stats->stadistinct = aopt->n_distinct;
847 MemoryContextResetAndDeleteChildren(col_context);
852 MemoryContextSwitchTo(ind_context);
854 ExecDropSingleTupleTableSlot(slot);
855 FreeExecutorState(estate);
856 MemoryContextResetAndDeleteChildren(ind_context);
859 MemoryContextSwitchTo(old_context);
860 MemoryContextDelete(ind_context);
864 * examine_attribute -- pre-analysis of a single column
866 * Determine whether the column is analyzable; if so, create and initialize
867 * a VacAttrStats struct for it. If not, return NULL.
869 * If index_expr isn't NULL, then we're trying to analyze an expression index,
870 * and index_expr is the expression tree representing the column's data.
872 static VacAttrStats *
873 examine_attribute(Relation onerel, int attnum, Node *index_expr)
875 Form_pg_attribute attr = TupleDescAttr(onerel->rd_att, attnum - 1);
881 /* Never analyze dropped columns */
882 if (attr->attisdropped)
885 /* Don't analyze column if user has specified not to */
886 if (attr->attstattarget == 0)
890 * Create the VacAttrStats struct. Note that we only have a copy of the
891 * fixed fields of the pg_attribute tuple.
893 stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
894 stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
895 memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
898 * When analyzing an expression index, believe the expression tree's type
899 * not the column datatype --- the latter might be the opckeytype storage
900 * type of the opclass, which is not interesting for our purposes. (Note:
901 * if we did anything with non-expression index columns, we'd need to
902 * figure out where to get the correct type info from, but for now that's
903 * not a problem.) It's not clear whether anyone will care about the
904 * typmod, but we store that too just in case.
908 stats->attrtypid = exprType(index_expr);
909 stats->attrtypmod = exprTypmod(index_expr);
912 * If a collation has been specified for the index column, use that in
913 * preference to anything else; but if not, fall back to whatever we
914 * can get from the expression.
916 if (OidIsValid(onerel->rd_indcollation[attnum - 1]))
917 stats->attrcollid = onerel->rd_indcollation[attnum - 1];
919 stats->attrcollid = exprCollation(index_expr);
923 stats->attrtypid = attr->atttypid;
924 stats->attrtypmod = attr->atttypmod;
925 stats->attrcollid = attr->attcollation;
928 typtuple = SearchSysCacheCopy1(TYPEOID,
929 ObjectIdGetDatum(stats->attrtypid));
930 if (!HeapTupleIsValid(typtuple))
931 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
932 stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
933 stats->anl_context = anl_context;
934 stats->tupattnum = attnum;
937 * The fields describing the stats->stavalues[n] element types default to
938 * the type of the data being analyzed, but the type-specific typanalyze
939 * function can change them if it wants to store something else.
941 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
943 stats->statypid[i] = stats->attrtypid;
944 stats->statyplen[i] = stats->attrtype->typlen;
945 stats->statypbyval[i] = stats->attrtype->typbyval;
946 stats->statypalign[i] = stats->attrtype->typalign;
950 * Call the type-specific typanalyze function. If none is specified, use
953 if (OidIsValid(stats->attrtype->typanalyze))
954 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
955 PointerGetDatum(stats)));
957 ok = std_typanalyze(stats);
959 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
961 heap_freetuple(typtuple);
971 * acquire_sample_rows -- acquire a random sample of rows from the table
973 * Selected rows are returned in the caller-allocated array rows[], which
974 * must have at least targrows entries.
975 * The actual number of rows selected is returned as the function result.
976 * We also estimate the total numbers of live and dead rows in the table,
977 * and return them into *totalrows and *totaldeadrows, respectively.
979 * The returned list of tuples is in order by physical position in the table.
980 * (We will rely on this later to derive correlation estimates.)
982 * As of May 2004 we use a new two-stage method: Stage one selects up
983 * to targrows random blocks (or all blocks, if there aren't so many).
984 * Stage two scans these blocks and uses the Vitter algorithm to create
985 * a random sample of targrows rows (or less, if there are less in the
986 * sample of blocks). The two stages are executed simultaneously: each
987 * block is processed as soon as stage one returns its number and while
988 * the rows are read stage two controls which ones are to be inserted
991 * Although every row has an equal chance of ending up in the final
992 * sample, this sampling method is not perfect: not every possible
993 * sample has an equal chance of being selected. For large relations
994 * the number of different blocks represented by the sample tends to be
995 * too small. We can live with that for now. Improvements are welcome.
997 * An important property of this sampling method is that because we do
998 * look at a statistically unbiased set of blocks, we should get
999 * unbiased estimates of the average numbers of live and dead rows per
1000 * block. The previous sampling method put too much credence in the row
1001 * density near the start of the table.
1004 acquire_sample_rows(Relation onerel, int elevel,
1005 HeapTuple *rows, int targrows,
1006 double *totalrows, double *totaldeadrows)
1008 int numrows = 0; /* # rows now in reservoir */
1009 double samplerows = 0; /* total # rows collected */
1010 double liverows = 0; /* # live rows seen */
1011 double deadrows = 0; /* # dead rows seen */
1012 double rowstoskip = -1; /* -1 means not set yet */
1013 BlockNumber totalblocks;
1014 TransactionId OldestXmin;
1015 BlockSamplerData bs;
1016 ReservoirStateData rstate;
1018 Assert(targrows > 0);
1020 totalblocks = RelationGetNumberOfBlocks(onerel);
1022 /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1023 OldestXmin = GetOldestXmin(onerel, PROCARRAY_FLAGS_VACUUM);
1025 /* Prepare for sampling block numbers */
1026 BlockSampler_Init(&bs, totalblocks, targrows, random());
1027 /* Prepare for sampling rows */
1028 reservoir_init_selection_state(&rstate, targrows);
1030 /* Outer loop over blocks to sample */
1031 while (BlockSampler_HasMore(&bs))
1033 BlockNumber targblock = BlockSampler_Next(&bs);
1036 OffsetNumber targoffset,
1039 vacuum_delay_point();
1042 * We must maintain a pin on the target page's buffer to ensure that
1043 * the maxoffset value stays good (else concurrent VACUUM might delete
1044 * tuples out from under us). Hence, pin the page until we are done
1045 * looking at it. We also choose to hold sharelock on the buffer
1046 * throughout --- we could release and re-acquire sharelock for each
1047 * tuple, but since we aren't doing much work per tuple, the extra
1048 * lock traffic is probably better avoided.
1050 targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1051 RBM_NORMAL, vac_strategy);
1052 LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1053 targpage = BufferGetPage(targbuffer);
1054 maxoffset = PageGetMaxOffsetNumber(targpage);
1056 /* Inner loop over all tuples on the selected page */
1057 for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1060 HeapTupleData targtuple;
1061 bool sample_it = false;
1063 itemid = PageGetItemId(targpage, targoffset);
1066 * We ignore unused and redirect line pointers. DEAD line
1067 * pointers should be counted as dead, because we need vacuum to
1068 * run to get rid of them. Note that this rule agrees with the
1069 * way that heap_page_prune() counts things.
1071 if (!ItemIdIsNormal(itemid))
1073 if (ItemIdIsDead(itemid))
1078 ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1080 targtuple.t_tableOid = RelationGetRelid(onerel);
1081 targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1082 targtuple.t_len = ItemIdGetLength(itemid);
1084 switch (HeapTupleSatisfiesVacuum(&targtuple,
1088 case HEAPTUPLE_LIVE:
1093 case HEAPTUPLE_DEAD:
1094 case HEAPTUPLE_RECENTLY_DEAD:
1095 /* Count dead and recently-dead rows */
1099 case HEAPTUPLE_INSERT_IN_PROGRESS:
1102 * Insert-in-progress rows are not counted. We assume
1103 * that when the inserting transaction commits or aborts,
1104 * it will send a stats message to increment the proper
1105 * count. This works right only if that transaction ends
1106 * after we finish analyzing the table; if things happen
1107 * in the other order, its stats update will be
1108 * overwritten by ours. However, the error will be large
1109 * only if the other transaction runs long enough to
1110 * insert many tuples, so assuming it will finish after us
1111 * is the safer option.
1113 * A special case is that the inserting transaction might
1114 * be our own. In this case we should count and sample
1115 * the row, to accommodate users who load a table and
1116 * analyze it in one transaction. (pgstat_report_analyze
1117 * has to adjust the numbers we send to the stats
1118 * collector to make this come out right.)
1120 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
1127 case HEAPTUPLE_DELETE_IN_PROGRESS:
1130 * We count and sample delete-in-progress rows the same as
1131 * live ones, so that the stats counters come out right if
1132 * the deleting transaction commits after us, per the same
1133 * reasoning given above.
1135 * If the delete was done by our own transaction, however,
1136 * we must count the row as dead to make
1137 * pgstat_report_analyze's stats adjustments come out
1138 * right. (Note: this works out properly when the row was
1139 * both inserted and deleted in our xact.)
1141 * The net effect of these choices is that we act as
1142 * though an IN_PROGRESS transaction hasn't happened yet,
1143 * except if it is our own transaction, which we assume
1146 * This approach ensures that we behave sanely if we see
1147 * both the pre-image and post-image rows for a row being
1148 * updated by a concurrent transaction: we will sample the
1149 * pre-image but not the post-image. We also get sane
1150 * results if the concurrent transaction never commits.
1152 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(targtuple.t_data)))
1162 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1169 * The first targrows sample rows are simply copied into the
1170 * reservoir. Then we start replacing tuples in the sample
1171 * until we reach the end of the relation. This algorithm is
1172 * from Jeff Vitter's paper (see full citation below). It
1173 * works by repeatedly computing the number of tuples to skip
1174 * before selecting a tuple, which replaces a randomly chosen
1175 * element of the reservoir (current set of tuples). At all
1176 * times the reservoir is a true random sample of the tuples
1177 * we've passed over so far, so when we fall off the end of
1178 * the relation we're done.
1180 if (numrows < targrows)
1181 rows[numrows++] = heap_copytuple(&targtuple);
1185 * t in Vitter's paper is the number of records already
1186 * processed. If we need to compute a new S value, we
1187 * must use the not-yet-incremented value of samplerows as
1191 rowstoskip = reservoir_get_next_S(&rstate, samplerows, targrows);
1193 if (rowstoskip <= 0)
1196 * Found a suitable tuple, so save it, replacing one
1197 * old tuple at random
1199 int k = (int) (targrows * sampler_random_fract(rstate.randstate));
1201 Assert(k >= 0 && k < targrows);
1202 heap_freetuple(rows[k]);
1203 rows[k] = heap_copytuple(&targtuple);
1213 /* Now release the lock and pin on the page */
1214 UnlockReleaseBuffer(targbuffer);
1218 * If we didn't find as many tuples as we wanted then we're done. No sort
1219 * is needed, since they're already in order.
1221 * Otherwise we need to sort the collected tuples by position
1222 * (itempointer). It's not worth worrying about corner cases where the
1223 * tuples are already sorted.
1225 if (numrows == targrows)
1226 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1229 * Estimate total numbers of live and dead rows in relation, extrapolating
1230 * on the assumption that the average tuple density in pages we didn't
1231 * scan is the same as in the pages we did scan. Since what we scanned is
1232 * a random sample of the pages in the relation, this should be a good
1237 *totalrows = floor((liverows / bs.m) * totalblocks + 0.5);
1238 *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1243 *totaldeadrows = 0.0;
1247 * Emit some interesting relation info
1250 (errmsg("\"%s\": scanned %d of %u pages, "
1251 "containing %.0f live rows and %.0f dead rows; "
1252 "%d rows in sample, %.0f estimated total rows",
1253 RelationGetRelationName(onerel),
1256 numrows, *totalrows)));
1262 * qsort comparator for sorting rows[] array
1265 compare_rows(const void *a, const void *b)
1267 HeapTuple ha = *(const HeapTuple *) a;
1268 HeapTuple hb = *(const HeapTuple *) b;
1269 BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1270 OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1271 BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1272 OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1287 * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1289 * This has the same API as acquire_sample_rows, except that rows are
1290 * collected from all inheritance children as well as the specified table.
1291 * We fail and return zero if there are no inheritance children, or if all
1292 * children are foreign tables that don't support ANALYZE.
1295 acquire_inherited_sample_rows(Relation onerel, int elevel,
1296 HeapTuple *rows, int targrows,
1297 double *totalrows, double *totaldeadrows)
1301 AcquireSampleRowsFunc *acquirefuncs;
1311 * Find all members of inheritance set. We only need AccessShareLock on
1315 find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
1318 * Check that there's at least one descendant, else fail. This could
1319 * happen despite analyze_rel's relhassubclass check, if table once had a
1320 * child but no longer does. In that case, we can clear the
1321 * relhassubclass field so as not to make the same mistake again later.
1322 * (This is safe because we hold ShareUpdateExclusiveLock.)
1324 if (list_length(tableOIDs) < 2)
1326 /* CCI because we already updated the pg_class row in this command */
1327 CommandCounterIncrement();
1328 SetRelationHasSubclass(RelationGetRelid(onerel), false);
1330 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no child tables",
1331 get_namespace_name(RelationGetNamespace(onerel)),
1332 RelationGetRelationName(onerel))));
1337 * Identify acquirefuncs to use, and count blocks in all the relations.
1338 * The result could overflow BlockNumber, so we use double arithmetic.
1340 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1341 acquirefuncs = (AcquireSampleRowsFunc *)
1342 palloc(list_length(tableOIDs) * sizeof(AcquireSampleRowsFunc));
1343 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1347 foreach(lc, tableOIDs)
1349 Oid childOID = lfirst_oid(lc);
1351 AcquireSampleRowsFunc acquirefunc = NULL;
1352 BlockNumber relpages = 0;
1354 /* We already got the needed lock */
1355 childrel = heap_open(childOID, NoLock);
1357 /* Ignore if temp table of another backend */
1358 if (RELATION_IS_OTHER_TEMP(childrel))
1360 /* ... but release the lock on it */
1361 Assert(childrel != onerel);
1362 heap_close(childrel, AccessShareLock);
1366 /* Check table type (MATVIEW can't happen, but might as well allow) */
1367 if (childrel->rd_rel->relkind == RELKIND_RELATION ||
1368 childrel->rd_rel->relkind == RELKIND_MATVIEW)
1370 /* Regular table, so use the regular row acquisition function */
1371 acquirefunc = acquire_sample_rows;
1372 relpages = RelationGetNumberOfBlocks(childrel);
1374 else if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1377 * For a foreign table, call the FDW's hook function to see
1378 * whether it supports analysis.
1380 FdwRoutine *fdwroutine;
1383 fdwroutine = GetFdwRoutineForRelation(childrel, false);
1385 if (fdwroutine->AnalyzeForeignTable != NULL)
1386 ok = fdwroutine->AnalyzeForeignTable(childrel,
1392 /* ignore, but release the lock on it */
1393 Assert(childrel != onerel);
1394 heap_close(childrel, AccessShareLock);
1401 * ignore, but release the lock on it. don't try to unlock the
1402 * passed-in relation
1404 Assert(childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1405 if (childrel != onerel)
1406 heap_close(childrel, AccessShareLock);
1408 heap_close(childrel, NoLock);
1412 /* OK, we'll process this child */
1414 rels[nrels] = childrel;
1415 acquirefuncs[nrels] = acquirefunc;
1416 relblocks[nrels] = (double) relpages;
1417 totalblocks += (double) relpages;
1422 * If we don't have at least one child table to consider, fail. If the
1423 * relation is a partitioned table, it's not counted as a child table.
1428 (errmsg("skipping analyze of \"%s.%s\" inheritance tree --- this inheritance tree contains no analyzable child tables",
1429 get_namespace_name(RelationGetNamespace(onerel)),
1430 RelationGetRelationName(onerel))));
1435 * Now sample rows from each relation, proportionally to its fraction of
1436 * the total block count. (This might be less than desirable if the child
1437 * rels have radically different free-space percentages, but it's not
1438 * clear that it's worth working harder.)
1443 for (i = 0; i < nrels; i++)
1445 Relation childrel = rels[i];
1446 AcquireSampleRowsFunc acquirefunc = acquirefuncs[i];
1447 double childblocks = relblocks[i];
1449 if (childblocks > 0)
1453 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1454 /* Make sure we don't overrun due to roundoff error */
1455 childtargrows = Min(childtargrows, targrows - numrows);
1456 if (childtargrows > 0)
1462 /* Fetch a random sample of the child's rows */
1463 childrows = (*acquirefunc) (childrel, elevel,
1464 rows + numrows, childtargrows,
1467 /* We may need to convert from child's rowtype to parent's */
1468 if (childrows > 0 &&
1469 !equalTupleDescs(RelationGetDescr(childrel),
1470 RelationGetDescr(onerel)))
1472 TupleConversionMap *map;
1474 map = convert_tuples_by_name(RelationGetDescr(childrel),
1475 RelationGetDescr(onerel),
1476 gettext_noop("could not convert row type"));
1481 for (j = 0; j < childrows; j++)
1485 newtup = execute_attr_map_tuple(rows[numrows + j], map);
1486 heap_freetuple(rows[numrows + j]);
1487 rows[numrows + j] = newtup;
1489 free_conversion_map(map);
1493 /* And add to counts */
1494 numrows += childrows;
1495 *totalrows += trows;
1496 *totaldeadrows += tdrows;
1501 * Note: we cannot release the child-table locks, since we may have
1502 * pointers to their TOAST tables in the sampled rows.
1504 heap_close(childrel, NoLock);
1512 * update_attstats() -- update attribute statistics for one relation
1514 * Statistics are stored in several places: the pg_class row for the
1515 * relation has stats about the whole relation, and there is a
1516 * pg_statistic row for each (non-system) attribute that has ever
1517 * been analyzed. The pg_class values are updated by VACUUM, not here.
1519 * pg_statistic rows are just added or updated normally. This means
1520 * that pg_statistic will probably contain some deleted rows at the
1521 * completion of a vacuum cycle, unless it happens to get vacuumed last.
1523 * To keep things simple, we punt for pg_statistic, and don't try
1524 * to compute or store rows for pg_statistic itself in pg_statistic.
1525 * This could possibly be made to work, but it's not worth the trouble.
1526 * Note analyze_rel() has seen to it that we won't come here when
1527 * vacuuming pg_statistic itself.
1529 * Note: there would be a race condition here if two backends could
1530 * ANALYZE the same table concurrently. Presently, we lock that out
1531 * by taking a self-exclusive lock on the relation in analyze_rel().
1534 update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1540 return; /* nothing to do */
1542 sd = heap_open(StatisticRelationId, RowExclusiveLock);
1544 for (attno = 0; attno < natts; attno++)
1546 VacAttrStats *stats = vacattrstats[attno];
1552 Datum values[Natts_pg_statistic];
1553 bool nulls[Natts_pg_statistic];
1554 bool replaces[Natts_pg_statistic];
1556 /* Ignore attr if we weren't able to collect stats */
1557 if (!stats->stats_valid)
1561 * Construct a new pg_statistic tuple
1563 for (i = 0; i < Natts_pg_statistic; ++i)
1569 values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1570 values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1571 values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1572 values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1573 values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1574 values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1575 i = Anum_pg_statistic_stakind1 - 1;
1576 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1578 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1580 i = Anum_pg_statistic_staop1 - 1;
1581 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1583 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1585 i = Anum_pg_statistic_stacoll1 - 1;
1586 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1588 values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
1590 i = Anum_pg_statistic_stanumbers1 - 1;
1591 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1593 int nnum = stats->numnumbers[k];
1597 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1600 for (n = 0; n < nnum; n++)
1601 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1602 /* XXX knows more than it should about type float4: */
1603 arry = construct_array(numdatums, nnum,
1605 sizeof(float4), FLOAT4PASSBYVAL, 'i');
1606 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1611 values[i++] = (Datum) 0;
1614 i = Anum_pg_statistic_stavalues1 - 1;
1615 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1617 if (stats->numvalues[k] > 0)
1621 arry = construct_array(stats->stavalues[k],
1622 stats->numvalues[k],
1624 stats->statyplen[k],
1625 stats->statypbyval[k],
1626 stats->statypalign[k]);
1627 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1632 values[i++] = (Datum) 0;
1636 /* Is there already a pg_statistic tuple for this attribute? */
1637 oldtup = SearchSysCache3(STATRELATTINH,
1638 ObjectIdGetDatum(relid),
1639 Int16GetDatum(stats->attr->attnum),
1642 if (HeapTupleIsValid(oldtup))
1644 /* Yes, replace it */
1645 stup = heap_modify_tuple(oldtup,
1646 RelationGetDescr(sd),
1650 ReleaseSysCache(oldtup);
1651 CatalogTupleUpdate(sd, &stup->t_self, stup);
1655 /* No, insert new tuple */
1656 stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1657 CatalogTupleInsert(sd, stup);
1660 heap_freetuple(stup);
1663 heap_close(sd, RowExclusiveLock);
1667 * Standard fetch function for use by compute_stats subroutines.
1669 * This exists to provide some insulation between compute_stats routines
1670 * and the actual storage of the sample data.
1673 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1675 int attnum = stats->tupattnum;
1676 HeapTuple tuple = stats->rows[rownum];
1677 TupleDesc tupDesc = stats->tupDesc;
1679 return heap_getattr(tuple, attnum, tupDesc, isNull);
1683 * Fetch function for analyzing index expressions.
1685 * We have not bothered to construct index tuples, instead the data is
1686 * just in Datum arrays.
1689 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1693 /* exprvals and exprnulls are already offset for proper column */
1694 i = rownum * stats->rowstride;
1695 *isNull = stats->exprnulls[i];
1696 return stats->exprvals[i];
1700 /*==========================================================================
1702 * Code below this point represents the "standard" type-specific statistics
1703 * analysis algorithms. This code can be replaced on a per-data-type basis
1704 * by setting a nonzero value in pg_type.typanalyze.
1706 *==========================================================================
1711 * To avoid consuming too much memory during analysis and/or too much space
1712 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1713 * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1714 * and distinct-value calculations since a wide value is unlikely to be
1715 * duplicated at all, much less be a most-common value. For the same reason,
1716 * ignoring wide values will not affect our estimates of histogram bin
1717 * boundaries very much.
1719 #define WIDTH_THRESHOLD 1024
1721 #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1722 #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1725 * Extra information used by the default analysis routines
1729 int count; /* # of duplicates */
1730 int first; /* values[] index of first occurrence */
1737 } CompareScalarsContext;
1740 static void compute_trivial_stats(VacAttrStatsP stats,
1741 AnalyzeAttrFetchFunc fetchfunc,
1744 static void compute_distinct_stats(VacAttrStatsP stats,
1745 AnalyzeAttrFetchFunc fetchfunc,
1748 static void compute_scalar_stats(VacAttrStatsP stats,
1749 AnalyzeAttrFetchFunc fetchfunc,
1752 static int compare_scalars(const void *a, const void *b, void *arg);
1753 static int compare_mcvs(const void *a, const void *b);
1754 static int analyze_mcv_list(int *mcv_counts,
1763 * std_typanalyze -- the default type-specific typanalyze function
1766 std_typanalyze(VacAttrStats *stats)
1768 Form_pg_attribute attr = stats->attr;
1771 StdAnalyzeData *mystats;
1773 /* If the attstattarget column is negative, use the default value */
1774 /* NB: it is okay to scribble on stats->attr since it's a copy */
1775 if (attr->attstattarget < 0)
1776 attr->attstattarget = default_statistics_target;
1778 /* Look for default "<" and "=" operators for column's type */
1779 get_sort_group_operators(stats->attrtypid,
1780 false, false, false,
1781 <opr, &eqopr, NULL,
1784 /* Save the operator info for compute_stats routines */
1785 mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1786 mystats->eqopr = eqopr;
1787 mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1788 mystats->ltopr = ltopr;
1789 stats->extra_data = mystats;
1792 * Determine which standard statistics algorithm to use
1794 if (OidIsValid(eqopr) && OidIsValid(ltopr))
1796 /* Seems to be a scalar datatype */
1797 stats->compute_stats = compute_scalar_stats;
1798 /*--------------------
1799 * The following choice of minrows is based on the paper
1800 * "Random sampling for histogram construction: how much is enough?"
1801 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1802 * Proceedings of ACM SIGMOD International Conference on Management
1803 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1804 * says that for table size n, histogram size k, maximum relative
1805 * error in bin size f, and error probability gamma, the minimum
1806 * random sample size is
1807 * r = 4 * k * ln(2*n/gamma) / f^2
1808 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1810 * Note that because of the log function, the dependence on n is
1811 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1812 * bin size error with probability 0.99. So there's no real need to
1813 * scale for n, which is a good thing because we don't necessarily
1814 * know it at this point.
1815 *--------------------
1817 stats->minrows = 300 * attr->attstattarget;
1819 else if (OidIsValid(eqopr))
1821 /* We can still recognize distinct values */
1822 stats->compute_stats = compute_distinct_stats;
1823 /* Might as well use the same minrows as above */
1824 stats->minrows = 300 * attr->attstattarget;
1828 /* Can't do much but the trivial stuff */
1829 stats->compute_stats = compute_trivial_stats;
1830 /* Might as well use the same minrows as above */
1831 stats->minrows = 300 * attr->attstattarget;
1839 * compute_trivial_stats() -- compute very basic column statistics
1841 * We use this when we cannot find a hash "=" operator for the datatype.
1843 * We determine the fraction of non-null rows and the average datum width.
1846 compute_trivial_stats(VacAttrStatsP stats,
1847 AnalyzeAttrFetchFunc fetchfunc,
1853 int nonnull_cnt = 0;
1854 double total_width = 0;
1855 bool is_varlena = (!stats->attrtype->typbyval &&
1856 stats->attrtype->typlen == -1);
1857 bool is_varwidth = (!stats->attrtype->typbyval &&
1858 stats->attrtype->typlen < 0);
1860 for (i = 0; i < samplerows; i++)
1865 vacuum_delay_point();
1867 value = fetchfunc(stats, i, &isnull);
1869 /* Check for null/nonnull */
1878 * If it's a variable-width field, add up widths for average width
1879 * calculation. Note that if the value is toasted, we use the toasted
1880 * width. We don't bother with this calculation if it's a fixed-width
1885 total_width += VARSIZE_ANY(DatumGetPointer(value));
1887 else if (is_varwidth)
1889 /* must be cstring */
1890 total_width += strlen(DatumGetCString(value)) + 1;
1894 /* We can only compute average width if we found some non-null values. */
1895 if (nonnull_cnt > 0)
1897 stats->stats_valid = true;
1898 /* Do the simple null-frac and width stats */
1899 stats->stanullfrac = (double) null_cnt / (double) samplerows;
1901 stats->stawidth = total_width / (double) nonnull_cnt;
1903 stats->stawidth = stats->attrtype->typlen;
1904 stats->stadistinct = 0.0; /* "unknown" */
1906 else if (null_cnt > 0)
1908 /* We found only nulls; assume the column is entirely null */
1909 stats->stats_valid = true;
1910 stats->stanullfrac = 1.0;
1912 stats->stawidth = 0; /* "unknown" */
1914 stats->stawidth = stats->attrtype->typlen;
1915 stats->stadistinct = 0.0; /* "unknown" */
1921 * compute_distinct_stats() -- compute column statistics including ndistinct
1923 * We use this when we can find only an "=" operator for the datatype.
1925 * We determine the fraction of non-null rows, the average width, the
1926 * most common values, and the (estimated) number of distinct values.
1928 * The most common values are determined by brute force: we keep a list
1929 * of previously seen values, ordered by number of times seen, as we scan
1930 * the samples. A newly seen value is inserted just after the last
1931 * multiply-seen value, causing the bottommost (oldest) singly-seen value
1932 * to drop off the list. The accuracy of this method, and also its cost,
1933 * depend mainly on the length of the list we are willing to keep.
1936 compute_distinct_stats(VacAttrStatsP stats,
1937 AnalyzeAttrFetchFunc fetchfunc,
1943 int nonnull_cnt = 0;
1944 int toowide_cnt = 0;
1945 double total_width = 0;
1946 bool is_varlena = (!stats->attrtype->typbyval &&
1947 stats->attrtype->typlen == -1);
1948 bool is_varwidth = (!stats->attrtype->typbyval &&
1949 stats->attrtype->typlen < 0);
1959 int num_mcv = stats->attr->attstattarget;
1960 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1963 * We track up to 2*n values for an n-element MCV list; but at least 10
1965 track_max = 2 * num_mcv;
1968 track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1971 fmgr_info(mystats->eqfunc, &f_cmpeq);
1973 for (i = 0; i < samplerows; i++)
1981 vacuum_delay_point();
1983 value = fetchfunc(stats, i, &isnull);
1985 /* Check for null/nonnull */
1994 * If it's a variable-width field, add up widths for average width
1995 * calculation. Note that if the value is toasted, we use the toasted
1996 * width. We don't bother with this calculation if it's a fixed-width
2001 total_width += VARSIZE_ANY(DatumGetPointer(value));
2004 * If the value is toasted, we want to detoast it just once to
2005 * avoid repeated detoastings and resultant excess memory usage
2006 * during the comparisons. Also, check to see if the value is
2007 * excessively wide, and if so don't detoast at all --- just
2010 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2015 value = PointerGetDatum(PG_DETOAST_DATUM(value));
2017 else if (is_varwidth)
2019 /* must be cstring */
2020 total_width += strlen(DatumGetCString(value)) + 1;
2024 * See if the value matches anything we're already tracking.
2027 firstcount1 = track_cnt;
2028 for (j = 0; j < track_cnt; j++)
2030 if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
2032 value, track[j].value)))
2037 if (j < firstcount1 && track[j].count == 1)
2045 /* This value may now need to "bubble up" in the track list */
2046 while (j > 0 && track[j].count > track[j - 1].count)
2048 swapDatum(track[j].value, track[j - 1].value);
2049 swapInt(track[j].count, track[j - 1].count);
2055 /* No match. Insert at head of count-1 list */
2056 if (track_cnt < track_max)
2058 for (j = track_cnt - 1; j > firstcount1; j--)
2060 track[j].value = track[j - 1].value;
2061 track[j].count = track[j - 1].count;
2063 if (firstcount1 < track_cnt)
2065 track[firstcount1].value = value;
2066 track[firstcount1].count = 1;
2071 /* We can only compute real stats if we found some non-null values. */
2072 if (nonnull_cnt > 0)
2077 stats->stats_valid = true;
2078 /* Do the simple null-frac and width stats */
2079 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2081 stats->stawidth = total_width / (double) nonnull_cnt;
2083 stats->stawidth = stats->attrtype->typlen;
2085 /* Count the number of values we found multiple times */
2087 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2089 if (track[nmultiple].count == 1)
2091 summultiple += track[nmultiple].count;
2097 * If we found no repeated non-null values, assume it's a unique
2098 * column; but be sure to discount for any nulls we found.
2100 stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2102 else if (track_cnt < track_max && toowide_cnt == 0 &&
2103 nmultiple == track_cnt)
2106 * Our track list includes every value in the sample, and every
2107 * value appeared more than once. Assume the column has just
2108 * these values. (This case is meant to address columns with
2109 * small, fixed sets of possible values, such as boolean or enum
2110 * columns. If there are any values that appear just once in the
2111 * sample, including too-wide values, we should assume that that's
2112 * not what we're dealing with.)
2114 stats->stadistinct = track_cnt;
2119 * Estimate the number of distinct values using the estimator
2120 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2121 * n*d / (n - f1 + f1*n/N)
2122 * where f1 is the number of distinct values that occurred
2123 * exactly once in our sample of n rows (from a total of N),
2124 * and d is the total number of distinct values in the sample.
2125 * This is their Duj1 estimator; the other estimators they
2126 * recommend are considerably more complex, and are numerically
2127 * very unstable when n is much smaller than N.
2129 * In this calculation, we consider only non-nulls. We used to
2130 * include rows with null values in the n and N counts, but that
2131 * leads to inaccurate answers in columns with many nulls, and
2132 * it's intuitively bogus anyway considering the desired result is
2133 * the number of distinct non-null values.
2135 * We assume (not very reliably!) that all the multiply-occurring
2136 * values are reflected in the final track[] list, and the other
2137 * nonnull values all appeared but once. (XXX this usually
2138 * results in a drastic overestimate of ndistinct. Can we do
2142 int f1 = nonnull_cnt - summultiple;
2143 int d = f1 + nmultiple;
2144 double n = samplerows - null_cnt;
2145 double N = totalrows * (1.0 - stats->stanullfrac);
2148 /* N == 0 shouldn't happen, but just in case ... */
2150 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2154 /* Clamp to sane range in case of roundoff error */
2155 if (stadistinct < d)
2157 if (stadistinct > N)
2159 /* And round to integer */
2160 stats->stadistinct = floor(stadistinct + 0.5);
2164 * If we estimated the number of distinct values at more than 10% of
2165 * the total row count (a very arbitrary limit), then assume that
2166 * stadistinct should scale with the row count rather than be a fixed
2169 if (stats->stadistinct > 0.1 * totalrows)
2170 stats->stadistinct = -(stats->stadistinct / totalrows);
2173 * Decide how many values are worth storing as most-common values. If
2174 * we are able to generate a complete MCV list (all the values in the
2175 * sample will fit, and we think these are all the ones in the table),
2176 * then do so. Otherwise, store only those values that are
2177 * significantly more common than the values not in the list.
2179 * Note: the first of these cases is meant to address columns with
2180 * small, fixed sets of possible values, such as boolean or enum
2181 * columns. If we can *completely* represent the column population by
2182 * an MCV list that will fit into the stats target, then we should do
2183 * so and thus provide the planner with complete information. But if
2184 * the MCV list is not complete, it's generally worth being more
2185 * selective, and not just filling it all the way up to the stats
2188 if (track_cnt < track_max && toowide_cnt == 0 &&
2189 stats->stadistinct > 0 &&
2190 track_cnt <= num_mcv)
2192 /* Track list includes all values seen, and all will fit */
2193 num_mcv = track_cnt;
2199 /* Incomplete list; decide how many values are worth keeping */
2200 if (num_mcv > track_cnt)
2201 num_mcv = track_cnt;
2205 mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2206 for (i = 0; i < num_mcv; i++)
2207 mcv_counts[i] = track[i].count;
2209 num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2212 samplerows, totalrows);
2216 /* Generate MCV slot entry */
2219 MemoryContext old_context;
2223 /* Must copy the target values into anl_context */
2224 old_context = MemoryContextSwitchTo(stats->anl_context);
2225 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2226 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2227 for (i = 0; i < num_mcv; i++)
2229 mcv_values[i] = datumCopy(track[i].value,
2230 stats->attrtype->typbyval,
2231 stats->attrtype->typlen);
2232 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2234 MemoryContextSwitchTo(old_context);
2236 stats->stakind[0] = STATISTIC_KIND_MCV;
2237 stats->staop[0] = mystats->eqopr;
2238 stats->stacoll[0] = stats->attrcollid;
2239 stats->stanumbers[0] = mcv_freqs;
2240 stats->numnumbers[0] = num_mcv;
2241 stats->stavalues[0] = mcv_values;
2242 stats->numvalues[0] = num_mcv;
2245 * Accept the defaults for stats->statypid and others. They have
2246 * been set before we were called (see vacuum.h)
2250 else if (null_cnt > 0)
2252 /* We found only nulls; assume the column is entirely null */
2253 stats->stats_valid = true;
2254 stats->stanullfrac = 1.0;
2256 stats->stawidth = 0; /* "unknown" */
2258 stats->stawidth = stats->attrtype->typlen;
2259 stats->stadistinct = 0.0; /* "unknown" */
2262 /* We don't need to bother cleaning up any of our temporary palloc's */
2267 * compute_scalar_stats() -- compute column statistics
2269 * We use this when we can find "=" and "<" operators for the datatype.
2271 * We determine the fraction of non-null rows, the average width, the
2272 * most common values, the (estimated) number of distinct values, the
2273 * distribution histogram, and the correlation of physical to logical order.
2275 * The desired stats can be determined fairly easily after sorting the
2276 * data values into order.
2279 compute_scalar_stats(VacAttrStatsP stats,
2280 AnalyzeAttrFetchFunc fetchfunc,
2286 int nonnull_cnt = 0;
2287 int toowide_cnt = 0;
2288 double total_width = 0;
2289 bool is_varlena = (!stats->attrtype->typbyval &&
2290 stats->attrtype->typlen == -1);
2291 bool is_varwidth = (!stats->attrtype->typbyval &&
2292 stats->attrtype->typlen < 0);
2294 SortSupportData ssup;
2298 ScalarMCVItem *track;
2300 int num_mcv = stats->attr->attstattarget;
2301 int num_bins = stats->attr->attstattarget;
2302 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2304 values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2305 tupnoLink = (int *) palloc(samplerows * sizeof(int));
2306 track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2308 memset(&ssup, 0, sizeof(ssup));
2309 ssup.ssup_cxt = CurrentMemoryContext;
2310 ssup.ssup_collation = stats->attrcollid;
2311 ssup.ssup_nulls_first = false;
2314 * For now, don't perform abbreviated key conversion, because full values
2315 * are required for MCV slot generation. Supporting that optimization
2316 * would necessitate teaching compare_scalars() to call a tie-breaker.
2318 ssup.abbreviate = false;
2320 PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
2322 /* Initial scan to find sortable values */
2323 for (i = 0; i < samplerows; i++)
2328 vacuum_delay_point();
2330 value = fetchfunc(stats, i, &isnull);
2332 /* Check for null/nonnull */
2341 * If it's a variable-width field, add up widths for average width
2342 * calculation. Note that if the value is toasted, we use the toasted
2343 * width. We don't bother with this calculation if it's a fixed-width
2348 total_width += VARSIZE_ANY(DatumGetPointer(value));
2351 * If the value is toasted, we want to detoast it just once to
2352 * avoid repeated detoastings and resultant excess memory usage
2353 * during the comparisons. Also, check to see if the value is
2354 * excessively wide, and if so don't detoast at all --- just
2357 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2362 value = PointerGetDatum(PG_DETOAST_DATUM(value));
2364 else if (is_varwidth)
2366 /* must be cstring */
2367 total_width += strlen(DatumGetCString(value)) + 1;
2370 /* Add it to the list to be sorted */
2371 values[values_cnt].value = value;
2372 values[values_cnt].tupno = values_cnt;
2373 tupnoLink[values_cnt] = values_cnt;
2377 /* We can only compute real stats if we found some sortable values. */
2380 int ndistinct, /* # distinct values in sample */
2381 nmultiple, /* # that appear multiple times */
2385 CompareScalarsContext cxt;
2387 /* Sort the collected values */
2389 cxt.tupnoLink = tupnoLink;
2390 qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2391 compare_scalars, (void *) &cxt);
2394 * Now scan the values in order, find the most common ones, and also
2395 * accumulate ordering-correlation statistics.
2397 * To determine which are most common, we first have to count the
2398 * number of duplicates of each value. The duplicates are adjacent in
2399 * the sorted list, so a brute-force approach is to compare successive
2400 * datum values until we find two that are not equal. However, that
2401 * requires N-1 invocations of the datum comparison routine, which are
2402 * completely redundant with work that was done during the sort. (The
2403 * sort algorithm must at some point have compared each pair of items
2404 * that are adjacent in the sorted order; otherwise it could not know
2405 * that it's ordered the pair correctly.) We exploit this by having
2406 * compare_scalars remember the highest tupno index that each
2407 * ScalarItem has been found equal to. At the end of the sort, a
2408 * ScalarItem's tupnoLink will still point to itself if and only if it
2409 * is the last item of its group of duplicates (since the group will
2410 * be ordered by tupno).
2416 for (i = 0; i < values_cnt; i++)
2418 int tupno = values[i].tupno;
2420 corr_xysum += ((double) i) * ((double) tupno);
2422 if (tupnoLink[tupno] == tupno)
2424 /* Reached end of duplicates of this value */
2429 if (track_cnt < num_mcv ||
2430 dups_cnt > track[track_cnt - 1].count)
2433 * Found a new item for the mcv list; find its
2434 * position, bubbling down old items if needed. Loop
2435 * invariant is that j points at an empty/ replaceable
2440 if (track_cnt < num_mcv)
2442 for (j = track_cnt - 1; j > 0; j--)
2444 if (dups_cnt <= track[j - 1].count)
2446 track[j].count = track[j - 1].count;
2447 track[j].first = track[j - 1].first;
2449 track[j].count = dups_cnt;
2450 track[j].first = i + 1 - dups_cnt;
2457 stats->stats_valid = true;
2458 /* Do the simple null-frac and width stats */
2459 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2461 stats->stawidth = total_width / (double) nonnull_cnt;
2463 stats->stawidth = stats->attrtype->typlen;
2468 * If we found no repeated non-null values, assume it's a unique
2469 * column; but be sure to discount for any nulls we found.
2471 stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2473 else if (toowide_cnt == 0 && nmultiple == ndistinct)
2476 * Every value in the sample appeared more than once. Assume the
2477 * column has just these values. (This case is meant to address
2478 * columns with small, fixed sets of possible values, such as
2479 * boolean or enum columns. If there are any values that appear
2480 * just once in the sample, including too-wide values, we should
2481 * assume that that's not what we're dealing with.)
2483 stats->stadistinct = ndistinct;
2488 * Estimate the number of distinct values using the estimator
2489 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2490 * n*d / (n - f1 + f1*n/N)
2491 * where f1 is the number of distinct values that occurred
2492 * exactly once in our sample of n rows (from a total of N),
2493 * and d is the total number of distinct values in the sample.
2494 * This is their Duj1 estimator; the other estimators they
2495 * recommend are considerably more complex, and are numerically
2496 * very unstable when n is much smaller than N.
2498 * In this calculation, we consider only non-nulls. We used to
2499 * include rows with null values in the n and N counts, but that
2500 * leads to inaccurate answers in columns with many nulls, and
2501 * it's intuitively bogus anyway considering the desired result is
2502 * the number of distinct non-null values.
2504 * Overwidth values are assumed to have been distinct.
2507 int f1 = ndistinct - nmultiple + toowide_cnt;
2508 int d = f1 + nmultiple;
2509 double n = samplerows - null_cnt;
2510 double N = totalrows * (1.0 - stats->stanullfrac);
2513 /* N == 0 shouldn't happen, but just in case ... */
2515 stadistinct = (n * d) / ((n - f1) + f1 * n / N);
2519 /* Clamp to sane range in case of roundoff error */
2520 if (stadistinct < d)
2522 if (stadistinct > N)
2524 /* And round to integer */
2525 stats->stadistinct = floor(stadistinct + 0.5);
2529 * If we estimated the number of distinct values at more than 10% of
2530 * the total row count (a very arbitrary limit), then assume that
2531 * stadistinct should scale with the row count rather than be a fixed
2534 if (stats->stadistinct > 0.1 * totalrows)
2535 stats->stadistinct = -(stats->stadistinct / totalrows);
2538 * Decide how many values are worth storing as most-common values. If
2539 * we are able to generate a complete MCV list (all the values in the
2540 * sample will fit, and we think these are all the ones in the table),
2541 * then do so. Otherwise, store only those values that are
2542 * significantly more common than the values not in the list.
2544 * Note: the first of these cases is meant to address columns with
2545 * small, fixed sets of possible values, such as boolean or enum
2546 * columns. If we can *completely* represent the column population by
2547 * an MCV list that will fit into the stats target, then we should do
2548 * so and thus provide the planner with complete information. But if
2549 * the MCV list is not complete, it's generally worth being more
2550 * selective, and not just filling it all the way up to the stats
2553 if (track_cnt == ndistinct && toowide_cnt == 0 &&
2554 stats->stadistinct > 0 &&
2555 track_cnt <= num_mcv)
2557 /* Track list includes all values seen, and all will fit */
2558 num_mcv = track_cnt;
2564 /* Incomplete list; decide how many values are worth keeping */
2565 if (num_mcv > track_cnt)
2566 num_mcv = track_cnt;
2570 mcv_counts = (int *) palloc(num_mcv * sizeof(int));
2571 for (i = 0; i < num_mcv; i++)
2572 mcv_counts[i] = track[i].count;
2574 num_mcv = analyze_mcv_list(mcv_counts, num_mcv,
2577 samplerows, totalrows);
2581 /* Generate MCV slot entry */
2584 MemoryContext old_context;
2588 /* Must copy the target values into anl_context */
2589 old_context = MemoryContextSwitchTo(stats->anl_context);
2590 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2591 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2592 for (i = 0; i < num_mcv; i++)
2594 mcv_values[i] = datumCopy(values[track[i].first].value,
2595 stats->attrtype->typbyval,
2596 stats->attrtype->typlen);
2597 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2599 MemoryContextSwitchTo(old_context);
2601 stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2602 stats->staop[slot_idx] = mystats->eqopr;
2603 stats->stacoll[slot_idx] = stats->attrcollid;
2604 stats->stanumbers[slot_idx] = mcv_freqs;
2605 stats->numnumbers[slot_idx] = num_mcv;
2606 stats->stavalues[slot_idx] = mcv_values;
2607 stats->numvalues[slot_idx] = num_mcv;
2610 * Accept the defaults for stats->statypid and others. They have
2611 * been set before we were called (see vacuum.h)
2617 * Generate a histogram slot entry if there are at least two distinct
2618 * values not accounted for in the MCV list. (This ensures the
2619 * histogram won't collapse to empty or a singleton.)
2621 num_hist = ndistinct - num_mcv;
2622 if (num_hist > num_bins)
2623 num_hist = num_bins + 1;
2626 MemoryContext old_context;
2634 /* Sort the MCV items into position order to speed next loop */
2635 qsort((void *) track, num_mcv,
2636 sizeof(ScalarMCVItem), compare_mcvs);
2639 * Collapse out the MCV items from the values[] array.
2641 * Note we destroy the values[] array here... but we don't need it
2642 * for anything more. We do, however, still need values_cnt.
2643 * nvals will be the number of remaining entries in values[].
2652 j = 0; /* index of next interesting MCV item */
2653 while (src < values_cnt)
2659 int first = track[j].first;
2663 /* advance past this MCV item */
2664 src = first + track[j].count;
2668 ncopy = first - src;
2671 ncopy = values_cnt - src;
2672 memmove(&values[dest], &values[src],
2673 ncopy * sizeof(ScalarItem));
2681 Assert(nvals >= num_hist);
2683 /* Must copy the target values into anl_context */
2684 old_context = MemoryContextSwitchTo(stats->anl_context);
2685 hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2688 * The object of this loop is to copy the first and last values[]
2689 * entries along with evenly-spaced values in between. So the
2690 * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2691 * computing that subscript directly risks integer overflow when
2692 * the stats target is more than a couple thousand. Instead we
2693 * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2694 * the integral and fractional parts of the sum separately.
2696 delta = (nvals - 1) / (num_hist - 1);
2697 deltafrac = (nvals - 1) % (num_hist - 1);
2700 for (i = 0; i < num_hist; i++)
2702 hist_values[i] = datumCopy(values[pos].value,
2703 stats->attrtype->typbyval,
2704 stats->attrtype->typlen);
2706 posfrac += deltafrac;
2707 if (posfrac >= (num_hist - 1))
2709 /* fractional part exceeds 1, carry to integer part */
2711 posfrac -= (num_hist - 1);
2715 MemoryContextSwitchTo(old_context);
2717 stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2718 stats->staop[slot_idx] = mystats->ltopr;
2719 stats->stacoll[slot_idx] = stats->attrcollid;
2720 stats->stavalues[slot_idx] = hist_values;
2721 stats->numvalues[slot_idx] = num_hist;
2724 * Accept the defaults for stats->statypid and others. They have
2725 * been set before we were called (see vacuum.h)
2730 /* Generate a correlation entry if there are multiple values */
2733 MemoryContext old_context;
2738 /* Must copy the target values into anl_context */
2739 old_context = MemoryContextSwitchTo(stats->anl_context);
2740 corrs = (float4 *) palloc(sizeof(float4));
2741 MemoryContextSwitchTo(old_context);
2744 * Since we know the x and y value sets are both
2745 * 0, 1, ..., values_cnt-1
2746 * we have sum(x) = sum(y) =
2747 * (values_cnt-1)*values_cnt / 2
2748 * and sum(x^2) = sum(y^2) =
2749 * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2752 corr_xsum = ((double) (values_cnt - 1)) *
2753 ((double) values_cnt) / 2.0;
2754 corr_x2sum = ((double) (values_cnt - 1)) *
2755 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2757 /* And the correlation coefficient reduces to */
2758 corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2759 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2761 stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2762 stats->staop[slot_idx] = mystats->ltopr;
2763 stats->stacoll[slot_idx] = stats->attrcollid;
2764 stats->stanumbers[slot_idx] = corrs;
2765 stats->numnumbers[slot_idx] = 1;
2769 else if (nonnull_cnt > 0)
2771 /* We found some non-null values, but they were all too wide */
2772 Assert(nonnull_cnt == toowide_cnt);
2773 stats->stats_valid = true;
2774 /* Do the simple null-frac and width stats */
2775 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2777 stats->stawidth = total_width / (double) nonnull_cnt;
2779 stats->stawidth = stats->attrtype->typlen;
2780 /* Assume all too-wide values are distinct, so it's a unique column */
2781 stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
2783 else if (null_cnt > 0)
2785 /* We found only nulls; assume the column is entirely null */
2786 stats->stats_valid = true;
2787 stats->stanullfrac = 1.0;
2789 stats->stawidth = 0; /* "unknown" */
2791 stats->stawidth = stats->attrtype->typlen;
2792 stats->stadistinct = 0.0; /* "unknown" */
2795 /* We don't need to bother cleaning up any of our temporary palloc's */
2799 * qsort_arg comparator for sorting ScalarItems
2801 * Aside from sorting the items, we update the tupnoLink[] array
2802 * whenever two ScalarItems are found to contain equal datums. The array
2803 * is indexed by tupno; for each ScalarItem, it contains the highest
2804 * tupno that that item's datum has been found to be equal to. This allows
2805 * us to avoid additional comparisons in compute_scalar_stats().
2808 compare_scalars(const void *a, const void *b, void *arg)
2810 Datum da = ((const ScalarItem *) a)->value;
2811 int ta = ((const ScalarItem *) a)->tupno;
2812 Datum db = ((const ScalarItem *) b)->value;
2813 int tb = ((const ScalarItem *) b)->tupno;
2814 CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2817 compare = ApplySortComparator(da, false, db, false, cxt->ssup);
2822 * The two datums are equal, so update cxt->tupnoLink[].
2824 if (cxt->tupnoLink[ta] < tb)
2825 cxt->tupnoLink[ta] = tb;
2826 if (cxt->tupnoLink[tb] < ta)
2827 cxt->tupnoLink[tb] = ta;
2830 * For equal datums, sort by tupno
2836 * qsort comparator for sorting ScalarMCVItems by position
2839 compare_mcvs(const void *a, const void *b)
2841 int da = ((const ScalarMCVItem *) a)->first;
2842 int db = ((const ScalarMCVItem *) b)->first;
2848 * Analyze the list of common values in the sample and decide how many are
2849 * worth storing in the table's MCV list.
2851 * mcv_counts is assumed to be a list of the counts of the most common values
2852 * seen in the sample, starting with the most common. The return value is the
2853 * number that are significantly more common than the values not in the list,
2854 * and which are therefore deemed worth storing in the table's MCV list.
2857 analyze_mcv_list(int *mcv_counts,
2864 double ndistinct_table;
2869 * If the entire table was sampled, keep the whole list. This also
2870 * protects us against division by zero in the code below.
2872 if (samplerows == totalrows || totalrows <= 1.0)
2875 /* Re-extract the estimated number of distinct nonnull values in table */
2876 ndistinct_table = stadistinct;
2877 if (ndistinct_table < 0)
2878 ndistinct_table = -ndistinct_table * totalrows;
2881 * Exclude the least common values from the MCV list, if they are not
2882 * significantly more common than the estimated selectivity they would
2883 * have if they weren't in the list. All non-MCV values are assumed to be
2884 * equally common, after taking into account the frequencies of all the
2885 * values in the MCV list and the number of nulls (c.f. eqsel()).
2887 * Here sumcount tracks the total count of all but the last (least common)
2888 * value in the MCV list, allowing us to determine the effect of excluding
2889 * that value from the list.
2891 * Note that we deliberately do this by removing values from the full
2892 * list, rather than starting with an empty list and adding values,
2893 * because the latter approach can fail to add any values if all the most
2894 * common values have around the same frequency and make up the majority
2895 * of the table, so that the overall average frequency of all values is
2896 * roughly the same as that of the common values. This would lead to any
2897 * uncommon values being significantly overestimated.
2900 for (i = 0; i < num_mcv - 1; i++)
2901 sumcount += mcv_counts[i];
2914 * Estimated selectivity the least common value would have if it
2915 * wasn't in the MCV list (c.f. eqsel()).
2917 selec = 1.0 - sumcount / samplerows - stanullfrac;
2922 otherdistinct = ndistinct_table - (num_mcv - 1);
2923 if (otherdistinct > 1)
2924 selec /= otherdistinct;
2927 * If the value is kept in the MCV list, its population frequency is
2928 * assumed to equal its sample frequency. We use the lower end of a
2929 * textbook continuity-corrected Wald-type confidence interval to
2930 * determine if that is significantly more common than the non-MCV
2931 * frequency --- specifically we assume the population frequency is
2932 * highly likely to be within around 2 standard errors of the sample
2933 * frequency, which equates to an interval of 2 standard deviations
2934 * either side of the sample count, plus an additional 0.5 for the
2935 * continuity correction. Since we are sampling without replacement,
2936 * this is a hypergeometric distribution.
2938 * XXX: Empirically, this approach seems to work quite well, but it
2939 * may be worth considering more advanced techniques for estimating
2940 * the confidence interval of the hypergeometric distribution.
2944 K = N * mcv_counts[num_mcv - 1] / n;
2945 variance = n * K * (N - K) * (N - n) / (N * N * (N - 1));
2946 stddev = sqrt(variance);
2948 if (mcv_counts[num_mcv - 1] > selec * samplerows + 2 * stddev + 0.5)
2951 * The value is significantly more common than the non-MCV
2952 * selectivity would suggest. Keep it, and all the other more
2953 * common values in the list.
2959 /* Discard this value and consider the next least common value */
2963 sumcount -= mcv_counts[num_mcv - 1];