OSDN Git Service

c650ff88a1a27dad25b955b03064aad24b09aae9
[pg-rex/syncrep.git] / src / backend / commands / analyze.c
1 /*-------------------------------------------------------------------------
2  *
3  * analyze.c
4  *        the postgres statistics generator
5  *
6  * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/commands/analyze.c,v 1.20 2001/06/13 21:44:40 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <math.h>
18
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"
35
36
37 /*
38  * Analysis algorithms supported
39  */
40 typedef enum {
41         ALG_MINIMAL = 1,                        /* Compute only most-common-values */
42         ALG_SCALAR                                      /* Compute MCV, histogram, sort correlation */
43 } AlgCode;
44
45 /*
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.
53  */
54 #define WIDTH_THRESHOLD  256
55
56 /*
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.
60  */
61 typedef struct
62 {
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 */
72
73         /* These fields are filled in by the actual statistics-gathering routine */
74         bool            stats_valid;
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];
84 } VacAttrStats;
85
86
87 typedef struct
88 {
89         Datum           value;                  /* a data value */
90         int                     tupno;                  /* position index for tuple it came from */
91 } ScalarItem;
92
93 typedef struct
94 {
95         int                     count;                  /* # of duplicates */
96         int                     first;                  /* values[] index of first occurrence */
97 } ScalarMCVItem;
98
99
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;}
102
103
104 static int MESSAGE_LEVEL;
105
106 /* context information for compare_scalars() */
107 static FmgrInfo *datumCmpFn;
108 static SortFunctionKind datumCmpFnKind;
109 static int *datumCmpTupnoLink;
110
111
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);
130
131
132 /*
133  *      analyze_rel() -- analyze one relation
134  */
135 void
136 analyze_rel(Oid relid, VacuumStmt *vacstmt)
137 {
138         Relation        onerel;
139         Form_pg_attribute *attr;
140         int                     attr_cnt,
141                                 tcnt,
142                                 i;
143         VacAttrStats **vacattrstats;
144         int                     targrows,
145                                 numrows;
146         long            totalrows;
147         HeapTuple  *rows;
148         HeapTuple       tuple;
149
150         if (vacstmt->verbose)
151                 MESSAGE_LEVEL = NOTICE;
152         else
153                 MESSAGE_LEVEL = DEBUG;
154
155         /*
156          * Begin a transaction for analyzing this relation.
157          *
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.
161          */
162         StartTransactionCommand();
163
164         /*
165          * Check for user-requested abort.      Note we want this to be inside a
166          * transaction, so xact.c doesn't issue useless NOTICE.
167          */
168         CHECK_FOR_INTERRUPTS();
169
170         /*
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.
173          */
174         tuple = SearchSysCache(RELOID,
175                                                    ObjectIdGetDatum(relid),
176                                                    0, 0, 0);
177         if (!HeapTupleIsValid(tuple))
178         {
179                 CommitTransactionCommand();
180                 return;
181         }
182
183         /*
184          * We can ANALYZE any table except pg_statistic. See update_attstats
185          */
186         if (strcmp(NameStr(((Form_pg_class) GETSTRUCT(tuple))->relname),
187                            StatisticRelationName) == 0)
188         {
189                 ReleaseSysCache(tuple);
190                 CommitTransactionCommand();
191                 return;
192         }
193         ReleaseSysCache(tuple);
194
195         /*
196          * Open the class, getting only a read lock on it, and check permissions.
197          * Permissions check should match vacuum's check!
198          */
199         onerel = heap_open(relid, AccessShareLock);
200
201         if (! (pg_ownercheck(GetUserId(), RelationGetRelationName(onerel),
202                                                  RELNAME) ||
203                    (is_dbadmin(MyDatabaseId) && !onerel->rd_rel->relisshared)))
204         {
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();
211                 return;
212         }
213
214         elog(MESSAGE_LEVEL, "Analyzing %s", RelationGetRelationName(onerel));
215
216         /*
217          * Determine which columns to analyze
218          *
219          * Note that system attributes are never analyzed.
220          */
221         attr = onerel->rd_att->attrs;
222         attr_cnt = onerel->rd_att->natts;
223
224         if (vacstmt->va_cols != NIL)
225         {
226                 List       *le;
227
228                 vacattrstats = (VacAttrStats **) palloc(length(vacstmt->va_cols) *
229                                                                                                 sizeof(VacAttrStats *));
230                 tcnt = 0;
231                 foreach(le, vacstmt->va_cols)
232                 {
233                         char       *col = strVal(lfirst(le));
234
235                         for (i = 0; i < attr_cnt; i++)
236                         {
237                                 if (namestrcmp(&(attr[i]->attname), col) == 0)
238                                         break;
239                         }
240                         if (i >= attr_cnt)
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)
245                                 tcnt++;
246                 }
247                 attr_cnt = tcnt;
248         }
249         else
250         {
251                 vacattrstats = (VacAttrStats **) palloc(attr_cnt *
252                                                                                                 sizeof(VacAttrStats *));
253                 tcnt = 0;
254                 for (i = 0; i < attr_cnt; i++)
255                 {
256                         vacattrstats[tcnt] = examine_attribute(onerel, i+1);
257                         if (vacattrstats[tcnt] != NULL)
258                                 tcnt++;
259                 }
260                 attr_cnt = tcnt;
261         }
262
263         /*
264          * Quit if no analyzable columns
265          */
266         if (attr_cnt <= 0)
267         {
268                 heap_close(onerel, NoLock);
269                 CommitTransactionCommand();
270                 return;
271         }
272
273         /*
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.
277          */
278         targrows = 100;
279         for (i = 0; i < attr_cnt; i++)
280         {
281                 if (targrows < vacattrstats[i]->minrows)
282                         targrows = vacattrstats[i]->minrows;
283         }
284
285         /*
286          * Acquire the sample rows
287          */
288         rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
289         numrows = acquire_sample_rows(onerel, rows, targrows, &totalrows);
290
291         /*
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.
297          */
298         if (!vacstmt->vacuum)
299                 vac_update_relstats(RelationGetRelid(onerel),
300                                                         onerel->rd_nblocks,
301                                                         (double) totalrows,
302                                                         RelationGetForm(onerel)->relhasindex);
303
304         /*
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.
309          */
310         if (numrows > 0)
311         {
312                 MemoryContext col_context,
313                                         old_context;
314
315                 col_context = AllocSetContextCreate(CurrentMemoryContext,
316                                                                                         "Analyze Column",
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++)
322                 {
323                         switch (vacattrstats[i]->algcode)
324                         {
325                                 case ALG_MINIMAL:
326                                         compute_minimal_stats(vacattrstats[i],
327                                                                                   onerel->rd_att, totalrows,
328                                                                                   rows, numrows);
329                                         break;
330                                 case ALG_SCALAR:
331                                         compute_scalar_stats(vacattrstats[i],
332                                                                                  onerel->rd_att, totalrows,
333                                                                                  rows, numrows);
334                                         break;
335                         }
336                         MemoryContextResetAndDeleteChildren(col_context);
337                 }
338                 MemoryContextSwitchTo(old_context);
339                 MemoryContextDelete(col_context);
340
341                 /*
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.)
345                  */
346                 update_attstats(relid, attr_cnt, vacattrstats);
347         }
348
349         /*
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.)
353          */
354         heap_close(onerel, NoLock);
355
356         /* Commit and release working memory */
357         CommitTransactionCommand();
358 }
359
360 /*
361  * examine_attribute -- pre-analysis of a single column
362  *
363  * Determine whether the column is analyzable; if so, create and initialize
364  * a VacAttrStats struct for it.  If not, return NULL.
365  */
366 static VacAttrStats *
367 examine_attribute(Relation onerel, int attnum)
368 {
369         Form_pg_attribute attr = onerel->rd_att->attrs[attnum-1];
370         Operator        func_operator;
371         Oid                     oprrest;
372         HeapTuple       typtuple;
373         Oid                     eqopr = InvalidOid;
374         Oid                     eqfunc = InvalidOid;
375         Oid                     ltopr = InvalidOid;
376         VacAttrStats *stats;
377
378         /* Don't analyze column if user has specified not to */
379         if (attr->attstattarget <= 0)
380                 return NULL;
381
382         /* If column has no "=" operator, we can't do much of anything */
383         func_operator = compatible_oper("=",
384                                                                         attr->atttypid,
385                                                                         attr->atttypid,
386                                                                         true);
387         if (func_operator != NULL)
388         {
389                 oprrest = ((Form_pg_operator) GETSTRUCT(func_operator))->oprrest;
390                 if (oprrest == F_EQSEL)
391                 {
392                         eqopr = oprid(func_operator);
393                         eqfunc = oprfuncid(func_operator);
394                 }
395                 ReleaseSysCache(func_operator);
396         }
397         if (!OidIsValid(eqfunc))
398                 return NULL;
399
400         /*
401          * If we have "=" then we're at least able to do the minimal algorithm,
402          * so start filling in a VacAttrStats struct.
403          */
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),
411                                                           0, 0, 0);
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;
419
420         /* Is there a "<" operator with suitable semantics? */
421         func_operator = compatible_oper("<",
422                                                                         attr->atttypid,
423                                                                         attr->atttypid,
424                                                                         true);
425         if (func_operator != NULL)
426         {
427                 oprrest = ((Form_pg_operator) GETSTRUCT(func_operator))->oprrest;
428                 if (oprrest == F_SCALARLTSEL)
429                 {
430                         ltopr = oprid(func_operator);
431                 }
432                 ReleaseSysCache(func_operator);
433         }
434         stats->ltopr = ltopr;
435
436         /*
437          * Determine the algorithm to use (this will get more complicated later)
438          */
439         if (OidIsValid(ltopr))
440         {
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
454                  *              r = 305.82 * k
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                  *--------------------
461                  */
462                 stats->minrows = 300 * attr->attstattarget;
463         }
464         else
465         {
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;
470         }
471
472         return stats;
473 }
474
475 /*
476  * acquire_sample_rows -- acquire a random sample of rows from the table
477  *
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.
482  *
483  * We also estimate the total number of rows in the table, and return that
484  * into *totalrows.
485  *
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.)
488  */
489 static int
490 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
491                                         long *totalrows)
492 {
493         int                     numrows = 0;
494         HeapScanDesc scan;
495         HeapTuple       tuple;
496         ItemPointer     lasttuple;
497         BlockNumber     lastblock,
498                                 estblock;
499         OffsetNumber lastoffset;
500         int                     numest;
501         double          tuplesperpage;
502         long            t;
503         double          rstate;
504
505         Assert(targrows > 1);
506         /*
507          * Do a simple linear scan until we reach the target number of rows.
508          */
509         scan = heap_beginscan(onerel, false, SnapshotNow, 0, NULL);
510         while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
511         {
512                 rows[numrows++] = heap_copytuple(tuple);
513                 if (numrows >= targrows)
514                         break;
515         }
516         heap_endscan(scan);
517         /*
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.
520          */
521         if (!HeapTupleIsValid(tuple))
522         {
523                 *totalrows = numrows;
524                 return numrows;
525         }
526         /*
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.
534          *
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.
545          */
546         lasttuple = &(rows[numrows-1]->t_self);
547         lastblock = ItemPointerGetBlockNumber(lasttuple);
548         lastoffset = ItemPointerGetOffsetNumber(lasttuple);
549         /*
550          * If possible, estimate tuples/page using only completely-scanned pages.
551          */
552         for (numest = numrows; numest > 0; numest--)
553         {
554                 if (ItemPointerGetBlockNumber(&(rows[numest-1]->t_self)) != lastblock)
555                         break;
556         }
557         if (numest == 0)
558         {
559                 numest = numrows;               /* don't have a full page? */
560                 estblock = lastblock + 1;
561         }
562         else
563         {
564                 estblock = lastblock;
565         }
566         tuplesperpage = (double) numest / (double) estblock;
567
568         t = numrows;                            /* t is the # of records processed so far */
569         rstate = init_selection_state(targrows);
570         for (;;)
571         {
572                 double                  targpos;
573                 BlockNumber             targblock;
574                 OffsetNumber    targoffset,
575                                                 maxoffset;
576
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) + 
582                         FirstOffsetNumber;
583                 /* Make sure we are past the last selected record */
584                 if (targblock <= lastblock)
585                 {
586                         targblock = lastblock;
587                         if (targoffset <= lastoffset)
588                                 targoffset = lastoffset + 1;
589                 }
590                 /* Loop to find first valid record at or after given position */
591         pageloop:;
592                 /*
593                  * Have we fallen off the end of the relation?  (We rely on
594                  * heap_beginscan to have updated rd_nblocks.)
595                  */
596                 if (targblock >= onerel->rd_nblocks)
597                         break;
598                 maxoffset = get_page_max_offset(onerel, targblock);
599                 for (;;)
600                 {
601                         HeapTupleData targtuple;
602                         Buffer          targbuffer;
603
604                         if (targoffset > maxoffset)
605                         {
606                                 /* Fell off end of this page, try next */
607                                 targblock++;
608                                 targoffset = FirstOffsetNumber;
609                                 goto pageloop;
610                         }
611                         ItemPointerSet(&targtuple.t_self, targblock, targoffset);
612                         heap_fetch(onerel, SnapshotNow, &targtuple, &targbuffer);
613                         if (targtuple.t_data != NULL)
614                         {
615                                 /*
616                                  * Found a suitable tuple, so save it, replacing one old
617                                  * tuple at random
618                                  */
619                                 int             k = (int) (targrows * random_fract());
620
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;
627                                 break;
628                         }
629                         /* this tuple is dead, so advance to next one on same page */
630                         targoffset++;
631                 }
632         }
633
634         /*
635          * Now we need to sort the collected tuples by position (itempointer).
636          */
637         qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
638
639         /*
640          * Estimate total number of valid rows in relation.
641          */
642         *totalrows = (long) (onerel->rd_nblocks * tuplesperpage + 0.5);
643
644         return numrows;
645 }
646
647 /* Select a random value R uniformly distributed in 0 < R < 1 */
648 static double
649 random_fract(void)
650 {
651         long    z;
652
653         /* random() can produce endpoint values, try again if so */
654         do
655         {
656                 z = random();
657         } while (! (z > 0 && z < MAX_RANDOM_VALUE));
658         return (double) z / (double) MAX_RANDOM_VALUE;
659 }
660
661 /*
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.
669  *
670  * init_selection_state computes the initial W value.
671  *
672  * Given that we've already processed t records (t >= n),
673  * select_next_random_record determines the number of the next record to
674  * process.
675  */
676 static double
677 init_selection_state(int n)
678 {
679         /* Initial value of W (for use when Algorithm Z is first applied) */
680         return exp(- log(random_fract())/n);
681 }
682
683 static long
684 select_next_random_record(long t, int n, double *stateptr)
685 {
686         /* The magic constant here is T from Vitter's paper */
687         if (t <= (22 * n))
688         {
689                 /* Process records using Algorithm X until t is large enough */
690                 double  V,
691                                 quot;
692
693                 V = random_fract();             /* Generate V */
694                 t++;
695                 quot = (double) (t - n) / (double) t;
696                 /* Find min S satisfying (4.1) */
697                 while (quot > V)
698                 {
699                         t++;
700                         quot *= (double) (t - n) / (double) t;
701                 }
702         }
703         else
704         {
705                 /* Now apply Algorithm Z */
706                 double  W = *stateptr;
707                 long    term = t - n + 1;
708                 int             S;
709
710                 for (;;)
711                 {
712                         long    numer,
713                                         numer_lim,
714                                         denom;
715                         double  U,
716                                         X,
717                                         lhs,
718                                         rhs,
719                                         y,
720                                         tmp;
721
722                         /* Generate U and X */
723                         U = random_fract();
724                         X = t * (W - 1.0);
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;
730                         if (lhs <= rhs)
731                         {
732                                 W = rhs/lhs;
733                                 break;
734                         }
735                         /* Test if U <= f(S)/cg(X) */
736                         y = (((U * (t + 1))/term) * (t + S + 1))/(t + X);
737                         if (n < S)
738                         {
739                                 denom = t;
740                                 numer_lim = term + S;
741                         }
742                         else
743                         {
744                                 denom = t - n + S;
745                                 numer_lim = t + 1;
746                         }
747                         for (numer = t + S; numer >= numer_lim; numer--)
748                         {
749                                 y *= (double) numer / (double) denom;
750                                 denom--;
751                         }
752                         W = exp(- log(random_fract())/n); /* Generate W in advance */
753                         if (exp(log(y)/n) <= (t + X)/t)
754                                 break;
755                 }
756                 t += S + 1;
757                 *stateptr = W;
758         }
759         return t;
760 }
761
762 /*
763  * qsort comparator for sorting rows[] array
764  */
765 static int
766 compare_rows(const void *a, const void *b)
767 {
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);
774
775         if (ba < bb)
776                 return -1;
777         if (ba > bb)
778                 return 1;
779         if (oa < ob)
780                 return -1;
781         if (oa > ob)
782                 return 1;
783         return 0;
784 }
785
786 /*
787  * Discover the largest valid tuple offset number on the given page
788  *
789  * This code probably ought to live in some other module.
790  */
791 static OffsetNumber
792 get_page_max_offset(Relation relation, BlockNumber blocknumber)
793 {
794         Buffer          buffer;
795         Page            p;
796         OffsetNumber offnum;
797
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);
807         return offnum;
808 }
809
810
811 /*
812  *      compute_minimal_stats() -- compute minimal column statistics
813  *
814  *      We use this when we can find only an "=" operator for the datatype.
815  *
816  *      We determine the fraction of non-null rows, the average width, the
817  *      most common values, and the (estimated) number of distinct values.
818  *
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.
825  */
826 static void
827 compute_minimal_stats(VacAttrStats *stats,
828                                           TupleDesc tupDesc, long totalrows,
829                                           HeapTuple *rows, int numrows)
830 {
831         int                     i;
832         int                     null_cnt = 0;
833         int                     nonnull_cnt = 0;
834         int                     toowide_cnt = 0;
835         double          total_width = 0;
836         bool            is_varlena = (!stats->attr->attbyval &&
837                                                           stats->attr->attlen == -1);
838         FmgrInfo        f_cmpeq;
839         typedef struct
840         {
841                 Datum   value;
842                 int             count;
843         } TrackItem;
844         TrackItem  *track;
845         int                     track_cnt,
846                                 track_max;
847         int                     num_mcv = stats->attr->attstattarget;
848
849         /* We track up to 2*n values for an n-element MCV list; but at least 10 */
850         track_max = 2 * num_mcv;
851         if (track_max < 10)
852                 track_max = 10;
853         track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
854         track_cnt = 0;
855
856         fmgr_info(stats->eqfunc, &f_cmpeq);
857
858         for (i = 0; i < numrows; i++)
859         {
860                 HeapTuple       tuple = rows[i];
861                 Datum           value;
862                 bool            isnull;
863                 bool            match;
864                 int                     firstcount1,
865                                         j;
866
867                 value = heap_getattr(tuple, stats->attnum, tupDesc, &isnull);
868
869                 /* Check for null/nonnull */
870                 if (isnull)
871                 {
872                         null_cnt++;
873                         continue;
874                 }
875                 nonnull_cnt++;
876
877                 /*
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.
882                  */
883                 if (is_varlena)
884                 {
885                         total_width += VARSIZE(DatumGetPointer(value));
886                         /*
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
891                          * ignore the value.
892                          */
893                         if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
894                         {
895                                 toowide_cnt++;
896                                 continue;
897                         }
898                         value = PointerGetDatum(PG_DETOAST_DATUM(value));
899                 }
900
901                 /*
902                  * See if the value matches anything we're already tracking.
903                  */
904                 match = false;
905                 firstcount1 = track_cnt;
906                 for (j = 0; j < track_cnt; j++)
907                 {
908                         if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
909                         {
910                                 match = true;
911                                 break;
912                         }
913                         if (j < firstcount1 && track[j].count == 1)
914                                 firstcount1 = j;
915                 }
916
917                 if (match)
918                 {
919                         /* Found a match */
920                         track[j].count++;
921                         /* This value may now need to "bubble up" in the track list */
922                         while (j > 0 && track[j].count > track[j-1].count)
923                         {
924                                 swapDatum(track[j].value, track[j-1].value);
925                                 swapInt(track[j].count, track[j-1].count);
926                                 j--;
927                         }
928                 }
929                 else
930                 {
931                         /* No match.  Insert at head of count-1 list */
932                         if (track_cnt < track_max)
933                                 track_cnt++;
934                         for (j = track_cnt-1; j > firstcount1; j--)
935                         {
936                                 track[j].value = track[j-1].value;
937                                 track[j].count = track[j-1].count;
938                         }
939                         if (firstcount1 < track_cnt)
940                         {
941                                 track[firstcount1].value = value;
942                                 track[firstcount1].count = 1;
943                         }
944                 }
945         }
946
947         /* We can only compute valid stats if we found some non-null values. */
948         if (nonnull_cnt > 0)
949         {
950                 int             nmultiple,
951                                 summultiple;
952
953                 stats->stats_valid = true;
954                 /* Do the simple null-frac and width stats */
955                 stats->stanullfrac = (double) null_cnt / (double) numrows;
956                 if (is_varlena)
957                         stats->stawidth = total_width / (double) nonnull_cnt;
958                 else
959                         stats->stawidth = stats->attrtype->typlen;
960
961                 /* Count the number of values we found multiple times */
962                 summultiple = 0;
963                 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
964                 {
965                         if (track[nmultiple].count == 1)
966                                 break;
967                         summultiple += track[nmultiple].count;
968                 }
969
970                 if (nmultiple == 0)
971                 {
972                         /* If we found no repeated values, assume it's a unique column */
973                         stats->stadistinct = -1.0;
974                 }
975                 else if (track_cnt < track_max && toowide_cnt == 0 &&
976                                  nmultiple == track_cnt)
977                 {
978                         /*
979                          * Our track list includes every value in the sample, and every
980                          * value appeared more than once.  Assume the column has just
981                          * these values.
982                          */
983                         stats->stadistinct = track_cnt;
984                 }
985                 else
986                 {
987                         /*----------
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
997                          * any better?)
998                          *----------
999                          */
1000                         int             f1 = nonnull_cnt - summultiple;
1001                         double  term1;
1002
1003                         if (f1 < 1)
1004                                 f1 = 1;
1005                         term1 = sqrt((double) totalrows / (double) numrows) * f1;
1006                         stats->stadistinct = floor(term1 + nmultiple + 0.5);
1007                 }
1008
1009                 /*
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
1013                  * a fixed value.
1014                  */
1015                 if (stats->stadistinct > 0.1 * totalrows)
1016                         stats->stadistinct = - (stats->stadistinct / totalrows);
1017
1018                 /*
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.
1026                  */
1027                 if (track_cnt < track_max && toowide_cnt == 0 &&
1028                         stats->stadistinct > 0 &&
1029                         track_cnt <= num_mcv)
1030                 {
1031                         /* Track list includes all values seen, and all will fit */
1032                         num_mcv = track_cnt;
1033                 }
1034                 else
1035                 {
1036                         double  ndistinct = stats->stadistinct;
1037                         double  avgcount,
1038                                         mincount;
1039
1040                         if (ndistinct < 0)
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;
1046                         if (mincount < 2)
1047                                 mincount = 2;
1048                         if (num_mcv > track_cnt)
1049                                 num_mcv = track_cnt;
1050                         for (i = 0; i < num_mcv; i++)
1051                         {
1052                                 if (track[i].count < mincount)
1053                                 {
1054                                         num_mcv = i;
1055                                         break;
1056                                 }
1057                         }
1058                 }
1059
1060                 /* Generate MCV slot entry */
1061                 if (num_mcv > 0)
1062                 {
1063                         MemoryContext old_context;
1064                         Datum  *mcv_values;
1065                         float4 *mcv_freqs;
1066
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++)
1072                         {
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;
1077                         }
1078                         MemoryContextSwitchTo(old_context);
1079
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;
1086                 }
1087         }
1088
1089         /* We don't need to bother cleaning up any of our temporary palloc's */
1090 }
1091
1092
1093 /*
1094  *      compute_scalar_stats() -- compute column statistics
1095  *
1096  *      We use this when we can find "=" and "<" operators for the datatype.
1097  *
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.
1101  *
1102  *      The desired stats can be determined fairly easily after sorting the
1103  *      data values into order.
1104  */
1105 static void
1106 compute_scalar_stats(VacAttrStats *stats,
1107                                          TupleDesc tupDesc, long totalrows,
1108                                          HeapTuple *rows, int numrows)
1109 {
1110         int                     i;
1111         int                     null_cnt = 0;
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);
1117         double          corr_xysum;
1118         RegProcedure cmpFn;
1119         SortFunctionKind cmpFnKind;
1120         FmgrInfo        f_cmpfn;
1121         ScalarItem *values;
1122         int                     values_cnt = 0;
1123         int                *tupnoLink;
1124         ScalarMCVItem *track;
1125         int                     track_cnt = 0;
1126         int                     num_mcv = stats->attr->attstattarget;
1127         int                     num_bins = stats->attr->attstattarget;
1128
1129         values = (ScalarItem *) palloc(numrows * sizeof(ScalarItem));
1130         tupnoLink = (int *) palloc(numrows * sizeof(int));
1131         track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
1132
1133         SelectSortFunction(stats->ltopr, &cmpFn, &cmpFnKind);
1134         fmgr_info(cmpFn, &f_cmpfn);
1135
1136         /* Initial scan to find sortable values */
1137         for (i = 0; i < numrows; i++)
1138         {
1139                 HeapTuple       tuple = rows[i];
1140                 Datum           value;
1141                 bool            isnull;
1142
1143                 value = heap_getattr(tuple, stats->attnum, tupDesc, &isnull);
1144
1145                 /* Check for null/nonnull */
1146                 if (isnull)
1147                 {
1148                         null_cnt++;
1149                         continue;
1150                 }
1151                 nonnull_cnt++;
1152
1153                 /*
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.
1158                  */
1159                 if (is_varlena)
1160                 {
1161                         total_width += VARSIZE(DatumGetPointer(value));
1162                         /*
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
1167                          * ignore the value.
1168                          */
1169                         if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1170                         {
1171                                 toowide_cnt++;
1172                                 continue;
1173                         }
1174                         value = PointerGetDatum(PG_DETOAST_DATUM(value));
1175                 }
1176
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;
1181                 values_cnt++;
1182         }
1183
1184         /* We can only compute valid stats if we found some sortable values. */
1185         if (values_cnt > 0)
1186         {
1187                 int             ndistinct,              /* # distinct values in sample */
1188                                 nmultiple,              /* # that appear multiple times */
1189                                 num_hist,
1190                                 dups_cnt;
1191                 int             slot_idx = 0;
1192
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);
1199
1200                 /*
1201                  * Now scan the values in order, find the most common ones,
1202                  * and also accumulate ordering-correlation statistics.
1203                  *
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).
1218                  */
1219                 corr_xysum = 0;
1220                 ndistinct = 0;
1221                 nmultiple = 0;
1222                 dups_cnt = 0;
1223                 for (i = 0; i < values_cnt; i++)
1224                 {
1225                         int                     tupno = values[i].tupno;
1226
1227                         corr_xysum += (double) i * (double) tupno;
1228                         dups_cnt++;
1229                         if (tupnoLink[tupno] == tupno)
1230                         {
1231                                 /* Reached end of duplicates of this value */
1232                                 ndistinct++;
1233                                 if (dups_cnt > 1)
1234                                 {
1235                                         nmultiple++;
1236                                         if (track_cnt < num_mcv ||
1237                                                 dups_cnt > track[track_cnt-1].count)
1238                                         {
1239                                                 /*
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/
1243                                                  * replaceable slot.
1244                                                  */
1245                                                 int             j;
1246
1247                                                 if (track_cnt < num_mcv)
1248                                                         track_cnt++;
1249                                                 for (j = track_cnt-1; j > 0; j--)
1250                                                 {
1251                                                         if (dups_cnt <= track[j-1].count)
1252                                                                 break;
1253                                                         track[j].count = track[j-1].count;
1254                                                         track[j].first = track[j-1].first;
1255                                                 }
1256                                                 track[j].count = dups_cnt;
1257                                                 track[j].first = i + 1 - dups_cnt;
1258                                         }
1259                                 }
1260                                 dups_cnt = 0;
1261                         }
1262                 }
1263
1264                 stats->stats_valid = true;
1265                 /* Do the simple null-frac and width stats */
1266                 stats->stanullfrac = (double) null_cnt / (double) numrows;
1267                 if (is_varlena)
1268                         stats->stawidth = total_width / (double) nonnull_cnt;
1269                 else
1270                         stats->stawidth = stats->attrtype->typlen;
1271
1272                 if (nmultiple == 0)
1273                 {
1274                         /* If we found no repeated values, assume it's a unique column */
1275                         stats->stadistinct = -1.0;
1276                 }
1277                 else if (toowide_cnt == 0 && nmultiple == ndistinct)
1278                 {
1279                         /*
1280                          * Every value in the sample appeared more than once.  Assume the
1281                          * column has just these values.
1282                          */
1283                         stats->stadistinct = ndistinct;
1284                 }
1285                 else
1286                 {
1287                         /*----------
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.
1294                          *----------
1295                          */
1296                         int             f1 = ndistinct - nmultiple + toowide_cnt;
1297                         double  term1;
1298
1299                         if (f1 < 1)
1300                                 f1 = 1;
1301                         term1 = sqrt((double) totalrows / (double) numrows) * f1;
1302                         stats->stadistinct = floor(term1 + nmultiple + 0.5);
1303                 }
1304
1305                 /*
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
1309                  * a fixed value.
1310                  */
1311                 if (stats->stadistinct > 0.1 * totalrows)
1312                         stats->stadistinct = - (stats->stadistinct / totalrows);
1313
1314                 /*
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.
1325                  */
1326                 if (track_cnt == ndistinct && toowide_cnt == 0 &&
1327                         stats->stadistinct > 0 &&
1328                         track_cnt <= num_mcv)
1329                 {
1330                         /* Track list includes all values seen, and all will fit */
1331                         num_mcv = track_cnt;
1332                 }
1333                 else
1334                 {
1335                         double  ndistinct = stats->stadistinct;
1336                         double  avgcount,
1337                                         mincount,
1338                                         maxmincount;
1339
1340                         if (ndistinct < 0)
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;
1346                         if (mincount < 2)
1347                                 mincount = 2;
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++)
1355                         {
1356                                 if (track[i].count < mincount)
1357                                 {
1358                                         num_mcv = i;
1359                                         break;
1360                                 }
1361                         }
1362                 }
1363
1364                 /* Generate MCV slot entry */
1365                 if (num_mcv > 0)
1366                 {
1367                         MemoryContext old_context;
1368                         Datum  *mcv_values;
1369                         float4 *mcv_freqs;
1370
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++)
1376                         {
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;
1381                         }
1382                         MemoryContextSwitchTo(old_context);
1383
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;
1390                         slot_idx++;
1391                 }
1392
1393                 /*
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.)
1397                  */
1398                 num_hist = ndistinct - num_mcv;
1399                 if (num_hist > num_bins)
1400                         num_hist = num_bins + 1;
1401                 if (num_hist >= 2)
1402                 {
1403                         MemoryContext old_context;
1404                         Datum  *hist_values;
1405                         int             nvals;
1406
1407                         /* Sort the MCV items into position order to speed next loop */
1408                         qsort((void *) track, num_mcv,
1409                                   sizeof(ScalarMCVItem), compare_mcvs);
1410
1411                         /*
1412                          * Collapse out the MCV items from the values[] array.
1413                          *
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[].
1417                          */
1418                         if (num_mcv > 0)
1419                         {
1420                                 int             src,
1421                                                 dest;
1422                                 int             j;
1423
1424                                 src = dest = 0;
1425                                 j = 0;                  /* index of next interesting MCV item */
1426                                 while (src < values_cnt)
1427                                 {
1428                                         int             ncopy;
1429
1430                                         if (j < num_mcv)
1431                                         {
1432                                                 int             first = track[j].first;
1433
1434                                                 if (src >= first)
1435                                                 {
1436                                                         /* advance past this MCV item */
1437                                                         src = first + track[j].count;
1438                                                         j++;
1439                                                         continue;
1440                                                 }
1441                                                 ncopy = first - src;
1442                                         }
1443                                         else
1444                                         {
1445                                                 ncopy = values_cnt - src;
1446                                         }
1447                                         memmove(&values[dest], &values[src],
1448                                                         ncopy * sizeof(ScalarItem));
1449                                         src += ncopy;
1450                                         dest += ncopy;
1451                                 }
1452                                 nvals = dest;
1453                         }
1454                         else
1455                                 nvals = values_cnt;
1456                         Assert(nvals >= num_hist);
1457
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++)
1462                         {
1463                                 int             pos;
1464
1465                                 pos = (i * (nvals - 1)) / (num_hist - 1);
1466                                 hist_values[i] = datumCopy(values[pos].value,
1467                                                                                    stats->attr->attbyval,
1468                                                                                    stats->attr->attlen);
1469                         }
1470                         MemoryContextSwitchTo(old_context);
1471
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;
1476                         slot_idx++;
1477                 }
1478
1479                 /* Generate a correlation entry if there are multiple values */
1480                 if (values_cnt > 1)
1481                 {
1482                         MemoryContext old_context;
1483                         float4 *corrs;
1484                         double  corr_xsum,
1485                                         corr_x2sum;
1486
1487                         /* Must copy the target values into TransactionCommandContext */
1488                         old_context = MemoryContextSwitchTo(TransactionCommandContext);
1489                         corrs = (float4 *) palloc(sizeof(float4));
1490                         MemoryContextSwitchTo(old_context);
1491
1492                         /*----------
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.
1499                          *----------
1500                          */
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);
1507
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;
1512                         slot_idx++;
1513                 }
1514         }
1515
1516         /* We don't need to bother cleaning up any of our temporary palloc's */
1517 }
1518
1519 /*
1520  * qsort comparator for sorting ScalarItems
1521  *
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().
1527  */
1528 static int
1529 compare_scalars(const void *a, const void *b)
1530 {
1531         Datum           da = ((ScalarItem *) a)->value;
1532         int                     ta = ((ScalarItem *) a)->tupno;
1533         Datum           db = ((ScalarItem *) b)->value;
1534         int                     tb = ((ScalarItem *) b)->tupno;
1535         int32           compare;
1536
1537         compare = ApplySortFunction(datumCmpFn, datumCmpFnKind,
1538                                                                 da, false, db, false);
1539         if (compare != 0)
1540                 return compare;
1541
1542         /*
1543          * The two datums are equal, so update datumCmpTupnoLink[].
1544          */
1545         if (datumCmpTupnoLink[ta] < tb)
1546                 datumCmpTupnoLink[ta] = tb;
1547         if (datumCmpTupnoLink[tb] < ta)
1548                 datumCmpTupnoLink[tb] = ta;
1549
1550         /*
1551          * For equal datums, sort by tupno
1552          */
1553         return ta - tb;
1554 }
1555
1556 /*
1557  * qsort comparator for sorting ScalarMCVItems by position
1558  */
1559 static int
1560 compare_mcvs(const void *a, const void *b)
1561 {
1562         int                     da = ((ScalarMCVItem *) a)->first;
1563         int                     db = ((ScalarMCVItem *) b)->first;
1564
1565         return da - db;
1566 }
1567
1568
1569 /*
1570  *      update_attstats() -- update attribute statistics for one relation
1571  *
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.
1576  *
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.
1580  *
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.
1586  */
1587 static void
1588 update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats)
1589 {
1590         Relation        sd;
1591         int                     attno;
1592
1593         /*
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.
1597          */
1598         sd = heap_openr(StatisticRelationName, ExclusiveLock);
1599
1600         for (attno = 0; attno < natts; attno++)
1601         {
1602                 VacAttrStats *stats = vacattrstats[attno];
1603                 FmgrInfo        out_function;
1604                 HeapTuple       stup,
1605                                         oldtup;
1606                 int                     i, k, n;
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];
1611
1612                 /* Ignore attr if we weren't able to collect stats */
1613                 if (!stats->stats_valid)
1614                         continue;
1615
1616                 fmgr_info(stats->attrtype->typoutput, &out_function);
1617
1618                 /*
1619                  * Construct a new pg_statistic tuple
1620                  */
1621                 for (i = 0; i < Natts_pg_statistic; ++i)
1622                 {
1623                         nulls[i] = ' ';
1624                         replaces[i] = 'r';
1625                 }
1626
1627                 i = 0;
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++)
1634                 {
1635                         values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
1636                 }
1637                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1638                 {
1639                         values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
1640                 }
1641                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1642                 {
1643                         int             nnum = stats->numnumbers[k];
1644
1645                         if (nnum > 0)
1646                         {
1647                                 Datum      *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1648                                 ArrayType  *arry;
1649
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 */
1656                         }
1657                         else
1658                         {
1659                                 nulls[i] = 'n';
1660                                 values[i++] = (Datum) 0;
1661                         }
1662                 }
1663                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1664                 {
1665                         int             ntxt = stats->numvalues[k];
1666
1667                         if (ntxt > 0)
1668                         {
1669                                 Datum      *txtdatums = (Datum *) palloc(ntxt * sizeof(Datum));
1670                                 ArrayType  *arry;
1671
1672                                 for (n = 0; n < ntxt; n++)
1673                                 {
1674                                         /*
1675                                          * Convert data values to a text string to be inserted
1676                                          * into the text array.
1677                                          */
1678                                         Datum   stringdatum;
1679
1680                                         stringdatum =
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));
1687                                 }
1688                                 /* XXX knows more than it should about type text: */
1689                                 arry = construct_array(txtdatums, ntxt,
1690                                                                            false, -1, 'i');
1691                                 values[i++] = PointerGetDatum(arry); /* stavaluesN */
1692                         }
1693                         else
1694                         {
1695                                 nulls[i] = 'n';
1696                                 values[i++] = (Datum) 0;
1697                         }
1698                 }
1699
1700                 /* Is there already a pg_statistic tuple for this attribute? */
1701                 oldtup = SearchSysCache(STATRELATT,
1702                                                                 ObjectIdGetDatum(relid),
1703                                                                 Int16GetDatum(stats->attnum),
1704                                                                 0, 0);
1705
1706                 if (HeapTupleIsValid(oldtup))
1707                 {
1708                         /* Yes, replace it */
1709                         stup = heap_modifytuple(oldtup,
1710                                                                         sd,
1711                                                                         values,
1712                                                                         nulls,
1713                                                                         replaces);
1714                         ReleaseSysCache(oldtup);
1715                         simple_heap_update(sd, &stup->t_self, stup);
1716                 }
1717                 else
1718                 {
1719                         /* No, insert new tuple */
1720                         stup = heap_formtuple(sd->rd_att, values, nulls);
1721                         heap_insert(sd, stup);
1722                 }
1723
1724                 /* update indices too */
1725                 CatalogOpenIndices(Num_pg_statistic_indices, Name_pg_statistic_indices,
1726                                                    irelations);
1727                 CatalogIndexInsert(irelations, Num_pg_statistic_indices, sd, stup);
1728                 CatalogCloseIndices(Num_pg_statistic_indices, irelations);
1729
1730                 heap_freetuple(stup);
1731         }
1732
1733         /* close rel, but hold lock till upcoming commit */
1734         heap_close(sd, NoLock);
1735 }