1 /*-------------------------------------------------------------------------
4 * the Postgres statistics generator
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/analyze.c
13 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "access/transam.h"
21 #include "access/tupconvert.h"
22 #include "access/tuptoaster.h"
23 #include "access/xact.h"
24 #include "catalog/index.h"
25 #include "catalog/indexing.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_collation.h"
28 #include "catalog/pg_inherits_fn.h"
29 #include "catalog/pg_namespace.h"
30 #include "commands/dbcommands.h"
31 #include "commands/vacuum.h"
32 #include "executor/executor.h"
33 #include "miscadmin.h"
34 #include "nodes/nodeFuncs.h"
35 #include "parser/parse_oper.h"
36 #include "parser/parse_relation.h"
38 #include "postmaster/autovacuum.h"
39 #include "storage/bufmgr.h"
40 #include "storage/lmgr.h"
41 #include "storage/proc.h"
42 #include "storage/procarray.h"
43 #include "utils/acl.h"
44 #include "utils/attoptcache.h"
45 #include "utils/datum.h"
46 #include "utils/guc.h"
47 #include "utils/lsyscache.h"
48 #include "utils/memutils.h"
49 #include "utils/pg_rusage.h"
50 #include "utils/syscache.h"
51 #include "utils/tuplesort.h"
52 #include "utils/tqual.h"
55 /* Data structure for Algorithm S from Knuth 3.4.2 */
58 BlockNumber N; /* number of blocks, known in advance */
59 int n; /* desired sample size */
60 BlockNumber t; /* current block number */
61 int m; /* blocks selected so far */
64 typedef BlockSamplerData *BlockSampler;
66 /* Per-index data for ANALYZE */
67 typedef struct AnlIndexData
69 IndexInfo *indexInfo; /* BuildIndexInfo result */
70 double tupleFract; /* fraction of rows for partial index */
71 VacAttrStats **vacattrstats; /* index attrs to analyze */
76 /* Default statistics target (GUC parameter) */
77 int default_statistics_target = 100;
79 /* A few variables that don't seem worth passing around as parameters */
80 static int elevel = -1;
82 static MemoryContext anl_context = NULL;
84 static BufferAccessStrategy vac_strategy;
87 static void do_analyze_rel(Relation onerel, VacuumStmt *vacstmt, bool inh);
88 static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
90 static bool BlockSampler_HasMore(BlockSampler bs);
91 static BlockNumber BlockSampler_Next(BlockSampler bs);
92 static void compute_index_stats(Relation onerel, double totalrows,
93 AnlIndexData *indexdata, int nindexes,
94 HeapTuple *rows, int numrows,
95 MemoryContext col_context);
96 static VacAttrStats *examine_attribute(Relation onerel, int attnum,
98 static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
99 int targrows, double *totalrows, double *totaldeadrows);
100 static double random_fract(void);
101 static double init_selection_state(int n);
102 static double get_next_S(double t, int n, double *stateptr);
103 static int compare_rows(const void *a, const void *b);
104 static int acquire_inherited_sample_rows(Relation onerel,
105 HeapTuple *rows, int targrows,
106 double *totalrows, double *totaldeadrows);
107 static void update_attstats(Oid relid, bool inh,
108 int natts, VacAttrStats **vacattrstats);
109 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
110 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
112 static bool std_typanalyze(VacAttrStats *stats);
116 * analyze_rel() -- analyze one relation
119 analyze_rel(Oid relid, VacuumStmt *vacstmt, BufferAccessStrategy bstrategy)
123 /* Set up static variables */
124 if (vacstmt->options & VACOPT_VERBOSE)
129 vac_strategy = bstrategy;
132 * Check for user-requested abort.
134 CHECK_FOR_INTERRUPTS();
137 * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
138 * ANALYZEs don't run on it concurrently. (This also locks out a
139 * concurrent VACUUM, which doesn't matter much at the moment but might
140 * matter if we ever try to accumulate stats on dead tuples.) If the rel
141 * has been dropped since we last saw it, we don't need to process it.
143 if (!(vacstmt->options & VACOPT_NOWAIT))
144 onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
145 else if (ConditionalLockRelationOid(relid, ShareUpdateExclusiveLock))
146 onerel = try_relation_open(relid, NoLock);
150 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
152 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
153 errmsg("skipping analyze of \"%s\" --- lock not available",
154 vacstmt->relation->relname)));
160 * Check permissions --- this should match vacuum's check!
162 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
163 (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
165 /* No need for a WARNING if we already complained during VACUUM */
166 if (!(vacstmt->options & VACOPT_VACUUM))
168 if (onerel->rd_rel->relisshared)
170 (errmsg("skipping \"%s\" --- only superuser can analyze it",
171 RelationGetRelationName(onerel))));
172 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
174 (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
175 RelationGetRelationName(onerel))));
178 (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
179 RelationGetRelationName(onerel))));
181 relation_close(onerel, ShareUpdateExclusiveLock);
186 * Check that it's a plain table; we used to do this in get_rel_oids() but
187 * seems safer to check after we've locked the relation.
189 if (onerel->rd_rel->relkind != RELKIND_RELATION)
191 /* No need for a WARNING if we already complained during VACUUM */
192 if (!(vacstmt->options & VACOPT_VACUUM))
194 (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
195 RelationGetRelationName(onerel))));
196 relation_close(onerel, ShareUpdateExclusiveLock);
201 * Silently ignore tables that are temp tables of other backends ---
202 * trying to analyze these is rather pointless, since their contents are
203 * probably not up-to-date on disk. (We don't throw a warning here; it
204 * would just lead to chatter during a database-wide ANALYZE.)
206 if (RELATION_IS_OTHER_TEMP(onerel))
208 relation_close(onerel, ShareUpdateExclusiveLock);
213 * We can ANALYZE any table except pg_statistic. See update_attstats
215 if (RelationGetRelid(onerel) == StatisticRelationId)
217 relation_close(onerel, ShareUpdateExclusiveLock);
222 * OK, let's do it. First let other backends know I'm in ANALYZE.
224 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
225 MyProc->vacuumFlags |= PROC_IN_ANALYZE;
226 LWLockRelease(ProcArrayLock);
229 * Do the normal non-recursive ANALYZE.
231 do_analyze_rel(onerel, vacstmt, false);
234 * If there are child tables, do recursive ANALYZE.
236 if (onerel->rd_rel->relhassubclass)
237 do_analyze_rel(onerel, vacstmt, true);
240 * Close source relation now, but keep lock so that no one deletes it
241 * before we commit. (If someone did, they'd fail to clean up the entries
242 * we made in pg_statistic. Also, releasing the lock before commit would
243 * expose us to concurrent-update failures in update_attstats.)
245 relation_close(onerel, NoLock);
248 * Reset my PGPROC flag. Note: we need this here, and not in vacuum_rel,
249 * because the vacuum flag is cleared by the end-of-xact code.
251 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
252 MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
253 LWLockRelease(ProcArrayLock);
257 * do_analyze_rel() -- analyze one relation, recursively or not
260 do_analyze_rel(Relation onerel, VacuumStmt *vacstmt, bool inh)
269 bool analyzableindex;
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);
383 analyzableindex = false;
386 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
387 for (ind = 0; ind < nindexes; ind++)
389 AnlIndexData *thisdata = &indexdata[ind];
390 IndexInfo *indexInfo;
392 thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
393 thisdata->tupleFract = 1.0; /* fix later if partial */
394 if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
396 ListCell *indexpr_item = list_head(indexInfo->ii_Expressions);
398 thisdata->vacattrstats = (VacAttrStats **)
399 palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
401 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
403 int keycol = indexInfo->ii_KeyAttrNumbers[i];
407 /* Found an index expression */
410 if (indexpr_item == NULL) /* shouldn't happen */
411 elog(ERROR, "too few entries in indexprs list");
412 indexkey = (Node *) lfirst(indexpr_item);
413 indexpr_item = lnext(indexpr_item);
414 thisdata->vacattrstats[tcnt] =
415 examine_attribute(Irel[ind], i + 1, indexkey);
416 if (thisdata->vacattrstats[tcnt] != NULL)
419 analyzableindex = true;
423 thisdata->attr_cnt = tcnt;
429 * Quit if no analyzable columns.
431 if (attr_cnt <= 0 && !analyzableindex)
435 * Determine how many rows we need to sample, using the worst case from
436 * all analyzable columns. We use a lower bound of 100 rows to avoid
437 * possible overflow in Vitter's algorithm.
440 for (i = 0; i < attr_cnt; i++)
442 if (targrows < vacattrstats[i]->minrows)
443 targrows = vacattrstats[i]->minrows;
445 for (ind = 0; ind < nindexes; ind++)
447 AnlIndexData *thisdata = &indexdata[ind];
449 for (i = 0; i < thisdata->attr_cnt; i++)
451 if (targrows < thisdata->vacattrstats[i]->minrows)
452 targrows = thisdata->vacattrstats[i]->minrows;
457 * Acquire the sample rows
459 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
461 numrows = acquire_inherited_sample_rows(onerel, rows, targrows,
462 &totalrows, &totaldeadrows);
464 numrows = acquire_sample_rows(onerel, rows, targrows,
465 &totalrows, &totaldeadrows);
468 * Compute the statistics. Temporary results during the calculations for
469 * each column are stored in a child context. The calc routines are
470 * responsible to make sure that whatever they store into the VacAttrStats
471 * structure is allocated in anl_context.
475 MemoryContext col_context,
478 col_context = AllocSetContextCreate(anl_context,
480 ALLOCSET_DEFAULT_MINSIZE,
481 ALLOCSET_DEFAULT_INITSIZE,
482 ALLOCSET_DEFAULT_MAXSIZE);
483 old_context = MemoryContextSwitchTo(col_context);
485 for (i = 0; i < attr_cnt; i++)
487 VacAttrStats *stats = vacattrstats[i];
488 AttributeOpts *aopt =
489 get_attribute_options(onerel->rd_id, stats->attr->attnum);
492 stats->tupDesc = onerel->rd_att;
493 (*stats->compute_stats) (stats,
499 * If the appropriate flavor of the n_distinct option is
500 * specified, override with the corresponding value.
505 inh ? aopt->n_distinct_inherited : aopt->n_distinct;
507 if (n_distinct != 0.0)
508 stats->stadistinct = n_distinct;
511 MemoryContextResetAndDeleteChildren(col_context);
515 compute_index_stats(onerel, totalrows,
520 MemoryContextSwitchTo(old_context);
521 MemoryContextDelete(col_context);
524 * Emit the completed stats rows into pg_statistic, replacing any
525 * previous statistics for the target columns. (If there are stats in
526 * pg_statistic for columns we didn't process, we leave them alone.)
528 update_attstats(RelationGetRelid(onerel), inh,
529 attr_cnt, vacattrstats);
531 for (ind = 0; ind < nindexes; ind++)
533 AnlIndexData *thisdata = &indexdata[ind];
535 update_attstats(RelationGetRelid(Irel[ind]), false,
536 thisdata->attr_cnt, thisdata->vacattrstats);
541 * Update pages/tuples stats in pg_class ... but not if we're doing
545 vac_update_relstats(onerel,
546 RelationGetNumberOfBlocks(onerel),
547 totalrows, hasindex, InvalidTransactionId);
550 * Same for indexes. Vacuum always scans all indexes, so if we're part of
551 * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
554 if (!inh && !(vacstmt->options & VACOPT_VACUUM))
556 for (ind = 0; ind < nindexes; ind++)
558 AnlIndexData *thisdata = &indexdata[ind];
559 double totalindexrows;
561 totalindexrows = ceil(thisdata->tupleFract * totalrows);
562 vac_update_relstats(Irel[ind],
563 RelationGetNumberOfBlocks(Irel[ind]),
564 totalindexrows, false, InvalidTransactionId);
569 * Report ANALYZE to the stats collector, too. However, if doing
570 * inherited stats we shouldn't report, because the stats collector only
571 * tracks per-table stats.
574 pgstat_report_analyze(onerel, totalrows, totaldeadrows);
576 /* We skip to here if there were no analyzable columns */
579 /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
580 if (!(vacstmt->options & VACOPT_VACUUM))
582 for (ind = 0; ind < nindexes; ind++)
584 IndexBulkDeleteResult *stats;
585 IndexVacuumInfo ivinfo;
587 ivinfo.index = Irel[ind];
588 ivinfo.analyze_only = true;
589 ivinfo.estimated_count = true;
590 ivinfo.message_level = elevel;
591 ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
592 ivinfo.strategy = vac_strategy;
594 stats = index_vacuum_cleanup(&ivinfo, NULL);
601 /* Done with indexes */
602 vac_close_indexes(nindexes, Irel, NoLock);
604 /* Log the action if appropriate */
605 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
607 if (Log_autovacuum_min_duration == 0 ||
608 TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
609 Log_autovacuum_min_duration))
611 (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
612 get_database_name(MyDatabaseId),
613 get_namespace_name(RelationGetNamespace(onerel)),
614 RelationGetRelationName(onerel),
615 pg_rusage_show(&ru0))));
618 /* Roll back any GUC changes executed by index functions */
619 AtEOXact_GUC(false, save_nestlevel);
621 /* Restore userid and security context */
622 SetUserIdAndSecContext(save_userid, save_sec_context);
624 /* Restore current context and release memory */
625 MemoryContextSwitchTo(caller_context);
626 MemoryContextDelete(anl_context);
631 * Compute statistics about indexes of a relation
634 compute_index_stats(Relation onerel, double totalrows,
635 AnlIndexData *indexdata, int nindexes,
636 HeapTuple *rows, int numrows,
637 MemoryContext col_context)
639 MemoryContext ind_context,
641 Datum values[INDEX_MAX_KEYS];
642 bool isnull[INDEX_MAX_KEYS];
646 ind_context = AllocSetContextCreate(anl_context,
648 ALLOCSET_DEFAULT_MINSIZE,
649 ALLOCSET_DEFAULT_INITSIZE,
650 ALLOCSET_DEFAULT_MAXSIZE);
651 old_context = MemoryContextSwitchTo(ind_context);
653 for (ind = 0; ind < nindexes; ind++)
655 AnlIndexData *thisdata = &indexdata[ind];
656 IndexInfo *indexInfo = thisdata->indexInfo;
657 int attr_cnt = thisdata->attr_cnt;
658 TupleTableSlot *slot;
660 ExprContext *econtext;
667 double totalindexrows;
669 /* Ignore index if no columns to analyze and not partial */
670 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
674 * Need an EState for evaluation of index expressions and
675 * partial-index predicates. Create it in the per-index context to be
676 * sure it gets cleaned up at the bottom of the loop.
678 estate = CreateExecutorState();
679 econtext = GetPerTupleExprContext(estate);
680 /* Need a slot to hold the current heap tuple, too */
681 slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
683 /* Arrange for econtext's scan tuple to be the tuple under test */
684 econtext->ecxt_scantuple = slot;
686 /* Set up execution state for predicate. */
688 ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
691 /* Compute and save index expression values */
692 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
693 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
696 for (rowno = 0; rowno < numrows; rowno++)
698 HeapTuple heapTuple = rows[rowno];
701 * Reset the per-tuple context each time, to reclaim any cruft
702 * left behind by evaluating the predicate or index expressions.
704 ResetExprContext(econtext);
706 /* Set up for predicate or expression evaluation */
707 ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
709 /* If index is partial, check predicate */
710 if (predicate != NIL)
712 if (!ExecQual(predicate, econtext, false))
720 * Evaluate the index row to compute expression values. We
721 * could do this by hand, but FormIndexDatum is convenient.
723 FormIndexDatum(indexInfo,
730 * Save just the columns we care about. We copy the values
731 * into ind_context from the estate's per-tuple context.
733 for (i = 0; i < attr_cnt; i++)
735 VacAttrStats *stats = thisdata->vacattrstats[i];
736 int attnum = stats->attr->attnum;
738 if (isnull[attnum - 1])
740 exprvals[tcnt] = (Datum) 0;
741 exprnulls[tcnt] = true;
745 exprvals[tcnt] = datumCopy(values[attnum - 1],
746 stats->attrtype->typbyval,
747 stats->attrtype->typlen);
748 exprnulls[tcnt] = false;
756 * Having counted the number of rows that pass the predicate in the
757 * sample, we can estimate the total number of rows in the index.
759 thisdata->tupleFract = (double) numindexrows / (double) numrows;
760 totalindexrows = ceil(thisdata->tupleFract * totalrows);
763 * Now we can compute the statistics for the expression columns.
765 if (numindexrows > 0)
767 MemoryContextSwitchTo(col_context);
768 for (i = 0; i < attr_cnt; i++)
770 VacAttrStats *stats = thisdata->vacattrstats[i];
771 AttributeOpts *aopt =
772 get_attribute_options(stats->attr->attrelid,
773 stats->attr->attnum);
775 stats->exprvals = exprvals + i;
776 stats->exprnulls = exprnulls + i;
777 stats->rowstride = attr_cnt;
778 (*stats->compute_stats) (stats,
784 * If the n_distinct option is specified, it overrides the
785 * above computation. For indices, we always use just
786 * n_distinct, not n_distinct_inherited.
788 if (aopt != NULL && aopt->n_distinct != 0.0)
789 stats->stadistinct = aopt->n_distinct;
791 MemoryContextResetAndDeleteChildren(col_context);
796 MemoryContextSwitchTo(ind_context);
798 ExecDropSingleTupleTableSlot(slot);
799 FreeExecutorState(estate);
800 MemoryContextResetAndDeleteChildren(ind_context);
803 MemoryContextSwitchTo(old_context);
804 MemoryContextDelete(ind_context);
808 * examine_attribute -- pre-analysis of a single column
810 * Determine whether the column is analyzable; if so, create and initialize
811 * a VacAttrStats struct for it. If not, return NULL.
813 * If index_expr isn't NULL, then we're trying to analyze an expression index,
814 * and index_expr is the expression tree representing the column's data.
816 static VacAttrStats *
817 examine_attribute(Relation onerel, int attnum, Node *index_expr)
819 Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
825 /* Never analyze dropped columns */
826 if (attr->attisdropped)
829 /* Don't analyze column if user has specified not to */
830 if (attr->attstattarget == 0)
834 * Create the VacAttrStats struct. Note that we only have a copy of the
835 * fixed fields of the pg_attribute tuple.
837 stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
838 stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
839 memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
842 * When analyzing an expression index, believe the expression tree's type
843 * not the column datatype --- the latter might be the opckeytype storage
844 * type of the opclass, which is not interesting for our purposes. (Note:
845 * if we did anything with non-expression index columns, we'd need to
846 * figure out where to get the correct type info from, but for now that's
847 * not a problem.) It's not clear whether anyone will care about the
848 * typmod, but we store that too just in case.
852 stats->attrtypid = exprType(index_expr);
853 stats->attrtypmod = exprTypmod(index_expr);
857 stats->attrtypid = attr->atttypid;
858 stats->attrtypmod = attr->atttypmod;
861 typtuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(stats->attrtypid));
862 if (!HeapTupleIsValid(typtuple))
863 elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
864 stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
865 memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
866 ReleaseSysCache(typtuple);
867 stats->anl_context = anl_context;
868 stats->tupattnum = attnum;
871 * The fields describing the stats->stavalues[n] element types default to
872 * the type of the data being analyzed, but the type-specific typanalyze
873 * function can change them if it wants to store something else.
875 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
877 stats->statypid[i] = stats->attrtypid;
878 stats->statyplen[i] = stats->attrtype->typlen;
879 stats->statypbyval[i] = stats->attrtype->typbyval;
880 stats->statypalign[i] = stats->attrtype->typalign;
884 * Call the type-specific typanalyze function. If none is specified, use
887 if (OidIsValid(stats->attrtype->typanalyze))
888 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
889 PointerGetDatum(stats)));
891 ok = std_typanalyze(stats);
893 if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
895 pfree(stats->attrtype);
905 * BlockSampler_Init -- prepare for random sampling of blocknumbers
907 * BlockSampler is used for stage one of our new two-stage tuple
908 * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
909 * "Large DB"). It selects a random sample of samplesize blocks out of
910 * the nblocks blocks in the table. If the table has less than
911 * samplesize blocks, all blocks are selected.
913 * Since we know the total number of blocks in advance, we can use the
914 * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
918 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
920 bs->N = nblocks; /* measured table size */
923 * If we decide to reduce samplesize for tables that have less or not much
924 * more than samplesize blocks, here is the place to do it.
927 bs->t = 0; /* blocks scanned so far */
928 bs->m = 0; /* blocks selected so far */
932 BlockSampler_HasMore(BlockSampler bs)
934 return (bs->t < bs->N) && (bs->m < bs->n);
938 BlockSampler_Next(BlockSampler bs)
940 BlockNumber K = bs->N - bs->t; /* remaining blocks */
941 int k = bs->n - bs->m; /* blocks still to sample */
942 double p; /* probability to skip block */
943 double V; /* random */
945 Assert(BlockSampler_HasMore(bs)); /* hence K > 0 and k > 0 */
947 if ((BlockNumber) k >= K)
949 /* need all the rest */
955 * It is not obvious that this code matches Knuth's Algorithm S.
956 * Knuth says to skip the current block with probability 1 - k/K.
957 * If we are to skip, we should advance t (hence decrease K), and
958 * repeat the same probabilistic test for the next block. The naive
959 * implementation thus requires a random_fract() call for each block
960 * number. But we can reduce this to one random_fract() call per
961 * selected block, by noting that each time the while-test succeeds,
962 * we can reinterpret V as a uniform random number in the range 0 to p.
963 * Therefore, instead of choosing a new V, we just adjust p to be
964 * the appropriate fraction of its former value, and our next loop
965 * makes the appropriate probabilistic test.
967 * We have initially K > k > 0. If the loop reduces K to equal k,
968 * the next while-test must fail since p will become exactly zero
969 * (we assume there will not be roundoff error in the division).
970 * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
971 * to be doubly sure about roundoff error.) Therefore K cannot become
972 * less than k, which means that we cannot fail to select enough blocks.
976 p = 1.0 - (double) k / (double) K;
981 K--; /* keep K == N - t */
983 /* adjust p to be new cutoff point in reduced range */
984 p *= 1.0 - (double) k / (double) K;
993 * acquire_sample_rows -- acquire a random sample of rows from the table
995 * Selected rows are returned in the caller-allocated array rows[], which
996 * must have at least targrows entries.
997 * The actual number of rows selected is returned as the function result.
998 * We also estimate the total numbers of live and dead rows in the table,
999 * and return them into *totalrows and *totaldeadrows, respectively.
1001 * The returned list of tuples is in order by physical position in the table.
1002 * (We will rely on this later to derive correlation estimates.)
1004 * As of May 2004 we use a new two-stage method: Stage one selects up
1005 * to targrows random blocks (or all blocks, if there aren't so many).
1006 * Stage two scans these blocks and uses the Vitter algorithm to create
1007 * a random sample of targrows rows (or less, if there are less in the
1008 * sample of blocks). The two stages are executed simultaneously: each
1009 * block is processed as soon as stage one returns its number and while
1010 * the rows are read stage two controls which ones are to be inserted
1013 * Although every row has an equal chance of ending up in the final
1014 * sample, this sampling method is not perfect: not every possible
1015 * sample has an equal chance of being selected. For large relations
1016 * the number of different blocks represented by the sample tends to be
1017 * too small. We can live with that for now. Improvements are welcome.
1019 * An important property of this sampling method is that because we do
1020 * look at a statistically unbiased set of blocks, we should get
1021 * unbiased estimates of the average numbers of live and dead rows per
1022 * block. The previous sampling method put too much credence in the row
1023 * density near the start of the table.
1026 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1027 double *totalrows, double *totaldeadrows)
1029 int numrows = 0; /* # rows now in reservoir */
1030 double samplerows = 0; /* total # rows collected */
1031 double liverows = 0; /* # live rows seen */
1032 double deadrows = 0; /* # dead rows seen */
1033 double rowstoskip = -1; /* -1 means not set yet */
1034 BlockNumber totalblocks;
1035 TransactionId OldestXmin;
1036 BlockSamplerData bs;
1039 Assert(targrows > 0);
1041 totalblocks = RelationGetNumberOfBlocks(onerel);
1043 /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
1044 OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
1046 /* Prepare for sampling block numbers */
1047 BlockSampler_Init(&bs, totalblocks, targrows);
1048 /* Prepare for sampling rows */
1049 rstate = init_selection_state(targrows);
1051 /* Outer loop over blocks to sample */
1052 while (BlockSampler_HasMore(&bs))
1054 BlockNumber targblock = BlockSampler_Next(&bs);
1057 OffsetNumber targoffset,
1060 vacuum_delay_point();
1063 * We must maintain a pin on the target page's buffer to ensure that
1064 * the maxoffset value stays good (else concurrent VACUUM might delete
1065 * tuples out from under us). Hence, pin the page until we are done
1066 * looking at it. We also choose to hold sharelock on the buffer
1067 * throughout --- we could release and re-acquire sharelock for each
1068 * tuple, but since we aren't doing much work per tuple, the extra
1069 * lock traffic is probably better avoided.
1071 targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
1072 RBM_NORMAL, vac_strategy);
1073 LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
1074 targpage = BufferGetPage(targbuffer);
1075 maxoffset = PageGetMaxOffsetNumber(targpage);
1077 /* Inner loop over all tuples on the selected page */
1078 for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
1081 HeapTupleData targtuple;
1082 bool sample_it = false;
1084 itemid = PageGetItemId(targpage, targoffset);
1087 * We ignore unused and redirect line pointers. DEAD line
1088 * pointers should be counted as dead, because we need vacuum to
1089 * run to get rid of them. Note that this rule agrees with the
1090 * way that heap_page_prune() counts things.
1092 if (!ItemIdIsNormal(itemid))
1094 if (ItemIdIsDead(itemid))
1099 ItemPointerSet(&targtuple.t_self, targblock, targoffset);
1101 targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
1102 targtuple.t_len = ItemIdGetLength(itemid);
1104 switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
1108 case HEAPTUPLE_LIVE:
1113 case HEAPTUPLE_DEAD:
1114 case HEAPTUPLE_RECENTLY_DEAD:
1115 /* Count dead and recently-dead rows */
1119 case HEAPTUPLE_INSERT_IN_PROGRESS:
1122 * Insert-in-progress rows are not counted. We assume
1123 * that when the inserting transaction commits or aborts,
1124 * it will send a stats message to increment the proper
1125 * count. This works right only if that transaction ends
1126 * after we finish analyzing the table; if things happen
1127 * in the other order, its stats update will be
1128 * overwritten by ours. However, the error will be large
1129 * only if the other transaction runs long enough to
1130 * insert many tuples, so assuming it will finish after us
1131 * is the safer option.
1133 * A special case is that the inserting transaction might
1134 * be our own. In this case we should count and sample
1135 * the row, to accommodate users who load a table and
1136 * analyze it in one transaction. (pgstat_report_analyze
1137 * has to adjust the numbers we send to the stats
1138 * collector to make this come out right.)
1140 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
1147 case HEAPTUPLE_DELETE_IN_PROGRESS:
1150 * We count delete-in-progress rows as still live, using
1151 * the same reasoning given above; but we don't bother to
1152 * include them in the sample.
1154 * If the delete was done by our own transaction, however,
1155 * we must count the row as dead to make
1156 * pgstat_report_analyze's stats adjustments come out
1157 * right. (Note: this works out properly when the row was
1158 * both inserted and deleted in our xact.)
1160 if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
1167 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1174 * The first targrows sample rows are simply copied into the
1175 * reservoir. Then we start replacing tuples in the sample
1176 * until we reach the end of the relation. This algorithm is
1177 * from Jeff Vitter's paper (see full citation below). It
1178 * works by repeatedly computing the number of tuples to skip
1179 * before selecting a tuple, which replaces a randomly chosen
1180 * element of the reservoir (current set of tuples). At all
1181 * times the reservoir is a true random sample of the tuples
1182 * we've passed over so far, so when we fall off the end of
1183 * the relation we're done.
1185 if (numrows < targrows)
1186 rows[numrows++] = heap_copytuple(&targtuple);
1190 * t in Vitter's paper is the number of records already
1191 * processed. If we need to compute a new S value, we
1192 * must use the not-yet-incremented value of samplerows as
1196 rowstoskip = get_next_S(samplerows, targrows, &rstate);
1198 if (rowstoskip <= 0)
1201 * Found a suitable tuple, so save it, replacing one
1202 * old tuple at random
1204 int k = (int) (targrows * random_fract());
1206 Assert(k >= 0 && k < targrows);
1207 heap_freetuple(rows[k]);
1208 rows[k] = heap_copytuple(&targtuple);
1218 /* Now release the lock and pin on the page */
1219 UnlockReleaseBuffer(targbuffer);
1223 * If we didn't find as many tuples as we wanted then we're done. No sort
1224 * is needed, since they're already in order.
1226 * Otherwise we need to sort the collected tuples by position
1227 * (itempointer). It's not worth worrying about corner cases where the
1228 * tuples are already sorted.
1230 if (numrows == targrows)
1231 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1234 * Estimate total numbers of rows in relation. For live rows, use
1235 * vac_estimate_reltuples; for dead rows, we have no source of old
1236 * information, so we have to assume the density is the same in unseen
1237 * pages as in the pages we scanned.
1239 *totalrows = vac_estimate_reltuples(onerel, true,
1244 *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
1246 *totaldeadrows = 0.0;
1249 * Emit some interesting relation info
1252 (errmsg("\"%s\": scanned %d of %u pages, "
1253 "containing %.0f live rows and %.0f dead rows; "
1254 "%d rows in sample, %.0f estimated total rows",
1255 RelationGetRelationName(onerel),
1258 numrows, *totalrows)));
1263 /* Select a random value R uniformly distributed in (0 - 1) */
1267 return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
1271 * These two routines embody Algorithm Z from "Random sampling with a
1272 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1273 * (Mar. 1985), Pages 37-57. Vitter describes his algorithm in terms
1274 * of the count S of records to skip before processing another record.
1275 * It is computed primarily based on t, the number of records already read.
1276 * The only extra state needed between calls is W, a random state variable.
1278 * init_selection_state computes the initial W value.
1280 * Given that we've already read t records (t >= n), get_next_S
1281 * determines the number of records to skip before the next record is
1285 init_selection_state(int n)
1287 /* Initial value of W (for use when Algorithm Z is first applied) */
1288 return exp(-log(random_fract()) / n);
1292 get_next_S(double t, int n, double *stateptr)
1296 /* The magic constant here is T from Vitter's paper */
1297 if (t <= (22.0 * n))
1299 /* Process records using Algorithm X until t is large enough */
1303 V = random_fract(); /* Generate V */
1306 /* Note: "num" in Vitter's code is always equal to t - n */
1307 quot = (t - (double) n) / t;
1308 /* Find min S satisfying (4.1) */
1313 quot *= (t - (double) n) / t;
1318 /* Now apply Algorithm Z */
1319 double W = *stateptr;
1320 double term = t - (double) n + 1;
1334 /* Generate U and X */
1337 S = floor(X); /* S is tentatively set to floor(X) */
1338 /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1339 tmp = (t + 1) / term;
1340 lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
1341 rhs = (((t + X) / (term + S)) * term) / t;
1347 /* Test if U <= f(S)/cg(X) */
1348 y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1352 numer_lim = term + S;
1356 denom = t - (double) n + S;
1359 for (numer = t + S; numer >= numer_lim; numer -= 1)
1364 W = exp(-log(random_fract()) / n); /* Generate W in advance */
1365 if (exp(log(y) / n) <= (t + X) / t)
1374 * qsort comparator for sorting rows[] array
1377 compare_rows(const void *a, const void *b)
1379 HeapTuple ha = *(HeapTuple *) a;
1380 HeapTuple hb = *(HeapTuple *) b;
1381 BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1382 OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1383 BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1384 OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1399 * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
1401 * This has the same API as acquire_sample_rows, except that rows are
1402 * collected from all inheritance children as well as the specified table.
1403 * We fail and return zero if there are no inheritance children.
1406 acquire_inherited_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
1407 double *totalrows, double *totaldeadrows)
1419 * Find all members of inheritance set. We only need AccessShareLock on
1423 find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
1426 * Check that there's at least one descendant, else fail. This could
1427 * happen despite analyze_rel's relhassubclass check, if table once had a
1428 * child but no longer does.
1430 if (list_length(tableOIDs) < 2)
1433 * XXX It would be desirable to clear relhassubclass here, but we
1434 * don't have adequate lock to do that safely.
1440 * Count the blocks in all the relations. The result could overflow
1441 * BlockNumber, so we use double arithmetic.
1443 rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
1444 relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
1447 foreach(lc, tableOIDs)
1449 Oid childOID = lfirst_oid(lc);
1452 /* We already got the needed lock */
1453 childrel = heap_open(childOID, NoLock);
1455 /* Ignore if temp table of another backend */
1456 if (RELATION_IS_OTHER_TEMP(childrel))
1458 /* ... but release the lock on it */
1459 Assert(childrel != onerel);
1460 heap_close(childrel, AccessShareLock);
1464 rels[nrels] = childrel;
1465 relblocks[nrels] = (double) RelationGetNumberOfBlocks(childrel);
1466 totalblocks += relblocks[nrels];
1471 * Now sample rows from each relation, proportionally to its fraction of
1472 * the total block count. (This might be less than desirable if the child
1473 * rels have radically different free-space percentages, but it's not
1474 * clear that it's worth working harder.)
1479 for (i = 0; i < nrels; i++)
1481 Relation childrel = rels[i];
1482 double childblocks = relblocks[i];
1484 if (childblocks > 0)
1488 childtargrows = (int) rint(targrows * childblocks / totalblocks);
1489 /* Make sure we don't overrun due to roundoff error */
1490 childtargrows = Min(childtargrows, targrows - numrows);
1491 if (childtargrows > 0)
1497 /* Fetch a random sample of the child's rows */
1498 childrows = acquire_sample_rows(childrel,
1504 /* We may need to convert from child's rowtype to parent's */
1505 if (childrows > 0 &&
1506 !equalTupleDescs(RelationGetDescr(childrel),
1507 RelationGetDescr(onerel)))
1509 TupleConversionMap *map;
1511 map = convert_tuples_by_name(RelationGetDescr(childrel),
1512 RelationGetDescr(onerel),
1513 gettext_noop("could not convert row type"));
1518 for (j = 0; j < childrows; j++)
1522 newtup = do_convert_tuple(rows[numrows + j], map);
1523 heap_freetuple(rows[numrows + j]);
1524 rows[numrows + j] = newtup;
1526 free_conversion_map(map);
1530 /* And add to counts */
1531 numrows += childrows;
1532 *totalrows += trows;
1533 *totaldeadrows += tdrows;
1538 * Note: we cannot release the child-table locks, since we may have
1539 * pointers to their TOAST tables in the sampled rows.
1541 heap_close(childrel, NoLock);
1549 * update_attstats() -- update attribute statistics for one relation
1551 * Statistics are stored in several places: the pg_class row for the
1552 * relation has stats about the whole relation, and there is a
1553 * pg_statistic row for each (non-system) attribute that has ever
1554 * been analyzed. The pg_class values are updated by VACUUM, not here.
1556 * pg_statistic rows are just added or updated normally. This means
1557 * that pg_statistic will probably contain some deleted rows at the
1558 * completion of a vacuum cycle, unless it happens to get vacuumed last.
1560 * To keep things simple, we punt for pg_statistic, and don't try
1561 * to compute or store rows for pg_statistic itself in pg_statistic.
1562 * This could possibly be made to work, but it's not worth the trouble.
1563 * Note analyze_rel() has seen to it that we won't come here when
1564 * vacuuming pg_statistic itself.
1566 * Note: there would be a race condition here if two backends could
1567 * ANALYZE the same table concurrently. Presently, we lock that out
1568 * by taking a self-exclusive lock on the relation in analyze_rel().
1571 update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
1577 return; /* nothing to do */
1579 sd = heap_open(StatisticRelationId, RowExclusiveLock);
1581 for (attno = 0; attno < natts; attno++)
1583 VacAttrStats *stats = vacattrstats[attno];
1589 Datum values[Natts_pg_statistic];
1590 bool nulls[Natts_pg_statistic];
1591 bool replaces[Natts_pg_statistic];
1593 /* Ignore attr if we weren't able to collect stats */
1594 if (!stats->stats_valid)
1598 * Construct a new pg_statistic tuple
1600 for (i = 0; i < Natts_pg_statistic; ++i)
1606 values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
1607 values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
1608 values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
1609 values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
1610 values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
1611 values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
1612 i = Anum_pg_statistic_stakind1 - 1;
1613 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1615 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1617 i = Anum_pg_statistic_staop1 - 1;
1618 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1620 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1622 i = Anum_pg_statistic_stanumbers1 - 1;
1623 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1625 int nnum = stats->numnumbers[k];
1629 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1632 for (n = 0; n < nnum; n++)
1633 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1634 /* XXX knows more than it should about type float4: */
1635 arry = construct_array(numdatums, nnum,
1637 sizeof(float4), FLOAT4PASSBYVAL, 'i');
1638 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1643 values[i++] = (Datum) 0;
1646 i = Anum_pg_statistic_stavalues1 - 1;
1647 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1649 if (stats->numvalues[k] > 0)
1653 arry = construct_array(stats->stavalues[k],
1654 stats->numvalues[k],
1656 stats->statyplen[k],
1657 stats->statypbyval[k],
1658 stats->statypalign[k]);
1659 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1664 values[i++] = (Datum) 0;
1668 /* Is there already a pg_statistic tuple for this attribute? */
1669 oldtup = SearchSysCache3(STATRELATTINH,
1670 ObjectIdGetDatum(relid),
1671 Int16GetDatum(stats->attr->attnum),
1674 if (HeapTupleIsValid(oldtup))
1676 /* Yes, replace it */
1677 stup = heap_modify_tuple(oldtup,
1678 RelationGetDescr(sd),
1682 ReleaseSysCache(oldtup);
1683 simple_heap_update(sd, &stup->t_self, stup);
1687 /* No, insert new tuple */
1688 stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
1689 simple_heap_insert(sd, stup);
1692 /* update indexes too */
1693 CatalogUpdateIndexes(sd, stup);
1695 heap_freetuple(stup);
1698 heap_close(sd, RowExclusiveLock);
1702 * Standard fetch function for use by compute_stats subroutines.
1704 * This exists to provide some insulation between compute_stats routines
1705 * and the actual storage of the sample data.
1708 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1710 int attnum = stats->tupattnum;
1711 HeapTuple tuple = stats->rows[rownum];
1712 TupleDesc tupDesc = stats->tupDesc;
1714 return heap_getattr(tuple, attnum, tupDesc, isNull);
1718 * Fetch function for analyzing index expressions.
1720 * We have not bothered to construct index tuples, instead the data is
1721 * just in Datum arrays.
1724 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1728 /* exprvals and exprnulls are already offset for proper column */
1729 i = rownum * stats->rowstride;
1730 *isNull = stats->exprnulls[i];
1731 return stats->exprvals[i];
1735 /*==========================================================================
1737 * Code below this point represents the "standard" type-specific statistics
1738 * analysis algorithms. This code can be replaced on a per-data-type basis
1739 * by setting a nonzero value in pg_type.typanalyze.
1741 *==========================================================================
1746 * To avoid consuming too much memory during analysis and/or too much space
1747 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1748 * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
1749 * and distinct-value calculations since a wide value is unlikely to be
1750 * duplicated at all, much less be a most-common value. For the same reason,
1751 * ignoring wide values will not affect our estimates of histogram bin
1752 * boundaries very much.
1754 #define WIDTH_THRESHOLD 1024
1756 #define swapInt(a,b) do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1757 #define swapDatum(a,b) do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1760 * Extra information used by the default analysis routines
1764 Oid eqopr; /* '=' operator for datatype, if any */
1765 Oid eqfunc; /* and associated function */
1766 Oid ltopr; /* '<' operator for datatype, if any */
1771 Datum value; /* a data value */
1772 int tupno; /* position index for tuple it came from */
1777 int count; /* # of duplicates */
1778 int first; /* values[] index of first occurrence */
1786 } CompareScalarsContext;
1789 static void compute_minimal_stats(VacAttrStatsP stats,
1790 AnalyzeAttrFetchFunc fetchfunc,
1793 static void compute_scalar_stats(VacAttrStatsP stats,
1794 AnalyzeAttrFetchFunc fetchfunc,
1797 static int compare_scalars(const void *a, const void *b, void *arg);
1798 static int compare_mcvs(const void *a, const void *b);
1802 * std_typanalyze -- the default type-specific typanalyze function
1805 std_typanalyze(VacAttrStats *stats)
1807 Form_pg_attribute attr = stats->attr;
1810 StdAnalyzeData *mystats;
1812 /* If the attstattarget column is negative, use the default value */
1813 /* NB: it is okay to scribble on stats->attr since it's a copy */
1814 if (attr->attstattarget < 0)
1815 attr->attstattarget = default_statistics_target;
1817 /* Look for default "<" and "=" operators for column's type */
1818 get_sort_group_operators(stats->attrtypid,
1819 false, false, false,
1820 <opr, &eqopr, NULL,
1823 /* If column has no "=" operator, we can't do much of anything */
1824 if (!OidIsValid(eqopr))
1827 /* Save the operator info for compute_stats routines */
1828 mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1829 mystats->eqopr = eqopr;
1830 mystats->eqfunc = get_opcode(eqopr);
1831 mystats->ltopr = ltopr;
1832 stats->extra_data = mystats;
1835 * Determine which standard statistics algorithm to use
1837 if (OidIsValid(ltopr))
1839 /* Seems to be a scalar datatype */
1840 stats->compute_stats = compute_scalar_stats;
1841 /*--------------------
1842 * The following choice of minrows is based on the paper
1843 * "Random sampling for histogram construction: how much is enough?"
1844 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1845 * Proceedings of ACM SIGMOD International Conference on Management
1846 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1847 * says that for table size n, histogram size k, maximum relative
1848 * error in bin size f, and error probability gamma, the minimum
1849 * random sample size is
1850 * r = 4 * k * ln(2*n/gamma) / f^2
1851 * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1853 * Note that because of the log function, the dependence on n is
1854 * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1855 * bin size error with probability 0.99. So there's no real need to
1856 * scale for n, which is a good thing because we don't necessarily
1857 * know it at this point.
1858 *--------------------
1860 stats->minrows = 300 * attr->attstattarget;
1864 /* Can't do much but the minimal stuff */
1865 stats->compute_stats = compute_minimal_stats;
1866 /* Might as well use the same minrows as above */
1867 stats->minrows = 300 * attr->attstattarget;
1874 * compute_minimal_stats() -- compute minimal column statistics
1876 * We use this when we can find only an "=" operator for the datatype.
1878 * We determine the fraction of non-null rows, the average width, the
1879 * most common values, and the (estimated) number of distinct values.
1881 * The most common values are determined by brute force: we keep a list
1882 * of previously seen values, ordered by number of times seen, as we scan
1883 * the samples. A newly seen value is inserted just after the last
1884 * multiply-seen value, causing the bottommost (oldest) singly-seen value
1885 * to drop off the list. The accuracy of this method, and also its cost,
1886 * depend mainly on the length of the list we are willing to keep.
1889 compute_minimal_stats(VacAttrStatsP stats,
1890 AnalyzeAttrFetchFunc fetchfunc,
1896 int nonnull_cnt = 0;
1897 int toowide_cnt = 0;
1898 double total_width = 0;
1899 bool is_varlena = (!stats->attrtype->typbyval &&
1900 stats->attrtype->typlen == -1);
1901 bool is_varwidth = (!stats->attrtype->typbyval &&
1902 stats->attrtype->typlen < 0);
1912 int num_mcv = stats->attr->attstattarget;
1913 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1916 * We track up to 2*n values for an n-element MCV list; but at least 10
1918 track_max = 2 * num_mcv;
1921 track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1924 fmgr_info(mystats->eqfunc, &f_cmpeq);
1926 for (i = 0; i < samplerows; i++)
1934 vacuum_delay_point();
1936 value = fetchfunc(stats, i, &isnull);
1938 /* Check for null/nonnull */
1947 * If it's a variable-width field, add up widths for average width
1948 * calculation. Note that if the value is toasted, we use the toasted
1949 * width. We don't bother with this calculation if it's a fixed-width
1954 total_width += VARSIZE_ANY(DatumGetPointer(value));
1957 * If the value is toasted, we want to detoast it just once to
1958 * avoid repeated detoastings and resultant excess memory usage
1959 * during the comparisons. Also, check to see if the value is
1960 * excessively wide, and if so don't detoast at all --- just
1963 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1968 value = PointerGetDatum(PG_DETOAST_DATUM(value));
1970 else if (is_varwidth)
1972 /* must be cstring */
1973 total_width += strlen(DatumGetCString(value)) + 1;
1977 * See if the value matches anything we're already tracking.
1980 firstcount1 = track_cnt;
1981 for (j = 0; j < track_cnt; j++)
1983 /* We always use the default collation for statistics */
1984 if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
1985 DEFAULT_COLLATION_OID,
1986 value, track[j].value)))
1991 if (j < firstcount1 && track[j].count == 1)
1999 /* This value may now need to "bubble up" in the track list */
2000 while (j > 0 && track[j].count > track[j - 1].count)
2002 swapDatum(track[j].value, track[j - 1].value);
2003 swapInt(track[j].count, track[j - 1].count);
2009 /* No match. Insert at head of count-1 list */
2010 if (track_cnt < track_max)
2012 for (j = track_cnt - 1; j > firstcount1; j--)
2014 track[j].value = track[j - 1].value;
2015 track[j].count = track[j - 1].count;
2017 if (firstcount1 < track_cnt)
2019 track[firstcount1].value = value;
2020 track[firstcount1].count = 1;
2025 /* We can only compute real stats if we found some non-null values. */
2026 if (nonnull_cnt > 0)
2031 stats->stats_valid = true;
2032 /* Do the simple null-frac and width stats */
2033 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2035 stats->stawidth = total_width / (double) nonnull_cnt;
2037 stats->stawidth = stats->attrtype->typlen;
2039 /* Count the number of values we found multiple times */
2041 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
2043 if (track[nmultiple].count == 1)
2045 summultiple += track[nmultiple].count;
2050 /* If we found no repeated values, assume it's a unique column */
2051 stats->stadistinct = -1.0;
2053 else if (track_cnt < track_max && toowide_cnt == 0 &&
2054 nmultiple == track_cnt)
2057 * Our track list includes every value in the sample, and every
2058 * value appeared more than once. Assume the column has just
2061 stats->stadistinct = track_cnt;
2066 * Estimate the number of distinct values using the estimator
2067 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2068 * n*d / (n - f1 + f1*n/N)
2069 * where f1 is the number of distinct values that occurred
2070 * exactly once in our sample of n rows (from a total of N),
2071 * and d is the total number of distinct values in the sample.
2072 * This is their Duj1 estimator; the other estimators they
2073 * recommend are considerably more complex, and are numerically
2074 * very unstable when n is much smaller than N.
2076 * We assume (not very reliably!) that all the multiply-occurring
2077 * values are reflected in the final track[] list, and the other
2078 * nonnull values all appeared but once. (XXX this usually
2079 * results in a drastic overestimate of ndistinct. Can we do
2083 int f1 = nonnull_cnt - summultiple;
2084 int d = f1 + nmultiple;
2089 numer = (double) samplerows *(double) d;
2091 denom = (double) (samplerows - f1) +
2092 (double) f1 *(double) samplerows / totalrows;
2094 stadistinct = numer / denom;
2095 /* Clamp to sane range in case of roundoff error */
2096 if (stadistinct < (double) d)
2097 stadistinct = (double) d;
2098 if (stadistinct > totalrows)
2099 stadistinct = totalrows;
2100 stats->stadistinct = floor(stadistinct + 0.5);
2104 * If we estimated the number of distinct values at more than 10% of
2105 * the total row count (a very arbitrary limit), then assume that
2106 * stadistinct should scale with the row count rather than be a fixed
2109 if (stats->stadistinct > 0.1 * totalrows)
2110 stats->stadistinct = -(stats->stadistinct / totalrows);
2113 * Decide how many values are worth storing as most-common values. If
2114 * we are able to generate a complete MCV list (all the values in the
2115 * sample will fit, and we think these are all the ones in the table),
2116 * then do so. Otherwise, store only those values that are
2117 * significantly more common than the (estimated) average. We set the
2118 * threshold rather arbitrarily at 25% more than average, with at
2119 * least 2 instances in the sample.
2121 if (track_cnt < track_max && toowide_cnt == 0 &&
2122 stats->stadistinct > 0 &&
2123 track_cnt <= num_mcv)
2125 /* Track list includes all values seen, and all will fit */
2126 num_mcv = track_cnt;
2130 double ndistinct = stats->stadistinct;
2135 ndistinct = -ndistinct * totalrows;
2136 /* estimate # of occurrences in sample of a typical value */
2137 avgcount = (double) samplerows / ndistinct;
2138 /* set minimum threshold count to store a value */
2139 mincount = avgcount * 1.25;
2142 if (num_mcv > track_cnt)
2143 num_mcv = track_cnt;
2144 for (i = 0; i < num_mcv; i++)
2146 if (track[i].count < mincount)
2154 /* Generate MCV slot entry */
2157 MemoryContext old_context;
2161 /* Must copy the target values into anl_context */
2162 old_context = MemoryContextSwitchTo(stats->anl_context);
2163 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2164 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2165 for (i = 0; i < num_mcv; i++)
2167 mcv_values[i] = datumCopy(track[i].value,
2168 stats->attrtype->typbyval,
2169 stats->attrtype->typlen);
2170 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2172 MemoryContextSwitchTo(old_context);
2174 stats->stakind[0] = STATISTIC_KIND_MCV;
2175 stats->staop[0] = mystats->eqopr;
2176 stats->stanumbers[0] = mcv_freqs;
2177 stats->numnumbers[0] = num_mcv;
2178 stats->stavalues[0] = mcv_values;
2179 stats->numvalues[0] = num_mcv;
2182 * Accept the defaults for stats->statypid and others. They have
2183 * been set before we were called (see vacuum.h)
2187 else if (null_cnt > 0)
2189 /* We found only nulls; assume the column is entirely null */
2190 stats->stats_valid = true;
2191 stats->stanullfrac = 1.0;
2193 stats->stawidth = 0; /* "unknown" */
2195 stats->stawidth = stats->attrtype->typlen;
2196 stats->stadistinct = 0.0; /* "unknown" */
2199 /* We don't need to bother cleaning up any of our temporary palloc's */
2204 * compute_scalar_stats() -- compute column statistics
2206 * We use this when we can find "=" and "<" operators for the datatype.
2208 * We determine the fraction of non-null rows, the average width, the
2209 * most common values, the (estimated) number of distinct values, the
2210 * distribution histogram, and the correlation of physical to logical order.
2212 * The desired stats can be determined fairly easily after sorting the
2213 * data values into order.
2216 compute_scalar_stats(VacAttrStatsP stats,
2217 AnalyzeAttrFetchFunc fetchfunc,
2223 int nonnull_cnt = 0;
2224 int toowide_cnt = 0;
2225 double total_width = 0;
2226 bool is_varlena = (!stats->attrtype->typbyval &&
2227 stats->attrtype->typlen == -1);
2228 bool is_varwidth = (!stats->attrtype->typbyval &&
2229 stats->attrtype->typlen < 0);
2237 ScalarMCVItem *track;
2239 int num_mcv = stats->attr->attstattarget;
2240 int num_bins = stats->attr->attstattarget;
2241 StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
2243 values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
2244 tupnoLink = (int *) palloc(samplerows * sizeof(int));
2245 track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
2247 SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
2248 fmgr_info(cmpFn, &f_cmpfn);
2250 /* Initial scan to find sortable values */
2251 for (i = 0; i < samplerows; i++)
2256 vacuum_delay_point();
2258 value = fetchfunc(stats, i, &isnull);
2260 /* Check for null/nonnull */
2269 * If it's a variable-width field, add up widths for average width
2270 * calculation. Note that if the value is toasted, we use the toasted
2271 * width. We don't bother with this calculation if it's a fixed-width
2276 total_width += VARSIZE_ANY(DatumGetPointer(value));
2279 * If the value is toasted, we want to detoast it just once to
2280 * avoid repeated detoastings and resultant excess memory usage
2281 * during the comparisons. Also, check to see if the value is
2282 * excessively wide, and if so don't detoast at all --- just
2285 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
2290 value = PointerGetDatum(PG_DETOAST_DATUM(value));
2292 else if (is_varwidth)
2294 /* must be cstring */
2295 total_width += strlen(DatumGetCString(value)) + 1;
2298 /* Add it to the list to be sorted */
2299 values[values_cnt].value = value;
2300 values[values_cnt].tupno = values_cnt;
2301 tupnoLink[values_cnt] = values_cnt;
2305 /* We can only compute real stats if we found some sortable values. */
2308 int ndistinct, /* # distinct values in sample */
2309 nmultiple, /* # that appear multiple times */
2313 CompareScalarsContext cxt;
2315 /* Sort the collected values */
2316 cxt.cmpFn = &f_cmpfn;
2317 cxt.cmpFlags = cmpFlags;
2318 cxt.tupnoLink = tupnoLink;
2319 qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2320 compare_scalars, (void *) &cxt);
2323 * Now scan the values in order, find the most common ones, and also
2324 * accumulate ordering-correlation statistics.
2326 * To determine which are most common, we first have to count the
2327 * number of duplicates of each value. The duplicates are adjacent in
2328 * the sorted list, so a brute-force approach is to compare successive
2329 * datum values until we find two that are not equal. However, that
2330 * requires N-1 invocations of the datum comparison routine, which are
2331 * completely redundant with work that was done during the sort. (The
2332 * sort algorithm must at some point have compared each pair of items
2333 * that are adjacent in the sorted order; otherwise it could not know
2334 * that it's ordered the pair correctly.) We exploit this by having
2335 * compare_scalars remember the highest tupno index that each
2336 * ScalarItem has been found equal to. At the end of the sort, a
2337 * ScalarItem's tupnoLink will still point to itself if and only if it
2338 * is the last item of its group of duplicates (since the group will
2339 * be ordered by tupno).
2345 for (i = 0; i < values_cnt; i++)
2347 int tupno = values[i].tupno;
2349 corr_xysum += ((double) i) * ((double) tupno);
2351 if (tupnoLink[tupno] == tupno)
2353 /* Reached end of duplicates of this value */
2358 if (track_cnt < num_mcv ||
2359 dups_cnt > track[track_cnt - 1].count)
2362 * Found a new item for the mcv list; find its
2363 * position, bubbling down old items if needed. Loop
2364 * invariant is that j points at an empty/ replaceable
2369 if (track_cnt < num_mcv)
2371 for (j = track_cnt - 1; j > 0; j--)
2373 if (dups_cnt <= track[j - 1].count)
2375 track[j].count = track[j - 1].count;
2376 track[j].first = track[j - 1].first;
2378 track[j].count = dups_cnt;
2379 track[j].first = i + 1 - dups_cnt;
2386 stats->stats_valid = true;
2387 /* Do the simple null-frac and width stats */
2388 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2390 stats->stawidth = total_width / (double) nonnull_cnt;
2392 stats->stawidth = stats->attrtype->typlen;
2396 /* If we found no repeated values, assume it's a unique column */
2397 stats->stadistinct = -1.0;
2399 else if (toowide_cnt == 0 && nmultiple == ndistinct)
2402 * Every value in the sample appeared more than once. Assume the
2403 * column has just these values.
2405 stats->stadistinct = ndistinct;
2410 * Estimate the number of distinct values using the estimator
2411 * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2412 * n*d / (n - f1 + f1*n/N)
2413 * where f1 is the number of distinct values that occurred
2414 * exactly once in our sample of n rows (from a total of N),
2415 * and d is the total number of distinct values in the sample.
2416 * This is their Duj1 estimator; the other estimators they
2417 * recommend are considerably more complex, and are numerically
2418 * very unstable when n is much smaller than N.
2420 * Overwidth values are assumed to have been distinct.
2423 int f1 = ndistinct - nmultiple + toowide_cnt;
2424 int d = f1 + nmultiple;
2429 numer = (double) samplerows *(double) d;
2431 denom = (double) (samplerows - f1) +
2432 (double) f1 *(double) samplerows / totalrows;
2434 stadistinct = numer / denom;
2435 /* Clamp to sane range in case of roundoff error */
2436 if (stadistinct < (double) d)
2437 stadistinct = (double) d;
2438 if (stadistinct > totalrows)
2439 stadistinct = totalrows;
2440 stats->stadistinct = floor(stadistinct + 0.5);
2444 * If we estimated the number of distinct values at more than 10% of
2445 * the total row count (a very arbitrary limit), then assume that
2446 * stadistinct should scale with the row count rather than be a fixed
2449 if (stats->stadistinct > 0.1 * totalrows)
2450 stats->stadistinct = -(stats->stadistinct / totalrows);
2453 * Decide how many values are worth storing as most-common values. If
2454 * we are able to generate a complete MCV list (all the values in the
2455 * sample will fit, and we think these are all the ones in the table),
2456 * then do so. Otherwise, store only those values that are
2457 * significantly more common than the (estimated) average. We set the
2458 * threshold rather arbitrarily at 25% more than average, with at
2459 * least 2 instances in the sample. Also, we won't suppress values
2460 * that have a frequency of at least 1/K where K is the intended
2461 * number of histogram bins; such values might otherwise cause us to
2462 * emit duplicate histogram bin boundaries. (We might end up with
2463 * duplicate histogram entries anyway, if the distribution is skewed;
2464 * but we prefer to treat such values as MCVs if at all possible.)
2466 if (track_cnt == ndistinct && toowide_cnt == 0 &&
2467 stats->stadistinct > 0 &&
2468 track_cnt <= num_mcv)
2470 /* Track list includes all values seen, and all will fit */
2471 num_mcv = track_cnt;
2475 double ndistinct = stats->stadistinct;
2481 ndistinct = -ndistinct * totalrows;
2482 /* estimate # of occurrences in sample of a typical value */
2483 avgcount = (double) samplerows / ndistinct;
2484 /* set minimum threshold count to store a value */
2485 mincount = avgcount * 1.25;
2488 /* don't let threshold exceed 1/K, however */
2489 maxmincount = (double) samplerows / (double) num_bins;
2490 if (mincount > maxmincount)
2491 mincount = maxmincount;
2492 if (num_mcv > track_cnt)
2493 num_mcv = track_cnt;
2494 for (i = 0; i < num_mcv; i++)
2496 if (track[i].count < mincount)
2504 /* Generate MCV slot entry */
2507 MemoryContext old_context;
2511 /* Must copy the target values into anl_context */
2512 old_context = MemoryContextSwitchTo(stats->anl_context);
2513 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2514 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2515 for (i = 0; i < num_mcv; i++)
2517 mcv_values[i] = datumCopy(values[track[i].first].value,
2518 stats->attrtype->typbyval,
2519 stats->attrtype->typlen);
2520 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2522 MemoryContextSwitchTo(old_context);
2524 stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2525 stats->staop[slot_idx] = mystats->eqopr;
2526 stats->stanumbers[slot_idx] = mcv_freqs;
2527 stats->numnumbers[slot_idx] = num_mcv;
2528 stats->stavalues[slot_idx] = mcv_values;
2529 stats->numvalues[slot_idx] = num_mcv;
2532 * Accept the defaults for stats->statypid and others. They have
2533 * been set before we were called (see vacuum.h)
2539 * Generate a histogram slot entry if there are at least two distinct
2540 * values not accounted for in the MCV list. (This ensures the
2541 * histogram won't collapse to empty or a singleton.)
2543 num_hist = ndistinct - num_mcv;
2544 if (num_hist > num_bins)
2545 num_hist = num_bins + 1;
2548 MemoryContext old_context;
2556 /* Sort the MCV items into position order to speed next loop */
2557 qsort((void *) track, num_mcv,
2558 sizeof(ScalarMCVItem), compare_mcvs);
2561 * Collapse out the MCV items from the values[] array.
2563 * Note we destroy the values[] array here... but we don't need it
2564 * for anything more. We do, however, still need values_cnt.
2565 * nvals will be the number of remaining entries in values[].
2574 j = 0; /* index of next interesting MCV item */
2575 while (src < values_cnt)
2581 int first = track[j].first;
2585 /* advance past this MCV item */
2586 src = first + track[j].count;
2590 ncopy = first - src;
2593 ncopy = values_cnt - src;
2594 memmove(&values[dest], &values[src],
2595 ncopy * sizeof(ScalarItem));
2603 Assert(nvals >= num_hist);
2605 /* Must copy the target values into anl_context */
2606 old_context = MemoryContextSwitchTo(stats->anl_context);
2607 hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2610 * The object of this loop is to copy the first and last values[]
2611 * entries along with evenly-spaced values in between. So the
2612 * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)]. But
2613 * computing that subscript directly risks integer overflow when
2614 * the stats target is more than a couple thousand. Instead we
2615 * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
2616 * the integral and fractional parts of the sum separately.
2618 delta = (nvals - 1) / (num_hist - 1);
2619 deltafrac = (nvals - 1) % (num_hist - 1);
2622 for (i = 0; i < num_hist; i++)
2624 hist_values[i] = datumCopy(values[pos].value,
2625 stats->attrtype->typbyval,
2626 stats->attrtype->typlen);
2628 posfrac += deltafrac;
2629 if (posfrac >= (num_hist - 1))
2631 /* fractional part exceeds 1, carry to integer part */
2633 posfrac -= (num_hist - 1);
2637 MemoryContextSwitchTo(old_context);
2639 stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2640 stats->staop[slot_idx] = mystats->ltopr;
2641 stats->stavalues[slot_idx] = hist_values;
2642 stats->numvalues[slot_idx] = num_hist;
2645 * Accept the defaults for stats->statypid and others. They have
2646 * been set before we were called (see vacuum.h)
2651 /* Generate a correlation entry if there are multiple values */
2654 MemoryContext old_context;
2659 /* Must copy the target values into anl_context */
2660 old_context = MemoryContextSwitchTo(stats->anl_context);
2661 corrs = (float4 *) palloc(sizeof(float4));
2662 MemoryContextSwitchTo(old_context);
2665 * Since we know the x and y value sets are both
2666 * 0, 1, ..., values_cnt-1
2667 * we have sum(x) = sum(y) =
2668 * (values_cnt-1)*values_cnt / 2
2669 * and sum(x^2) = sum(y^2) =
2670 * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2673 corr_xsum = ((double) (values_cnt - 1)) *
2674 ((double) values_cnt) / 2.0;
2675 corr_x2sum = ((double) (values_cnt - 1)) *
2676 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2678 /* And the correlation coefficient reduces to */
2679 corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2680 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2682 stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2683 stats->staop[slot_idx] = mystats->ltopr;
2684 stats->stanumbers[slot_idx] = corrs;
2685 stats->numnumbers[slot_idx] = 1;
2689 else if (nonnull_cnt == 0 && null_cnt > 0)
2691 /* We found only nulls; assume the column is entirely null */
2692 stats->stats_valid = true;
2693 stats->stanullfrac = 1.0;
2695 stats->stawidth = 0; /* "unknown" */
2697 stats->stawidth = stats->attrtype->typlen;
2698 stats->stadistinct = 0.0; /* "unknown" */
2701 /* We don't need to bother cleaning up any of our temporary palloc's */
2705 * qsort_arg comparator for sorting ScalarItems
2707 * Aside from sorting the items, we update the tupnoLink[] array
2708 * whenever two ScalarItems are found to contain equal datums. The array
2709 * is indexed by tupno; for each ScalarItem, it contains the highest
2710 * tupno that that item's datum has been found to be equal to. This allows
2711 * us to avoid additional comparisons in compute_scalar_stats().
2714 compare_scalars(const void *a, const void *b, void *arg)
2716 Datum da = ((ScalarItem *) a)->value;
2717 int ta = ((ScalarItem *) a)->tupno;
2718 Datum db = ((ScalarItem *) b)->value;
2719 int tb = ((ScalarItem *) b)->tupno;
2720 CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2723 /* We always use the default collation for statistics */
2724 compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2725 DEFAULT_COLLATION_OID,
2726 da, false, db, false);
2731 * The two datums are equal, so update cxt->tupnoLink[].
2733 if (cxt->tupnoLink[ta] < tb)
2734 cxt->tupnoLink[ta] = tb;
2735 if (cxt->tupnoLink[tb] < ta)
2736 cxt->tupnoLink[tb] = ta;
2739 * For equal datums, sort by tupno
2745 * qsort comparator for sorting ScalarMCVItems by position
2748 compare_mcvs(const void *a, const void *b)
2750 int da = ((ScalarMCVItem *) a)->first;
2751 int db = ((ScalarMCVItem *) b)->first;