1 /*-------------------------------------------------------------------------
4 * the Postgres statistics generator
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/analyze.c
13 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "access/transam.h"
21 #include "access/tupconvert.h"
22 #include "access/tuptoaster.h"
23 #include "access/xact.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_inherits_fn.h"
28 #include "catalog/pg_namespace.h"
29 #include "commands/dbcommands.h"
30 #include "commands/vacuum.h"
31 #include "executor/executor.h"
32 #include "miscadmin.h"
33 #include "nodes/nodeFuncs.h"
34 #include "parser/parse_oper.h"
35 #include "parser/parse_relation.h"
37 #include "postmaster/autovacuum.h"
38 #include "storage/bufmgr.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "utils/acl.h"
42 #include "utils/attoptcache.h"
43 #include "utils/datum.h"
44 #include "utils/guc.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/pg_rusage.h"
48 #include "utils/syscache.h"
49 #include "utils/tuplesort.h"
50 #include "utils/tqual.h"
53 /* Data structure for Algorithm S from Knuth 3.4.2 */
56 BlockNumber N; /* number of blocks, known in advance */
57 int n; /* desired sample size */
58 BlockNumber t; /* current block number */
59 int m; /* blocks selected so far */
62 typedef BlockSamplerData *BlockSampler;
64 /* Per-index data for ANALYZE */
65 typedef struct AnlIndexData
67 IndexInfo *indexInfo; /* BuildIndexInfo result */
68 double tupleFract; /* fraction of rows for partial index */
69 VacAttrStats **vacattrstats; /* index attrs to analyze */
74 /* Default statistics target (GUC parameter) */
75 int default_statistics_target = 100;
77 /* A few variables that don't seem worth passing around as parameters */
78 static int elevel = -1;
80 static MemoryContext anl_context = NULL;
82 static BufferAccessStrategy vac_strategy;
85 static void do_analyze_rel(Relation onerel, VacuumStmt *vacstmt,
86 bool update_reltuples, bool inh);
87 static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
89 static bool BlockSampler_HasMore(BlockSampler bs);
90 static BlockNumber BlockSampler_Next(BlockSampler bs);
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, HeapTuple *rows,
98 int targrows, double *totalrows, double *totaldeadrows);
99 static double random_fract(void);
100 static double init_selection_state(int n);
101 static double get_next_S(double t, int n, double *stateptr);
102 static int compare_rows(const void *a, const void *b);
103 static int acquire_inherited_sample_rows(Relation onerel,
104 HeapTuple *rows, int targrows,
105 double *totalrows, double *totaldeadrows);
106 static void update_attstats(Oid relid, bool inh,
107 int natts, VacAttrStats **vacattrstats);
108 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
109 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
111 static bool std_typanalyze(VacAttrStats *stats);
115 * analyze_rel() -- analyze one relation
117 * If update_reltuples is true, we update reltuples and relpages columns
118 * in pg_class. Caller should pass false if we're part of VACUUM ANALYZE,
119 * and the VACUUM didn't skip any pages. We only have an approximate count,
120 * so we don't want to overwrite the accurate values already inserted by the
121 * VACUUM in that case. VACUUM always scans all indexes, however, so the
122 * pg_class entries for indexes are never updated if we're part of VACUUM
126 analyze_rel(Oid relid, VacuumStmt *vacstmt,
127 BufferAccessStrategy bstrategy, bool update_reltuples)
131 /* Set up static variables */
132 if (vacstmt->options & VACOPT_VERBOSE)
137 vac_strategy = bstrategy;
140 * Check for user-requested abort.
142 CHECK_FOR_INTERRUPTS();
145 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
146 * ANALYZEs don't run on it concurrently. (This also locks out a
147 * concurrent VACUUM, which doesn't matter much at the moment but might
148 * matter if we ever try to accumulate stats on dead tuples.) If the rel
149 * has been dropped since we last saw it, we don't need to process it.
151 onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
156 * Check permissions --- this should match vacuum's check!
158 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
159 (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
161 /* No need for a WARNING if we already complained during VACUUM */
162 if (!(vacstmt->options & VACOPT_VACUUM))
164 if (onerel->rd_rel->relisshared)
166 (errmsg("skipping \"%s\" --- only superuser can analyze it",
167 RelationGetRelationName(onerel))));
168 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
170 (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
171 RelationGetRelationName(onerel))));
174 (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
175 RelationGetRelationName(onerel))));
177 relation_close(onerel, ShareUpdateExclusiveLock);
182 * Check that it's a plain table; we used to do this in get_rel_oids() but
183 * seems safer to check after we've locked the relation.
185 if (onerel->rd_rel->relkind != RELKIND_RELATION)
187 /* No need for a WARNING if we already complained during VACUUM */
188 if (!(vacstmt->options & VACOPT_VACUUM))
190 (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
191 RelationGetRelationName(onerel))));
192 relation_close(onerel, ShareUpdateExclusiveLock);
197 * Silently ignore tables that are temp tables of other backends ---
198 * trying to analyze these is rather pointless, since their contents are
199 * probably not up-to-date on disk. (We don't throw a warning here; it
200 * would just lead to chatter during a database-wide ANALYZE.)
202 if (RELATION_IS_OTHER_TEMP(onerel))
204 relation_close(onerel, ShareUpdateExclusiveLock);
209 * We can ANALYZE any table except pg_statistic. See update_attstats
211 if (RelationGetRelid(onerel) == StatisticRelationId)
213 relation_close(onerel, ShareUpdateExclusiveLock);
218 * OK, let's do it. First let other backends know I'm in ANALYZE.
220 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
221 MyProc->vacuumFlags |= PROC_IN_ANALYZE;
222 LWLockRelease(ProcArrayLock);
225 * Do the normal non-recursive ANALYZE.
227 do_analyze_rel(onerel, vacstmt, update_reltuples, false);
230 * If there are child tables, do recursive ANALYZE.
232 if (onerel->rd_rel->relhassubclass)
233 do_analyze_rel(onerel, vacstmt, false, true);
236 * Close source relation now, but keep lock so that no one deletes it
237 * before we commit. (If someone did, they'd fail to clean up the entries
238 * we made in pg_statistic. Also, releasing the lock before commit would
239 * expose us to concurrent-update failures in update_attstats.)
241 relation_close(onerel, NoLock);
244 * Reset my PGPROC flag. Note: we need this here, and not in vacuum_rel,
245 * because the vacuum flag is cleared by the end-of-xact code.
247 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
248 MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
249 LWLockRelease(ProcArrayLock);
253 * do_analyze_rel() -- analyze one relation, recursively or not
256 do_analyze_rel(Relation onerel, VacuumStmt *vacstmt,
257 bool update_reltuples, bool inh)
266 bool analyzableindex;
267 VacAttrStats **vacattrstats;
268 AnlIndexData *indexdata;
275 TimestampTz starttime = 0;
276 MemoryContext caller_context;
278 int save_sec_context;
283 (errmsg("analyzing \"%s.%s\" inheritance tree",
284 get_namespace_name(RelationGetNamespace(onerel)),
285 RelationGetRelationName(onerel))));
288 (errmsg("analyzing \"%s.%s\"",
289 get_namespace_name(RelationGetNamespace(onerel)),
290 RelationGetRelationName(onerel))));
293 * Set up a working context so that we can easily free whatever junk gets
296 anl_context = AllocSetContextCreate(CurrentMemoryContext,
298 ALLOCSET_DEFAULT_MINSIZE,
299 ALLOCSET_DEFAULT_INITSIZE,
300 ALLOCSET_DEFAULT_MAXSIZE);
301 caller_context = MemoryContextSwitchTo(anl_context);
304 * Switch to the table owner's userid, so that any index functions are run
305 * as that user. Also lock down security-restricted operations and
306 * arrange to make GUC variable changes local to this command.
308 GetUserIdAndSecContext(&save_userid, &save_sec_context);
309 SetUserIdAndSecContext(onerel->rd_rel->relowner,
310 save_sec_context | SECURITY_RESTRICTED_OPERATION);
311 save_nestlevel = NewGUCNestLevel();
313 /* measure elapsed time iff autovacuum logging requires it */
314 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
316 pg_rusage_init(&ru0);
317 if (Log_autovacuum_min_duration > 0)
318 starttime = GetCurrentTimestamp();
322 * Determine which columns to analyze
324 * Note that system attributes are never analyzed.
326 if (vacstmt->va_cols != NIL)
330 vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
331 sizeof(VacAttrStats *));
333 foreach(le, vacstmt->va_cols)
335 char *col = strVal(lfirst(le));
337 i = attnameAttNum(onerel, col, false);
338 if (i == InvalidAttrNumber)
340 (errcode(ERRCODE_UNDEFINED_COLUMN),
341 errmsg("column \"%s\" of relation \"%s\" does not exist",
342 col, RelationGetRelationName(onerel))));
343 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
344 if (vacattrstats[tcnt] != NULL)
351 attr_cnt = onerel->rd_att->natts;
352 vacattrstats = (VacAttrStats **)
353 palloc(attr_cnt * sizeof(VacAttrStats *));
355 for (i = 1; i <= attr_cnt; i++)
357 vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
358 if (vacattrstats[tcnt] != NULL)
365 * Open all indexes of the relation, and see if there are any analyzable
366 * columns in the indexes. We do not analyze index columns if there was
367 * an explicit column list in the ANALYZE command, however. If we are
368 * doing a recursive scan, we don't want to touch the parent's indexes at
372 vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
378 hasindex = (nindexes > 0);
380 analyzableindex = false;
383 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
384 for (ind = 0; ind < nindexes; ind++)
386 AnlIndexData *thisdata = &indexdata[ind];
387 IndexInfo *indexInfo;
389 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
390 thisdata->tupleFract = 1.0; /* fix later if partial */
391 if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
393 ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
395 thisdata->vacattrstats = (VacAttrStats **)
396 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
398 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
400 int keycol = indexInfo->ii_KeyAttrNumbers[i];
404 /* Found an index expression */
407 if (indexpr_item == NULL) /* shouldn't happen */
408 elog(ERROR, "too few entries in indexprs list");
409 indexkey = (Node *) lfirst(indexpr_item);
410 indexpr_item = lnext(indexpr_item);
411 thisdata->vacattrstats[tcnt] =
412 examine_attribute(Irel[ind], i + 1, indexkey);
413 if (thisdata->vacattrstats[tcnt] != NULL)
416 analyzableindex = true;
420 thisdata->attr_cnt = tcnt;
426 * Quit if no analyzable columns and no pg_class update needed.
428 if (attr_cnt <= 0 && !analyzableindex && !update_reltuples)
432 * Determine how many rows we need to sample, using the worst case from
433 * all analyzable columns. We use a lower bound of 100 rows to avoid
434 * possible overflow in Vitter's algorithm.
437 for (i = 0; i < attr_cnt; i++)
439 if (targrows < vacattrstats[i]->minrows)
440 targrows = vacattrstats[i]->minrows;
442 for (ind = 0; ind < nindexes; ind++)
444 AnlIndexData *thisdata = &indexdata[ind];
446 for (i = 0; i < thisdata->attr_cnt; i++)
448 if (targrows < thisdata->vacattrstats[i]->minrows)
449 targrows = thisdata->vacattrstats[i]->minrows;
454 * Acquire the sample rows
456 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
458 numrows = acquire_inherited_sample_rows(onerel, rows, targrows,
459 &totalrows, &totaldeadrows);
461 numrows = acquire_sample_rows(onerel, rows, targrows,
462 &totalrows, &totaldeadrows);
465 * Compute the statistics. Temporary results during the calculations for
466 * each column are stored in a child context. The calc routines are
467 * responsible to make sure that whatever they store into the VacAttrStats
468 * structure is allocated in anl_context.
472 MemoryContext col_context,
475 col_context = AllocSetContextCreate(anl_context,
477 ALLOCSET_DEFAULT_MINSIZE,
478 ALLOCSET_DEFAULT_INITSIZE,
479 ALLOCSET_DEFAULT_MAXSIZE);
480 old_context = MemoryContextSwitchTo(col_context);
482 for (i = 0; i < attr_cnt; i++)
484 VacAttrStats *stats = vacattrstats[i];
485 AttributeOpts *aopt =
486 get_attribute_options(onerel->rd_id, stats->attr->attnum);
489 stats->tupDesc = onerel->rd_att;
490 (*stats->compute_stats) (stats,
496 * If the appropriate flavor of the n_distinct option is
497 * specified, override with the corresponding value.
502 inh ? aopt->n_distinct_inherited : aopt->n_distinct;
504 if (n_distinct != 0.0)
505 stats->stadistinct = n_distinct;
508 MemoryContextResetAndDeleteChildren(col_context);
512 compute_index_stats(onerel, totalrows,
517 MemoryContextSwitchTo(old_context);
518 MemoryContextDelete(col_context);
521 * Emit the completed stats rows into pg_statistic, replacing any
522 * previous statistics for the target columns. (If there are stats in
523 * pg_statistic for columns we didn't process, we leave them alone.)
525 update_attstats(RelationGetRelid(onerel), inh,
526 attr_cnt, vacattrstats);
528 for (ind = 0; ind < nindexes; ind++)
530 AnlIndexData *thisdata = &indexdata[ind];
532 update_attstats(RelationGetRelid(Irel[ind]), false,
533 thisdata->attr_cnt, thisdata->vacattrstats);
538 * Update pages/tuples stats in pg_class, but not if we're inside a VACUUM
539 * that got a more precise number.
541 if (update_reltuples)
542 vac_update_relstats(onerel,
543 RelationGetNumberOfBlocks(onerel),
544 totalrows, hasindex, InvalidTransactionId);
547 * Same for indexes. Vacuum always scans all indexes, so if we're part of
548 * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
551 if (!(vacstmt->options & VACOPT_VACUUM))
553 for (ind = 0; ind < nindexes; ind++)
555 AnlIndexData *thisdata = &indexdata[ind];
556 double totalindexrows;
558 totalindexrows = ceil(thisdata->tupleFract * totalrows);
559 vac_update_relstats(Irel[ind],
560 RelationGetNumberOfBlocks(Irel[ind]),
561 totalindexrows, false, InvalidTransactionId);
566 * Report ANALYZE to the stats collector, too; likewise, tell it to adopt
567 * these numbers only if we're not inside a VACUUM that got a better
568 * number. However, a call with inh = true shouldn't reset the stats.
571 pgstat_report_analyze(onerel, update_reltuples,
572 totalrows, totaldeadrows);
574 /* We skip to here if there were no analyzable columns */
577 /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
578 if (!(vacstmt->options & VACOPT_VACUUM))
580 for (ind = 0; ind < nindexes; ind++)
582 IndexBulkDeleteResult *stats;
583 IndexVacuumInfo ivinfo;
585 ivinfo.index = Irel[ind];
586 ivinfo.analyze_only = true;
587 ivinfo.estimated_count = true;
588 ivinfo.message_level = elevel;
589 ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
590 ivinfo.strategy = vac_strategy;
592 stats = index_vacuum_cleanup(&ivinfo, NULL);
599 /* Done with indexes */
600 vac_close_indexes(nindexes, Irel, NoLock);
602 /* Log the action if appropriate */
603 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
605 if (Log_autovacuum_min_duration == 0 ||
606 TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
607 Log_autovacuum_min_duration))
609 (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
610 get_database_name(MyDatabaseId),
611 get_namespace_name(RelationGetNamespace(onerel)),
612 RelationGetRelationName(onerel),
613 pg_rusage_show(&ru0))));
616 /* Roll back any GUC changes executed by index functions */
617 AtEOXact_GUC(false, save_nestlevel);
619 /* Restore userid and security context */
620 SetUserIdAndSecContext(save_userid, save_sec_context);
622 /* Restore current context and release memory */
623 MemoryContextSwitchTo(caller_context);
624 MemoryContextDelete(anl_context);
629 * Compute statistics about indexes of a relation
632 compute_index_stats(Relation onerel, double totalrows,
633 AnlIndexData *indexdata, int nindexes,
634 HeapTuple *rows, int numrows,
635 MemoryContext col_context)
637 MemoryContext ind_context,
639 Datum values[INDEX_MAX_KEYS];
640 bool isnull[INDEX_MAX_KEYS];
644 ind_context = AllocSetContextCreate(anl_context,
646 ALLOCSET_DEFAULT_MINSIZE,
647 ALLOCSET_DEFAULT_INITSIZE,
648 ALLOCSET_DEFAULT_MAXSIZE);
649 old_context = MemoryContextSwitchTo(ind_context);
651 for (ind = 0; ind < nindexes; ind++)
653 AnlIndexData *thisdata = &indexdata[ind];
654 IndexInfo *indexInfo = thisdata->indexInfo;
655 int attr_cnt = thisdata->attr_cnt;
656 TupleTableSlot *slot;
658 ExprContext *econtext;
665 double totalindexrows;
667 /* Ignore index if no columns to analyze and not partial */
668 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
672 * Need an EState for evaluation of index expressions and
673 * partial-index predicates. Create it in the per-index context to be
674 * sure it gets cleaned up at the bottom of the loop.
676 estate = CreateExecutorState();
677 econtext = GetPerTupleExprContext(estate);
678 /* Need a slot to hold the current heap tuple, too */
679 slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
681 /* Arrange for econtext's scan tuple to be the tuple under test */
682 econtext->ecxt_scantuple = slot;
684 /* Set up execution state for predicate. */
686 ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
689 /* Compute and save index expression values */
690 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
691 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
694 for (rowno = 0; rowno < numrows; rowno++)
696 HeapTuple heapTuple = rows[rowno];
699 * Reset the per-tuple context each time, to reclaim any cruft
700 * left behind by evaluating the predicate or index expressions.
702 ResetExprContext(econtext);
704 /* Set up for predicate or expression evaluation */
705 ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
707 /* If index is partial, check predicate */
708 if (predicate != NIL)
710 if (!ExecQual(predicate, econtext, false))
718 * Evaluate the index row to compute expression values. We
719 * could do this by hand, but FormIndexDatum is convenient.
721 FormIndexDatum(indexInfo,
728 * Save just the columns we care about. We copy the values
729 * into ind_context from the estate's per-tuple context.
731 for (i = 0; i < attr_cnt; i++)
733 VacAttrStats *stats = thisdata->vacattrstats[i];
734 int attnum = stats->attr->attnum;
736 if (isnull[attnum - 1])
738 exprvals[tcnt] = (Datum) 0;
739 exprnulls[tcnt] = true;
743 exprvals[tcnt] = datumCopy(values[attnum - 1],
744 stats->attrtype->typbyval,
745 stats->attrtype->typlen);
746 exprnulls[tcnt] = false;
754 * Having counted the number of rows that pass the predicate in the
755 * sample, we can estimate the total number of rows in the index.
757 thisdata->tupleFract = (double) numindexrows / (double) numrows;
758 totalindexrows = ceil(thisdata->tupleFract * totalrows);
761 * Now we can compute the statistics for the expression columns.
763 if (numindexrows > 0)
765 MemoryContextSwitchTo(col_context);
766 for (i = 0; i < attr_cnt; i++)
768 VacAttrStats *stats = thisdata->vacattrstats[i];
769 AttributeOpts *aopt =
770 get_attribute_options(stats->attr->attrelid,
771 stats->attr->attnum);
773 stats->exprvals = exprvals + i;
774 stats->exprnulls = exprnulls + i;
775 stats->rowstride = attr_cnt;
776 (*stats->compute_stats) (stats,
782 * If the n_distinct option is specified, it overrides the
783 * above computation. For indices, we always use just
784 * n_distinct, not n_distinct_inherited.
786 if (aopt != NULL && aopt->n_distinct != 0.0)
787 stats->stadistinct = aopt->n_distinct;
789 MemoryContextResetAndDeleteChildren(col_context);
794 MemoryContextSwitchTo(ind_context);
796 ExecDropSingleTupleTableSlot(slot);
797 FreeExecutorState(estate);
798 MemoryContextResetAndDeleteChildren(ind_context);
801 MemoryContextSwitchTo(old_context);
802 MemoryContextDelete(ind_context);
806 * examine_attribute -- pre-analysis of a single column
808 * Determine whether the column is analyzable; if so, create and initialize
809 * a VacAttrStats struct for it. If not, return NULL.
811 * If index_expr isn't NULL, then we're trying to analyze an expression index,
812 * and index_expr is the expression tree representing the column's data.
814 static VacAttrStats *
815 examine_attribute(Relation onerel, int attnum, Node *index_expr)
817 Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
823 /* Never analyze dropped columns */
824 if (attr->attisdropped)
827 /* Don't analyze column if user has specified not to */
828 if (attr->attstattarget == 0)
832 * Create the VacAttrStats struct. Note that we only have a copy of the
833 * fixed fields of the pg_attribute tuple.
835 stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
836 stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
837 memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
840 * When analyzing an expression index, believe the expression tree's type
841 * not the column datatype --- the latter might be the opckeytype storage
842 * type of the opclass, which is not interesting for our purposes. (Note:
843 * if we did anything with non-expression index columns, we'd need to
844 * figure out where to get the correct type info from, but for now that's
845 * not a problem.) It's not clear whether anyone will care about the
846 * typmod, but we store that too just in case.
850 stats->attrtypid = exprType(index_expr);
851 stats->attrtypmod = exprTypmod(index_expr);
855 stats->attrtypid = attr->atttypid;
856 stats->attrtypmod = attr->atttypmod;
859 typtuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(stats->attrtypid));
860 if (!HeapTupleIsValid(typtuple))
861 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
862 stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
863 memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
864 ReleaseSysCache(typtuple);
865 stats->anl_context = anl_context;
866 stats->tupattnum = attnum;
869 * The fields describing the stats->stavalues[n] element types default to
870 * the type of the data being analyzed, but the type-specific typanalyze
871 * function can change them if it wants to store something else.
873 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
875 stats->statypid[i] = stats->attrtypid;
876 stats->statyplen[i] = stats->attrtype->typlen;
877 stats->statypbyval[i] = stats->attrtype->typbyval;
878 stats->statypalign[i] = stats->attrtype->typalign;
882 * Call the type-specific typanalyze function. If none is specified, use
885 if (OidIsValid(stats->attrtype->typanalyze))
886 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
887 PointerGetDatum(stats)));
889 ok = std_typanalyze(stats);
891 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
893 pfree(stats->attrtype);
903 * BlockSampler_Init -- prepare for random sampling of blocknumbers
905 * BlockSampler is used for stage one of our new two-stage tuple
906 * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
907 * "Large DB"). It selects a random sample of samplesize blocks out of
908 * the nblocks blocks in the table. If the table has less than
909 * samplesize blocks, all blocks are selected.
911 * Since we know the total number of blocks in advance, we can use the
912 * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
916 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
918 bs->N = nblocks; /* measured table size */
921 * If we decide to reduce samplesize for tables that have less or not much
922 * more than samplesize blocks, here is the place to do it.
925 bs->t = 0; /* blocks scanned so far */
926 bs->m = 0; /* blocks selected so far */
930 BlockSampler_HasMore(BlockSampler bs)
932 return (bs->t < bs->N) && (bs->m < bs->n);
936 BlockSampler_Next(BlockSampler bs)
938 BlockNumber K = bs->N - bs->t; /* remaining blocks */
939 int k = bs->n - bs->m; /* blocks still to sample */
940 double p; /* probability to skip block */
941 double V; /* random */
943 Assert(BlockSampler_HasMore(bs)); /* hence K > 0 and k > 0 */
945 if ((BlockNumber) k >= K)
947 /* need all the rest */
953 * It is not obvious that this code matches Knuth's Algorithm S.
954 * Knuth says to skip the current block with probability 1 - k/K.
955 * If we are to skip, we should advance t (hence decrease K), and
956 * repeat the same probabilistic test for the next block. The naive
957 * implementation thus requires a random_fract() call for each block
958 * number. But we can reduce this to one random_fract() call per
959 * selected block, by noting that each time the while-test succeeds,
960 * we can reinterpret V as a uniform random number in the range 0 to p.
961 * Therefore, instead of choosing a new V, we just adjust p to be
962 * the appropriate fraction of its former value, and our next loop
963 * makes the appropriate probabilistic test.
965 * We have initially K > k > 0. If the loop reduces K to equal k,
966 * the next while-test must fail since p will become exactly zero
967 * (we assume there will not be roundoff error in the division).
968 * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
969 * to be doubly sure about roundoff error.) Therefore K cannot become
970 * less than k, which means that we cannot fail to select enough blocks.
974 p = 1.0 - (double) k / (double) K;
979 K--; /* keep K == N - t */
981 /* adjust p to be new cutoff point in reduced range */
982 p *= 1.0 - (double) k / (double) K;
991 * acquire_sample_rows -- acquire a random sample of rows from the table
993 * Selected rows are returned in the caller-allocated array rows[], which
994 * must have at least targrows entries.
995 * The actual number of rows selected is returned as the function result.
996 * We also estimate the total numbers of live and dead rows in the table,
997 * and return them into *totalrows and *totaldeadrows, respectively.
999 * The returned list of tuples is in order by physical position in the table.
1000 * (We will rely on this later to derive correlation estimates.)
1002 * As of May 2004 we use a new two-stage method: Stage one selects up
1003 * to targrows random blocks (or all blocks, if there aren't so many).
1004 * Stage two scans these blocks and uses the Vitter algorithm to create
1005 * a random sample of targrows rows (or less, if there are less in the
1006 * sample of blocks). The two stages are executed simultaneously: each
1007 * block is processed as soon as stage one returns its number and while
1008 * the rows are read stage two controls which ones are to be inserted
1011 * Although every row has an equal chance of ending up in the final
1012 * sample, this sampling method is not perfect: not every possible
1013 * sample has an equal chance of being selected. For large relations
1014 * the number of different blocks represented by the sample tends to be
1015 * too small. We can live with that for now. Improvements are welcome.
1017 * An important property of this sampling method is that because we do
1018 * look at a statistically unbiased set of blocks, we should get
1019 * unbiased estimates of the average numbers of live and dead rows per
1020 * block. The previous sampling method put too much credence in the row
1021 * density near the start of the table.
1024 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1025 double *totalrows, double *totaldeadrows)
1027 int numrows = 0; /* # rows now in reservoir */
1028 double samplerows = 0; /* total # rows collected */
1029 double liverows = 0; /* # live rows seen */
1030 double deadrows = 0; /* # dead rows seen */
1031 double rowstoskip = -1; /* -1 means not set yet */
1032 BlockNumber totalblocks;
1033 TransactionId OldestXmin;
1034 BlockSamplerData bs;
1037 Assert(targrows > 0);
1039 totalblocks = RelationGetNumberOfBlocks(onerel);
1041 /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1042 OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
1044 /* Prepare for sampling block numbers */
1045 BlockSampler_Init(&bs, totalblocks, targrows);
1046 /* Prepare for sampling rows */
1047 rstate = init_selection_state(targrows);
1049 /* Outer loop over blocks to sample */
1050 while (BlockSampler_HasMore(&bs))
1052 BlockNumber targblock = BlockSampler_Next(&bs);
1055 OffsetNumber targoffset,
1058 vacuum_delay_point();
1061 * We must maintain a pin on the target page's buffer to ensure that
1062 * the maxoffset value stays good (else concurrent VACUUM might delete
1063 * tuples out from under us). Hence, pin the page until we are done
1064 * looking at it. We also choose to hold sharelock on the buffer
1065 * throughout --- we could release and re-acquire sharelock for each
1066 * tuple, but since we aren't doing much work per tuple, the extra
1067 * lock traffic is probably better avoided.
1069 targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1070 RBM_NORMAL, vac_strategy);
1071 LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1072 targpage = BufferGetPage(targbuffer);
1073 maxoffset = PageGetMaxOffsetNumber(targpage);
1075 /* Inner loop over all tuples on the selected page */
1076 for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1079 HeapTupleData targtuple;
1080 bool sample_it = false;
1082 itemid = PageGetItemId(targpage, targoffset);
1085 * We ignore unused and redirect line pointers. DEAD line
1086 * pointers should be counted as dead, because we need vacuum to
1087 * run to get rid of them. Note that this rule agrees with the
1088 * way that heap_page_prune() counts things.
1090 if (!ItemIdIsNormal(itemid))
1092 if (ItemIdIsDead(itemid))
1097 ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1099 targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1100 targtuple.t_len = ItemIdGetLength(itemid);
1102 switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
1106 case HEAPTUPLE_LIVE:
1111 case HEAPTUPLE_DEAD:
1112 case HEAPTUPLE_RECENTLY_DEAD:
1113 /* Count dead and recently-dead rows */
1117 case HEAPTUPLE_INSERT_IN_PROGRESS:
1120 * Insert-in-progress rows are not counted. We assume
1121 * that when the inserting transaction commits or aborts,
1122 * it will send a stats message to increment the proper
1123 * count. This works right only if that transaction ends
1124 * after we finish analyzing the table; if things happen
1125 * in the other order, its stats update will be
1126 * overwritten by ours. However, the error will be large
1127 * only if the other transaction runs long enough to
1128 * insert many tuples, so assuming it will finish after us
1129 * is the safer option.
1131 * A special case is that the inserting transaction might
1132 * be our own. In this case we should count and sample
1133 * the row, to accommodate users who load a table and
1134 * analyze it in one transaction. (pgstat_report_analyze
1135 * has to adjust the numbers we send to the stats
1136 * collector to make this come out right.)
1138 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
1145 case HEAPTUPLE_DELETE_IN_PROGRESS:
1148 * We count delete-in-progress rows as still live, using
1149 * the same reasoning given above; but we don't bother to
1150 * include them in the sample.
1152 * If the delete was done by our own transaction, however,
1153 * we must count the row as dead to make
1154 * pgstat_report_analyze's stats adjustments come out
1155 * right. (Note: this works out properly when the row was
1156 * both inserted and deleted in our xact.)
1158 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
1165 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1172 * The first targrows sample rows are simply copied into the
1173 * reservoir. Then we start replacing tuples in the sample
1174 * until we reach the end of the relation. This algorithm is
1175 * from Jeff Vitter's paper (see full citation below). It
1176 * works by repeatedly computing the number of tuples to skip
1177 * before selecting a tuple, which replaces a randomly chosen
1178 * element of the reservoir (current set of tuples). At all
1179 * times the reservoir is a true random sample of the tuples
1180 * we've passed over so far, so when we fall off the end of
1181 * the relation we're done.
1183 if (numrows < targrows)
1184 rows[numrows++] = heap_copytuple(&targtuple);
1188 * t in Vitter's paper is the number of records already
1189 * processed. If we need to compute a new S value, we
1190 * must use the not-yet-incremented value of samplerows as
1194 rowstoskip = get_next_S(samplerows, targrows, &rstate);
1196 if (rowstoskip <= 0)
1199 * Found a suitable tuple, so save it, replacing one
1200 * old tuple at random
1202 int k = (int) (targrows * random_fract());
1204 Assert(k >= 0 && k < targrows);
1205 heap_freetuple(rows[k]);
1206 rows[k] = heap_copytuple(&targtuple);
1216 /* Now release the lock and pin on the page */
1217 UnlockReleaseBuffer(targbuffer);
1221 * If we didn't find as many tuples as we wanted then we're done. No sort
1222 * is needed, since they're already in order.
1224 * Otherwise we need to sort the collected tuples by position
1225 * (itempointer). It's not worth worrying about corner cases where the
1226 * tuples are already sorted.
1228 if (numrows == targrows)
1229 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1232 * Estimate total numbers of rows in relation.
1236 *totalrows = floor((liverows * totalblocks) / bs.m + 0.5);
1237 *totaldeadrows = floor((deadrows * totalblocks) / bs.m + 0.5);
1242 *totaldeadrows = 0.0;
1246 * Emit some interesting relation info
1249 (errmsg("\"%s\": scanned %d of %u pages, "
1250 "containing %.0f live rows and %.0f dead rows; "
1251 "%d rows in sample, %.0f estimated total rows",
1252 RelationGetRelationName(onerel),
1255 numrows, *totalrows)));
1260 /* Select a random value R uniformly distributed in (0 - 1) */
1264 return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
1268 * These two routines embody Algorithm Z from "Random sampling with a
1269 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1270 * (Mar. 1985), Pages 37-57. Vitter describes his algorithm in terms
1271 * of the count S of records to skip before processing another record.
1272 * It is computed primarily based on t, the number of records already read.
1273 * The only extra state needed between calls is W, a random state variable.
1275 * init_selection_state computes the initial W value.
1277 * Given that we've already read t records (t >= n), get_next_S
1278 * determines the number of records to skip before the next record is
1282 init_selection_state(int n)
1284 /* Initial value of W (for use when Algorithm Z is first applied) */
1285 return exp(-log(random_fract()) / n);
1289 get_next_S(double t, int n, double *stateptr)
1293 /* The magic constant here is T from Vitter's paper */
1294 if (t <= (22.0 * n))
1296 /* Process records using Algorithm X until t is large enough */
1300 V = random_fract(); /* Generate V */
1303 /* Note: "num" in Vitter's code is always equal to t - n */
1304 quot = (t - (double) n) / t;
1305 /* Find min S satisfying (4.1) */
1310 quot *= (t - (double) n) / t;
1315 /* Now apply Algorithm Z */
1316 double W = *stateptr;
1317 double term = t - (double) n + 1;
1331 /* Generate U and X */
1334 S = floor(X); /* S is tentatively set to floor(X) */
1335 /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1336 tmp = (t + 1) / term;
1337 lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
1338 rhs = (((t + X) / (term + S)) * term) / t;
1344 /* Test if U <= f(S)/cg(X) */
1345 y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1349 numer_lim = term + S;
1353 denom = t - (double) n + S;
1356 for (numer = t + S; numer >= numer_lim; numer -= 1)
1361 W = exp(-log(random_fract()) / n); /* Generate W in advance */
1362 if (exp(log(y) / n) <= (t + X) / t)
1371 * qsort comparator for sorting rows[] array
1374 compare_rows(const void *a, const void *b)
1376 HeapTuple ha = *(HeapTuple *) a;
1377 HeapTuple hb = *(HeapTuple *) b;
1378 BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1379 OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1380 BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1381 OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1396 * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1398 * This has the same API as acquire_sample_rows, except that rows are
1399 * collected from all inheritance children as well as the specified table.
1400 * We fail and return zero if there are no inheritance children.
1403 acquire_inherited_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1404 double *totalrows, double *totaldeadrows)
1416 * Find all members of inheritance set. We only need AccessShareLock on
1420 find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
1423 * Check that there's at least one descendant, else fail. This could
1424 * happen despite analyze_rel's relhassubclass check, if table once had a
1425 * child but no longer does.
1427 if (list_length(tableOIDs) < 2)
1430 * XXX It would be desirable to clear relhassubclass here, but we
1431 * don't have adequate lock to do that safely.
1437 * Count the blocks in all the relations. The result could overflow
1438 * BlockNumber, so we use double arithmetic.
1440 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1441 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1444 foreach(lc, tableOIDs)
1446 Oid childOID = lfirst_oid(lc);
1449 /* We already got the needed lock */
1450 childrel = heap_open(childOID, NoLock);
1452 /* Ignore if temp table of another backend */
1453 if (RELATION_IS_OTHER_TEMP(childrel))
1455 /* ... but release the lock on it */
1456 Assert(childrel != onerel);
1457 heap_close(childrel, AccessShareLock);
1461 rels[nrels] = childrel;
1462 relblocks[nrels] = (double) RelationGetNumberOfBlocks(childrel);
1463 totalblocks += relblocks[nrels];
1468 * Now sample rows from each relation, proportionally to its fraction of
1469 * the total block count. (This might be less than desirable if the child
1470 * rels have radically different free-space percentages, but it's not
1471 * clear that it's worth working harder.)
1476 for (i = 0; i < nrels; i++)
1478 Relation childrel = rels[i];
1479 double childblocks = relblocks[i];
1481 if (childblocks > 0)
1485 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1486 /* Make sure we don't overrun due to roundoff error */
1487 childtargrows = Min(childtargrows, targrows - numrows);
1488 if (childtargrows > 0)
1494 /* Fetch a random sample of the child's rows */
1495 childrows = acquire_sample_rows(childrel,
1501 /* We may need to convert from child's rowtype to parent's */
1502 if (childrows > 0 &&
1503 !equalTupleDescs(RelationGetDescr(childrel),
1504 RelationGetDescr(onerel)))
1506 TupleConversionMap *map;
1508 map = convert_tuples_by_name(RelationGetDescr(childrel),
1509 RelationGetDescr(onerel),
1510 gettext_noop("could not convert row type"));
1515 for (j = 0; j < childrows; j++)
1519 newtup = do_convert_tuple(rows[numrows + j], map);
1520 heap_freetuple(rows[numrows + j]);
1521 rows[numrows + j] = newtup;
1523 free_conversion_map(map);
1527 /* And add to counts */
1528 numrows += childrows;
1529 *totalrows += trows;
1530 *totaldeadrows += tdrows;
1535 * Note: we cannot release the child-table locks, since we may have
1536 * pointers to their TOAST tables in the sampled rows.
1538 heap_close(childrel, NoLock);
1546 * update_attstats() -- update attribute statistics for one relation
1548 * Statistics are stored in several places: the pg_class row for the
1549 * relation has stats about the whole relation, and there is a
1550 * pg_statistic row for each (non-system) attribute that has ever
1551 * been analyzed. The pg_class values are updated by VACUUM, not here.
1553 * pg_statistic rows are just added or updated normally. This means
1554 * that pg_statistic will probably contain some deleted rows at the
1555 * completion of a vacuum cycle, unless it happens to get vacuumed last.
1557 * To keep things simple, we punt for pg_statistic, and don't try
1558 * to compute or store rows for pg_statistic itself in pg_statistic.
1559 * This could possibly be made to work, but it's not worth the trouble.
1560 * Note analyze_rel() has seen to it that we won't come here when
1561 * vacuuming pg_statistic itself.
1563 * Note: there would be a race condition here if two backends could
1564 * ANALYZE the same table concurrently. Presently, we lock that out
1565 * by taking a self-exclusive lock on the relation in analyze_rel().
1568 update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1574 return; /* nothing to do */
1576 sd = heap_open(StatisticRelationId, RowExclusiveLock);
1578 for (attno = 0; attno < natts; attno++)
1580 VacAttrStats *stats = vacattrstats[attno];
1586 Datum values[Natts_pg_statistic];
1587 bool nulls[Natts_pg_statistic];
1588 bool replaces[Natts_pg_statistic];
1590 /* Ignore attr if we weren't able to collect stats */
1591 if (!stats->stats_valid)
1595 * Construct a new pg_statistic tuple
1597 for (i = 0; i < Natts_pg_statistic; ++i)
1604 values[i++] = ObjectIdGetDatum(relid); /* starelid */
1605 values[i++] = Int16GetDatum(stats->attr->attnum); /* staattnum */
1606 values[i++] = BoolGetDatum(inh); /* stainherit */
1607 values[i++] = Float4GetDatum(stats->stanullfrac); /* stanullfrac */
1608 values[i++] = Int32GetDatum(stats->stawidth); /* stawidth */
1609 values[i++] = Float4GetDatum(stats->stadistinct); /* stadistinct */
1610 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1612 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1614 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1616 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1618 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1620 int nnum = stats->numnumbers[k];
1624 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1627 for (n = 0; n < nnum; n++)
1628 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1629 /* XXX knows more than it should about type float4: */
1630 arry = construct_array(numdatums, nnum,
1632 sizeof(float4), FLOAT4PASSBYVAL, 'i');
1633 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1638 values[i++] = (Datum) 0;
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 if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
1982 if (j < firstcount1 && track[j].count == 1)
1990 /* This value may now need to "bubble up" in the track list */
1991 while (j > 0 && track[j].count > track[j - 1].count)
1993 swapDatum(track[j].value, track[j - 1].value);
1994 swapInt(track[j].count, track[j - 1].count);
2000 /* No match. Insert at head of count-1 list */
2001 if (track_cnt < track_max)
2003 for (j = track_cnt - 1; j > firstcount1; j--)
2005 track[j].value = track[j - 1].value;
2006 track[j].count = track[j - 1].count;
2008 if (firstcount1 < track_cnt)
2010 track[firstcount1].value = value;
2011 track[firstcount1].count = 1;
2016 /* We can only compute real stats if we found some non-null values. */
2017 if (nonnull_cnt > 0)
2022 stats->stats_valid = true;
2023 /* Do the simple null-frac and width stats */
2024 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2026 stats->stawidth = total_width / (double) nonnull_cnt;
2028 stats->stawidth = stats->attrtype->typlen;
2030 /* Count the number of values we found multiple times */
2032 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2034 if (track[nmultiple].count == 1)
2036 summultiple += track[nmultiple].count;
2041 /* If we found no repeated values, assume it's a unique column */
2042 stats->stadistinct = -1.0;
2044 else if (track_cnt < track_max && toowide_cnt == 0 &&
2045 nmultiple == track_cnt)
2048 * Our track list includes every value in the sample, and every
2049 * value appeared more than once. Assume the column has just
2052 stats->stadistinct = track_cnt;
2057 * Estimate the number of distinct values using the estimator
2058 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2059 * n*d / (n - f1 + f1*n/N)
2060 * where f1 is the number of distinct values that occurred
2061 * exactly once in our sample of n rows (from a total of N),
2062 * and d is the total number of distinct values in the sample.
2063 * This is their Duj1 estimator; the other estimators they
2064 * recommend are considerably more complex, and are numerically
2065 * very unstable when n is much smaller than N.
2067 * We assume (not very reliably!) that all the multiply-occurring
2068 * values are reflected in the final track[] list, and the other
2069 * nonnull values all appeared but once. (XXX this usually
2070 * results in a drastic overestimate of ndistinct. Can we do
2074 int f1 = nonnull_cnt - summultiple;
2075 int d = f1 + nmultiple;
2080 numer = (double) samplerows *(double) d;
2082 denom = (double) (samplerows - f1) +
2083 (double) f1 *(double) samplerows / totalrows;
2085 stadistinct = numer / denom;
2086 /* Clamp to sane range in case of roundoff error */
2087 if (stadistinct < (double) d)
2088 stadistinct = (double) d;
2089 if (stadistinct > totalrows)
2090 stadistinct = totalrows;
2091 stats->stadistinct = floor(stadistinct + 0.5);
2095 * If we estimated the number of distinct values at more than 10% of
2096 * the total row count (a very arbitrary limit), then assume that
2097 * stadistinct should scale with the row count rather than be a fixed
2100 if (stats->stadistinct > 0.1 * totalrows)
2101 stats->stadistinct = -(stats->stadistinct / totalrows);
2104 * Decide how many values are worth storing as most-common values. If
2105 * we are able to generate a complete MCV list (all the values in the
2106 * sample will fit, and we think these are all the ones in the table),
2107 * then do so. Otherwise, store only those values that are
2108 * significantly more common than the (estimated) average. We set the
2109 * threshold rather arbitrarily at 25% more than average, with at
2110 * least 2 instances in the sample.
2112 if (track_cnt < track_max && toowide_cnt == 0 &&
2113 stats->stadistinct > 0 &&
2114 track_cnt <= num_mcv)
2116 /* Track list includes all values seen, and all will fit */
2117 num_mcv = track_cnt;
2121 double ndistinct = stats->stadistinct;
2126 ndistinct = -ndistinct * totalrows;
2127 /* estimate # of occurrences in sample of a typical value */
2128 avgcount = (double) samplerows / ndistinct;
2129 /* set minimum threshold count to store a value */
2130 mincount = avgcount * 1.25;
2133 if (num_mcv > track_cnt)
2134 num_mcv = track_cnt;
2135 for (i = 0; i < num_mcv; i++)
2137 if (track[i].count < mincount)
2145 /* Generate MCV slot entry */
2148 MemoryContext old_context;
2152 /* Must copy the target values into anl_context */
2153 old_context = MemoryContextSwitchTo(stats->anl_context);
2154 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2155 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2156 for (i = 0; i < num_mcv; i++)
2158 mcv_values[i] = datumCopy(track[i].value,
2159 stats->attrtype->typbyval,
2160 stats->attrtype->typlen);
2161 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2163 MemoryContextSwitchTo(old_context);
2165 stats->stakind[0] = STATISTIC_KIND_MCV;
2166 stats->staop[0] = mystats->eqopr;
2167 stats->stanumbers[0] = mcv_freqs;
2168 stats->numnumbers[0] = num_mcv;
2169 stats->stavalues[0] = mcv_values;
2170 stats->numvalues[0] = num_mcv;
2173 * Accept the defaults for stats->statypid and others. They have
2174 * been set before we were called (see vacuum.h)
2178 else if (null_cnt > 0)
2180 /* We found only nulls; assume the column is entirely null */
2181 stats->stats_valid = true;
2182 stats->stanullfrac = 1.0;
2184 stats->stawidth = 0; /* "unknown" */
2186 stats->stawidth = stats->attrtype->typlen;
2187 stats->stadistinct = 0.0; /* "unknown" */
2190 /* We don't need to bother cleaning up any of our temporary palloc's */
2195 * compute_scalar_stats() -- compute column statistics
2197 * We use this when we can find "=" and "<" operators for the datatype.
2199 * We determine the fraction of non-null rows, the average width, the
2200 * most common values, the (estimated) number of distinct values, the
2201 * distribution histogram, and the correlation of physical to logical order.
2203 * The desired stats can be determined fairly easily after sorting the
2204 * data values into order.
2207 compute_scalar_stats(VacAttrStatsP stats,
2208 AnalyzeAttrFetchFunc fetchfunc,
2214 int nonnull_cnt = 0;
2215 int toowide_cnt = 0;
2216 double total_width = 0;
2217 bool is_varlena = (!stats->attrtype->typbyval &&
2218 stats->attrtype->typlen == -1);
2219 bool is_varwidth = (!stats->attrtype->typbyval &&
2220 stats->attrtype->typlen < 0);
2228 ScalarMCVItem *track;
2230 int num_mcv = stats->attr->attstattarget;
2231 int num_bins = stats->attr->attstattarget;
2232 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2234 values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2235 tupnoLink = (int *) palloc(samplerows * sizeof(int));
2236 track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2238 SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
2239 fmgr_info(cmpFn, &f_cmpfn);
2241 /* Initial scan to find sortable values */
2242 for (i = 0; i < samplerows; i++)
2247 vacuum_delay_point();
2249 value = fetchfunc(stats, i, &isnull);
2251 /* Check for null/nonnull */
2260 * If it's a variable-width field, add up widths for average width
2261 * calculation. Note that if the value is toasted, we use the toasted
2262 * width. We don't bother with this calculation if it's a fixed-width
2267 total_width += VARSIZE_ANY(DatumGetPointer(value));
2270 * If the value is toasted, we want to detoast it just once to
2271 * avoid repeated detoastings and resultant excess memory usage
2272 * during the comparisons. Also, check to see if the value is
2273 * excessively wide, and if so don't detoast at all --- just
2276 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2281 value = PointerGetDatum(PG_DETOAST_DATUM(value));
2283 else if (is_varwidth)
2285 /* must be cstring */
2286 total_width += strlen(DatumGetCString(value)) + 1;
2289 /* Add it to the list to be sorted */
2290 values[values_cnt].value = value;
2291 values[values_cnt].tupno = values_cnt;
2292 tupnoLink[values_cnt] = values_cnt;
2296 /* We can only compute real stats if we found some sortable values. */
2299 int ndistinct, /* # distinct values in sample */
2300 nmultiple, /* # that appear multiple times */
2304 CompareScalarsContext cxt;
2306 /* Sort the collected values */
2307 cxt.cmpFn = &f_cmpfn;
2308 cxt.cmpFlags = cmpFlags;
2309 cxt.tupnoLink = tupnoLink;
2310 qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2311 compare_scalars, (void *) &cxt);
2314 * Now scan the values in order, find the most common ones, and also
2315 * accumulate ordering-correlation statistics.
2317 * To determine which are most common, we first have to count the
2318 * number of duplicates of each value. The duplicates are adjacent in
2319 * the sorted list, so a brute-force approach is to compare successive
2320 * datum values until we find two that are not equal. However, that
2321 * requires N-1 invocations of the datum comparison routine, which are
2322 * completely redundant with work that was done during the sort. (The
2323 * sort algorithm must at some point have compared each pair of items
2324 * that are adjacent in the sorted order; otherwise it could not know
2325 * that it's ordered the pair correctly.) We exploit this by having
2326 * compare_scalars remember the highest tupno index that each
2327 * ScalarItem has been found equal to. At the end of the sort, a
2328 * ScalarItem's tupnoLink will still point to itself if and only if it
2329 * is the last item of its group of duplicates (since the group will
2330 * be ordered by tupno).
2336 for (i = 0; i < values_cnt; i++)
2338 int tupno = values[i].tupno;
2340 corr_xysum += ((double) i) * ((double) tupno);
2342 if (tupnoLink[tupno] == tupno)
2344 /* Reached end of duplicates of this value */
2349 if (track_cnt < num_mcv ||
2350 dups_cnt > track[track_cnt - 1].count)
2353 * Found a new item for the mcv list; find its
2354 * position, bubbling down old items if needed. Loop
2355 * invariant is that j points at an empty/ replaceable
2360 if (track_cnt < num_mcv)
2362 for (j = track_cnt - 1; j > 0; j--)
2364 if (dups_cnt <= track[j - 1].count)
2366 track[j].count = track[j - 1].count;
2367 track[j].first = track[j - 1].first;
2369 track[j].count = dups_cnt;
2370 track[j].first = i + 1 - dups_cnt;
2377 stats->stats_valid = true;
2378 /* Do the simple null-frac and width stats */
2379 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2381 stats->stawidth = total_width / (double) nonnull_cnt;
2383 stats->stawidth = stats->attrtype->typlen;
2387 /* If we found no repeated values, assume it's a unique column */
2388 stats->stadistinct = -1.0;
2390 else if (toowide_cnt == 0 && nmultiple == ndistinct)
2393 * Every value in the sample appeared more than once. Assume the
2394 * column has just these values.
2396 stats->stadistinct = ndistinct;
2401 * Estimate the number of distinct values using the estimator
2402 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2403 * n*d / (n - f1 + f1*n/N)
2404 * where f1 is the number of distinct values that occurred
2405 * exactly once in our sample of n rows (from a total of N),
2406 * and d is the total number of distinct values in the sample.
2407 * This is their Duj1 estimator; the other estimators they
2408 * recommend are considerably more complex, and are numerically
2409 * very unstable when n is much smaller than N.
2411 * Overwidth values are assumed to have been distinct.
2414 int f1 = ndistinct - nmultiple + toowide_cnt;
2415 int d = f1 + nmultiple;
2420 numer = (double) samplerows *(double) d;
2422 denom = (double) (samplerows - f1) +
2423 (double) f1 *(double) samplerows / totalrows;
2425 stadistinct = numer / denom;
2426 /* Clamp to sane range in case of roundoff error */
2427 if (stadistinct < (double) d)
2428 stadistinct = (double) d;
2429 if (stadistinct > totalrows)
2430 stadistinct = totalrows;
2431 stats->stadistinct = floor(stadistinct + 0.5);
2435 * If we estimated the number of distinct values at more than 10% of
2436 * the total row count (a very arbitrary limit), then assume that
2437 * stadistinct should scale with the row count rather than be a fixed
2440 if (stats->stadistinct > 0.1 * totalrows)
2441 stats->stadistinct = -(stats->stadistinct / totalrows);
2444 * Decide how many values are worth storing as most-common values. If
2445 * we are able to generate a complete MCV list (all the values in the
2446 * sample will fit, and we think these are all the ones in the table),
2447 * then do so. Otherwise, store only those values that are
2448 * significantly more common than the (estimated) average. We set the
2449 * threshold rather arbitrarily at 25% more than average, with at
2450 * least 2 instances in the sample. Also, we won't suppress values
2451 * that have a frequency of at least 1/K where K is the intended
2452 * number of histogram bins; such values might otherwise cause us to
2453 * emit duplicate histogram bin boundaries. (We might end up with
2454 * duplicate histogram entries anyway, if the distribution is skewed;
2455 * but we prefer to treat such values as MCVs if at all possible.)
2457 if (track_cnt == ndistinct && toowide_cnt == 0 &&
2458 stats->stadistinct > 0 &&
2459 track_cnt <= num_mcv)
2461 /* Track list includes all values seen, and all will fit */
2462 num_mcv = track_cnt;
2466 double ndistinct = stats->stadistinct;
2472 ndistinct = -ndistinct * totalrows;
2473 /* estimate # of occurrences in sample of a typical value */
2474 avgcount = (double) samplerows / ndistinct;
2475 /* set minimum threshold count to store a value */
2476 mincount = avgcount * 1.25;
2479 /* don't let threshold exceed 1/K, however */
2480 maxmincount = (double) samplerows / (double) num_bins;
2481 if (mincount > maxmincount)
2482 mincount = maxmincount;
2483 if (num_mcv > track_cnt)
2484 num_mcv = track_cnt;
2485 for (i = 0; i < num_mcv; i++)
2487 if (track[i].count < mincount)
2495 /* Generate MCV slot entry */
2498 MemoryContext old_context;
2502 /* Must copy the target values into anl_context */
2503 old_context = MemoryContextSwitchTo(stats->anl_context);
2504 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2505 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2506 for (i = 0; i < num_mcv; i++)
2508 mcv_values[i] = datumCopy(values[track[i].first].value,
2509 stats->attrtype->typbyval,
2510 stats->attrtype->typlen);
2511 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2513 MemoryContextSwitchTo(old_context);
2515 stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2516 stats->staop[slot_idx] = mystats->eqopr;
2517 stats->stanumbers[slot_idx] = mcv_freqs;
2518 stats->numnumbers[slot_idx] = num_mcv;
2519 stats->stavalues[slot_idx] = mcv_values;
2520 stats->numvalues[slot_idx] = num_mcv;
2523 * Accept the defaults for stats->statypid and others. They have
2524 * been set before we were called (see vacuum.h)
2530 * Generate a histogram slot entry if there are at least two distinct
2531 * values not accounted for in the MCV list. (This ensures the
2532 * histogram won't collapse to empty or a singleton.)
2534 num_hist = ndistinct - num_mcv;
2535 if (num_hist > num_bins)
2536 num_hist = num_bins + 1;
2539 MemoryContext old_context;
2547 /* Sort the MCV items into position order to speed next loop */
2548 qsort((void *) track, num_mcv,
2549 sizeof(ScalarMCVItem), compare_mcvs);
2552 * Collapse out the MCV items from the values[] array.
2554 * Note we destroy the values[] array here... but we don't need it
2555 * for anything more. We do, however, still need values_cnt.
2556 * nvals will be the number of remaining entries in values[].
2565 j = 0; /* index of next interesting MCV item */
2566 while (src < values_cnt)
2572 int first = track[j].first;
2576 /* advance past this MCV item */
2577 src = first + track[j].count;
2581 ncopy = first - src;
2584 ncopy = values_cnt - src;
2585 memmove(&values[dest], &values[src],
2586 ncopy * sizeof(ScalarItem));
2594 Assert(nvals >= num_hist);
2596 /* Must copy the target values into anl_context */
2597 old_context = MemoryContextSwitchTo(stats->anl_context);
2598 hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2601 * The object of this loop is to copy the first and last values[]
2602 * entries along with evenly-spaced values in between. So the
2603 * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2604 * computing that subscript directly risks integer overflow when
2605 * the stats target is more than a couple thousand. Instead we
2606 * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2607 * the integral and fractional parts of the sum separately.
2609 delta = (nvals - 1) / (num_hist - 1);
2610 deltafrac = (nvals - 1) % (num_hist - 1);
2613 for (i = 0; i < num_hist; i++)
2615 hist_values[i] = datumCopy(values[pos].value,
2616 stats->attrtype->typbyval,
2617 stats->attrtype->typlen);
2619 posfrac += deltafrac;
2620 if (posfrac >= (num_hist - 1))
2622 /* fractional part exceeds 1, carry to integer part */
2624 posfrac -= (num_hist - 1);
2628 MemoryContextSwitchTo(old_context);
2630 stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2631 stats->staop[slot_idx] = mystats->ltopr;
2632 stats->stavalues[slot_idx] = hist_values;
2633 stats->numvalues[slot_idx] = num_hist;
2636 * Accept the defaults for stats->statypid and others. They have
2637 * been set before we were called (see vacuum.h)
2642 /* Generate a correlation entry if there are multiple values */
2645 MemoryContext old_context;
2650 /* Must copy the target values into anl_context */
2651 old_context = MemoryContextSwitchTo(stats->anl_context);
2652 corrs = (float4 *) palloc(sizeof(float4));
2653 MemoryContextSwitchTo(old_context);
2656 * Since we know the x and y value sets are both
2657 * 0, 1, ..., values_cnt-1
2658 * we have sum(x) = sum(y) =
2659 * (values_cnt-1)*values_cnt / 2
2660 * and sum(x^2) = sum(y^2) =
2661 * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2664 corr_xsum = ((double) (values_cnt - 1)) *
2665 ((double) values_cnt) / 2.0;
2666 corr_x2sum = ((double) (values_cnt - 1)) *
2667 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2669 /* And the correlation coefficient reduces to */
2670 corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2671 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2673 stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2674 stats->staop[slot_idx] = mystats->ltopr;
2675 stats->stanumbers[slot_idx] = corrs;
2676 stats->numnumbers[slot_idx] = 1;
2680 else if (nonnull_cnt == 0 && null_cnt > 0)
2682 /* We found only nulls; assume the column is entirely null */
2683 stats->stats_valid = true;
2684 stats->stanullfrac = 1.0;
2686 stats->stawidth = 0; /* "unknown" */
2688 stats->stawidth = stats->attrtype->typlen;
2689 stats->stadistinct = 0.0; /* "unknown" */
2692 /* We don't need to bother cleaning up any of our temporary palloc's */
2696 * qsort_arg comparator for sorting ScalarItems
2698 * Aside from sorting the items, we update the tupnoLink[] array
2699 * whenever two ScalarItems are found to contain equal datums. The array
2700 * is indexed by tupno; for each ScalarItem, it contains the highest
2701 * tupno that that item's datum has been found to be equal to. This allows
2702 * us to avoid additional comparisons in compute_scalar_stats().
2705 compare_scalars(const void *a, const void *b, void *arg)
2707 Datum da = ((ScalarItem *) a)->value;
2708 int ta = ((ScalarItem *) a)->tupno;
2709 Datum db = ((ScalarItem *) b)->value;
2710 int tb = ((ScalarItem *) b)->tupno;
2711 CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2714 compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2715 da, false, db, false);
2720 * The two datums are equal, so update cxt->tupnoLink[].
2722 if (cxt->tupnoLink[ta] < tb)
2723 cxt->tupnoLink[ta] = tb;
2724 if (cxt->tupnoLink[tb] < ta)
2725 cxt->tupnoLink[tb] = ta;
2728 * For equal datums, sort by tupno
2734 * qsort comparator for sorting ScalarMCVItems by position
2737 compare_mcvs(const void *a, const void *b)
2739 int da = ((ScalarMCVItem *) a)->first;
2740 int db = ((ScalarMCVItem *) b)->first;