1 /*-------------------------------------------------------------------------
4 * the postgres statistics generator
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.20 2001/06/13 21:44:40 tgl Exp $
13 *-------------------------------------------------------------------------
19 #include "access/heapam.h"
20 #include "access/tuptoaster.h"
21 #include "catalog/catname.h"
22 #include "catalog/indexing.h"
23 #include "catalog/pg_operator.h"
24 #include "catalog/pg_statistic.h"
25 #include "catalog/pg_type.h"
26 #include "commands/vacuum.h"
27 #include "miscadmin.h"
28 #include "parser/parse_oper.h"
29 #include "utils/acl.h"
30 #include "utils/builtins.h"
31 #include "utils/datum.h"
32 #include "utils/fmgroids.h"
33 #include "utils/syscache.h"
34 #include "utils/tuplesort.h"
38 * Analysis algorithms supported
41 ALG_MINIMAL = 1, /* Compute only most-common-values */
42 ALG_SCALAR /* Compute MCV, histogram, sort correlation */
46 * To avoid consuming too much memory during analysis and/or too much space
47 * in the resulting pg_statistic rows, we ignore varlena datums that are wider
48 * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
49 * and distinct-value calculations since a wide value is unlikely to be
50 * duplicated at all, much less be a most-common value. For the same reason,
51 * ignoring wide values will not affect our estimates of histogram bin
52 * boundaries very much.
54 #define WIDTH_THRESHOLD 256
57 * We build one of these structs for each attribute (column) that is to be
58 * analyzed. The struct and subsidiary data are in TransactionCommandContext,
59 * so they live until the end of the ANALYZE operation.
63 /* These fields are set up by examine_attribute */
64 int attnum; /* attribute number */
65 AlgCode algcode; /* Which algorithm to use for this column */
66 int minrows; /* Minimum # of rows wanted for stats */
67 Form_pg_attribute attr; /* copy of pg_attribute row for column */
68 Form_pg_type attrtype; /* copy of pg_type row for column */
69 Oid eqopr; /* '=' operator for datatype, if any */
70 Oid eqfunc; /* and associated function */
71 Oid ltopr; /* '<' operator for datatype, if any */
73 /* These fields are filled in by the actual statistics-gathering routine */
75 float4 stanullfrac; /* fraction of entries that are NULL */
76 int4 stawidth; /* average width */
77 float4 stadistinct; /* # distinct values */
78 int2 stakind[STATISTIC_NUM_SLOTS];
79 Oid staop[STATISTIC_NUM_SLOTS];
80 int numnumbers[STATISTIC_NUM_SLOTS];
81 float4 *stanumbers[STATISTIC_NUM_SLOTS];
82 int numvalues[STATISTIC_NUM_SLOTS];
83 Datum *stavalues[STATISTIC_NUM_SLOTS];
89 Datum value; /* a data value */
90 int tupno; /* position index for tuple it came from */
95 int count; /* # of duplicates */
96 int first; /* values[] index of first occurrence */
100 #define swapInt(a,b) {int _tmp; _tmp=a; a=b; b=_tmp;}
101 #define swapDatum(a,b) {Datum _tmp; _tmp=a; a=b; b=_tmp;}
104 static int MESSAGE_LEVEL;
106 /* context information for compare_scalars() */
107 static FmgrInfo *datumCmpFn;
108 static SortFunctionKind datumCmpFnKind;
109 static int *datumCmpTupnoLink;
112 static VacAttrStats *examine_attribute(Relation onerel, int attnum);
113 static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
114 int targrows, long *totalrows);
115 static double random_fract(void);
116 static double init_selection_state(int n);
117 static long select_next_random_record(long t, int n, double *stateptr);
118 static int compare_rows(const void *a, const void *b);
119 static int compare_scalars(const void *a, const void *b);
120 static int compare_mcvs(const void *a, const void *b);
121 static OffsetNumber get_page_max_offset(Relation relation,
122 BlockNumber blocknumber);
123 static void compute_minimal_stats(VacAttrStats *stats,
124 TupleDesc tupDesc, long totalrows,
125 HeapTuple *rows, int numrows);
126 static void compute_scalar_stats(VacAttrStats *stats,
127 TupleDesc tupDesc, long totalrows,
128 HeapTuple *rows, int numrows);
129 static void update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats);
133 * analyze_rel() -- analyze one relation
136 analyze_rel(Oid relid, VacuumStmt *vacstmt)
139 Form_pg_attribute *attr;
143 VacAttrStats **vacattrstats;
150 if (vacstmt->verbose)
151 MESSAGE_LEVEL = NOTICE;
153 MESSAGE_LEVEL = DEBUG;
156 * Begin a transaction for analyzing this relation.
158 * Note: All memory allocated during ANALYZE will live in
159 * TransactionCommandContext or a subcontext thereof, so it will
160 * all be released by transaction commit at the end of this routine.
162 StartTransactionCommand();
165 * Check for user-requested abort. Note we want this to be inside a
166 * transaction, so xact.c doesn't issue useless NOTICE.
168 CHECK_FOR_INTERRUPTS();
171 * Race condition -- if the pg_class tuple has gone away since the
172 * last time we saw it, we don't need to process it.
174 tuple = SearchSysCache(RELOID,
175 ObjectIdGetDatum(relid),
177 if (!HeapTupleIsValid(tuple))
179 CommitTransactionCommand();
184 * We can ANALYZE any table except pg_statistic. See update_attstats
186 if (strcmp(NameStr(((Form_pg_class) GETSTRUCT(tuple))->relname),
187 StatisticRelationName) == 0)
189 ReleaseSysCache(tuple);
190 CommitTransactionCommand();
193 ReleaseSysCache(tuple);
196 * Open the class, getting only a read lock on it, and check permissions.
197 * Permissions check should match vacuum's check!
199 onerel = heap_open(relid, AccessShareLock);
201 if (! (pg_ownercheck(GetUserId(), RelationGetRelationName(onerel),
203 (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared)))
205 /* No need for a notice if we already complained during VACUUM */
206 if (!vacstmt->vacuum)
207 elog(NOTICE, "Skipping \"%s\" --- only table or database owner can ANALYZE it",
208 RelationGetRelationName(onerel));
209 heap_close(onerel, NoLock);
210 CommitTransactionCommand();
214 elog(MESSAGE_LEVEL, "Analyzing %s", RelationGetRelationName(onerel));
217 * Determine which columns to analyze
219 * Note that system attributes are never analyzed.
221 attr = onerel->rd_att->attrs;
222 attr_cnt = onerel->rd_att->natts;
224 if (vacstmt->va_cols != NIL)
228 vacattrstats = (VacAttrStats **) palloc(length(vacstmt->va_cols) *
229 sizeof(VacAttrStats *));
231 foreach(le, vacstmt->va_cols)
233 char *col = strVal(lfirst(le));
235 for (i = 0; i < attr_cnt; i++)
237 if (namestrcmp(&(attr[i]->attname), col) == 0)
241 elog(ERROR, "ANALYZE: there is no attribute %s in %s",
242 col, RelationGetRelationName(onerel));
243 vacattrstats[tcnt] = examine_attribute(onerel, i+1);
244 if (vacattrstats[tcnt] != NULL)
251 vacattrstats = (VacAttrStats **) palloc(attr_cnt *
252 sizeof(VacAttrStats *));
254 for (i = 0; i < attr_cnt; i++)
256 vacattrstats[tcnt] = examine_attribute(onerel, i+1);
257 if (vacattrstats[tcnt] != NULL)
264 * Quit if no analyzable columns
268 heap_close(onerel, NoLock);
269 CommitTransactionCommand();
274 * Determine how many rows we need to sample, using the worst case
275 * from all analyzable columns. We use a lower bound of 100 rows
276 * to avoid possible overflow in Vitter's algorithm.
279 for (i = 0; i < attr_cnt; i++)
281 if (targrows < vacattrstats[i]->minrows)
282 targrows = vacattrstats[i]->minrows;
286 * Acquire the sample rows
288 rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
289 numrows = acquire_sample_rows(onerel, rows, targrows, &totalrows);
292 * If we are running a standalone ANALYZE, update pages/tuples stats
293 * in pg_class. We have the accurate page count from heap_beginscan,
294 * but only an approximate number of tuples; therefore, if we are
295 * part of VACUUM ANALYZE do *not* overwrite the accurate count already
296 * inserted by VACUUM.
298 if (!vacstmt->vacuum)
299 vac_update_relstats(RelationGetRelid(onerel),
302 RelationGetForm(onerel)->relhasindex);
305 * Compute the statistics. Temporary results during the calculations
306 * for each column are stored in a child context. The calc routines
307 * are responsible to make sure that whatever they store into the
308 * VacAttrStats structure is allocated in TransactionCommandContext.
312 MemoryContext col_context,
315 col_context = AllocSetContextCreate(CurrentMemoryContext,
317 ALLOCSET_DEFAULT_MINSIZE,
318 ALLOCSET_DEFAULT_INITSIZE,
319 ALLOCSET_DEFAULT_MAXSIZE);
320 old_context = MemoryContextSwitchTo(col_context);
321 for (i = 0; i < attr_cnt; i++)
323 switch (vacattrstats[i]->algcode)
326 compute_minimal_stats(vacattrstats[i],
327 onerel->rd_att, totalrows,
331 compute_scalar_stats(vacattrstats[i],
332 onerel->rd_att, totalrows,
336 MemoryContextResetAndDeleteChildren(col_context);
338 MemoryContextSwitchTo(old_context);
339 MemoryContextDelete(col_context);
342 * Emit the completed stats rows into pg_statistic, replacing any
343 * previous statistics for the target columns. (If there are stats
344 * in pg_statistic for columns we didn't process, we leave them alone.)
346 update_attstats(relid, attr_cnt, vacattrstats);
350 * Close source relation now, but keep lock so that no one deletes it
351 * before we commit. (If someone did, they'd fail to clean up the
352 * entries we made in pg_statistic.)
354 heap_close(onerel, NoLock);
356 /* Commit and release working memory */
357 CommitTransactionCommand();
361 * examine_attribute -- pre-analysis of a single column
363 * Determine whether the column is analyzable; if so, create and initialize
364 * a VacAttrStats struct for it. If not, return NULL.
366 static VacAttrStats *
367 examine_attribute(Relation onerel, int attnum)
369 Form_pg_attribute attr = onerel->rd_att->attrs[attnum-1];
370 Operator func_operator;
373 Oid eqopr = InvalidOid;
374 Oid eqfunc = InvalidOid;
375 Oid ltopr = InvalidOid;
378 /* Don't analyze column if user has specified not to */
379 if (attr->attstattarget <= 0)
382 /* If column has no "=" operator, we can't do much of anything */
383 func_operator = compatible_oper("=",
387 if (func_operator != NULL)
389 oprrest = ((Form_pg_operator) GETSTRUCT(func_operator))->oprrest;
390 if (oprrest == F_EQSEL)
392 eqopr = oprid(func_operator);
393 eqfunc = oprfuncid(func_operator);
395 ReleaseSysCache(func_operator);
397 if (!OidIsValid(eqfunc))
401 * If we have "=" then we're at least able to do the minimal algorithm,
402 * so start filling in a VacAttrStats struct.
404 stats = (VacAttrStats *) palloc(sizeof(VacAttrStats));
405 MemSet(stats, 0, sizeof(VacAttrStats));
406 stats->attnum = attnum;
407 stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_TUPLE_SIZE);
408 memcpy(stats->attr, attr, ATTRIBUTE_TUPLE_SIZE);
409 typtuple = SearchSysCache(TYPEOID,
410 ObjectIdGetDatum(attr->atttypid),
412 if (!HeapTupleIsValid(typtuple))
413 elog(ERROR, "cache lookup of type %u failed", attr->atttypid);
414 stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
415 memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
416 ReleaseSysCache(typtuple);
417 stats->eqopr = eqopr;
418 stats->eqfunc = eqfunc;
420 /* Is there a "<" operator with suitable semantics? */
421 func_operator = compatible_oper("<",
425 if (func_operator != NULL)
427 oprrest = ((Form_pg_operator) GETSTRUCT(func_operator))->oprrest;
428 if (oprrest == F_SCALARLTSEL)
430 ltopr = oprid(func_operator);
432 ReleaseSysCache(func_operator);
434 stats->ltopr = ltopr;
437 * Determine the algorithm to use (this will get more complicated later)
439 if (OidIsValid(ltopr))
441 /* Seems to be a scalar datatype */
442 stats->algcode = ALG_SCALAR;
443 /*--------------------
444 * The following choice of minrows is based on the paper
445 * "Random sampling for histogram construction: how much is enough?"
446 * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
447 * Proceedings of ACM SIGMOD International Conference on Management
448 * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
449 * says that for table size n, histogram size k, maximum relative
450 * error in bin size f, and error probability gamma, the minimum
451 * random sample size is
452 * r = 4 * k * ln(2*n/gamma) / f^2
453 * Taking f = 0.5, gamma = 0.01, n = 1 million rows, we obtain
455 * Note that because of the log function, the dependence on n is
456 * quite weak; even at n = 1 billion, a 300*k sample gives <= 0.59
457 * bin size error with probability 0.99. So there's no real need to
458 * scale for n, which is a good thing because we don't necessarily
459 * know it at this point.
460 *--------------------
462 stats->minrows = 300 * attr->attstattarget;
466 /* Can't do much but the minimal stuff */
467 stats->algcode = ALG_MINIMAL;
468 /* Might as well use the same minrows as above */
469 stats->minrows = 300 * attr->attstattarget;
476 * acquire_sample_rows -- acquire a random sample of rows from the table
478 * Up to targrows rows are collected (if there are fewer than that many
479 * rows in the table, all rows are collected). When the table is larger
480 * than targrows, a truly random sample is collected: every row has an
481 * equal chance of ending up in the final sample.
483 * We also estimate the total number of rows in the table, and return that
486 * The returned list of tuples is in order by physical position in the table.
487 * (We will rely on this later to derive correlation estimates.)
490 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
496 ItemPointer lasttuple;
497 BlockNumber lastblock,
499 OffsetNumber lastoffset;
501 double tuplesperpage;
505 Assert(targrows > 1);
507 * Do a simple linear scan until we reach the target number of rows.
509 scan = heap_beginscan(onerel, false, SnapshotNow, 0, NULL);
510 while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
512 rows[numrows++] = heap_copytuple(tuple);
513 if (numrows >= targrows)
518 * If we ran out of tuples then we're done, no matter how few we
519 * collected. No sort is needed, since they're already in order.
521 if (!HeapTupleIsValid(tuple))
523 *totalrows = numrows;
527 * Otherwise, start replacing tuples in the sample until we reach the
528 * end of the relation. This algorithm is from Jeff Vitter's paper
529 * (see full citation below). It works by repeatedly computing the number
530 * of the next tuple we want to fetch, which will replace a randomly
531 * chosen element of the reservoir (current set of tuples). At all times
532 * the reservoir is a true random sample of the tuples we've passed over
533 * so far, so when we fall off the end of the relation we're done.
535 * A slight difficulty is that since we don't want to fetch tuples or even
536 * pages that we skip over, it's not possible to fetch *exactly* the N'th
537 * tuple at each step --- we don't know how many valid tuples are on
538 * the skipped pages. We handle this by assuming that the average number
539 * of valid tuples/page on the pages already scanned over holds good for
540 * the rest of the relation as well; this lets us estimate which page
541 * the next tuple should be on and its position in the page. Then we
542 * fetch the first valid tuple at or after that position, being careful
543 * not to use the same tuple twice. This approach should still give a
544 * good random sample, although it's not perfect.
546 lasttuple = &(rows[numrows-1]->t_self);
547 lastblock = ItemPointerGetBlockNumber(lasttuple);
548 lastoffset = ItemPointerGetOffsetNumber(lasttuple);
550 * If possible, estimate tuples/page using only completely-scanned pages.
552 for (numest = numrows; numest > 0; numest--)
554 if (ItemPointerGetBlockNumber(&(rows[numest-1]->t_self)) != lastblock)
559 numest = numrows; /* don't have a full page? */
560 estblock = lastblock + 1;
564 estblock = lastblock;
566 tuplesperpage = (double) numest / (double) estblock;
568 t = numrows; /* t is the # of records processed so far */
569 rstate = init_selection_state(targrows);
573 BlockNumber targblock;
574 OffsetNumber targoffset,
577 t = select_next_random_record(t, targrows, &rstate);
578 /* Try to read the t'th record in the table */
579 targpos = (double) t / tuplesperpage;
580 targblock = (BlockNumber) targpos;
581 targoffset = ((int) (targpos - targblock) * tuplesperpage) +
583 /* Make sure we are past the last selected record */
584 if (targblock <= lastblock)
586 targblock = lastblock;
587 if (targoffset <= lastoffset)
588 targoffset = lastoffset + 1;
590 /* Loop to find first valid record at or after given position */
593 * Have we fallen off the end of the relation? (We rely on
594 * heap_beginscan to have updated rd_nblocks.)
596 if (targblock >= onerel->rd_nblocks)
598 maxoffset = get_page_max_offset(onerel, targblock);
601 HeapTupleData targtuple;
604 if (targoffset > maxoffset)
606 /* Fell off end of this page, try next */
608 targoffset = FirstOffsetNumber;
611 ItemPointerSet(&targtuple.t_self, targblock, targoffset);
612 heap_fetch(onerel, SnapshotNow, &targtuple, &targbuffer);
613 if (targtuple.t_data != NULL)
616 * Found a suitable tuple, so save it, replacing one old
619 int k = (int) (targrows * random_fract());
621 Assert(k >= 0 && k < targrows);
622 heap_freetuple(rows[k]);
623 rows[k] = heap_copytuple(&targtuple);
624 ReleaseBuffer(targbuffer);
625 lastblock = targblock;
626 lastoffset = targoffset;
629 /* this tuple is dead, so advance to next one on same page */
635 * Now we need to sort the collected tuples by position (itempointer).
637 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
640 * Estimate total number of valid rows in relation.
642 *totalrows = (long) (onerel->rd_nblocks * tuplesperpage + 0.5);
647 /* Select a random value R uniformly distributed in 0 < R < 1 */
653 /* random() can produce endpoint values, try again if so */
657 } while (! (z > 0 && z < MAX_RANDOM_VALUE));
658 return (double) z / (double) MAX_RANDOM_VALUE;
662 * These two routines embody Algorithm Z from "Random sampling with a
663 * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
664 * (Mar. 1985), Pages 37-57. While Vitter describes his algorithm in terms
665 * of the count S of records to skip before processing another record,
666 * it is convenient to work primarily with t, the index (counting from 1)
667 * of the last record processed and next record to process. The only extra
668 * state needed between calls is W, a random state variable.
670 * init_selection_state computes the initial W value.
672 * Given that we've already processed t records (t >= n),
673 * select_next_random_record determines the number of the next record to
677 init_selection_state(int n)
679 /* Initial value of W (for use when Algorithm Z is first applied) */
680 return exp(- log(random_fract())/n);
684 select_next_random_record(long t, int n, double *stateptr)
686 /* The magic constant here is T from Vitter's paper */
689 /* Process records using Algorithm X until t is large enough */
693 V = random_fract(); /* Generate V */
695 quot = (double) (t - n) / (double) t;
696 /* Find min S satisfying (4.1) */
700 quot *= (double) (t - n) / (double) t;
705 /* Now apply Algorithm Z */
706 double W = *stateptr;
707 long term = t - n + 1;
722 /* Generate U and X */
725 S = X; /* S is tentatively set to floor(X) */
726 /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
727 tmp = (double) (t + 1) / (double) term;
728 lhs = exp(log(((U * tmp * tmp) * (term + S))/(t + X))/n);
729 rhs = (((t + X)/(term + S)) * term)/t;
735 /* Test if U <= f(S)/cg(X) */
736 y = (((U * (t + 1))/term) * (t + S + 1))/(t + X);
740 numer_lim = term + S;
747 for (numer = t + S; numer >= numer_lim; numer--)
749 y *= (double) numer / (double) denom;
752 W = exp(- log(random_fract())/n); /* Generate W in advance */
753 if (exp(log(y)/n) <= (t + X)/t)
763 * qsort comparator for sorting rows[] array
766 compare_rows(const void *a, const void *b)
768 HeapTuple ha = * (HeapTuple *) a;
769 HeapTuple hb = * (HeapTuple *) b;
770 BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
771 OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
772 BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
773 OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
787 * Discover the largest valid tuple offset number on the given page
789 * This code probably ought to live in some other module.
792 get_page_max_offset(Relation relation, BlockNumber blocknumber)
798 buffer = ReadBuffer(relation, blocknumber);
799 if (!BufferIsValid(buffer))
800 elog(ERROR, "get_page_max_offset: %s relation: ReadBuffer(%ld) failed",
801 RelationGetRelationName(relation), (long) blocknumber);
802 LockBuffer(buffer, BUFFER_LOCK_SHARE);
803 p = BufferGetPage(buffer);
804 offnum = PageGetMaxOffsetNumber(p);
805 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
806 ReleaseBuffer(buffer);
812 * compute_minimal_stats() -- compute minimal column statistics
814 * We use this when we can find only an "=" operator for the datatype.
816 * We determine the fraction of non-null rows, the average width, the
817 * most common values, and the (estimated) number of distinct values.
819 * The most common values are determined by brute force: we keep a list
820 * of previously seen values, ordered by number of times seen, as we scan
821 * the samples. A newly seen value is inserted just after the last
822 * multiply-seen value, causing the bottommost (oldest) singly-seen value
823 * to drop off the list. The accuracy of this method, and also its cost,
824 * depend mainly on the length of the list we are willing to keep.
827 compute_minimal_stats(VacAttrStats *stats,
828 TupleDesc tupDesc, long totalrows,
829 HeapTuple *rows, int numrows)
835 double total_width = 0;
836 bool is_varlena = (!stats->attr->attbyval &&
837 stats->attr->attlen == -1);
847 int num_mcv = stats->attr->attstattarget;
849 /* We track up to 2*n values for an n-element MCV list; but at least 10 */
850 track_max = 2 * num_mcv;
853 track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
856 fmgr_info(stats->eqfunc, &f_cmpeq);
858 for (i = 0; i < numrows; i++)
860 HeapTuple tuple = rows[i];
867 value = heap_getattr(tuple, stats->attnum, tupDesc, &isnull);
869 /* Check for null/nonnull */
878 * If it's a varlena field, add up widths for average width
879 * calculation. Note that if the value is toasted, we
880 * use the toasted width. We don't bother with this calculation
881 * if it's a fixed-width type.
885 total_width += VARSIZE(DatumGetPointer(value));
887 * If the value is toasted, we want to detoast it just once to
888 * avoid repeated detoastings and resultant excess memory usage
889 * during the comparisons. Also, check to see if the value is
890 * excessively wide, and if so don't detoast at all --- just
893 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
898 value = PointerGetDatum(PG_DETOAST_DATUM(value));
902 * See if the value matches anything we're already tracking.
905 firstcount1 = track_cnt;
906 for (j = 0; j < track_cnt; j++)
908 if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
913 if (j < firstcount1 && track[j].count == 1)
921 /* This value may now need to "bubble up" in the track list */
922 while (j > 0 && track[j].count > track[j-1].count)
924 swapDatum(track[j].value, track[j-1].value);
925 swapInt(track[j].count, track[j-1].count);
931 /* No match. Insert at head of count-1 list */
932 if (track_cnt < track_max)
934 for (j = track_cnt-1; j > firstcount1; j--)
936 track[j].value = track[j-1].value;
937 track[j].count = track[j-1].count;
939 if (firstcount1 < track_cnt)
941 track[firstcount1].value = value;
942 track[firstcount1].count = 1;
947 /* We can only compute valid stats if we found some non-null values. */
953 stats->stats_valid = true;
954 /* Do the simple null-frac and width stats */
955 stats->stanullfrac = (double) null_cnt / (double) numrows;
957 stats->stawidth = total_width / (double) nonnull_cnt;
959 stats->stawidth = stats->attrtype->typlen;
961 /* Count the number of values we found multiple times */
963 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
965 if (track[nmultiple].count == 1)
967 summultiple += track[nmultiple].count;
972 /* If we found no repeated values, assume it's a unique column */
973 stats->stadistinct = -1.0;
975 else if (track_cnt < track_max && toowide_cnt == 0 &&
976 nmultiple == track_cnt)
979 * Our track list includes every value in the sample, and every
980 * value appeared more than once. Assume the column has just
983 stats->stadistinct = track_cnt;
988 * Estimate the number of distinct values using the estimator
989 * proposed by Chaudhuri et al (see citation above). This is
990 * sqrt(n/r) * max(f1,1) + f2 + f3 + ...
991 * where fk is the number of distinct values that occurred
992 * exactly k times in our sample of r rows (from a total of n).
993 * We assume (not very reliably!) that all the multiply-occurring
994 * values are reflected in the final track[] list, and the other
995 * nonnull values all appeared but once. (XXX this usually
996 * results in a drastic overestimate of ndistinct. Can we do
1000 int f1 = nonnull_cnt - summultiple;
1005 term1 = sqrt((double) totalrows / (double) numrows) * f1;
1006 stats->stadistinct = floor(term1 + nmultiple + 0.5);
1010 * If we estimated the number of distinct values at more than 10%
1011 * of the total row count (a very arbitrary limit), then assume
1012 * that stadistinct should scale with the row count rather than be
1015 if (stats->stadistinct > 0.1 * totalrows)
1016 stats->stadistinct = - (stats->stadistinct / totalrows);
1019 * Decide how many values are worth storing as most-common values.
1020 * If we are able to generate a complete MCV list (all the values
1021 * in the sample will fit, and we think these are all the ones in
1022 * the table), then do so. Otherwise, store only those values
1023 * that are significantly more common than the (estimated) average.
1024 * We set the threshold rather arbitrarily at 25% more than average,
1025 * with at least 2 instances in the sample.
1027 if (track_cnt < track_max && toowide_cnt == 0 &&
1028 stats->stadistinct > 0 &&
1029 track_cnt <= num_mcv)
1031 /* Track list includes all values seen, and all will fit */
1032 num_mcv = track_cnt;
1036 double ndistinct = stats->stadistinct;
1041 ndistinct = - ndistinct * totalrows;
1042 /* estimate # of occurrences in sample of a typical value */
1043 avgcount = (double) numrows / ndistinct;
1044 /* set minimum threshold count to store a value */
1045 mincount = avgcount * 1.25;
1048 if (num_mcv > track_cnt)
1049 num_mcv = track_cnt;
1050 for (i = 0; i < num_mcv; i++)
1052 if (track[i].count < mincount)
1060 /* Generate MCV slot entry */
1063 MemoryContext old_context;
1067 /* Must copy the target values into TransactionCommandContext */
1068 old_context = MemoryContextSwitchTo(TransactionCommandContext);
1069 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
1070 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
1071 for (i = 0; i < num_mcv; i++)
1073 mcv_values[i] = datumCopy(track[i].value,
1074 stats->attr->attbyval,
1075 stats->attr->attlen);
1076 mcv_freqs[i] = (double) track[i].count / (double) numrows;
1078 MemoryContextSwitchTo(old_context);
1080 stats->stakind[0] = STATISTIC_KIND_MCV;
1081 stats->staop[0] = stats->eqopr;
1082 stats->stanumbers[0] = mcv_freqs;
1083 stats->numnumbers[0] = num_mcv;
1084 stats->stavalues[0] = mcv_values;
1085 stats->numvalues[0] = num_mcv;
1089 /* We don't need to bother cleaning up any of our temporary palloc's */
1094 * compute_scalar_stats() -- compute column statistics
1096 * We use this when we can find "=" and "<" operators for the datatype.
1098 * We determine the fraction of non-null rows, the average width, the
1099 * most common values, the (estimated) number of distinct values, the
1100 * distribution histogram, and the correlation of physical to logical order.
1102 * The desired stats can be determined fairly easily after sorting the
1103 * data values into order.
1106 compute_scalar_stats(VacAttrStats *stats,
1107 TupleDesc tupDesc, long totalrows,
1108 HeapTuple *rows, int numrows)
1112 int nonnull_cnt = 0;
1113 int toowide_cnt = 0;
1114 double total_width = 0;
1115 bool is_varlena = (!stats->attr->attbyval &&
1116 stats->attr->attlen == -1);
1119 SortFunctionKind cmpFnKind;
1124 ScalarMCVItem *track;
1126 int num_mcv = stats->attr->attstattarget;
1127 int num_bins = stats->attr->attstattarget;
1129 values = (ScalarItem *) palloc(numrows * sizeof(ScalarItem));
1130 tupnoLink = (int *) palloc(numrows * sizeof(int));
1131 track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
1133 SelectSortFunction(stats->ltopr, &cmpFn, &cmpFnKind);
1134 fmgr_info(cmpFn, &f_cmpfn);
1136 /* Initial scan to find sortable values */
1137 for (i = 0; i < numrows; i++)
1139 HeapTuple tuple = rows[i];
1143 value = heap_getattr(tuple, stats->attnum, tupDesc, &isnull);
1145 /* Check for null/nonnull */
1154 * If it's a varlena field, add up widths for average width
1155 * calculation. Note that if the value is toasted, we
1156 * use the toasted width. We don't bother with this calculation
1157 * if it's a fixed-width type.
1161 total_width += VARSIZE(DatumGetPointer(value));
1163 * If the value is toasted, we want to detoast it just once to
1164 * avoid repeated detoastings and resultant excess memory usage
1165 * during the comparisons. Also, check to see if the value is
1166 * excessively wide, and if so don't detoast at all --- just
1169 if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1174 value = PointerGetDatum(PG_DETOAST_DATUM(value));
1177 /* Add it to the list to be sorted */
1178 values[values_cnt].value = value;
1179 values[values_cnt].tupno = values_cnt;
1180 tupnoLink[values_cnt] = values_cnt;
1184 /* We can only compute valid stats if we found some sortable values. */
1187 int ndistinct, /* # distinct values in sample */
1188 nmultiple, /* # that appear multiple times */
1193 /* Sort the collected values */
1194 datumCmpFn = &f_cmpfn;
1195 datumCmpFnKind = cmpFnKind;
1196 datumCmpTupnoLink = tupnoLink;
1197 qsort((void *) values, values_cnt,
1198 sizeof(ScalarItem), compare_scalars);
1201 * Now scan the values in order, find the most common ones,
1202 * and also accumulate ordering-correlation statistics.
1204 * To determine which are most common, we first have to count the
1205 * number of duplicates of each value. The duplicates are adjacent
1206 * in the sorted list, so a brute-force approach is to compare
1207 * successive datum values until we find two that are not equal.
1208 * However, that requires N-1 invocations of the datum comparison
1209 * routine, which are completely redundant with work that was done
1210 * during the sort. (The sort algorithm must at some point have
1211 * compared each pair of items that are adjacent in the sorted order;
1212 * otherwise it could not know that it's ordered the pair correctly.)
1213 * We exploit this by having compare_scalars remember the highest
1214 * tupno index that each ScalarItem has been found equal to. At the
1215 * end of the sort, a ScalarItem's tupnoLink will still point to
1216 * itself if and only if it is the last item of its group of
1217 * duplicates (since the group will be ordered by tupno).
1223 for (i = 0; i < values_cnt; i++)
1225 int tupno = values[i].tupno;
1227 corr_xysum += (double) i * (double) tupno;
1229 if (tupnoLink[tupno] == tupno)
1231 /* Reached end of duplicates of this value */
1236 if (track_cnt < num_mcv ||
1237 dups_cnt > track[track_cnt-1].count)
1240 * Found a new item for the mcv list; find its
1241 * position, bubbling down old items if needed.
1242 * Loop invariant is that j points at an empty/
1247 if (track_cnt < num_mcv)
1249 for (j = track_cnt-1; j > 0; j--)
1251 if (dups_cnt <= track[j-1].count)
1253 track[j].count = track[j-1].count;
1254 track[j].first = track[j-1].first;
1256 track[j].count = dups_cnt;
1257 track[j].first = i + 1 - dups_cnt;
1264 stats->stats_valid = true;
1265 /* Do the simple null-frac and width stats */
1266 stats->stanullfrac = (double) null_cnt / (double) numrows;
1268 stats->stawidth = total_width / (double) nonnull_cnt;
1270 stats->stawidth = stats->attrtype->typlen;
1274 /* If we found no repeated values, assume it's a unique column */
1275 stats->stadistinct = -1.0;
1277 else if (toowide_cnt == 0 && nmultiple == ndistinct)
1280 * Every value in the sample appeared more than once. Assume the
1281 * column has just these values.
1283 stats->stadistinct = ndistinct;
1288 * Estimate the number of distinct values using the estimator
1289 * proposed by Chaudhuri et al (see citation above). This is
1290 * sqrt(n/r) * max(f1,1) + f2 + f3 + ...
1291 * where fk is the number of distinct values that occurred
1292 * exactly k times in our sample of r rows (from a total of n).
1293 * Overwidth values are assumed to have been distinct.
1296 int f1 = ndistinct - nmultiple + toowide_cnt;
1301 term1 = sqrt((double) totalrows / (double) numrows) * f1;
1302 stats->stadistinct = floor(term1 + nmultiple + 0.5);
1306 * If we estimated the number of distinct values at more than 10%
1307 * of the total row count (a very arbitrary limit), then assume
1308 * that stadistinct should scale with the row count rather than be
1311 if (stats->stadistinct > 0.1 * totalrows)
1312 stats->stadistinct = - (stats->stadistinct / totalrows);
1315 * Decide how many values are worth storing as most-common values.
1316 * If we are able to generate a complete MCV list (all the values
1317 * in the sample will fit, and we think these are all the ones in
1318 * the table), then do so. Otherwise, store only those values
1319 * that are significantly more common than the (estimated) average.
1320 * We set the threshold rather arbitrarily at 25% more than average,
1321 * with at least 2 instances in the sample. Also, we won't suppress
1322 * values that have a frequency of at least 1/K where K is the
1323 * intended number of histogram bins; such values might otherwise
1324 * cause us to emit duplicate histogram bin boundaries.
1326 if (track_cnt == ndistinct && toowide_cnt == 0 &&
1327 stats->stadistinct > 0 &&
1328 track_cnt <= num_mcv)
1330 /* Track list includes all values seen, and all will fit */
1331 num_mcv = track_cnt;
1335 double ndistinct = stats->stadistinct;
1341 ndistinct = - ndistinct * totalrows;
1342 /* estimate # of occurrences in sample of a typical value */
1343 avgcount = (double) numrows / ndistinct;
1344 /* set minimum threshold count to store a value */
1345 mincount = avgcount * 1.25;
1348 /* don't let threshold exceed 1/K, however */
1349 maxmincount = (double) numrows / (double) num_bins;
1350 if (mincount > maxmincount)
1351 mincount = maxmincount;
1352 if (num_mcv > track_cnt)
1353 num_mcv = track_cnt;
1354 for (i = 0; i < num_mcv; i++)
1356 if (track[i].count < mincount)
1364 /* Generate MCV slot entry */
1367 MemoryContext old_context;
1371 /* Must copy the target values into TransactionCommandContext */
1372 old_context = MemoryContextSwitchTo(TransactionCommandContext);
1373 mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
1374 mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
1375 for (i = 0; i < num_mcv; i++)
1377 mcv_values[i] = datumCopy(values[track[i].first].value,
1378 stats->attr->attbyval,
1379 stats->attr->attlen);
1380 mcv_freqs[i] = (double) track[i].count / (double) numrows;
1382 MemoryContextSwitchTo(old_context);
1384 stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
1385 stats->staop[slot_idx] = stats->eqopr;
1386 stats->stanumbers[slot_idx] = mcv_freqs;
1387 stats->numnumbers[slot_idx] = num_mcv;
1388 stats->stavalues[slot_idx] = mcv_values;
1389 stats->numvalues[slot_idx] = num_mcv;
1394 * Generate a histogram slot entry if there are at least two
1395 * distinct values not accounted for in the MCV list. (This
1396 * ensures the histogram won't collapse to empty or a singleton.)
1398 num_hist = ndistinct - num_mcv;
1399 if (num_hist > num_bins)
1400 num_hist = num_bins + 1;
1403 MemoryContext old_context;
1407 /* Sort the MCV items into position order to speed next loop */
1408 qsort((void *) track, num_mcv,
1409 sizeof(ScalarMCVItem), compare_mcvs);
1412 * Collapse out the MCV items from the values[] array.
1414 * Note we destroy the values[] array here... but we don't need
1415 * it for anything more. We do, however, still need values_cnt.
1416 * nvals will be the number of remaining entries in values[].
1425 j = 0; /* index of next interesting MCV item */
1426 while (src < values_cnt)
1432 int first = track[j].first;
1436 /* advance past this MCV item */
1437 src = first + track[j].count;
1441 ncopy = first - src;
1445 ncopy = values_cnt - src;
1447 memmove(&values[dest], &values[src],
1448 ncopy * sizeof(ScalarItem));
1456 Assert(nvals >= num_hist);
1458 /* Must copy the target values into TransactionCommandContext */
1459 old_context = MemoryContextSwitchTo(TransactionCommandContext);
1460 hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
1461 for (i = 0; i < num_hist; i++)
1465 pos = (i * (nvals - 1)) / (num_hist - 1);
1466 hist_values[i] = datumCopy(values[pos].value,
1467 stats->attr->attbyval,
1468 stats->attr->attlen);
1470 MemoryContextSwitchTo(old_context);
1472 stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
1473 stats->staop[slot_idx] = stats->ltopr;
1474 stats->stavalues[slot_idx] = hist_values;
1475 stats->numvalues[slot_idx] = num_hist;
1479 /* Generate a correlation entry if there are multiple values */
1482 MemoryContext old_context;
1487 /* Must copy the target values into TransactionCommandContext */
1488 old_context = MemoryContextSwitchTo(TransactionCommandContext);
1489 corrs = (float4 *) palloc(sizeof(float4));
1490 MemoryContextSwitchTo(old_context);
1493 * Since we know the x and y value sets are both
1494 * 0, 1, ..., values_cnt-1
1495 * we have sum(x) = sum(y) =
1496 * (values_cnt-1)*values_cnt / 2
1497 * and sum(x^2) = sum(y^2) =
1498 * (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
1501 corr_xsum = (double) (values_cnt-1) * (double) values_cnt / 2.0;
1502 corr_x2sum = (double) (values_cnt-1) * (double) values_cnt *
1503 (double) (2*values_cnt-1) / 6.0;
1504 /* And the correlation coefficient reduces to */
1505 corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
1506 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
1508 stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
1509 stats->staop[slot_idx] = stats->ltopr;
1510 stats->stanumbers[slot_idx] = corrs;
1511 stats->numnumbers[slot_idx] = 1;
1516 /* We don't need to bother cleaning up any of our temporary palloc's */
1520 * qsort comparator for sorting ScalarItems
1522 * Aside from sorting the items, we update the datumCmpTupnoLink[] array
1523 * whenever two ScalarItems are found to contain equal datums. The array
1524 * is indexed by tupno; for each ScalarItem, it contains the highest
1525 * tupno that that item's datum has been found to be equal to. This allows
1526 * us to avoid additional comparisons in compute_scalar_stats().
1529 compare_scalars(const void *a, const void *b)
1531 Datum da = ((ScalarItem *) a)->value;
1532 int ta = ((ScalarItem *) a)->tupno;
1533 Datum db = ((ScalarItem *) b)->value;
1534 int tb = ((ScalarItem *) b)->tupno;
1537 compare = ApplySortFunction(datumCmpFn, datumCmpFnKind,
1538 da, false, db, false);
1543 * The two datums are equal, so update datumCmpTupnoLink[].
1545 if (datumCmpTupnoLink[ta] < tb)
1546 datumCmpTupnoLink[ta] = tb;
1547 if (datumCmpTupnoLink[tb] < ta)
1548 datumCmpTupnoLink[tb] = ta;
1551 * For equal datums, sort by tupno
1557 * qsort comparator for sorting ScalarMCVItems by position
1560 compare_mcvs(const void *a, const void *b)
1562 int da = ((ScalarMCVItem *) a)->first;
1563 int db = ((ScalarMCVItem *) b)->first;
1570 * update_attstats() -- update attribute statistics for one relation
1572 * Statistics are stored in several places: the pg_class row for the
1573 * relation has stats about the whole relation, and there is a
1574 * pg_statistic row for each (non-system) attribute that has ever
1575 * been analyzed. The pg_class values are updated by VACUUM, not here.
1577 * pg_statistic rows are just added or updated normally. This means
1578 * that pg_statistic will probably contain some deleted rows at the
1579 * completion of a vacuum cycle, unless it happens to get vacuumed last.
1581 * To keep things simple, we punt for pg_statistic, and don't try
1582 * to compute or store rows for pg_statistic itself in pg_statistic.
1583 * This could possibly be made to work, but it's not worth the trouble.
1584 * Note analyze_rel() has seen to it that we won't come here when
1585 * vacuuming pg_statistic itself.
1588 update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats)
1594 * We use an ExclusiveLock on pg_statistic to ensure that only one
1595 * backend is writing it at a time --- without that, we might have to
1596 * deal with concurrent updates here, and it's not worth the trouble.
1598 sd = heap_openr(StatisticRelationName, ExclusiveLock);
1600 for (attno = 0; attno < natts; attno++)
1602 VacAttrStats *stats = vacattrstats[attno];
1603 FmgrInfo out_function;
1607 Datum values[Natts_pg_statistic];
1608 char nulls[Natts_pg_statistic];
1609 char replaces[Natts_pg_statistic];
1610 Relation irelations[Num_pg_statistic_indices];
1612 /* Ignore attr if we weren't able to collect stats */
1613 if (!stats->stats_valid)
1616 fmgr_info(stats->attrtype->typoutput, &out_function);
1619 * Construct a new pg_statistic tuple
1621 for (i = 0; i < Natts_pg_statistic; ++i)
1628 values[i++] = ObjectIdGetDatum(relid); /* starelid */
1629 values[i++] = Int16GetDatum(stats->attnum); /* staattnum */
1630 values[i++] = Float4GetDatum(stats->stanullfrac); /* stanullfrac */
1631 values[i++] = Int32GetDatum(stats->stawidth); /* stawidth */
1632 values[i++] = Float4GetDatum(stats->stadistinct); /* stadistinct */
1633 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1635 values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1637 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1639 values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1641 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1643 int nnum = stats->numnumbers[k];
1647 Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1650 for (n = 0; n < nnum; n++)
1651 numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1652 /* XXX knows more than it should about type float4: */
1653 arry = construct_array(numdatums, nnum,
1654 false, sizeof(float4), 'i');
1655 values[i++] = PointerGetDatum(arry); /* stanumbersN */
1660 values[i++] = (Datum) 0;
1663 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1665 int ntxt = stats->numvalues[k];
1669 Datum *txtdatums = (Datum *) palloc(ntxt * sizeof(Datum));
1672 for (n = 0; n < ntxt; n++)
1675 * Convert data values to a text string to be inserted
1676 * into the text array.
1681 FunctionCall3(&out_function,
1682 stats->stavalues[k][n],
1683 ObjectIdGetDatum(stats->attrtype->typelem),
1684 Int32GetDatum(stats->attr->atttypmod));
1685 txtdatums[n] = DirectFunctionCall1(textin, stringdatum);
1686 pfree(DatumGetPointer(stringdatum));
1688 /* XXX knows more than it should about type text: */
1689 arry = construct_array(txtdatums, ntxt,
1691 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1696 values[i++] = (Datum) 0;
1700 /* Is there already a pg_statistic tuple for this attribute? */
1701 oldtup = SearchSysCache(STATRELATT,
1702 ObjectIdGetDatum(relid),
1703 Int16GetDatum(stats->attnum),
1706 if (HeapTupleIsValid(oldtup))
1708 /* Yes, replace it */
1709 stup = heap_modifytuple(oldtup,
1714 ReleaseSysCache(oldtup);
1715 simple_heap_update(sd, &stup->t_self, stup);
1719 /* No, insert new tuple */
1720 stup = heap_formtuple(sd->rd_att, values, nulls);
1721 heap_insert(sd, stup);
1724 /* update indices too */
1725 CatalogOpenIndices(Num_pg_statistic_indices, Name_pg_statistic_indices,
1727 CatalogIndexInsert(irelations, Num_pg_statistic_indices, sd, stup);
1728 CatalogCloseIndices(Num_pg_statistic_indices, irelations);
1730 heap_freetuple(stup);
1733 /* close rel, but hold lock till upcoming commit */
1734 heap_close(sd, NoLock);