1 /*-------------------------------------------------------------------------
4 * the Postgres statistics generator
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/analyze.c
13 *-------------------------------------------------------------------------
19 #include "access/transam.h"
20 #include "access/tupconvert.h"
21 #include "access/tuptoaster.h"
22 #include "access/visibilitymap.h"
23 #include "access/xact.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/pg_collation.h"
27 #include "catalog/pg_inherits_fn.h"
28 #include "catalog/pg_namespace.h"
29 #include "commands/dbcommands.h"
30 #include "commands/tablecmds.h"
31 #include "commands/vacuum.h"
32 #include "executor/executor.h"
33 #include "miscadmin.h"
34 #include "nodes/nodeFuncs.h"
35 #include "parser/parse_oper.h"
36 #include "parser/parse_relation.h"
38 #include "postmaster/autovacuum.h"
39 #include "storage/bufmgr.h"
40 #include "storage/lmgr.h"
41 #include "storage/proc.h"
42 #include "storage/procarray.h"
43 #include "utils/acl.h"
44 #include "utils/attoptcache.h"
45 #include "utils/datum.h"
46 #include "utils/guc.h"
47 #include "utils/lsyscache.h"
48 #include "utils/memutils.h"
49 #include "utils/pg_rusage.h"
50 #include "utils/syscache.h"
51 #include "utils/tuplesort.h"
52 #include "utils/timestamp.h"
53 #include "utils/tqual.h"
56 /* Data structure for Algorithm S from Knuth 3.4.2 */
59 BlockNumber N; /* number of blocks, known in advance */
60 int n; /* desired sample size */
61 BlockNumber t; /* current block number */
62 int m; /* blocks selected so far */
65 typedef BlockSamplerData *BlockSampler;
67 /* Per-index data for ANALYZE */
68 typedef struct AnlIndexData
70 IndexInfo *indexInfo; /* BuildIndexInfo result */
71 double tupleFract; /* fraction of rows for partial index */
72 VacAttrStats **vacattrstats; /* index attrs to analyze */
77 /* Default statistics target (GUC parameter) */
78 int default_statistics_target = 100;
80 /* A few variables that don't seem worth passing around as parameters */
81 static int elevel = -1;
83 static MemoryContext anl_context = NULL;
85 static BufferAccessStrategy vac_strategy;
88 static void do_analyze_rel(Relation onerel, VacuumStmt *vacstmt, bool inh);
89 static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
91 static bool BlockSampler_HasMore(BlockSampler bs);
92 static BlockNumber BlockSampler_Next(BlockSampler bs);
93 static void compute_index_stats(Relation onerel, double totalrows,
94 AnlIndexData *indexdata, int nindexes,
95 HeapTuple *rows, int numrows,
96 MemoryContext col_context);
97 static VacAttrStats *examine_attribute(Relation onerel, int attnum,
99 static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
100 int targrows, double *totalrows, double *totaldeadrows);
101 static double random_fract(void);
102 static double init_selection_state(int n);
103 static double get_next_S(double t, int n, double *stateptr);
104 static int compare_rows(const void *a, const void *b);
105 static int acquire_inherited_sample_rows(Relation onerel,
106 HeapTuple *rows, int targrows,
107 double *totalrows, double *totaldeadrows);
108 static void update_attstats(Oid relid, bool inh,
109 int natts, VacAttrStats **vacattrstats);
110 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
111 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
113 static bool std_typanalyze(VacAttrStats *stats);
117 * analyze_rel() -- analyze one relation
120 analyze_rel(Oid relid, VacuumStmt *vacstmt, BufferAccessStrategy bstrategy)
124 /* Set up static variables */
125 if (vacstmt->options & VACOPT_VERBOSE)
130 vac_strategy = bstrategy;
133 * Check for user-requested abort.
135 CHECK_FOR_INTERRUPTS();
138 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
139 * ANALYZEs don't run on it concurrently. (This also locks out a
140 * concurrent VACUUM, which doesn't matter much at the moment but might
141 * matter if we ever try to accumulate stats on dead tuples.) If the rel
142 * has been dropped since we last saw it, we don't need to process it.
144 if (!(vacstmt->options & VACOPT_NOWAIT))
145 onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
146 else if (ConditionalLockRelationOid(relid, ShareUpdateExclusiveLock))
147 onerel = try_relation_open(relid, NoLock);
151 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
153 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
154 errmsg("skipping analyze of \"%s\" --- lock not available",
155 vacstmt->relation->relname)));
161 * Check permissions --- this should match vacuum's check!
163 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
164 (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
166 /* No need for a WARNING if we already complained during VACUUM */
167 if (!(vacstmt->options & VACOPT_VACUUM))
169 if (onerel->rd_rel->relisshared)
171 (errmsg("skipping \"%s\" --- only superuser can analyze it",
172 RelationGetRelationName(onerel))));
173 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
175 (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
176 RelationGetRelationName(onerel))));
179 (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
180 RelationGetRelationName(onerel))));
182 relation_close(onerel, ShareUpdateExclusiveLock);
187 * Check that it's a plain table; we used to do this in get_rel_oids() but
188 * seems safer to check after we've locked the relation.
190 if (onerel->rd_rel->relkind != RELKIND_RELATION)
192 /* No need for a WARNING if we already complained during VACUUM */
193 if (!(vacstmt->options & VACOPT_VACUUM))
195 (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
196 RelationGetRelationName(onerel))));
197 relation_close(onerel, ShareUpdateExclusiveLock);
202 * Silently ignore tables that are temp tables of other backends ---
203 * trying to analyze these is rather pointless, since their contents are
204 * probably not up-to-date on disk. (We don't throw a warning here; it
205 * would just lead to chatter during a database-wide ANALYZE.)
207 if (RELATION_IS_OTHER_TEMP(onerel))
209 relation_close(onerel, ShareUpdateExclusiveLock);
214 * We can ANALYZE any table except pg_statistic. See update_attstats
216 if (RelationGetRelid(onerel) == StatisticRelationId)
218 relation_close(onerel, ShareUpdateExclusiveLock);
223 * OK, let's do it. First let other backends know I'm in ANALYZE.
225 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
226 MyProc->vacuumFlags |= PROC_IN_ANALYZE;
227 LWLockRelease(ProcArrayLock);
230 * Do the normal non-recursive ANALYZE.
232 do_analyze_rel(onerel, vacstmt, false);
235 * If there are child tables, do recursive ANALYZE.
237 if (onerel->rd_rel->relhassubclass)
238 do_analyze_rel(onerel, vacstmt, true);
241 * Close source relation now, but keep lock so that no one deletes it
242 * before we commit. (If someone did, they'd fail to clean up the entries
243 * we made in pg_statistic. Also, releasing the lock before commit would
244 * expose us to concurrent-update failures in update_attstats.)
246 relation_close(onerel, NoLock);
249 * Reset my PGPROC flag. Note: we need this here, and not in vacuum_rel,
250 * because the vacuum flag is cleared by the end-of-xact code.
252 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
253 MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
254 LWLockRelease(ProcArrayLock);
258 * do_analyze_rel() -- analyze one relation, recursively or not
261 do_analyze_rel(Relation onerel, VacuumStmt *vacstmt, bool inh)
270 VacAttrStats **vacattrstats;
271 AnlIndexData *indexdata;
278 TimestampTz starttime = 0;
279 MemoryContext caller_context;
281 int save_sec_context;
286 (errmsg("analyzing \"%s.%s\" inheritance tree",
287 get_namespace_name(RelationGetNamespace(onerel)),
288 RelationGetRelationName(onerel))));
291 (errmsg("analyzing \"%s.%s\"",
292 get_namespace_name(RelationGetNamespace(onerel)),
293 RelationGetRelationName(onerel))));
296 * Set up a working context so that we can easily free whatever junk gets
299 anl_context = AllocSetContextCreate(CurrentMemoryContext,
301 ALLOCSET_DEFAULT_MINSIZE,
302 ALLOCSET_DEFAULT_INITSIZE,
303 ALLOCSET_DEFAULT_MAXSIZE);
304 caller_context = MemoryContextSwitchTo(anl_context);
307 * Switch to the table owner's userid, so that any index functions are run
308 * as that user. Also lock down security-restricted operations and
309 * arrange to make GUC variable changes local to this command.
311 GetUserIdAndSecContext(&save_userid, &save_sec_context);
312 SetUserIdAndSecContext(onerel->rd_rel->relowner,
313 save_sec_context | SECURITY_RESTRICTED_OPERATION);
314 save_nestlevel = NewGUCNestLevel();
316 /* measure elapsed time iff autovacuum logging requires it */
317 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
319 pg_rusage_init(&ru0);
320 if (Log_autovacuum_min_duration > 0)
321 starttime = GetCurrentTimestamp();
325 * Determine which columns to analyze
327 * Note that system attributes are never analyzed.
329 if (vacstmt->va_cols != NIL)
333 vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
334 sizeof(VacAttrStats *));
336 foreach(le, vacstmt->va_cols)
338 char *col = strVal(lfirst(le));
340 i = attnameAttNum(onerel, col, false);
341 if (i == InvalidAttrNumber)
343 (errcode(ERRCODE_UNDEFINED_COLUMN),
344 errmsg("column \"%s\" of relation \"%s\" does not exist",
345 col, RelationGetRelationName(onerel))));
346 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
347 if (vacattrstats[tcnt] != NULL)
354 attr_cnt = onerel->rd_att->natts;
355 vacattrstats = (VacAttrStats **)
356 palloc(attr_cnt * sizeof(VacAttrStats *));
358 for (i = 1; i <= attr_cnt; i++)
360 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
361 if (vacattrstats[tcnt] != NULL)
368 * Open all indexes of the relation, and see if there are any analyzable
369 * columns in the indexes. We do not analyze index columns if there was
370 * an explicit column list in the ANALYZE command, however. If we are
371 * doing a recursive scan, we don't want to touch the parent's indexes at
375 vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
381 hasindex = (nindexes > 0);
385 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
386 for (ind = 0; ind < nindexes; ind++)
388 AnlIndexData *thisdata = &indexdata[ind];
389 IndexInfo *indexInfo;
391 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
392 thisdata->tupleFract = 1.0; /* fix later if partial */
393 if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
395 ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
397 thisdata->vacattrstats = (VacAttrStats **)
398 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
400 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
402 int keycol = indexInfo->ii_KeyAttrNumbers[i];
406 /* Found an index expression */
409 if (indexpr_item == NULL) /* shouldn't happen */
410 elog(ERROR, "too few entries in indexprs list");
411 indexkey = (Node *) lfirst(indexpr_item);
412 indexpr_item = lnext(indexpr_item);
413 thisdata->vacattrstats[tcnt] =
414 examine_attribute(Irel[ind], i + 1, indexkey);
415 if (thisdata->vacattrstats[tcnt] != NULL)
419 thisdata->attr_cnt = tcnt;
425 * Determine how many rows we need to sample, using the worst case from
426 * all analyzable columns. We use a lower bound of 100 rows to avoid
427 * possible overflow in Vitter's algorithm. (Note: that will also be
428 * the target in the corner case where there are no analyzable columns.)
431 for (i = 0; i < attr_cnt; i++)
433 if (targrows < vacattrstats[i]->minrows)
434 targrows = vacattrstats[i]->minrows;
436 for (ind = 0; ind < nindexes; ind++)
438 AnlIndexData *thisdata = &indexdata[ind];
440 for (i = 0; i < thisdata->attr_cnt; i++)
442 if (targrows < thisdata->vacattrstats[i]->minrows)
443 targrows = thisdata->vacattrstats[i]->minrows;
448 * Acquire the sample rows
450 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
452 numrows = acquire_inherited_sample_rows(onerel, rows, targrows,
453 &totalrows, &totaldeadrows);
455 numrows = acquire_sample_rows(onerel, rows, targrows,
456 &totalrows, &totaldeadrows);
459 * Compute the statistics. Temporary results during the calculations for
460 * each column are stored in a child context. The calc routines are
461 * responsible to make sure that whatever they store into the VacAttrStats
462 * structure is allocated in anl_context.
466 MemoryContext col_context,
469 col_context = AllocSetContextCreate(anl_context,
471 ALLOCSET_DEFAULT_MINSIZE,
472 ALLOCSET_DEFAULT_INITSIZE,
473 ALLOCSET_DEFAULT_MAXSIZE);
474 old_context = MemoryContextSwitchTo(col_context);
476 for (i = 0; i < attr_cnt; i++)
478 VacAttrStats *stats = vacattrstats[i];
479 AttributeOpts *aopt =
480 get_attribute_options(onerel->rd_id, stats->attr->attnum);
483 stats->tupDesc = onerel->rd_att;
484 (*stats->compute_stats) (stats,
490 * If the appropriate flavor of the n_distinct option is
491 * specified, override with the corresponding value.
496 inh ? aopt->n_distinct_inherited : aopt->n_distinct;
498 if (n_distinct != 0.0)
499 stats->stadistinct = n_distinct;
502 MemoryContextResetAndDeleteChildren(col_context);
506 compute_index_stats(onerel, totalrows,
511 MemoryContextSwitchTo(old_context);
512 MemoryContextDelete(col_context);
515 * Emit the completed stats rows into pg_statistic, replacing any
516 * previous statistics for the target columns. (If there are stats in
517 * pg_statistic for columns we didn't process, we leave them alone.)
519 update_attstats(RelationGetRelid(onerel), inh,
520 attr_cnt, vacattrstats);
522 for (ind = 0; ind < nindexes; ind++)
524 AnlIndexData *thisdata = &indexdata[ind];
526 update_attstats(RelationGetRelid(Irel[ind]), false,
527 thisdata->attr_cnt, thisdata->vacattrstats);
532 * Update pages/tuples stats in pg_class ... but not if we're doing
536 vac_update_relstats(onerel,
537 RelationGetNumberOfBlocks(onerel),
539 visibilitymap_count(onerel),
541 InvalidTransactionId);
544 * Same for indexes. Vacuum always scans all indexes, so if we're part of
545 * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
548 if (!inh && !(vacstmt->options & VACOPT_VACUUM))
550 for (ind = 0; ind < nindexes; ind++)
552 AnlIndexData *thisdata = &indexdata[ind];
553 double totalindexrows;
555 totalindexrows = ceil(thisdata->tupleFract * totalrows);
556 vac_update_relstats(Irel[ind],
557 RelationGetNumberOfBlocks(Irel[ind]),
561 InvalidTransactionId);
566 * Report ANALYZE to the stats collector, too. However, if doing
567 * inherited stats we shouldn't report, because the stats collector only
568 * tracks per-table stats.
571 pgstat_report_analyze(onerel, totalrows, totaldeadrows);
573 /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
574 if (!(vacstmt->options & VACOPT_VACUUM))
576 for (ind = 0; ind < nindexes; ind++)
578 IndexBulkDeleteResult *stats;
579 IndexVacuumInfo ivinfo;
581 ivinfo.index = Irel[ind];
582 ivinfo.analyze_only = true;
583 ivinfo.estimated_count = true;
584 ivinfo.message_level = elevel;
585 ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
586 ivinfo.strategy = vac_strategy;
588 stats = index_vacuum_cleanup(&ivinfo, NULL);
595 /* Done with indexes */
596 vac_close_indexes(nindexes, Irel, NoLock);
598 /* Log the action if appropriate */
599 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
601 if (Log_autovacuum_min_duration == 0 ||
602 TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
603 Log_autovacuum_min_duration))
605 (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
606 get_database_name(MyDatabaseId),
607 get_namespace_name(RelationGetNamespace(onerel)),
608 RelationGetRelationName(onerel),
609 pg_rusage_show(&ru0))));
612 /* Roll back any GUC changes executed by index functions */
613 AtEOXact_GUC(false, save_nestlevel);
615 /* Restore userid and security context */
616 SetUserIdAndSecContext(save_userid, save_sec_context);
618 /* Restore current context and release memory */
619 MemoryContextSwitchTo(caller_context);
620 MemoryContextDelete(anl_context);
625 * Compute statistics about indexes of a relation
628 compute_index_stats(Relation onerel, double totalrows,
629 AnlIndexData *indexdata, int nindexes,
630 HeapTuple *rows, int numrows,
631 MemoryContext col_context)
633 MemoryContext ind_context,
635 Datum values[INDEX_MAX_KEYS];
636 bool isnull[INDEX_MAX_KEYS];
640 ind_context = AllocSetContextCreate(anl_context,
642 ALLOCSET_DEFAULT_MINSIZE,
643 ALLOCSET_DEFAULT_INITSIZE,
644 ALLOCSET_DEFAULT_MAXSIZE);
645 old_context = MemoryContextSwitchTo(ind_context);
647 for (ind = 0; ind < nindexes; ind++)
649 AnlIndexData *thisdata = &indexdata[ind];
650 IndexInfo *indexInfo = thisdata->indexInfo;
651 int attr_cnt = thisdata->attr_cnt;
652 TupleTableSlot *slot;
654 ExprContext *econtext;
661 double totalindexrows;
663 /* Ignore index if no columns to analyze and not partial */
664 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
668 * Need an EState for evaluation of index expressions and
669 * partial-index predicates. Create it in the per-index context to be
670 * sure it gets cleaned up at the bottom of the loop.
672 estate = CreateExecutorState();
673 econtext = GetPerTupleExprContext(estate);
674 /* Need a slot to hold the current heap tuple, too */
675 slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
677 /* Arrange for econtext's scan tuple to be the tuple under test */
678 econtext->ecxt_scantuple = slot;
680 /* Set up execution state for predicate. */
682 ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
685 /* Compute and save index expression values */
686 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
687 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
690 for (rowno = 0; rowno < numrows; rowno++)
692 HeapTuple heapTuple = rows[rowno];
695 * Reset the per-tuple context each time, to reclaim any cruft
696 * left behind by evaluating the predicate or index expressions.
698 ResetExprContext(econtext);
700 /* Set up for predicate or expression evaluation */
701 ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
703 /* If index is partial, check predicate */
704 if (predicate != NIL)
706 if (!ExecQual(predicate, econtext, false))
714 * Evaluate the index row to compute expression values. We
715 * could do this by hand, but FormIndexDatum is convenient.
717 FormIndexDatum(indexInfo,
724 * Save just the columns we care about. We copy the values
725 * into ind_context from the estate's per-tuple context.
727 for (i = 0; i < attr_cnt; i++)
729 VacAttrStats *stats = thisdata->vacattrstats[i];
730 int attnum = stats->attr->attnum;
732 if (isnull[attnum - 1])
734 exprvals[tcnt] = (Datum) 0;
735 exprnulls[tcnt] = true;
739 exprvals[tcnt] = datumCopy(values[attnum - 1],
740 stats->attrtype->typbyval,
741 stats->attrtype->typlen);
742 exprnulls[tcnt] = false;
750 * Having counted the number of rows that pass the predicate in the
751 * sample, we can estimate the total number of rows in the index.
753 thisdata->tupleFract = (double) numindexrows / (double) numrows;
754 totalindexrows = ceil(thisdata->tupleFract * totalrows);
757 * Now we can compute the statistics for the expression columns.
759 if (numindexrows > 0)
761 MemoryContextSwitchTo(col_context);
762 for (i = 0; i < attr_cnt; i++)
764 VacAttrStats *stats = thisdata->vacattrstats[i];
765 AttributeOpts *aopt =
766 get_attribute_options(stats->attr->attrelid,
767 stats->attr->attnum);
769 stats->exprvals = exprvals + i;
770 stats->exprnulls = exprnulls + i;
771 stats->rowstride = attr_cnt;
772 (*stats->compute_stats) (stats,
778 * If the n_distinct option is specified, it overrides the
779 * above computation. For indices, we always use just
780 * n_distinct, not n_distinct_inherited.
782 if (aopt != NULL && aopt->n_distinct != 0.0)
783 stats->stadistinct = aopt->n_distinct;
785 MemoryContextResetAndDeleteChildren(col_context);
790 MemoryContextSwitchTo(ind_context);
792 ExecDropSingleTupleTableSlot(slot);
793 FreeExecutorState(estate);
794 MemoryContextResetAndDeleteChildren(ind_context);
797 MemoryContextSwitchTo(old_context);
798 MemoryContextDelete(ind_context);
802 * examine_attribute -- pre-analysis of a single column
804 * Determine whether the column is analyzable; if so, create and initialize
805 * a VacAttrStats struct for it. If not, return NULL.
807 * If index_expr isn't NULL, then we're trying to analyze an expression index,
808 * and index_expr is the expression tree representing the column's data.
810 static VacAttrStats *
811 examine_attribute(Relation onerel, int attnum, Node *index_expr)
813 Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
819 /* Never analyze dropped columns */
820 if (attr->attisdropped)
823 /* Don't analyze column if user has specified not to */
824 if (attr->attstattarget == 0)
828 * Create the VacAttrStats struct. Note that we only have a copy of the
829 * fixed fields of the pg_attribute tuple.
831 stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
832 stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
833 memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
836 * When analyzing an expression index, believe the expression tree's type
837 * not the column datatype --- the latter might be the opckeytype storage
838 * type of the opclass, which is not interesting for our purposes. (Note:
839 * if we did anything with non-expression index columns, we'd need to
840 * figure out where to get the correct type info from, but for now that's
841 * not a problem.) It's not clear whether anyone will care about the
842 * typmod, but we store that too just in case.
846 stats->attrtypid = exprType(index_expr);
847 stats->attrtypmod = exprTypmod(index_expr);
851 stats->attrtypid = attr->atttypid;
852 stats->attrtypmod = attr->atttypmod;
855 typtuple = SearchSysCacheCopy1(TYPEOID,
856 ObjectIdGetDatum(stats->attrtypid));
857 if (!HeapTupleIsValid(typtuple))
858 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
859 stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
860 stats->anl_context = anl_context;
861 stats->tupattnum = attnum;
864 * The fields describing the stats->stavalues[n] element types default to
865 * the type of the data being analyzed, but the type-specific typanalyze
866 * function can change them if it wants to store something else.
868 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
870 stats->statypid[i] = stats->attrtypid;
871 stats->statyplen[i] = stats->attrtype->typlen;
872 stats->statypbyval[i] = stats->attrtype->typbyval;
873 stats->statypalign[i] = stats->attrtype->typalign;
877 * Call the type-specific typanalyze function. If none is specified, use
880 if (OidIsValid(stats->attrtype->typanalyze))
881 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
882 PointerGetDatum(stats)));
884 ok = std_typanalyze(stats);
886 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
888 heap_freetuple(typtuple);
898 * BlockSampler_Init -- prepare for random sampling of blocknumbers
900 * BlockSampler is used for stage one of our new two-stage tuple
901 * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
902 * "Large DB"). It selects a random sample of samplesize blocks out of
903 * the nblocks blocks in the table. If the table has less than
904 * samplesize blocks, all blocks are selected.
906 * Since we know the total number of blocks in advance, we can use the
907 * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
911 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
913 bs->N = nblocks; /* measured table size */
916 * If we decide to reduce samplesize for tables that have less or not much
917 * more than samplesize blocks, here is the place to do it.
920 bs->t = 0; /* blocks scanned so far */
921 bs->m = 0; /* blocks selected so far */
925 BlockSampler_HasMore(BlockSampler bs)
927 return (bs->t < bs->N) && (bs->m < bs->n);
931 BlockSampler_Next(BlockSampler bs)
933 BlockNumber K = bs->N - bs->t; /* remaining blocks */
934 int k = bs->n - bs->m; /* blocks still to sample */
935 double p; /* probability to skip block */
936 double V; /* random */
938 Assert(BlockSampler_HasMore(bs)); /* hence K > 0 and k > 0 */
940 if ((BlockNumber) k >= K)
942 /* need all the rest */
948 * It is not obvious that this code matches Knuth's Algorithm S.
949 * Knuth says to skip the current block with probability 1 - k/K.
950 * If we are to skip, we should advance t (hence decrease K), and
951 * repeat the same probabilistic test for the next block. The naive
952 * implementation thus requires a random_fract() call for each block
953 * number. But we can reduce this to one random_fract() call per
954 * selected block, by noting that each time the while-test succeeds,
955 * we can reinterpret V as a uniform random number in the range 0 to p.
956 * Therefore, instead of choosing a new V, we just adjust p to be
957 * the appropriate fraction of its former value, and our next loop
958 * makes the appropriate probabilistic test.
960 * We have initially K > k > 0. If the loop reduces K to equal k,
961 * the next while-test must fail since p will become exactly zero
962 * (we assume there will not be roundoff error in the division).
963 * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
964 * to be doubly sure about roundoff error.) Therefore K cannot become
965 * less than k, which means that we cannot fail to select enough blocks.
969 p = 1.0 - (double) k / (double) K;
974 K--; /* keep K == N - t */
976 /* adjust p to be new cutoff point in reduced range */
977 p *= 1.0 - (double) k / (double) K;
986 * acquire_sample_rows -- acquire a random sample of rows from the table
988 * Selected rows are returned in the caller-allocated array rows[], which
989 * must have at least targrows entries.
990 * The actual number of rows selected is returned as the function result.
991 * We also estimate the total numbers of live and dead rows in the table,
992 * and return them into *totalrows and *totaldeadrows, respectively.
994 * The returned list of tuples is in order by physical position in the table.
995 * (We will rely on this later to derive correlation estimates.)
997 * As of May 2004 we use a new two-stage method: Stage one selects up
998 * to targrows random blocks (or all blocks, if there aren't so many).
999 * Stage two scans these blocks and uses the Vitter algorithm to create
1000 * a random sample of targrows rows (or less, if there are less in the
1001 * sample of blocks). The two stages are executed simultaneously: each
1002 * block is processed as soon as stage one returns its number and while
1003 * the rows are read stage two controls which ones are to be inserted
1006 * Although every row has an equal chance of ending up in the final
1007 * sample, this sampling method is not perfect: not every possible
1008 * sample has an equal chance of being selected. For large relations
1009 * the number of different blocks represented by the sample tends to be
1010 * too small. We can live with that for now. Improvements are welcome.
1012 * An important property of this sampling method is that because we do
1013 * look at a statistically unbiased set of blocks, we should get
1014 * unbiased estimates of the average numbers of live and dead rows per
1015 * block. The previous sampling method put too much credence in the row
1016 * density near the start of the table.
1019 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1020 double *totalrows, double *totaldeadrows)
1022 int numrows = 0; /* # rows now in reservoir */
1023 double samplerows = 0; /* total # rows collected */
1024 double liverows = 0; /* # live rows seen */
1025 double deadrows = 0; /* # dead rows seen */
1026 double rowstoskip = -1; /* -1 means not set yet */
1027 BlockNumber totalblocks;
1028 TransactionId OldestXmin;
1029 BlockSamplerData bs;
1032 Assert(targrows > 0);
1034 totalblocks = RelationGetNumberOfBlocks(onerel);
1036 /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1037 OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
1039 /* Prepare for sampling block numbers */
1040 BlockSampler_Init(&bs, totalblocks, targrows);
1041 /* Prepare for sampling rows */
1042 rstate = init_selection_state(targrows);
1044 /* Outer loop over blocks to sample */
1045 while (BlockSampler_HasMore(&bs))
1047 BlockNumber targblock = BlockSampler_Next(&bs);
1050 OffsetNumber targoffset,
1053 vacuum_delay_point();
1056 * We must maintain a pin on the target page's buffer to ensure that
1057 * the maxoffset value stays good (else concurrent VACUUM might delete
1058 * tuples out from under us). Hence, pin the page until we are done
1059 * looking at it. We also choose to hold sharelock on the buffer
1060 * throughout --- we could release and re-acquire sharelock for each
1061 * tuple, but since we aren't doing much work per tuple, the extra
1062 * lock traffic is probably better avoided.
1064 targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1065 RBM_NORMAL, vac_strategy);
1066 LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1067 targpage = BufferGetPage(targbuffer);
1068 maxoffset = PageGetMaxOffsetNumber(targpage);
1070 /* Inner loop over all tuples on the selected page */
1071 for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1074 HeapTupleData targtuple;
1075 bool sample_it = false;
1077 itemid = PageGetItemId(targpage, targoffset);
1080 * We ignore unused and redirect line pointers. DEAD line
1081 * pointers should be counted as dead, because we need vacuum to
1082 * run to get rid of them. Note that this rule agrees with the
1083 * way that heap_page_prune() counts things.
1085 if (!ItemIdIsNormal(itemid))
1087 if (ItemIdIsDead(itemid))
1092 ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1094 targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1095 targtuple.t_len = ItemIdGetLength(itemid);
1097 switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
1101 case HEAPTUPLE_LIVE:
1106 case HEAPTUPLE_DEAD:
1107 case HEAPTUPLE_RECENTLY_DEAD:
1108 /* Count dead and recently-dead rows */
1112 case HEAPTUPLE_INSERT_IN_PROGRESS:
1115 * Insert-in-progress rows are not counted. We assume
1116 * that when the inserting transaction commits or aborts,
1117 * it will send a stats message to increment the proper
1118 * count. This works right only if that transaction ends
1119 * after we finish analyzing the table; if things happen
1120 * in the other order, its stats update will be
1121 * overwritten by ours. However, the error will be large
1122 * only if the other transaction runs long enough to
1123 * insert many tuples, so assuming it will finish after us
1124 * is the safer option.
1126 * A special case is that the inserting transaction might
1127 * be our own. In this case we should count and sample
1128 * the row, to accommodate users who load a table and
1129 * analyze it in one transaction. (pgstat_report_analyze
1130 * has to adjust the numbers we send to the stats
1131 * collector to make this come out right.)
1133 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
1140 case HEAPTUPLE_DELETE_IN_PROGRESS:
1143 * We count delete-in-progress rows as still live, using
1144 * the same reasoning given above; but we don't bother to
1145 * include them in the sample.
1147 * If the delete was done by our own transaction, however,
1148 * we must count the row as dead to make
1149 * pgstat_report_analyze's stats adjustments come out
1150 * right. (Note: this works out properly when the row was
1151 * both inserted and deleted in our xact.)
1153 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
1160 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1167 * The first targrows sample rows are simply copied into the
1168 * reservoir. Then we start replacing tuples in the sample
1169 * until we reach the end of the relation. This algorithm is
1170 * from Jeff Vitter's paper (see full citation below). It
1171 * works by repeatedly computing the number of tuples to skip
1172 * before selecting a tuple, which replaces a randomly chosen
1173 * element of the reservoir (current set of tuples). At all
1174 * times the reservoir is a true random sample of the tuples
1175 * we've passed over so far, so when we fall off the end of
1176 * the relation we're done.
1178 if (numrows < targrows)
1179 rows[numrows++] = heap_copytuple(&targtuple);
1183 * t in Vitter's paper is the number of records already
1184 * processed. If we need to compute a new S value, we
1185 * must use the not-yet-incremented value of samplerows as
1189 rowstoskip = get_next_S(samplerows, targrows, &rstate);
1191 if (rowstoskip <= 0)
1194 * Found a suitable tuple, so save it, replacing one
1195 * old tuple at random
1197 int k = (int) (targrows * random_fract());
1199 Assert(k >= 0 && k < targrows);
1200 heap_freetuple(rows[k]);
1201 rows[k] = heap_copytuple(&targtuple);
1211 /* Now release the lock and pin on the page */
1212 UnlockReleaseBuffer(targbuffer);
1216 * If we didn't find as many tuples as we wanted then we're done. No sort
1217 * is needed, since they're already in order.
1219 * Otherwise we need to sort the collected tuples by position
1220 * (itempointer). It's not worth worrying about corner cases where the
1221 * tuples are already sorted.
1223 if (numrows == targrows)
1224 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1227 * Estimate total numbers of rows in relation. For live rows, use
1228 * vac_estimate_reltuples; for dead rows, we have no source of old
1229 * information, so we have to assume the density is the same in unseen
1230 * pages as in the pages we scanned.
1232 *totalrows = vac_estimate_reltuples(onerel, true,
1237 *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1239 *totaldeadrows = 0.0;
1242 * Emit some interesting relation info
1245 (errmsg("\"%s\": scanned %d of %u pages, "
1246 "containing %.0f live rows and %.0f dead rows; "
1247 "%d rows in sample, %.0f estimated total rows",
1248 RelationGetRelationName(onerel),
1251 numrows, *totalrows)));
1256 /* Select a random value R uniformly distributed in (0 - 1) */
1260 return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
1264 * These two routines embody Algorithm Z from "Random sampling with a
1265 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1266 * (Mar. 1985), Pages 37-57. Vitter describes his algorithm in terms
1267 * of the count S of records to skip before processing another record.
1268 * It is computed primarily based on t, the number of records already read.
1269 * The only extra state needed between calls is W, a random state variable.
1271 * init_selection_state computes the initial W value.
1273 * Given that we've already read t records (t >= n), get_next_S
1274 * determines the number of records to skip before the next record is
1278 init_selection_state(int n)
1280 /* Initial value of W (for use when Algorithm Z is first applied) */
1281 return exp(-log(random_fract()) / n);
1285 get_next_S(double t, int n, double *stateptr)
1289 /* The magic constant here is T from Vitter's paper */
1290 if (t <= (22.0 * n))
1292 /* Process records using Algorithm X until t is large enough */
1296 V = random_fract(); /* Generate V */
1299 /* Note: "num" in Vitter's code is always equal to t - n */
1300 quot = (t - (double) n) / t;
1301 /* Find min S satisfying (4.1) */
1306 quot *= (t - (double) n) / t;
1311 /* Now apply Algorithm Z */
1312 double W = *stateptr;
1313 double term = t - (double) n + 1;
1327 /* Generate U and X */
1330 S = floor(X); /* S is tentatively set to floor(X) */
1331 /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1332 tmp = (t + 1) / term;
1333 lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
1334 rhs = (((t + X) / (term + S)) * term) / t;
1340 /* Test if U <= f(S)/cg(X) */
1341 y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1345 numer_lim = term + S;
1349 denom = t - (double) n + S;
1352 for (numer = t + S; numer >= numer_lim; numer -= 1)
1357 W = exp(-log(random_fract()) / n); /* Generate W in advance */
1358 if (exp(log(y) / n) <= (t + X) / t)
1367 * qsort comparator for sorting rows[] array
1370 compare_rows(const void *a, const void *b)
1372 HeapTuple ha = *(const HeapTuple *) a;
1373 HeapTuple hb = *(const HeapTuple *) b;
1374 BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1375 OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1376 BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1377 OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1392 * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1394 * This has the same API as acquire_sample_rows, except that rows are
1395 * collected from all inheritance children as well as the specified table.
1396 * We fail and return zero if there are no inheritance children.
1399 acquire_inherited_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1400 double *totalrows, double *totaldeadrows)
1412 * Find all members of inheritance set. We only need AccessShareLock on
1416 find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
1419 * Check that there's at least one descendant, else fail. This could
1420 * happen despite analyze_rel's relhassubclass check, if table once had a
1421 * child but no longer does. In that case, we can clear the
1422 * relhassubclass field so as not to make the same mistake again later.
1423 * (This is safe because we hold ShareUpdateExclusiveLock.)
1425 if (list_length(tableOIDs) < 2)
1427 /* CCI because we already updated the pg_class row in this command */
1428 CommandCounterIncrement();
1429 SetRelationHasSubclass(RelationGetRelid(onerel), false);
1434 * Count the blocks in all the relations. The result could overflow
1435 * BlockNumber, so we use double arithmetic.
1437 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1438 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1441 foreach(lc, tableOIDs)
1443 Oid childOID = lfirst_oid(lc);
1446 /* We already got the needed lock */
1447 childrel = heap_open(childOID, NoLock);
1449 /* Ignore if temp table of another backend */
1450 if (RELATION_IS_OTHER_TEMP(childrel))
1452 /* ... but release the lock on it */
1453 Assert(childrel != onerel);
1454 heap_close(childrel, AccessShareLock);
1458 rels[nrels] = childrel;
1459 relblocks[nrels] = (double) RelationGetNumberOfBlocks(childrel);
1460 totalblocks += relblocks[nrels];
1465 * Now sample rows from each relation, proportionally to its fraction of
1466 * the total block count. (This might be less than desirable if the child
1467 * rels have radically different free-space percentages, but it's not
1468 * clear that it's worth working harder.)
1473 for (i = 0; i < nrels; i++)
1475 Relation childrel = rels[i];
1476 double childblocks = relblocks[i];
1478 if (childblocks > 0)
1482 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1483 /* Make sure we don't overrun due to roundoff error */
1484 childtargrows = Min(childtargrows, targrows - numrows);
1485 if (childtargrows > 0)
1491 /* Fetch a random sample of the child's rows */
1492 childrows = acquire_sample_rows(childrel,
1498 /* We may need to convert from child's rowtype to parent's */
1499 if (childrows > 0 &&
1500 !equalTupleDescs(RelationGetDescr(childrel),
1501 RelationGetDescr(onerel)))
1503 TupleConversionMap *map;
1505 map = convert_tuples_by_name(RelationGetDescr(childrel),
1506 RelationGetDescr(onerel),
1507 gettext_noop("could not convert row type"));
1512 for (j = 0; j < childrows; j++)
1516 newtup = do_convert_tuple(rows[numrows + j], map);
1517 heap_freetuple(rows[numrows + j]);
1518 rows[numrows + j] = newtup;
1520 free_conversion_map(map);
1524 /* And add to counts */
1525 numrows += childrows;
1526 *totalrows += trows;
1527 *totaldeadrows += tdrows;
1532 * Note: we cannot release the child-table locks, since we may have
1533 * pointers to their TOAST tables in the sampled rows.
1535 heap_close(childrel, NoLock);
1543 * update_attstats() -- update attribute statistics for one relation
1545 * Statistics are stored in several places: the pg_class row for the
1546 * relation has stats about the whole relation, and there is a
1547 * pg_statistic row for each (non-system) attribute that has ever
1548 * been analyzed. The pg_class values are updated by VACUUM, not here.
1550 * pg_statistic rows are just added or updated normally. This means
1551 * that pg_statistic will probably contain some deleted rows at the
1552 * completion of a vacuum cycle, unless it happens to get vacuumed last.
1554 * To keep things simple, we punt for pg_statistic, and don't try
1555 * to compute or store rows for pg_statistic itself in pg_statistic.
1556 * This could possibly be made to work, but it's not worth the trouble.
1557 * Note analyze_rel() has seen to it that we won't come here when
1558 * vacuuming pg_statistic itself.
1560 * Note: there would be a race condition here if two backends could
1561 * ANALYZE the same table concurrently. Presently, we lock that out
1562 * by taking a self-exclusive lock on the relation in analyze_rel().
1565 update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1571 return; /* nothing to do */
1573 sd = heap_open(StatisticRelationId, RowExclusiveLock);
1575 for (attno = 0; attno < natts; attno++)
1577 VacAttrStats *stats = vacattrstats[attno];
1583 Datum values[Natts_pg_statistic];
1584 bool nulls[Natts_pg_statistic];
1585 bool replaces[Natts_pg_statistic];
1587 /* Ignore attr if we weren't able to collect stats */
1588 if (!stats->stats_valid)
1592 * Construct a new pg_statistic tuple
1594 for (i = 0; i < Natts_pg_statistic; ++i)
1600 values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1601 values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1602 values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1603 values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1604 values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1605 values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1606 i = Anum_pg_statistic_stakind1 - 1;
1607 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1609 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1611 i = Anum_pg_statistic_staop1 - 1;
1612 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1614 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1616 i = Anum_pg_statistic_stanumbers1 - 1;
1617 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1619 int nnum = stats->numnumbers[k];
1623 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1626 for (n = 0; n < nnum; n++)
1627 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1628 /* XXX knows more than it should about type float4: */
1629 arry = construct_array(numdatums, nnum,
1631 sizeof(float4), FLOAT4PASSBYVAL, 'i');
1632 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1637 values[i++] = (Datum) 0;
1640 i = Anum_pg_statistic_stavalues1 - 1;
1641 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1643 if (stats->numvalues[k] > 0)
1647 arry = construct_array(stats->stavalues[k],
1648 stats->numvalues[k],
1650 stats->statyplen[k],
1651 stats->statypbyval[k],
1652 stats->statypalign[k]);
1653 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1658 values[i++] = (Datum) 0;
1662 /* Is there already a pg_statistic tuple for this attribute? */
1663 oldtup = SearchSysCache3(STATRELATTINH,
1664 ObjectIdGetDatum(relid),
1665 Int16GetDatum(stats->attr->attnum),
1668 if (HeapTupleIsValid(oldtup))
1670 /* Yes, replace it */
1671 stup = heap_modify_tuple(oldtup,
1672 RelationGetDescr(sd),
1676 ReleaseSysCache(oldtup);
1677 simple_heap_update(sd, &stup->t_self, stup);
1681 /* No, insert new tuple */
1682 stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1683 simple_heap_insert(sd, stup);
1686 /* update indexes too */
1687 CatalogUpdateIndexes(sd, stup);
1689 heap_freetuple(stup);
1692 heap_close(sd, RowExclusiveLock);
1696 * Standard fetch function for use by compute_stats subroutines.
1698 * This exists to provide some insulation between compute_stats routines
1699 * and the actual storage of the sample data.
1702 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1704 int attnum = stats->tupattnum;
1705 HeapTuple tuple = stats->rows[rownum];
1706 TupleDesc tupDesc = stats->tupDesc;
1708 return heap_getattr(tuple, attnum, tupDesc, isNull);
1712 * Fetch function for analyzing index expressions.
1714 * We have not bothered to construct index tuples, instead the data is
1715 * just in Datum arrays.
1718 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1722 /* exprvals and exprnulls are already offset for proper column */
1723 i = rownum * stats->rowstride;
1724 *isNull = stats->exprnulls[i];
1725 return stats->exprvals[i];
1729 /*==========================================================================
1731 * Code below this point represents the "standard" type-specific statistics
1732 * analysis algorithms. This code can be replaced on a per-data-type basis
1733 * by setting a nonzero value in pg_type.typanalyze.
1735 *==========================================================================
1740 * To avoid consuming too much memory during analysis and/or too much space
1741 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1742 * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1743 * and distinct-value calculations since a wide value is unlikely to be
1744 * duplicated at all, much less be a most-common value. For the same reason,
1745 * ignoring wide values will not affect our estimates of histogram bin
1746 * boundaries very much.
1748 #define WIDTH_THRESHOLD 1024
1750 #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1751 #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1754 * Extra information used by the default analysis routines
1758 Oid eqopr; /* '=' operator for datatype, if any */
1759 Oid eqfunc; /* and associated function */
1760 Oid ltopr; /* '<' operator for datatype, if any */
1765 Datum value; /* a data value */
1766 int tupno; /* position index for tuple it came from */
1771 int count; /* # of duplicates */
1772 int first; /* values[] index of first occurrence */
1780 } CompareScalarsContext;
1783 static void compute_minimal_stats(VacAttrStatsP stats,
1784 AnalyzeAttrFetchFunc fetchfunc,
1787 static void compute_scalar_stats(VacAttrStatsP stats,
1788 AnalyzeAttrFetchFunc fetchfunc,
1791 static int compare_scalars(const void *a, const void *b, void *arg);
1792 static int compare_mcvs(const void *a, const void *b);
1796 * std_typanalyze -- the default type-specific typanalyze function
1799 std_typanalyze(VacAttrStats *stats)
1801 Form_pg_attribute attr = stats->attr;
1804 StdAnalyzeData *mystats;
1806 /* If the attstattarget column is negative, use the default value */
1807 /* NB: it is okay to scribble on stats->attr since it's a copy */
1808 if (attr->attstattarget < 0)
1809 attr->attstattarget = default_statistics_target;
1811 /* Look for default "<" and "=" operators for column's type */
1812 get_sort_group_operators(stats->attrtypid,
1813 false, false, false,
1814 <opr, &eqopr, NULL,
1817 /* If column has no "=" operator, we can't do much of anything */
1818 if (!OidIsValid(eqopr))
1821 /* Save the operator info for compute_stats routines */
1822 mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1823 mystats->eqopr = eqopr;
1824 mystats->eqfunc = get_opcode(eqopr);
1825 mystats->ltopr = ltopr;
1826 stats->extra_data = mystats;
1829 * Determine which standard statistics algorithm to use
1831 if (OidIsValid(ltopr))
1833 /* Seems to be a scalar datatype */
1834 stats->compute_stats = compute_scalar_stats;
1835 /*--------------------
1836 * The following choice of minrows is based on the paper
1837 * "Random sampling for histogram construction: how much is enough?"
1838 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1839 * Proceedings of ACM SIGMOD International Conference on Management
1840 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1841 * says that for table size n, histogram size k, maximum relative
1842 * error in bin size f, and error probability gamma, the minimum
1843 * random sample size is
1844 * r = 4 * k * ln(2*n/gamma) / f^2
1845 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1847 * Note that because of the log function, the dependence on n is
1848 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1849 * bin size error with probability 0.99. So there's no real need to
1850 * scale for n, which is a good thing because we don't necessarily
1851 * know it at this point.
1852 *--------------------
1854 stats->minrows = 300 * attr->attstattarget;
1858 /* Can't do much but the minimal stuff */
1859 stats->compute_stats = compute_minimal_stats;
1860 /* Might as well use the same minrows as above */
1861 stats->minrows = 300 * attr->attstattarget;
1868 * compute_minimal_stats() -- compute minimal column statistics
1870 * We use this when we can find only an "=" operator for the datatype.
1872 * We determine the fraction of non-null rows, the average width, the
1873 * most common values, and the (estimated) number of distinct values.
1875 * The most common values are determined by brute force: we keep a list
1876 * of previously seen values, ordered by number of times seen, as we scan
1877 * the samples. A newly seen value is inserted just after the last
1878 * multiply-seen value, causing the bottommost (oldest) singly-seen value
1879 * to drop off the list. The accuracy of this method, and also its cost,
1880 * depend mainly on the length of the list we are willing to keep.
1883 compute_minimal_stats(VacAttrStatsP stats,
1884 AnalyzeAttrFetchFunc fetchfunc,
1890 int nonnull_cnt = 0;
1891 int toowide_cnt = 0;
1892 double total_width = 0;
1893 bool is_varlena = (!stats->attrtype->typbyval &&
1894 stats->attrtype->typlen == -1);
1895 bool is_varwidth = (!stats->attrtype->typbyval &&
1896 stats->attrtype->typlen < 0);
1906 int num_mcv = stats->attr->attstattarget;
1907 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1910 * We track up to 2*n values for an n-element MCV list; but at least 10
1912 track_max = 2 * num_mcv;
1915 track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1918 fmgr_info(mystats->eqfunc, &f_cmpeq);
1920 for (i = 0; i < samplerows; i++)
1928 vacuum_delay_point();
1930 value = fetchfunc(stats, i, &isnull);
1932 /* Check for null/nonnull */
1941 * If it's a variable-width field, add up widths for average width
1942 * calculation. Note that if the value is toasted, we use the toasted
1943 * width. We don't bother with this calculation if it's a fixed-width
1948 total_width += VARSIZE_ANY(DatumGetPointer(value));
1951 * If the value is toasted, we want to detoast it just once to
1952 * avoid repeated detoastings and resultant excess memory usage
1953 * during the comparisons. Also, check to see if the value is
1954 * excessively wide, and if so don't detoast at all --- just
1957 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1962 value = PointerGetDatum(PG_DETOAST_DATUM(value));
1964 else if (is_varwidth)
1966 /* must be cstring */
1967 total_width += strlen(DatumGetCString(value)) + 1;
1971 * See if the value matches anything we're already tracking.
1974 firstcount1 = track_cnt;
1975 for (j = 0; j < track_cnt; j++)
1977 /* We always use the default collation for statistics */
1978 if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
1979 DEFAULT_COLLATION_OID,
1980 value, track[j].value)))
1985 if (j < firstcount1 && track[j].count == 1)
1993 /* This value may now need to "bubble up" in the track list */
1994 while (j > 0 && track[j].count > track[j - 1].count)
1996 swapDatum(track[j].value, track[j - 1].value);
1997 swapInt(track[j].count, track[j - 1].count);
2003 /* No match. Insert at head of count-1 list */
2004 if (track_cnt < track_max)
2006 for (j = track_cnt - 1; j > firstcount1; j--)
2008 track[j].value = track[j - 1].value;
2009 track[j].count = track[j - 1].count;
2011 if (firstcount1 < track_cnt)
2013 track[firstcount1].value = value;
2014 track[firstcount1].count = 1;
2019 /* We can only compute real stats if we found some non-null values. */
2020 if (nonnull_cnt > 0)
2025 stats->stats_valid = true;
2026 /* Do the simple null-frac and width stats */
2027 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2029 stats->stawidth = total_width / (double) nonnull_cnt;
2031 stats->stawidth = stats->attrtype->typlen;
2033 /* Count the number of values we found multiple times */
2035 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2037 if (track[nmultiple].count == 1)
2039 summultiple += track[nmultiple].count;
2044 /* If we found no repeated values, assume it's a unique column */
2045 stats->stadistinct = -1.0;
2047 else if (track_cnt < track_max && toowide_cnt == 0 &&
2048 nmultiple == track_cnt)
2051 * Our track list includes every value in the sample, and every
2052 * value appeared more than once. Assume the column has just
2055 stats->stadistinct = track_cnt;
2060 * Estimate the number of distinct values using the estimator
2061 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2062 * n*d / (n - f1 + f1*n/N)
2063 * where f1 is the number of distinct values that occurred
2064 * exactly once in our sample of n rows (from a total of N),
2065 * and d is the total number of distinct values in the sample.
2066 * This is their Duj1 estimator; the other estimators they
2067 * recommend are considerably more complex, and are numerically
2068 * very unstable when n is much smaller than N.
2070 * We assume (not very reliably!) that all the multiply-occurring
2071 * values are reflected in the final track[] list, and the other
2072 * nonnull values all appeared but once. (XXX this usually
2073 * results in a drastic overestimate of ndistinct. Can we do
2077 int f1 = nonnull_cnt - summultiple;
2078 int d = f1 + nmultiple;
2083 numer = (double) samplerows *(double) d;
2085 denom = (double) (samplerows - f1) +
2086 (double) f1 *(double) samplerows / totalrows;
2088 stadistinct = numer / denom;
2089 /* Clamp to sane range in case of roundoff error */
2090 if (stadistinct < (double) d)
2091 stadistinct = (double) d;
2092 if (stadistinct > totalrows)
2093 stadistinct = totalrows;
2094 stats->stadistinct = floor(stadistinct + 0.5);
2098 * If we estimated the number of distinct values at more than 10% of
2099 * the total row count (a very arbitrary limit), then assume that
2100 * stadistinct should scale with the row count rather than be a fixed
2103 if (stats->stadistinct > 0.1 * totalrows)
2104 stats->stadistinct = -(stats->stadistinct / totalrows);
2107 * Decide how many values are worth storing as most-common values. If
2108 * we are able to generate a complete MCV list (all the values in the
2109 * sample will fit, and we think these are all the ones in the table),
2110 * then do so. Otherwise, store only those values that are
2111 * significantly more common than the (estimated) average. We set the
2112 * threshold rather arbitrarily at 25% more than average, with at
2113 * least 2 instances in the sample.
2115 if (track_cnt < track_max && toowide_cnt == 0 &&
2116 stats->stadistinct > 0 &&
2117 track_cnt <= num_mcv)
2119 /* Track list includes all values seen, and all will fit */
2120 num_mcv = track_cnt;
2124 double ndistinct = stats->stadistinct;
2129 ndistinct = -ndistinct * totalrows;
2130 /* estimate # of occurrences in sample of a typical value */
2131 avgcount = (double) samplerows / ndistinct;
2132 /* set minimum threshold count to store a value */
2133 mincount = avgcount * 1.25;
2136 if (num_mcv > track_cnt)
2137 num_mcv = track_cnt;
2138 for (i = 0; i < num_mcv; i++)
2140 if (track[i].count < mincount)
2148 /* Generate MCV slot entry */
2151 MemoryContext old_context;
2155 /* Must copy the target values into anl_context */
2156 old_context = MemoryContextSwitchTo(stats->anl_context);
2157 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2158 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2159 for (i = 0; i < num_mcv; i++)
2161 mcv_values[i] = datumCopy(track[i].value,
2162 stats->attrtype->typbyval,
2163 stats->attrtype->typlen);
2164 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2166 MemoryContextSwitchTo(old_context);
2168 stats->stakind[0] = STATISTIC_KIND_MCV;
2169 stats->staop[0] = mystats->eqopr;
2170 stats->stanumbers[0] = mcv_freqs;
2171 stats->numnumbers[0] = num_mcv;
2172 stats->stavalues[0] = mcv_values;
2173 stats->numvalues[0] = num_mcv;
2176 * Accept the defaults for stats->statypid and others. They have
2177 * been set before we were called (see vacuum.h)
2181 else if (null_cnt > 0)
2183 /* We found only nulls; assume the column is entirely null */
2184 stats->stats_valid = true;
2185 stats->stanullfrac = 1.0;
2187 stats->stawidth = 0; /* "unknown" */
2189 stats->stawidth = stats->attrtype->typlen;
2190 stats->stadistinct = 0.0; /* "unknown" */
2193 /* We don't need to bother cleaning up any of our temporary palloc's */
2198 * compute_scalar_stats() -- compute column statistics
2200 * We use this when we can find "=" and "<" operators for the datatype.
2202 * We determine the fraction of non-null rows, the average width, the
2203 * most common values, the (estimated) number of distinct values, the
2204 * distribution histogram, and the correlation of physical to logical order.
2206 * The desired stats can be determined fairly easily after sorting the
2207 * data values into order.
2210 compute_scalar_stats(VacAttrStatsP stats,
2211 AnalyzeAttrFetchFunc fetchfunc,
2217 int nonnull_cnt = 0;
2218 int toowide_cnt = 0;
2219 double total_width = 0;
2220 bool is_varlena = (!stats->attrtype->typbyval &&
2221 stats->attrtype->typlen == -1);
2222 bool is_varwidth = (!stats->attrtype->typbyval &&
2223 stats->attrtype->typlen < 0);
2231 ScalarMCVItem *track;
2233 int num_mcv = stats->attr->attstattarget;
2234 int num_bins = stats->attr->attstattarget;
2235 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2237 values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2238 tupnoLink = (int *) palloc(samplerows * sizeof(int));
2239 track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2241 SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
2242 fmgr_info(cmpFn, &f_cmpfn);
2244 /* Initial scan to find sortable values */
2245 for (i = 0; i < samplerows; i++)
2250 vacuum_delay_point();
2252 value = fetchfunc(stats, i, &isnull);
2254 /* Check for null/nonnull */
2263 * If it's a variable-width field, add up widths for average width
2264 * calculation. Note that if the value is toasted, we use the toasted
2265 * width. We don't bother with this calculation if it's a fixed-width
2270 total_width += VARSIZE_ANY(DatumGetPointer(value));
2273 * If the value is toasted, we want to detoast it just once to
2274 * avoid repeated detoastings and resultant excess memory usage
2275 * during the comparisons. Also, check to see if the value is
2276 * excessively wide, and if so don't detoast at all --- just
2279 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2284 value = PointerGetDatum(PG_DETOAST_DATUM(value));
2286 else if (is_varwidth)
2288 /* must be cstring */
2289 total_width += strlen(DatumGetCString(value)) + 1;
2292 /* Add it to the list to be sorted */
2293 values[values_cnt].value = value;
2294 values[values_cnt].tupno = values_cnt;
2295 tupnoLink[values_cnt] = values_cnt;
2299 /* We can only compute real stats if we found some sortable values. */
2302 int ndistinct, /* # distinct values in sample */
2303 nmultiple, /* # that appear multiple times */
2307 CompareScalarsContext cxt;
2309 /* Sort the collected values */
2310 cxt.cmpFn = &f_cmpfn;
2311 cxt.cmpFlags = cmpFlags;
2312 cxt.tupnoLink = tupnoLink;
2313 qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2314 compare_scalars, (void *) &cxt);
2317 * Now scan the values in order, find the most common ones, and also
2318 * accumulate ordering-correlation statistics.
2320 * To determine which are most common, we first have to count the
2321 * number of duplicates of each value. The duplicates are adjacent in
2322 * the sorted list, so a brute-force approach is to compare successive
2323 * datum values until we find two that are not equal. However, that
2324 * requires N-1 invocations of the datum comparison routine, which are
2325 * completely redundant with work that was done during the sort. (The
2326 * sort algorithm must at some point have compared each pair of items
2327 * that are adjacent in the sorted order; otherwise it could not know
2328 * that it's ordered the pair correctly.) We exploit this by having
2329 * compare_scalars remember the highest tupno index that each
2330 * ScalarItem has been found equal to. At the end of the sort, a
2331 * ScalarItem's tupnoLink will still point to itself if and only if it
2332 * is the last item of its group of duplicates (since the group will
2333 * be ordered by tupno).
2339 for (i = 0; i < values_cnt; i++)
2341 int tupno = values[i].tupno;
2343 corr_xysum += ((double) i) * ((double) tupno);
2345 if (tupnoLink[tupno] == tupno)
2347 /* Reached end of duplicates of this value */
2352 if (track_cnt < num_mcv ||
2353 dups_cnt > track[track_cnt - 1].count)
2356 * Found a new item for the mcv list; find its
2357 * position, bubbling down old items if needed. Loop
2358 * invariant is that j points at an empty/ replaceable
2363 if (track_cnt < num_mcv)
2365 for (j = track_cnt - 1; j > 0; j--)
2367 if (dups_cnt <= track[j - 1].count)
2369 track[j].count = track[j - 1].count;
2370 track[j].first = track[j - 1].first;
2372 track[j].count = dups_cnt;
2373 track[j].first = i + 1 - dups_cnt;
2380 stats->stats_valid = true;
2381 /* Do the simple null-frac and width stats */
2382 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2384 stats->stawidth = total_width / (double) nonnull_cnt;
2386 stats->stawidth = stats->attrtype->typlen;
2390 /* If we found no repeated values, assume it's a unique column */
2391 stats->stadistinct = -1.0;
2393 else if (toowide_cnt == 0 && nmultiple == ndistinct)
2396 * Every value in the sample appeared more than once. Assume the
2397 * column has just these values.
2399 stats->stadistinct = ndistinct;
2404 * Estimate the number of distinct values using the estimator
2405 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2406 * n*d / (n - f1 + f1*n/N)
2407 * where f1 is the number of distinct values that occurred
2408 * exactly once in our sample of n rows (from a total of N),
2409 * and d is the total number of distinct values in the sample.
2410 * This is their Duj1 estimator; the other estimators they
2411 * recommend are considerably more complex, and are numerically
2412 * very unstable when n is much smaller than N.
2414 * Overwidth values are assumed to have been distinct.
2417 int f1 = ndistinct - nmultiple + toowide_cnt;
2418 int d = f1 + nmultiple;
2423 numer = (double) samplerows *(double) d;
2425 denom = (double) (samplerows - f1) +
2426 (double) f1 *(double) samplerows / totalrows;
2428 stadistinct = numer / denom;
2429 /* Clamp to sane range in case of roundoff error */
2430 if (stadistinct < (double) d)
2431 stadistinct = (double) d;
2432 if (stadistinct > totalrows)
2433 stadistinct = totalrows;
2434 stats->stadistinct = floor(stadistinct + 0.5);
2438 * If we estimated the number of distinct values at more than 10% of
2439 * the total row count (a very arbitrary limit), then assume that
2440 * stadistinct should scale with the row count rather than be a fixed
2443 if (stats->stadistinct > 0.1 * totalrows)
2444 stats->stadistinct = -(stats->stadistinct / totalrows);
2447 * Decide how many values are worth storing as most-common values. If
2448 * we are able to generate a complete MCV list (all the values in the
2449 * sample will fit, and we think these are all the ones in the table),
2450 * then do so. Otherwise, store only those values that are
2451 * significantly more common than the (estimated) average. We set the
2452 * threshold rather arbitrarily at 25% more than average, with at
2453 * least 2 instances in the sample. Also, we won't suppress values
2454 * that have a frequency of at least 1/K where K is the intended
2455 * number of histogram bins; such values might otherwise cause us to
2456 * emit duplicate histogram bin boundaries. (We might end up with
2457 * duplicate histogram entries anyway, if the distribution is skewed;
2458 * but we prefer to treat such values as MCVs if at all possible.)
2460 if (track_cnt == ndistinct && toowide_cnt == 0 &&
2461 stats->stadistinct > 0 &&
2462 track_cnt <= num_mcv)
2464 /* Track list includes all values seen, and all will fit */
2465 num_mcv = track_cnt;
2469 double ndistinct = stats->stadistinct;
2475 ndistinct = -ndistinct * totalrows;
2476 /* estimate # of occurrences in sample of a typical value */
2477 avgcount = (double) samplerows / ndistinct;
2478 /* set minimum threshold count to store a value */
2479 mincount = avgcount * 1.25;
2482 /* don't let threshold exceed 1/K, however */
2483 maxmincount = (double) samplerows / (double) num_bins;
2484 if (mincount > maxmincount)
2485 mincount = maxmincount;
2486 if (num_mcv > track_cnt)
2487 num_mcv = track_cnt;
2488 for (i = 0; i < num_mcv; i++)
2490 if (track[i].count < mincount)
2498 /* Generate MCV slot entry */
2501 MemoryContext old_context;
2505 /* Must copy the target values into anl_context */
2506 old_context = MemoryContextSwitchTo(stats->anl_context);
2507 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2508 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2509 for (i = 0; i < num_mcv; i++)
2511 mcv_values[i] = datumCopy(values[track[i].first].value,
2512 stats->attrtype->typbyval,
2513 stats->attrtype->typlen);
2514 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2516 MemoryContextSwitchTo(old_context);
2518 stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2519 stats->staop[slot_idx] = mystats->eqopr;
2520 stats->stanumbers[slot_idx] = mcv_freqs;
2521 stats->numnumbers[slot_idx] = num_mcv;
2522 stats->stavalues[slot_idx] = mcv_values;
2523 stats->numvalues[slot_idx] = num_mcv;
2526 * Accept the defaults for stats->statypid and others. They have
2527 * been set before we were called (see vacuum.h)
2533 * Generate a histogram slot entry if there are at least two distinct
2534 * values not accounted for in the MCV list. (This ensures the
2535 * histogram won't collapse to empty or a singleton.)
2537 num_hist = ndistinct - num_mcv;
2538 if (num_hist > num_bins)
2539 num_hist = num_bins + 1;
2542 MemoryContext old_context;
2550 /* Sort the MCV items into position order to speed next loop */
2551 qsort((void *) track, num_mcv,
2552 sizeof(ScalarMCVItem), compare_mcvs);
2555 * Collapse out the MCV items from the values[] array.
2557 * Note we destroy the values[] array here... but we don't need it
2558 * for anything more. We do, however, still need values_cnt.
2559 * nvals will be the number of remaining entries in values[].
2568 j = 0; /* index of next interesting MCV item */
2569 while (src < values_cnt)
2575 int first = track[j].first;
2579 /* advance past this MCV item */
2580 src = first + track[j].count;
2584 ncopy = first - src;
2587 ncopy = values_cnt - src;
2588 memmove(&values[dest], &values[src],
2589 ncopy * sizeof(ScalarItem));
2597 Assert(nvals >= num_hist);
2599 /* Must copy the target values into anl_context */
2600 old_context = MemoryContextSwitchTo(stats->anl_context);
2601 hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2604 * The object of this loop is to copy the first and last values[]
2605 * entries along with evenly-spaced values in between. So the
2606 * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2607 * computing that subscript directly risks integer overflow when
2608 * the stats target is more than a couple thousand. Instead we
2609 * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2610 * the integral and fractional parts of the sum separately.
2612 delta = (nvals - 1) / (num_hist - 1);
2613 deltafrac = (nvals - 1) % (num_hist - 1);
2616 for (i = 0; i < num_hist; i++)
2618 hist_values[i] = datumCopy(values[pos].value,
2619 stats->attrtype->typbyval,
2620 stats->attrtype->typlen);
2622 posfrac += deltafrac;
2623 if (posfrac >= (num_hist - 1))
2625 /* fractional part exceeds 1, carry to integer part */
2627 posfrac -= (num_hist - 1);
2631 MemoryContextSwitchTo(old_context);
2633 stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2634 stats->staop[slot_idx] = mystats->ltopr;
2635 stats->stavalues[slot_idx] = hist_values;
2636 stats->numvalues[slot_idx] = num_hist;
2639 * Accept the defaults for stats->statypid and others. They have
2640 * been set before we were called (see vacuum.h)
2645 /* Generate a correlation entry if there are multiple values */
2648 MemoryContext old_context;
2653 /* Must copy the target values into anl_context */
2654 old_context = MemoryContextSwitchTo(stats->anl_context);
2655 corrs = (float4 *) palloc(sizeof(float4));
2656 MemoryContextSwitchTo(old_context);
2659 * Since we know the x and y value sets are both
2660 * 0, 1, ..., values_cnt-1
2661 * we have sum(x) = sum(y) =
2662 * (values_cnt-1)*values_cnt / 2
2663 * and sum(x^2) = sum(y^2) =
2664 * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2667 corr_xsum = ((double) (values_cnt - 1)) *
2668 ((double) values_cnt) / 2.0;
2669 corr_x2sum = ((double) (values_cnt - 1)) *
2670 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2672 /* And the correlation coefficient reduces to */
2673 corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2674 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2676 stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2677 stats->staop[slot_idx] = mystats->ltopr;
2678 stats->stanumbers[slot_idx] = corrs;
2679 stats->numnumbers[slot_idx] = 1;
2683 else if (nonnull_cnt == 0 && null_cnt > 0)
2685 /* We found only nulls; assume the column is entirely null */
2686 stats->stats_valid = true;
2687 stats->stanullfrac = 1.0;
2689 stats->stawidth = 0; /* "unknown" */
2691 stats->stawidth = stats->attrtype->typlen;
2692 stats->stadistinct = 0.0; /* "unknown" */
2695 /* We don't need to bother cleaning up any of our temporary palloc's */
2699 * qsort_arg comparator for sorting ScalarItems
2701 * Aside from sorting the items, we update the tupnoLink[] array
2702 * whenever two ScalarItems are found to contain equal datums. The array
2703 * is indexed by tupno; for each ScalarItem, it contains the highest
2704 * tupno that that item's datum has been found to be equal to. This allows
2705 * us to avoid additional comparisons in compute_scalar_stats().
2708 compare_scalars(const void *a, const void *b, void *arg)
2710 Datum da = ((const ScalarItem *) a)->value;
2711 int ta = ((const ScalarItem *) a)->tupno;
2712 Datum db = ((const ScalarItem *) b)->value;
2713 int tb = ((const ScalarItem *) b)->tupno;
2714 CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2717 /* We always use the default collation for statistics */
2718 compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2719 DEFAULT_COLLATION_OID,
2720 da, false, db, false);
2725 * The two datums are equal, so update cxt->tupnoLink[].
2727 if (cxt->tupnoLink[ta] < tb)
2728 cxt->tupnoLink[ta] = tb;
2729 if (cxt->tupnoLink[tb] < ta)
2730 cxt->tupnoLink[tb] = ta;
2733 * For equal datums, sort by tupno
2739 * qsort comparator for sorting ScalarMCVItems by position
2742 compare_mcvs(const void *a, const void *b)
2744 int da = ((const ScalarMCVItem *) a)->first;
2745 int db = ((const ScalarMCVItem *) b)->first;