]> granicus.if.org Git - postgresql/blob - src/backend/commands/analyze.c
4845e6a381573c6acb61434e4f5ae84a18ad3936
[postgresql] / src / backend / commands / analyze.c
1 /*-------------------------------------------------------------------------
2  *
3  * analyze.c
4  *        the Postgres statistics generator
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/commands/analyze.c,v 1.123 2008/07/01 10:33:09 heikki Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <math.h>
18
19 #include "access/heapam.h"
20 #include "access/transam.h"
21 #include "access/tuptoaster.h"
22 #include "access/xact.h"
23 #include "catalog/index.h"
24 #include "catalog/indexing.h"
25 #include "catalog/namespace.h"
26 #include "catalog/pg_namespace.h"
27 #include "commands/dbcommands.h"
28 #include "commands/vacuum.h"
29 #include "executor/executor.h"
30 #include "miscadmin.h"
31 #include "parser/parse_expr.h"
32 #include "parser/parse_oper.h"
33 #include "parser/parse_relation.h"
34 #include "pgstat.h"
35 #include "postmaster/autovacuum.h"
36 #include "storage/bufmgr.h"
37 #include "storage/proc.h"
38 #include "storage/procarray.h"
39 #include "utils/acl.h"
40 #include "utils/datum.h"
41 #include "utils/lsyscache.h"
42 #include "utils/memutils.h"
43 #include "utils/pg_rusage.h"
44 #include "utils/syscache.h"
45 #include "utils/tuplesort.h"
46 #include "utils/tqual.h"
47
48
49 /* Data structure for Algorithm S from Knuth 3.4.2 */
50 typedef struct
51 {
52         BlockNumber N;                          /* number of blocks, known in advance */
53         int                     n;                              /* desired sample size */
54         BlockNumber t;                          /* current block number */
55         int                     m;                              /* blocks selected so far */
56 } BlockSamplerData;
57 typedef BlockSamplerData *BlockSampler;
58
59 /* Per-index data for ANALYZE */
60 typedef struct AnlIndexData
61 {
62         IndexInfo  *indexInfo;          /* BuildIndexInfo result */
63         double          tupleFract;             /* fraction of rows for partial index */
64         VacAttrStats **vacattrstats;    /* index attrs to analyze */
65         int                     attr_cnt;
66 } AnlIndexData;
67
68
69 /* Default statistics target (GUC parameter) */
70 int                     default_statistics_target = 10;
71
72 /* A few variables that don't seem worth passing around as parameters */
73 static int      elevel = -1;
74
75 static MemoryContext anl_context = NULL;
76
77 static BufferAccessStrategy vac_strategy;
78
79
80 static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
81                                   int samplesize);
82 static bool BlockSampler_HasMore(BlockSampler bs);
83 static BlockNumber BlockSampler_Next(BlockSampler bs);
84 static void compute_index_stats(Relation onerel, double totalrows,
85                                         AnlIndexData *indexdata, int nindexes,
86                                         HeapTuple *rows, int numrows,
87                                         MemoryContext col_context);
88 static VacAttrStats *examine_attribute(Relation onerel, int attnum);
89 static int acquire_sample_rows(Relation onerel, HeapTuple *rows,
90                                         int targrows, double *totalrows, double *totaldeadrows);
91 static double random_fract(void);
92 static double init_selection_state(int n);
93 static double get_next_S(double t, int n, double *stateptr);
94 static int      compare_rows(const void *a, const void *b);
95 static void update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats);
96 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
97 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
98
99 static bool std_typanalyze(VacAttrStats *stats);
100
101
102 /*
103  *      analyze_rel() -- analyze one relation
104  */
105 void
106 analyze_rel(Oid relid, VacuumStmt *vacstmt,
107                         BufferAccessStrategy bstrategy)
108 {
109         Relation        onerel;
110         int                     attr_cnt,
111                                 tcnt,
112                                 i,
113                                 ind;
114         Relation   *Irel;
115         int                     nindexes;
116         bool            hasindex;
117         bool            analyzableindex;
118         VacAttrStats **vacattrstats;
119         AnlIndexData *indexdata;
120         int                     targrows,
121                                 numrows;
122         double          totalrows,
123                                 totaldeadrows;
124         HeapTuple  *rows;
125         PGRUsage        ru0;
126         TimestampTz starttime = 0;
127         Oid                     save_userid;
128         bool            save_secdefcxt;
129
130         if (vacstmt->verbose)
131                 elevel = INFO;
132         else
133                 elevel = DEBUG2;
134
135         vac_strategy = bstrategy;
136
137         /*
138          * Use the current context for storing analysis info.  vacuum.c ensures
139          * that this context will be cleared when I return, thus releasing the
140          * memory allocated here.
141          */
142         anl_context = CurrentMemoryContext;
143
144         /*
145          * Check for user-requested abort.      Note we want this to be inside a
146          * transaction, so xact.c doesn't issue useless WARNING.
147          */
148         CHECK_FOR_INTERRUPTS();
149
150         /*
151          * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
152          * ANALYZEs don't run on it concurrently.  (This also locks out a
153          * concurrent VACUUM, which doesn't matter much at the moment but might
154          * matter if we ever try to accumulate stats on dead tuples.) If the rel
155          * has been dropped since we last saw it, we don't need to process it.
156          */
157         onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
158         if (!onerel)
159                 return;
160
161         /*
162          * Check permissions --- this should match vacuum's check!
163          */
164         if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
165                   (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
166         {
167                 /* No need for a WARNING if we already complained during VACUUM */
168                 if (!vacstmt->vacuum)
169                 {
170                         if (onerel->rd_rel->relisshared)
171                                 ereport(WARNING,
172                                                 (errmsg("skipping \"%s\" --- only superuser can analyze it",
173                                                                 RelationGetRelationName(onerel))));
174                         else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
175                                 ereport(WARNING,
176                                                 (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
177                                                                 RelationGetRelationName(onerel))));
178                         else
179                                 ereport(WARNING,
180                                                 (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
181                                                                 RelationGetRelationName(onerel))));
182                 }
183                 relation_close(onerel, ShareUpdateExclusiveLock);
184                 return;
185         }
186
187         /*
188          * Check that it's a plain table; we used to do this in get_rel_oids() but
189          * seems safer to check after we've locked the relation.
190          */
191         if (onerel->rd_rel->relkind != RELKIND_RELATION)
192         {
193                 /* No need for a WARNING if we already complained during VACUUM */
194                 if (!vacstmt->vacuum)
195                         ereport(WARNING,
196                                         (errmsg("skipping \"%s\" --- cannot analyze indexes, views, or special system tables",
197                                                         RelationGetRelationName(onerel))));
198                 relation_close(onerel, ShareUpdateExclusiveLock);
199                 return;
200         }
201
202         /*
203          * Silently ignore tables that are temp tables of other backends ---
204          * trying to analyze these is rather pointless, since their contents are
205          * probably not up-to-date on disk.  (We don't throw a warning here; it
206          * would just lead to chatter during a database-wide ANALYZE.)
207          */
208         if (isOtherTempNamespace(RelationGetNamespace(onerel)))
209         {
210                 relation_close(onerel, ShareUpdateExclusiveLock);
211                 return;
212         }
213
214         /*
215          * We can ANALYZE any table except pg_statistic. See update_attstats
216          */
217         if (RelationGetRelid(onerel) == StatisticRelationId)
218         {
219                 relation_close(onerel, ShareUpdateExclusiveLock);
220                 return;
221         }
222
223         ereport(elevel,
224                         (errmsg("analyzing \"%s.%s\"",
225                                         get_namespace_name(RelationGetNamespace(onerel)),
226                                         RelationGetRelationName(onerel))));
227
228         /*
229          * Switch to the table owner's userid, so that any index functions are
230          * run as that user.
231          */
232         GetUserIdAndContext(&save_userid, &save_secdefcxt);
233         SetUserIdAndContext(onerel->rd_rel->relowner, true);
234
235         /* let others know what I'm doing */
236         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
237         MyProc->vacuumFlags |= PROC_IN_ANALYZE;
238         LWLockRelease(ProcArrayLock);
239
240         /* measure elapsed time iff autovacuum logging requires it */
241         if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
242         {
243                 pg_rusage_init(&ru0);
244                 if (Log_autovacuum_min_duration > 0)
245                         starttime = GetCurrentTimestamp();
246         }
247
248         /*
249          * Determine which columns to analyze
250          *
251          * Note that system attributes are never analyzed.
252          */
253         if (vacstmt->va_cols != NIL)
254         {
255                 ListCell   *le;
256
257                 vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
258                                                                                                 sizeof(VacAttrStats *));
259                 tcnt = 0;
260                 foreach(le, vacstmt->va_cols)
261                 {
262                         char       *col = strVal(lfirst(le));
263
264                         i = attnameAttNum(onerel, col, false);
265                         if (i == InvalidAttrNumber)
266                                 ereport(ERROR,
267                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
268                                         errmsg("column \"%s\" of relation \"%s\" does not exist",
269                                                    col, RelationGetRelationName(onerel))));
270                         vacattrstats[tcnt] = examine_attribute(onerel, i);
271                         if (vacattrstats[tcnt] != NULL)
272                                 tcnt++;
273                 }
274                 attr_cnt = tcnt;
275         }
276         else
277         {
278                 attr_cnt = onerel->rd_att->natts;
279                 vacattrstats = (VacAttrStats **)
280                         palloc(attr_cnt * sizeof(VacAttrStats *));
281                 tcnt = 0;
282                 for (i = 1; i <= attr_cnt; i++)
283                 {
284                         vacattrstats[tcnt] = examine_attribute(onerel, i);
285                         if (vacattrstats[tcnt] != NULL)
286                                 tcnt++;
287                 }
288                 attr_cnt = tcnt;
289         }
290
291         /*
292          * Open all indexes of the relation, and see if there are any analyzable
293          * columns in the indexes.      We do not analyze index columns if there was
294          * an explicit column list in the ANALYZE command, however.
295          */
296         vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
297         hasindex = (nindexes > 0);
298         indexdata = NULL;
299         analyzableindex = false;
300         if (hasindex)
301         {
302                 indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
303                 for (ind = 0; ind < nindexes; ind++)
304                 {
305                         AnlIndexData *thisdata = &indexdata[ind];
306                         IndexInfo  *indexInfo;
307
308                         thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
309                         thisdata->tupleFract = 1.0; /* fix later if partial */
310                         if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
311                         {
312                                 ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
313
314                                 thisdata->vacattrstats = (VacAttrStats **)
315                                         palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
316                                 tcnt = 0;
317                                 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
318                                 {
319                                         int                     keycol = indexInfo->ii_KeyAttrNumbers[i];
320
321                                         if (keycol == 0)
322                                         {
323                                                 /* Found an index expression */
324                                                 Node       *indexkey;
325
326                                                 if (indexpr_item == NULL)               /* shouldn't happen */
327                                                         elog(ERROR, "too few entries in indexprs list");
328                                                 indexkey = (Node *) lfirst(indexpr_item);
329                                                 indexpr_item = lnext(indexpr_item);
330
331                                                 /*
332                                                  * Can't analyze if the opclass uses a storage type
333                                                  * different from the expression result type. We'd get
334                                                  * confused because the type shown in pg_attribute for
335                                                  * the index column doesn't match what we are getting
336                                                  * from the expression. Perhaps this can be fixed
337                                                  * someday, but for now, punt.
338                                                  */
339                                                 if (exprType(indexkey) !=
340                                                         Irel[ind]->rd_att->attrs[i]->atttypid)
341                                                         continue;
342
343                                                 thisdata->vacattrstats[tcnt] =
344                                                         examine_attribute(Irel[ind], i + 1);
345                                                 if (thisdata->vacattrstats[tcnt] != NULL)
346                                                 {
347                                                         tcnt++;
348                                                         analyzableindex = true;
349                                                 }
350                                         }
351                                 }
352                                 thisdata->attr_cnt = tcnt;
353                         }
354                 }
355         }
356
357         /*
358          * Quit if no analyzable columns
359          */
360         if (attr_cnt <= 0 && !analyzableindex)
361         {
362                 /*
363                  * We report that the table is empty; this is just so that the
364                  * autovacuum code doesn't go nuts trying to get stats about a
365                  * zero-column table.
366                  */
367                 if (!vacstmt->vacuum)
368                         pgstat_report_analyze(onerel, 0, 0);
369                 goto cleanup;
370         }
371
372         /*
373          * Determine how many rows we need to sample, using the worst case from
374          * all analyzable columns.      We use a lower bound of 100 rows to avoid
375          * possible overflow in Vitter's algorithm.
376          */
377         targrows = 100;
378         for (i = 0; i < attr_cnt; i++)
379         {
380                 if (targrows < vacattrstats[i]->minrows)
381                         targrows = vacattrstats[i]->minrows;
382         }
383         for (ind = 0; ind < nindexes; ind++)
384         {
385                 AnlIndexData *thisdata = &indexdata[ind];
386
387                 for (i = 0; i < thisdata->attr_cnt; i++)
388                 {
389                         if (targrows < thisdata->vacattrstats[i]->minrows)
390                                 targrows = thisdata->vacattrstats[i]->minrows;
391                 }
392         }
393
394         /*
395          * Acquire the sample rows
396          */
397         rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
398         numrows = acquire_sample_rows(onerel, rows, targrows,
399                                                                   &totalrows, &totaldeadrows);
400
401         /*
402          * Compute the statistics.      Temporary results during the calculations for
403          * each column are stored in a child context.  The calc routines are
404          * responsible to make sure that whatever they store into the VacAttrStats
405          * structure is allocated in anl_context.
406          */
407         if (numrows > 0)
408         {
409                 MemoryContext col_context,
410                                         old_context;
411
412                 col_context = AllocSetContextCreate(anl_context,
413                                                                                         "Analyze Column",
414                                                                                         ALLOCSET_DEFAULT_MINSIZE,
415                                                                                         ALLOCSET_DEFAULT_INITSIZE,
416                                                                                         ALLOCSET_DEFAULT_MAXSIZE);
417                 old_context = MemoryContextSwitchTo(col_context);
418
419                 for (i = 0; i < attr_cnt; i++)
420                 {
421                         VacAttrStats *stats = vacattrstats[i];
422
423                         stats->rows = rows;
424                         stats->tupDesc = onerel->rd_att;
425                         (*stats->compute_stats) (stats,
426                                                                          std_fetch_func,
427                                                                          numrows,
428                                                                          totalrows);
429                         MemoryContextResetAndDeleteChildren(col_context);
430                 }
431
432                 if (hasindex)
433                         compute_index_stats(onerel, totalrows,
434                                                                 indexdata, nindexes,
435                                                                 rows, numrows,
436                                                                 col_context);
437
438                 MemoryContextSwitchTo(old_context);
439                 MemoryContextDelete(col_context);
440
441                 /*
442                  * Emit the completed stats rows into pg_statistic, replacing any
443                  * previous statistics for the target columns.  (If there are stats in
444                  * pg_statistic for columns we didn't process, we leave them alone.)
445                  */
446                 update_attstats(relid, attr_cnt, vacattrstats);
447
448                 for (ind = 0; ind < nindexes; ind++)
449                 {
450                         AnlIndexData *thisdata = &indexdata[ind];
451
452                         update_attstats(RelationGetRelid(Irel[ind]),
453                                                         thisdata->attr_cnt, thisdata->vacattrstats);
454                 }
455         }
456
457         /*
458          * If we are running a standalone ANALYZE, update pages/tuples stats in
459          * pg_class.  We know the accurate page count from the smgr, but only an
460          * approximate number of tuples; therefore, if we are part of VACUUM
461          * ANALYZE do *not* overwrite the accurate count already inserted by
462          * VACUUM.      The same consideration applies to indexes.
463          */
464         if (!vacstmt->vacuum)
465         {
466                 vac_update_relstats(RelationGetRelid(onerel),
467                                                         RelationGetNumberOfBlocks(onerel),
468                                                         totalrows, hasindex,
469                                                         InvalidTransactionId);
470
471                 for (ind = 0; ind < nindexes; ind++)
472                 {
473                         AnlIndexData *thisdata = &indexdata[ind];
474                         double          totalindexrows;
475
476                         totalindexrows = ceil(thisdata->tupleFract * totalrows);
477                         vac_update_relstats(RelationGetRelid(Irel[ind]),
478                                                                 RelationGetNumberOfBlocks(Irel[ind]),
479                                                                 totalindexrows, false,
480                                                                 InvalidTransactionId);
481                 }
482
483                 /* report results to the stats collector, too */
484                 pgstat_report_analyze(onerel, totalrows, totaldeadrows);
485         }
486
487         /* We skip to here if there were no analyzable columns */
488 cleanup:
489
490         /* Done with indexes */
491         vac_close_indexes(nindexes, Irel, NoLock);
492
493         /*
494          * Close source relation now, but keep lock so that no one deletes it
495          * before we commit.  (If someone did, they'd fail to clean up the entries
496          * we made in pg_statistic.  Also, releasing the lock before commit would
497          * expose us to concurrent-update failures in update_attstats.)
498          */
499         relation_close(onerel, NoLock);
500
501         /* Log the action if appropriate */
502         if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
503         {
504                 if (Log_autovacuum_min_duration == 0 ||
505                         TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
506                                                                            Log_autovacuum_min_duration))
507                         ereport(LOG,
508                                         (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
509                                                         get_database_name(MyDatabaseId),
510                                                         get_namespace_name(RelationGetNamespace(onerel)),
511                                                         RelationGetRelationName(onerel),
512                                                         pg_rusage_show(&ru0))));
513         }
514
515         /*
516          * Reset my PGPROC flag.  Note: we need this here, and not in vacuum_rel,
517          * because the vacuum flag is cleared by the end-of-xact code.
518          */
519         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
520         MyProc->vacuumFlags &= ~PROC_IN_ANALYZE;
521         LWLockRelease(ProcArrayLock);
522
523         /* Restore userid */
524         SetUserIdAndContext(save_userid, save_secdefcxt);
525 }
526
527 /*
528  * Compute statistics about indexes of a relation
529  */
530 static void
531 compute_index_stats(Relation onerel, double totalrows,
532                                         AnlIndexData *indexdata, int nindexes,
533                                         HeapTuple *rows, int numrows,
534                                         MemoryContext col_context)
535 {
536         MemoryContext ind_context,
537                                 old_context;
538         Datum           values[INDEX_MAX_KEYS];
539         bool            isnull[INDEX_MAX_KEYS];
540         int                     ind,
541                                 i;
542
543         ind_context = AllocSetContextCreate(anl_context,
544                                                                                 "Analyze Index",
545                                                                                 ALLOCSET_DEFAULT_MINSIZE,
546                                                                                 ALLOCSET_DEFAULT_INITSIZE,
547                                                                                 ALLOCSET_DEFAULT_MAXSIZE);
548         old_context = MemoryContextSwitchTo(ind_context);
549
550         for (ind = 0; ind < nindexes; ind++)
551         {
552                 AnlIndexData *thisdata = &indexdata[ind];
553                 IndexInfo  *indexInfo = thisdata->indexInfo;
554                 int                     attr_cnt = thisdata->attr_cnt;
555                 TupleTableSlot *slot;
556                 EState     *estate;
557                 ExprContext *econtext;
558                 List       *predicate;
559                 Datum      *exprvals;
560                 bool       *exprnulls;
561                 int                     numindexrows,
562                                         tcnt,
563                                         rowno;
564                 double          totalindexrows;
565
566                 /* Ignore index if no columns to analyze and not partial */
567                 if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
568                         continue;
569
570                 /*
571                  * Need an EState for evaluation of index expressions and
572                  * partial-index predicates.  Create it in the per-index context to be
573                  * sure it gets cleaned up at the bottom of the loop.
574                  */
575                 estate = CreateExecutorState();
576                 econtext = GetPerTupleExprContext(estate);
577                 /* Need a slot to hold the current heap tuple, too */
578                 slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
579
580                 /* Arrange for econtext's scan tuple to be the tuple under test */
581                 econtext->ecxt_scantuple = slot;
582
583                 /* Set up execution state for predicate. */
584                 predicate = (List *)
585                         ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
586                                                         estate);
587
588                 /* Compute and save index expression values */
589                 exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
590                 exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
591                 numindexrows = 0;
592                 tcnt = 0;
593                 for (rowno = 0; rowno < numrows; rowno++)
594                 {
595                         HeapTuple       heapTuple = rows[rowno];
596
597                         /* Set up for predicate or expression evaluation */
598                         ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
599
600                         /* If index is partial, check predicate */
601                         if (predicate != NIL)
602                         {
603                                 if (!ExecQual(predicate, econtext, false))
604                                         continue;
605                         }
606                         numindexrows++;
607
608                         if (attr_cnt > 0)
609                         {
610                                 /*
611                                  * Evaluate the index row to compute expression values. We
612                                  * could do this by hand, but FormIndexDatum is convenient.
613                                  */
614                                 FormIndexDatum(indexInfo,
615                                                            slot,
616                                                            estate,
617                                                            values,
618                                                            isnull);
619
620                                 /*
621                                  * Save just the columns we care about.
622                                  */
623                                 for (i = 0; i < attr_cnt; i++)
624                                 {
625                                         VacAttrStats *stats = thisdata->vacattrstats[i];
626                                         int                     attnum = stats->attr->attnum;
627
628                                         exprvals[tcnt] = values[attnum - 1];
629                                         exprnulls[tcnt] = isnull[attnum - 1];
630                                         tcnt++;
631                                 }
632                         }
633                 }
634
635                 /*
636                  * Having counted the number of rows that pass the predicate in the
637                  * sample, we can estimate the total number of rows in the index.
638                  */
639                 thisdata->tupleFract = (double) numindexrows / (double) numrows;
640                 totalindexrows = ceil(thisdata->tupleFract * totalrows);
641
642                 /*
643                  * Now we can compute the statistics for the expression columns.
644                  */
645                 if (numindexrows > 0)
646                 {
647                         MemoryContextSwitchTo(col_context);
648                         for (i = 0; i < attr_cnt; i++)
649                         {
650                                 VacAttrStats *stats = thisdata->vacattrstats[i];
651
652                                 stats->exprvals = exprvals + i;
653                                 stats->exprnulls = exprnulls + i;
654                                 stats->rowstride = attr_cnt;
655                                 (*stats->compute_stats) (stats,
656                                                                                  ind_fetch_func,
657                                                                                  numindexrows,
658                                                                                  totalindexrows);
659                                 MemoryContextResetAndDeleteChildren(col_context);
660                         }
661                 }
662
663                 /* And clean up */
664                 MemoryContextSwitchTo(ind_context);
665
666                 ExecDropSingleTupleTableSlot(slot);
667                 FreeExecutorState(estate);
668                 MemoryContextResetAndDeleteChildren(ind_context);
669         }
670
671         MemoryContextSwitchTo(old_context);
672         MemoryContextDelete(ind_context);
673 }
674
675 /*
676  * examine_attribute -- pre-analysis of a single column
677  *
678  * Determine whether the column is analyzable; if so, create and initialize
679  * a VacAttrStats struct for it.  If not, return NULL.
680  */
681 static VacAttrStats *
682 examine_attribute(Relation onerel, int attnum)
683 {
684         Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
685         HeapTuple       typtuple;
686         VacAttrStats *stats;
687         int                     i;
688         bool            ok;
689
690         /* Never analyze dropped columns */
691         if (attr->attisdropped)
692                 return NULL;
693
694         /* Don't analyze column if user has specified not to */
695         if (attr->attstattarget == 0)
696                 return NULL;
697
698         /*
699          * Create the VacAttrStats struct.
700          */
701         stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
702         stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_TUPLE_SIZE);
703         memcpy(stats->attr, attr, ATTRIBUTE_TUPLE_SIZE);
704         typtuple = SearchSysCache(TYPEOID,
705                                                           ObjectIdGetDatum(attr->atttypid),
706                                                           0, 0, 0);
707         if (!HeapTupleIsValid(typtuple))
708                 elog(ERROR, "cache lookup failed for type %u", attr->atttypid);
709         stats->attrtype = (Form_pg_type) palloc(sizeof(FormData_pg_type));
710         memcpy(stats->attrtype, GETSTRUCT(typtuple), sizeof(FormData_pg_type));
711         ReleaseSysCache(typtuple);
712         stats->anl_context = anl_context;
713         stats->tupattnum = attnum;
714
715         /*
716          * The fields describing the stats->stavalues[n] element types default
717          * to the type of the field being analyzed, but the type-specific
718          * typanalyze function can change them if it wants to store something
719          * else.
720          */
721         for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
722         {
723                 stats->statypid[i] = stats->attr->atttypid;
724                 stats->statyplen[i] = stats->attrtype->typlen;
725                 stats->statypbyval[i] = stats->attrtype->typbyval;
726                 stats->statypalign[i] = stats->attrtype->typalign;
727         }
728
729         /*
730          * Call the type-specific typanalyze function.  If none is specified, use
731          * std_typanalyze().
732          */
733         if (OidIsValid(stats->attrtype->typanalyze))
734                 ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
735                                                                                    PointerGetDatum(stats)));
736         else
737                 ok = std_typanalyze(stats);
738
739         if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
740         {
741                 pfree(stats->attrtype);
742                 pfree(stats->attr);
743                 pfree(stats);
744                 return NULL;
745         }
746
747         return stats;
748 }
749
750 /*
751  * BlockSampler_Init -- prepare for random sampling of blocknumbers
752  *
753  * BlockSampler is used for stage one of our new two-stage tuple
754  * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
755  * "Large DB").  It selects a random sample of samplesize blocks out of
756  * the nblocks blocks in the table.  If the table has less than
757  * samplesize blocks, all blocks are selected.
758  *
759  * Since we know the total number of blocks in advance, we can use the
760  * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
761  * algorithm.
762  */
763 static void
764 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
765 {
766         bs->N = nblocks;                        /* measured table size */
767
768         /*
769          * If we decide to reduce samplesize for tables that have less or not much
770          * more than samplesize blocks, here is the place to do it.
771          */
772         bs->n = samplesize;
773         bs->t = 0;                                      /* blocks scanned so far */
774         bs->m = 0;                                      /* blocks selected so far */
775 }
776
777 static bool
778 BlockSampler_HasMore(BlockSampler bs)
779 {
780         return (bs->t < bs->N) && (bs->m < bs->n);
781 }
782
783 static BlockNumber
784 BlockSampler_Next(BlockSampler bs)
785 {
786         BlockNumber K = bs->N - bs->t;          /* remaining blocks */
787         int                     k = bs->n - bs->m;              /* blocks still to sample */
788         double          p;                              /* probability to skip block */
789         double          V;                              /* random */
790
791         Assert(BlockSampler_HasMore(bs));       /* hence K > 0 and k > 0 */
792
793         if ((BlockNumber) k >= K)
794         {
795                 /* need all the rest */
796                 bs->m++;
797                 return bs->t++;
798         }
799
800         /*----------
801          * It is not obvious that this code matches Knuth's Algorithm S.
802          * Knuth says to skip the current block with probability 1 - k/K.
803          * If we are to skip, we should advance t (hence decrease K), and
804          * repeat the same probabilistic test for the next block.  The naive
805          * implementation thus requires a random_fract() call for each block
806          * number.      But we can reduce this to one random_fract() call per
807          * selected block, by noting that each time the while-test succeeds,
808          * we can reinterpret V as a uniform random number in the range 0 to p.
809          * Therefore, instead of choosing a new V, we just adjust p to be
810          * the appropriate fraction of its former value, and our next loop
811          * makes the appropriate probabilistic test.
812          *
813          * We have initially K > k > 0.  If the loop reduces K to equal k,
814          * the next while-test must fail since p will become exactly zero
815          * (we assume there will not be roundoff error in the division).
816          * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
817          * to be doubly sure about roundoff error.)  Therefore K cannot become
818          * less than k, which means that we cannot fail to select enough blocks.
819          *----------
820          */
821         V = random_fract();
822         p = 1.0 - (double) k / (double) K;
823         while (V < p)
824         {
825                 /* skip */
826                 bs->t++;
827                 K--;                                    /* keep K == N - t */
828
829                 /* adjust p to be new cutoff point in reduced range */
830                 p *= 1.0 - (double) k / (double) K;
831         }
832
833         /* select */
834         bs->m++;
835         return bs->t++;
836 }
837
838 /*
839  * acquire_sample_rows -- acquire a random sample of rows from the table
840  *
841  * As of May 2004 we use a new two-stage method:  Stage one selects up
842  * to targrows random blocks (or all blocks, if there aren't so many).
843  * Stage two scans these blocks and uses the Vitter algorithm to create
844  * a random sample of targrows rows (or less, if there are less in the
845  * sample of blocks).  The two stages are executed simultaneously: each
846  * block is processed as soon as stage one returns its number and while
847  * the rows are read stage two controls which ones are to be inserted
848  * into the sample.
849  *
850  * Although every row has an equal chance of ending up in the final
851  * sample, this sampling method is not perfect: not every possible
852  * sample has an equal chance of being selected.  For large relations
853  * the number of different blocks represented by the sample tends to be
854  * too small.  We can live with that for now.  Improvements are welcome.
855  *
856  * We also estimate the total numbers of live and dead rows in the table,
857  * and return them into *totalrows and *totaldeadrows, respectively.
858  *
859  * An important property of this sampling method is that because we do
860  * look at a statistically unbiased set of blocks, we should get
861  * unbiased estimates of the average numbers of live and dead rows per
862  * block.  The previous sampling method put too much credence in the row
863  * density near the start of the table.
864  *
865  * The returned list of tuples is in order by physical position in the table.
866  * (We will rely on this later to derive correlation estimates.)
867  */
868 static int
869 acquire_sample_rows(Relation onerel, HeapTuple *rows, int targrows,
870                                         double *totalrows, double *totaldeadrows)
871 {
872         int                     numrows = 0;    /* # rows now in reservoir */
873         double          samplerows = 0; /* total # rows collected */
874         double          liverows = 0;   /* # live rows seen */
875         double          deadrows = 0;   /* # dead rows seen */
876         double          rowstoskip = -1;        /* -1 means not set yet */
877         BlockNumber totalblocks;
878         TransactionId OldestXmin;
879         BlockSamplerData bs;
880         double          rstate;
881
882         Assert(targrows > 1);
883
884         totalblocks = RelationGetNumberOfBlocks(onerel);
885
886         /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
887         OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
888
889         /* Prepare for sampling block numbers */
890         BlockSampler_Init(&bs, totalblocks, targrows);
891         /* Prepare for sampling rows */
892         rstate = init_selection_state(targrows);
893
894         /* Outer loop over blocks to sample */
895         while (BlockSampler_HasMore(&bs))
896         {
897                 BlockNumber targblock = BlockSampler_Next(&bs);
898                 Buffer          targbuffer;
899                 Page            targpage;
900                 OffsetNumber targoffset,
901                                         maxoffset;
902
903                 vacuum_delay_point();
904
905                 /*
906                  * We must maintain a pin on the target page's buffer to ensure that
907                  * the maxoffset value stays good (else concurrent VACUUM might delete
908                  * tuples out from under us).  Hence, pin the page until we are done
909                  * looking at it.  We also choose to hold sharelock on the buffer
910                  * throughout --- we could release and re-acquire sharelock for
911                  * each tuple, but since we aren't doing much work per tuple, the
912                  * extra lock traffic is probably better avoided.
913                  */
914                 targbuffer = ReadBufferWithStrategy(onerel, targblock, vac_strategy);
915                 LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
916                 targpage = BufferGetPage(targbuffer);
917                 maxoffset = PageGetMaxOffsetNumber(targpage);
918
919                 /* Inner loop over all tuples on the selected page */
920                 for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
921                 {
922                         ItemId          itemid;
923                         HeapTupleData targtuple;
924                         bool            sample_it = false;
925
926                         itemid = PageGetItemId(targpage, targoffset);
927
928                         /*
929                          * We ignore unused and redirect line pointers.  DEAD line
930                          * pointers should be counted as dead, because we need vacuum
931                          * to run to get rid of them.  Note that this rule agrees with
932                          * the way that heap_page_prune() counts things.
933                          */
934                         if (!ItemIdIsNormal(itemid))
935                         {
936                                 if (ItemIdIsDead(itemid))
937                                         deadrows += 1;
938                                 continue;
939                         }
940
941                         ItemPointerSet(&targtuple.t_self, targblock, targoffset);
942
943                         targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
944                         targtuple.t_len = ItemIdGetLength(itemid);
945
946                         switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
947                                                                                          OldestXmin,
948                                                                                          targbuffer))
949                         {
950                                 case HEAPTUPLE_LIVE:
951                                         sample_it = true;
952                                         liverows += 1;
953                                         break;
954
955                                 case HEAPTUPLE_DEAD:
956                                 case HEAPTUPLE_RECENTLY_DEAD:
957                                         /* Count dead and recently-dead rows */
958                                         deadrows += 1;
959                                         break;
960
961                                 case HEAPTUPLE_INSERT_IN_PROGRESS:
962                                         /*
963                                          * Insert-in-progress rows are not counted.  We assume
964                                          * that when the inserting transaction commits or aborts,
965                                          * it will send a stats message to increment the proper
966                                          * count.  This works right only if that transaction ends
967                                          * after we finish analyzing the table; if things happen
968                                          * in the other order, its stats update will be
969                                          * overwritten by ours.  However, the error will be
970                                          * large only if the other transaction runs long enough
971                                          * to insert many tuples, so assuming it will finish
972                                          * after us is the safer option.
973                                          *
974                                          * A special case is that the inserting transaction might
975                                          * be our own.  In this case we should count and sample
976                                          * the row, to accommodate users who load a table and
977                                          * analyze it in one transaction.  (pgstat_report_analyze
978                                          * has to adjust the numbers we send to the stats collector
979                                          * to make this come out right.)
980                                          */
981                                         if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
982                                         {
983                                                 sample_it = true;
984                                                 liverows += 1;
985                                         }
986                                         break;
987
988                                 case HEAPTUPLE_DELETE_IN_PROGRESS:
989                                         /*
990                                          * We count delete-in-progress rows as still live, using
991                                          * the same reasoning given above; but we don't bother to
992                                          * include them in the sample.
993                                          *
994                                          * If the delete was done by our own transaction, however,
995                                          * we must count the row as dead to make
996                                          * pgstat_report_analyze's stats adjustments come out
997                                          * right.  (Note: this works out properly when the row
998                                          * was both inserted and deleted in our xact.)
999                                          */
1000                                         if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmax(targtuple.t_data)))
1001                                                 deadrows += 1;
1002                                         else
1003                                                 liverows += 1;
1004                                         break;
1005
1006                                 default:
1007                                         elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1008                                         break;
1009                         }
1010
1011                         if (sample_it)
1012                         {
1013                                 /*
1014                                  * The first targrows sample rows are simply copied into the
1015                                  * reservoir. Then we start replacing tuples in the sample
1016                                  * until we reach the end of the relation.      This algorithm is
1017                                  * from Jeff Vitter's paper (see full citation below). It
1018                                  * works by repeatedly computing the number of tuples to skip
1019                                  * before selecting a tuple, which replaces a randomly chosen
1020                                  * element of the reservoir (current set of tuples).  At all
1021                                  * times the reservoir is a true random sample of the tuples
1022                                  * we've passed over so far, so when we fall off the end of
1023                                  * the relation we're done.
1024                                  */
1025                                 if (numrows < targrows)
1026                                         rows[numrows++] = heap_copytuple(&targtuple);
1027                                 else
1028                                 {
1029                                         /*
1030                                          * t in Vitter's paper is the number of records already
1031                                          * processed.  If we need to compute a new S value, we
1032                                          * must use the not-yet-incremented value of samplerows
1033                                          * as t.
1034                                          */
1035                                         if (rowstoskip < 0)
1036                                                 rowstoskip = get_next_S(samplerows, targrows, &rstate);
1037
1038                                         if (rowstoskip <= 0)
1039                                         {
1040                                                 /*
1041                                                  * Found a suitable tuple, so save it, replacing one
1042                                                  * old tuple at random
1043                                                  */
1044                                                 int                     k = (int) (targrows * random_fract());
1045
1046                                                 Assert(k >= 0 && k < targrows);
1047                                                 heap_freetuple(rows[k]);
1048                                                 rows[k] = heap_copytuple(&targtuple);
1049                                         }
1050
1051                                         rowstoskip -= 1;
1052                                 }
1053
1054                                 samplerows += 1;
1055                         }
1056                 }
1057
1058                 /* Now release the lock and pin on the page */
1059                 UnlockReleaseBuffer(targbuffer);
1060         }
1061
1062         /*
1063          * If we didn't find as many tuples as we wanted then we're done. No sort
1064          * is needed, since they're already in order.
1065          *
1066          * Otherwise we need to sort the collected tuples by position
1067          * (itempointer). It's not worth worrying about corner cases where the
1068          * tuples are already sorted.
1069          */
1070         if (numrows == targrows)
1071                 qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
1072
1073         /*
1074          * Estimate total numbers of rows in relation.
1075          */
1076         if (bs.m > 0)
1077         {
1078                 *totalrows = floor((liverows * totalblocks) / bs.m + 0.5);
1079                 *totaldeadrows = floor((deadrows * totalblocks) / bs.m + 0.5);
1080         }
1081         else
1082         {
1083                 *totalrows = 0.0;
1084                 *totaldeadrows = 0.0;
1085         }
1086
1087         /*
1088          * Emit some interesting relation info
1089          */
1090         ereport(elevel,
1091                         (errmsg("\"%s\": scanned %d of %u pages, "
1092                                         "containing %.0f live rows and %.0f dead rows; "
1093                                         "%d rows in sample, %.0f estimated total rows",
1094                                         RelationGetRelationName(onerel),
1095                                         bs.m, totalblocks,
1096                                         liverows, deadrows,
1097                                         numrows, *totalrows)));
1098
1099         return numrows;
1100 }
1101
1102 /* Select a random value R uniformly distributed in (0 - 1) */
1103 static double
1104 random_fract(void)
1105 {
1106         return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
1107 }
1108
1109 /*
1110  * These two routines embody Algorithm Z from "Random sampling with a
1111  * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
1112  * (Mar. 1985), Pages 37-57.  Vitter describes his algorithm in terms
1113  * of the count S of records to skip before processing another record.
1114  * It is computed primarily based on t, the number of records already read.
1115  * The only extra state needed between calls is W, a random state variable.
1116  *
1117  * init_selection_state computes the initial W value.
1118  *
1119  * Given that we've already read t records (t >= n), get_next_S
1120  * determines the number of records to skip before the next record is
1121  * processed.
1122  */
1123 static double
1124 init_selection_state(int n)
1125 {
1126         /* Initial value of W (for use when Algorithm Z is first applied) */
1127         return exp(-log(random_fract()) / n);
1128 }
1129
1130 static double
1131 get_next_S(double t, int n, double *stateptr)
1132 {
1133         double          S;
1134
1135         /* The magic constant here is T from Vitter's paper */
1136         if (t <= (22.0 * n))
1137         {
1138                 /* Process records using Algorithm X until t is large enough */
1139                 double          V,
1140                                         quot;
1141
1142                 V = random_fract();             /* Generate V */
1143                 S = 0;
1144                 t += 1;
1145                 /* Note: "num" in Vitter's code is always equal to t - n */
1146                 quot = (t - (double) n) / t;
1147                 /* Find min S satisfying (4.1) */
1148                 while (quot > V)
1149                 {
1150                         S += 1;
1151                         t += 1;
1152                         quot *= (t - (double) n) / t;
1153                 }
1154         }
1155         else
1156         {
1157                 /* Now apply Algorithm Z */
1158                 double          W = *stateptr;
1159                 double          term = t - (double) n + 1;
1160
1161                 for (;;)
1162                 {
1163                         double          numer,
1164                                                 numer_lim,
1165                                                 denom;
1166                         double          U,
1167                                                 X,
1168                                                 lhs,
1169                                                 rhs,
1170                                                 y,
1171                                                 tmp;
1172
1173                         /* Generate U and X */
1174                         U = random_fract();
1175                         X = t * (W - 1.0);
1176                         S = floor(X);           /* S is tentatively set to floor(X) */
1177                         /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
1178                         tmp = (t + 1) / term;
1179                         lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
1180                         rhs = (((t + X) / (term + S)) * term) / t;
1181                         if (lhs <= rhs)
1182                         {
1183                                 W = rhs / lhs;
1184                                 break;
1185                         }
1186                         /* Test if U <= f(S)/cg(X) */
1187                         y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
1188                         if ((double) n < S)
1189                         {
1190                                 denom = t;
1191                                 numer_lim = term + S;
1192                         }
1193                         else
1194                         {
1195                                 denom = t - (double) n + S;
1196                                 numer_lim = t + 1;
1197                         }
1198                         for (numer = t + S; numer >= numer_lim; numer -= 1)
1199                         {
1200                                 y *= numer / denom;
1201                                 denom -= 1;
1202                         }
1203                         W = exp(-log(random_fract()) / n);      /* Generate W in advance */
1204                         if (exp(log(y) / n) <= (t + X) / t)
1205                                 break;
1206                 }
1207                 *stateptr = W;
1208         }
1209         return S;
1210 }
1211
1212 /*
1213  * qsort comparator for sorting rows[] array
1214  */
1215 static int
1216 compare_rows(const void *a, const void *b)
1217 {
1218         HeapTuple       ha = *(HeapTuple *) a;
1219         HeapTuple       hb = *(HeapTuple *) b;
1220         BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
1221         OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
1222         BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
1223         OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
1224
1225         if (ba < bb)
1226                 return -1;
1227         if (ba > bb)
1228                 return 1;
1229         if (oa < ob)
1230                 return -1;
1231         if (oa > ob)
1232                 return 1;
1233         return 0;
1234 }
1235
1236
1237 /*
1238  *      update_attstats() -- update attribute statistics for one relation
1239  *
1240  *              Statistics are stored in several places: the pg_class row for the
1241  *              relation has stats about the whole relation, and there is a
1242  *              pg_statistic row for each (non-system) attribute that has ever
1243  *              been analyzed.  The pg_class values are updated by VACUUM, not here.
1244  *
1245  *              pg_statistic rows are just added or updated normally.  This means
1246  *              that pg_statistic will probably contain some deleted rows at the
1247  *              completion of a vacuum cycle, unless it happens to get vacuumed last.
1248  *
1249  *              To keep things simple, we punt for pg_statistic, and don't try
1250  *              to compute or store rows for pg_statistic itself in pg_statistic.
1251  *              This could possibly be made to work, but it's not worth the trouble.
1252  *              Note analyze_rel() has seen to it that we won't come here when
1253  *              vacuuming pg_statistic itself.
1254  *
1255  *              Note: there would be a race condition here if two backends could
1256  *              ANALYZE the same table concurrently.  Presently, we lock that out
1257  *              by taking a self-exclusive lock on the relation in analyze_rel().
1258  */
1259 static void
1260 update_attstats(Oid relid, int natts, VacAttrStats **vacattrstats)
1261 {
1262         Relation        sd;
1263         int                     attno;
1264
1265         if (natts <= 0)
1266                 return;                                 /* nothing to do */
1267
1268         sd = heap_open(StatisticRelationId, RowExclusiveLock);
1269
1270         for (attno = 0; attno < natts; attno++)
1271         {
1272                 VacAttrStats *stats = vacattrstats[attno];
1273                 HeapTuple       stup,
1274                                         oldtup;
1275                 int                     i,
1276                                         k,
1277                                         n;
1278                 Datum           values[Natts_pg_statistic];
1279                 char            nulls[Natts_pg_statistic];
1280                 char            replaces[Natts_pg_statistic];
1281
1282                 /* Ignore attr if we weren't able to collect stats */
1283                 if (!stats->stats_valid)
1284                         continue;
1285
1286                 /*
1287                  * Construct a new pg_statistic tuple
1288                  */
1289                 for (i = 0; i < Natts_pg_statistic; ++i)
1290                 {
1291                         nulls[i] = ' ';
1292                         replaces[i] = 'r';
1293                 }
1294
1295                 i = 0;
1296                 values[i++] = ObjectIdGetDatum(relid);  /* starelid */
1297                 values[i++] = Int16GetDatum(stats->attr->attnum);               /* staattnum */
1298                 values[i++] = Float4GetDatum(stats->stanullfrac);               /* stanullfrac */
1299                 values[i++] = Int32GetDatum(stats->stawidth);   /* stawidth */
1300                 values[i++] = Float4GetDatum(stats->stadistinct);               /* stadistinct */
1301                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1302                 {
1303                         values[i++] = Int16GetDatum(stats->stakind[k]);         /* stakindN */
1304                 }
1305                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1306                 {
1307                         values[i++] = ObjectIdGetDatum(stats->staop[k]);        /* staopN */
1308                 }
1309                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1310                 {
1311                         int                     nnum = stats->numnumbers[k];
1312
1313                         if (nnum > 0)
1314                         {
1315                                 Datum      *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
1316                                 ArrayType  *arry;
1317
1318                                 for (n = 0; n < nnum; n++)
1319                                         numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1320                                 /* XXX knows more than it should about type float4: */
1321                                 arry = construct_array(numdatums, nnum,
1322                                                                            FLOAT4OID,
1323                                                                            sizeof(float4), FLOAT4PASSBYVAL, 'i');
1324                                 values[i++] = PointerGetDatum(arry);    /* stanumbersN */
1325                         }
1326                         else
1327                         {
1328                                 nulls[i] = 'n';
1329                                 values[i++] = (Datum) 0;
1330                         }
1331                 }
1332                 for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
1333                 {
1334                         if (stats->numvalues[k] > 0)
1335                         {
1336                                 ArrayType  *arry;
1337
1338                                 arry = construct_array(stats->stavalues[k],
1339                                                                            stats->numvalues[k],
1340                                                                            stats->statypid[k],
1341                                                                            stats->statyplen[k],
1342                                                                            stats->statypbyval[k],
1343                                                                            stats->statypalign[k]);
1344                                 values[i++] = PointerGetDatum(arry);    /* stavaluesN */
1345                         }
1346                         else
1347                         {
1348                                 nulls[i] = 'n';
1349                                 values[i++] = (Datum) 0;
1350                         }
1351                 }
1352
1353                 /* Is there already a pg_statistic tuple for this attribute? */
1354                 oldtup = SearchSysCache(STATRELATT,
1355                                                                 ObjectIdGetDatum(relid),
1356                                                                 Int16GetDatum(stats->attr->attnum),
1357                                                                 0, 0);
1358
1359                 if (HeapTupleIsValid(oldtup))
1360                 {
1361                         /* Yes, replace it */
1362                         stup = heap_modifytuple(oldtup,
1363                                                                         RelationGetDescr(sd),
1364                                                                         values,
1365                                                                         nulls,
1366                                                                         replaces);
1367                         ReleaseSysCache(oldtup);
1368                         simple_heap_update(sd, &stup->t_self, stup);
1369                 }
1370                 else
1371                 {
1372                         /* No, insert new tuple */
1373                         stup = heap_formtuple(RelationGetDescr(sd), values, nulls);
1374                         simple_heap_insert(sd, stup);
1375                 }
1376
1377                 /* update indexes too */
1378                 CatalogUpdateIndexes(sd, stup);
1379
1380                 heap_freetuple(stup);
1381         }
1382
1383         heap_close(sd, RowExclusiveLock);
1384 }
1385
1386 /*
1387  * Standard fetch function for use by compute_stats subroutines.
1388  *
1389  * This exists to provide some insulation between compute_stats routines
1390  * and the actual storage of the sample data.
1391  */
1392 static Datum
1393 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1394 {
1395         int                     attnum = stats->tupattnum;
1396         HeapTuple       tuple = stats->rows[rownum];
1397         TupleDesc       tupDesc = stats->tupDesc;
1398
1399         return heap_getattr(tuple, attnum, tupDesc, isNull);
1400 }
1401
1402 /*
1403  * Fetch function for analyzing index expressions.
1404  *
1405  * We have not bothered to construct index tuples, instead the data is
1406  * just in Datum arrays.
1407  */
1408 static Datum
1409 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
1410 {
1411         int                     i;
1412
1413         /* exprvals and exprnulls are already offset for proper column */
1414         i = rownum * stats->rowstride;
1415         *isNull = stats->exprnulls[i];
1416         return stats->exprvals[i];
1417 }
1418
1419
1420 /*==========================================================================
1421  *
1422  * Code below this point represents the "standard" type-specific statistics
1423  * analysis algorithms.  This code can be replaced on a per-data-type basis
1424  * by setting a nonzero value in pg_type.typanalyze.
1425  *
1426  *==========================================================================
1427  */
1428
1429
1430 /*
1431  * To avoid consuming too much memory during analysis and/or too much space
1432  * in the resulting pg_statistic rows, we ignore varlena datums that are wider
1433  * than WIDTH_THRESHOLD (after detoasting!).  This is legitimate for MCV
1434  * and distinct-value calculations since a wide value is unlikely to be
1435  * duplicated at all, much less be a most-common value.  For the same reason,
1436  * ignoring wide values will not affect our estimates of histogram bin
1437  * boundaries very much.
1438  */
1439 #define WIDTH_THRESHOLD  1024
1440
1441 #define swapInt(a,b)    do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1442 #define swapDatum(a,b)  do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
1443
1444 /*
1445  * Extra information used by the default analysis routines
1446  */
1447 typedef struct
1448 {
1449         Oid                     eqopr;                  /* '=' operator for datatype, if any */
1450         Oid                     eqfunc;                 /* and associated function */
1451         Oid                     ltopr;                  /* '<' operator for datatype, if any */
1452 } StdAnalyzeData;
1453
1454 typedef struct
1455 {
1456         Datum           value;                  /* a data value */
1457         int                     tupno;                  /* position index for tuple it came from */
1458 } ScalarItem;
1459
1460 typedef struct
1461 {
1462         int                     count;                  /* # of duplicates */
1463         int                     first;                  /* values[] index of first occurrence */
1464 } ScalarMCVItem;
1465
1466 typedef struct
1467 {
1468         FmgrInfo   *cmpFn;
1469         int                     cmpFlags;
1470         int                *tupnoLink;
1471 } CompareScalarsContext;
1472
1473
1474 static void compute_minimal_stats(VacAttrStatsP stats,
1475                                           AnalyzeAttrFetchFunc fetchfunc,
1476                                           int samplerows,
1477                                           double totalrows);
1478 static void compute_scalar_stats(VacAttrStatsP stats,
1479                                          AnalyzeAttrFetchFunc fetchfunc,
1480                                          int samplerows,
1481                                          double totalrows);
1482 static int      compare_scalars(const void *a, const void *b, void *arg);
1483 static int      compare_mcvs(const void *a, const void *b);
1484
1485
1486 /*
1487  * std_typanalyze -- the default type-specific typanalyze function
1488  */
1489 static bool
1490 std_typanalyze(VacAttrStats *stats)
1491 {
1492         Form_pg_attribute attr = stats->attr;
1493         Operator        func_operator;
1494         Oid                     eqopr = InvalidOid;
1495         Oid                     eqfunc = InvalidOid;
1496         Oid                     ltopr = InvalidOid;
1497         StdAnalyzeData *mystats;
1498
1499         /* If the attstattarget column is negative, use the default value */
1500         /* NB: it is okay to scribble on stats->attr since it's a copy */
1501         if (attr->attstattarget < 0)
1502                 attr->attstattarget = default_statistics_target;
1503
1504         /* If column has no "=" operator, we can't do much of anything */
1505         func_operator = equality_oper(attr->atttypid, true);
1506         if (func_operator != NULL)
1507         {
1508                 eqopr = oprid(func_operator);
1509                 eqfunc = oprfuncid(func_operator);
1510                 ReleaseSysCache(func_operator);
1511         }
1512         if (!OidIsValid(eqfunc))
1513                 return false;
1514
1515         /* Is there a "<" operator with suitable semantics? */
1516         func_operator = ordering_oper(attr->atttypid, true);
1517         if (func_operator != NULL)
1518         {
1519                 ltopr = oprid(func_operator);
1520                 ReleaseSysCache(func_operator);
1521         }
1522
1523         /* Save the operator info for compute_stats routines */
1524         mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1525         mystats->eqopr = eqopr;
1526         mystats->eqfunc = eqfunc;
1527         mystats->ltopr = ltopr;
1528         stats->extra_data = mystats;
1529
1530         /*
1531          * Determine which standard statistics algorithm to use
1532          */
1533         if (OidIsValid(ltopr))
1534         {
1535                 /* Seems to be a scalar datatype */
1536                 stats->compute_stats = compute_scalar_stats;
1537                 /*--------------------
1538                  * The following choice of minrows is based on the paper
1539                  * "Random sampling for histogram construction: how much is enough?"
1540                  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1541                  * Proceedings of ACM SIGMOD International Conference on Management
1542                  * of Data, 1998, Pages 436-447.  Their Corollary 1 to Theorem 5
1543                  * says that for table size n, histogram size k, maximum relative
1544                  * error in bin size f, and error probability gamma, the minimum
1545                  * random sample size is
1546                  *              r = 4 * k * ln(2*n/gamma) / f^2
1547                  * Taking f = 0.5, gamma = 0.01, n = 1 million rows, we obtain
1548                  *              r = 305.82 * k
1549                  * Note that because of the log function, the dependence on n is
1550                  * quite weak; even at n = 1 billion, a 300*k sample gives <= 0.59
1551                  * bin size error with probability 0.99.  So there's no real need to
1552                  * scale for n, which is a good thing because we don't necessarily
1553                  * know it at this point.
1554                  *--------------------
1555                  */
1556                 stats->minrows = 300 * attr->attstattarget;
1557         }
1558         else
1559         {
1560                 /* Can't do much but the minimal stuff */
1561                 stats->compute_stats = compute_minimal_stats;
1562                 /* Might as well use the same minrows as above */
1563                 stats->minrows = 300 * attr->attstattarget;
1564         }
1565
1566         return true;
1567 }
1568
1569 /*
1570  *      compute_minimal_stats() -- compute minimal column statistics
1571  *
1572  *      We use this when we can find only an "=" operator for the datatype.
1573  *
1574  *      We determine the fraction of non-null rows, the average width, the
1575  *      most common values, and the (estimated) number of distinct values.
1576  *
1577  *      The most common values are determined by brute force: we keep a list
1578  *      of previously seen values, ordered by number of times seen, as we scan
1579  *      the samples.  A newly seen value is inserted just after the last
1580  *      multiply-seen value, causing the bottommost (oldest) singly-seen value
1581  *      to drop off the list.  The accuracy of this method, and also its cost,
1582  *      depend mainly on the length of the list we are willing to keep.
1583  */
1584 static void
1585 compute_minimal_stats(VacAttrStatsP stats,
1586                                           AnalyzeAttrFetchFunc fetchfunc,
1587                                           int samplerows,
1588                                           double totalrows)
1589 {
1590         int                     i;
1591         int                     null_cnt = 0;
1592         int                     nonnull_cnt = 0;
1593         int                     toowide_cnt = 0;
1594         double          total_width = 0;
1595         bool            is_varlena = (!stats->attr->attbyval &&
1596                                                           stats->attr->attlen == -1);
1597         bool            is_varwidth = (!stats->attr->attbyval &&
1598                                                            stats->attr->attlen < 0);
1599         FmgrInfo        f_cmpeq;
1600         typedef struct
1601         {
1602                 Datum           value;
1603                 int                     count;
1604         } TrackItem;
1605         TrackItem  *track;
1606         int                     track_cnt,
1607                                 track_max;
1608         int                     num_mcv = stats->attr->attstattarget;
1609         StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1610
1611         /*
1612          * We track up to 2*n values for an n-element MCV list; but at least 10
1613          */
1614         track_max = 2 * num_mcv;
1615         if (track_max < 10)
1616                 track_max = 10;
1617         track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
1618         track_cnt = 0;
1619
1620         fmgr_info(mystats->eqfunc, &f_cmpeq);
1621
1622         for (i = 0; i < samplerows; i++)
1623         {
1624                 Datum           value;
1625                 bool            isnull;
1626                 bool            match;
1627                 int                     firstcount1,
1628                                         j;
1629
1630                 vacuum_delay_point();
1631
1632                 value = fetchfunc(stats, i, &isnull);
1633
1634                 /* Check for null/nonnull */
1635                 if (isnull)
1636                 {
1637                         null_cnt++;
1638                         continue;
1639                 }
1640                 nonnull_cnt++;
1641
1642                 /*
1643                  * If it's a variable-width field, add up widths for average width
1644                  * calculation.  Note that if the value is toasted, we use the toasted
1645                  * width.  We don't bother with this calculation if it's a fixed-width
1646                  * type.
1647                  */
1648                 if (is_varlena)
1649                 {
1650                         total_width += VARSIZE_ANY(DatumGetPointer(value));
1651
1652                         /*
1653                          * If the value is toasted, we want to detoast it just once to
1654                          * avoid repeated detoastings and resultant excess memory usage
1655                          * during the comparisons.      Also, check to see if the value is
1656                          * excessively wide, and if so don't detoast at all --- just
1657                          * ignore the value.
1658                          */
1659                         if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1660                         {
1661                                 toowide_cnt++;
1662                                 continue;
1663                         }
1664                         value = PointerGetDatum(PG_DETOAST_DATUM(value));
1665                 }
1666                 else if (is_varwidth)
1667                 {
1668                         /* must be cstring */
1669                         total_width += strlen(DatumGetCString(value)) + 1;
1670                 }
1671
1672                 /*
1673                  * See if the value matches anything we're already tracking.
1674                  */
1675                 match = false;
1676                 firstcount1 = track_cnt;
1677                 for (j = 0; j < track_cnt; j++)
1678                 {
1679                         if (DatumGetBool(FunctionCall2(&f_cmpeq, value, track[j].value)))
1680                         {
1681                                 match = true;
1682                                 break;
1683                         }
1684                         if (j < firstcount1 && track[j].count == 1)
1685                                 firstcount1 = j;
1686                 }
1687
1688                 if (match)
1689                 {
1690                         /* Found a match */
1691                         track[j].count++;
1692                         /* This value may now need to "bubble up" in the track list */
1693                         while (j > 0 && track[j].count > track[j - 1].count)
1694                         {
1695                                 swapDatum(track[j].value, track[j - 1].value);
1696                                 swapInt(track[j].count, track[j - 1].count);
1697                                 j--;
1698                         }
1699                 }
1700                 else
1701                 {
1702                         /* No match.  Insert at head of count-1 list */
1703                         if (track_cnt < track_max)
1704                                 track_cnt++;
1705                         for (j = track_cnt - 1; j > firstcount1; j--)
1706                         {
1707                                 track[j].value = track[j - 1].value;
1708                                 track[j].count = track[j - 1].count;
1709                         }
1710                         if (firstcount1 < track_cnt)
1711                         {
1712                                 track[firstcount1].value = value;
1713                                 track[firstcount1].count = 1;
1714                         }
1715                 }
1716         }
1717
1718         /* We can only compute real stats if we found some non-null values. */
1719         if (nonnull_cnt > 0)
1720         {
1721                 int                     nmultiple,
1722                                         summultiple;
1723
1724                 stats->stats_valid = true;
1725                 /* Do the simple null-frac and width stats */
1726                 stats->stanullfrac = (double) null_cnt / (double) samplerows;
1727                 if (is_varwidth)
1728                         stats->stawidth = total_width / (double) nonnull_cnt;
1729                 else
1730                         stats->stawidth = stats->attrtype->typlen;
1731
1732                 /* Count the number of values we found multiple times */
1733                 summultiple = 0;
1734                 for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
1735                 {
1736                         if (track[nmultiple].count == 1)
1737                                 break;
1738                         summultiple += track[nmultiple].count;
1739                 }
1740
1741                 if (nmultiple == 0)
1742                 {
1743                         /* If we found no repeated values, assume it's a unique column */
1744                         stats->stadistinct = -1.0;
1745                 }
1746                 else if (track_cnt < track_max && toowide_cnt == 0 &&
1747                                  nmultiple == track_cnt)
1748                 {
1749                         /*
1750                          * Our track list includes every value in the sample, and every
1751                          * value appeared more than once.  Assume the column has just
1752                          * these values.
1753                          */
1754                         stats->stadistinct = track_cnt;
1755                 }
1756                 else
1757                 {
1758                         /*----------
1759                          * Estimate the number of distinct values using the estimator
1760                          * proposed by Haas and Stokes in IBM Research Report RJ 10025:
1761                          *              n*d / (n - f1 + f1*n/N)
1762                          * where f1 is the number of distinct values that occurred
1763                          * exactly once in our sample of n rows (from a total of N),
1764                          * and d is the total number of distinct values in the sample.
1765                          * This is their Duj1 estimator; the other estimators they
1766                          * recommend are considerably more complex, and are numerically
1767                          * very unstable when n is much smaller than N.
1768                          *
1769                          * We assume (not very reliably!) that all the multiply-occurring
1770                          * values are reflected in the final track[] list, and the other
1771                          * nonnull values all appeared but once.  (XXX this usually
1772                          * results in a drastic overestimate of ndistinct.      Can we do
1773                          * any better?)
1774                          *----------
1775                          */
1776                         int                     f1 = nonnull_cnt - summultiple;
1777                         int                     d = f1 + nmultiple;
1778                         double          numer,
1779                                                 denom,
1780                                                 stadistinct;
1781
1782                         numer = (double) samplerows *(double) d;
1783
1784                         denom = (double) (samplerows - f1) +
1785                                 (double) f1 *(double) samplerows / totalrows;
1786
1787                         stadistinct = numer / denom;
1788                         /* Clamp to sane range in case of roundoff error */
1789                         if (stadistinct < (double) d)
1790                                 stadistinct = (double) d;
1791                         if (stadistinct > totalrows)
1792                                 stadistinct = totalrows;
1793                         stats->stadistinct = floor(stadistinct + 0.5);
1794                 }
1795
1796                 /*
1797                  * If we estimated the number of distinct values at more than 10% of
1798                  * the total row count (a very arbitrary limit), then assume that
1799                  * stadistinct should scale with the row count rather than be a fixed
1800                  * value.
1801                  */
1802                 if (stats->stadistinct > 0.1 * totalrows)
1803                         stats->stadistinct = -(stats->stadistinct / totalrows);
1804
1805                 /*
1806                  * Decide how many values are worth storing as most-common values. If
1807                  * we are able to generate a complete MCV list (all the values in the
1808                  * sample will fit, and we think these are all the ones in the table),
1809                  * then do so.  Otherwise, store only those values that are
1810                  * significantly more common than the (estimated) average. We set the
1811                  * threshold rather arbitrarily at 25% more than average, with at
1812                  * least 2 instances in the sample.
1813                  */
1814                 if (track_cnt < track_max && toowide_cnt == 0 &&
1815                         stats->stadistinct > 0 &&
1816                         track_cnt <= num_mcv)
1817                 {
1818                         /* Track list includes all values seen, and all will fit */
1819                         num_mcv = track_cnt;
1820                 }
1821                 else
1822                 {
1823                         double          ndistinct = stats->stadistinct;
1824                         double          avgcount,
1825                                                 mincount;
1826
1827                         if (ndistinct < 0)
1828                                 ndistinct = -ndistinct * totalrows;
1829                         /* estimate # of occurrences in sample of a typical value */
1830                         avgcount = (double) samplerows / ndistinct;
1831                         /* set minimum threshold count to store a value */
1832                         mincount = avgcount * 1.25;
1833                         if (mincount < 2)
1834                                 mincount = 2;
1835                         if (num_mcv > track_cnt)
1836                                 num_mcv = track_cnt;
1837                         for (i = 0; i < num_mcv; i++)
1838                         {
1839                                 if (track[i].count < mincount)
1840                                 {
1841                                         num_mcv = i;
1842                                         break;
1843                                 }
1844                         }
1845                 }
1846
1847                 /* Generate MCV slot entry */
1848                 if (num_mcv > 0)
1849                 {
1850                         MemoryContext old_context;
1851                         Datum      *mcv_values;
1852                         float4     *mcv_freqs;
1853
1854                         /* Must copy the target values into anl_context */
1855                         old_context = MemoryContextSwitchTo(stats->anl_context);
1856                         mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
1857                         mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
1858                         for (i = 0; i < num_mcv; i++)
1859                         {
1860                                 mcv_values[i] = datumCopy(track[i].value,
1861                                                                                   stats->attr->attbyval,
1862                                                                                   stats->attr->attlen);
1863                                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
1864                         }
1865                         MemoryContextSwitchTo(old_context);
1866
1867                         stats->stakind[0] = STATISTIC_KIND_MCV;
1868                         stats->staop[0] = mystats->eqopr;
1869                         stats->stanumbers[0] = mcv_freqs;
1870                         stats->numnumbers[0] = num_mcv;
1871                         stats->stavalues[0] = mcv_values;
1872                         stats->numvalues[0] = num_mcv;
1873                         /*
1874                          * Accept the defaults for stats->statypid and others.
1875                          * They have been set before we were called (see vacuum.h)
1876                          */
1877                 }
1878         }
1879         else if (null_cnt > 0)
1880         {
1881                 /* We found only nulls; assume the column is entirely null */
1882                 stats->stats_valid = true;
1883                 stats->stanullfrac = 1.0;
1884                 if (is_varwidth)
1885                         stats->stawidth = 0;    /* "unknown" */
1886                 else
1887                         stats->stawidth = stats->attrtype->typlen;
1888                 stats->stadistinct = 0.0;               /* "unknown" */
1889         }
1890
1891         /* We don't need to bother cleaning up any of our temporary palloc's */
1892 }
1893
1894
1895 /*
1896  *      compute_scalar_stats() -- compute column statistics
1897  *
1898  *      We use this when we can find "=" and "<" operators for the datatype.
1899  *
1900  *      We determine the fraction of non-null rows, the average width, the
1901  *      most common values, the (estimated) number of distinct values, the
1902  *      distribution histogram, and the correlation of physical to logical order.
1903  *
1904  *      The desired stats can be determined fairly easily after sorting the
1905  *      data values into order.
1906  */
1907 static void
1908 compute_scalar_stats(VacAttrStatsP stats,
1909                                          AnalyzeAttrFetchFunc fetchfunc,
1910                                          int samplerows,
1911                                          double totalrows)
1912 {
1913         int                     i;
1914         int                     null_cnt = 0;
1915         int                     nonnull_cnt = 0;
1916         int                     toowide_cnt = 0;
1917         double          total_width = 0;
1918         bool            is_varlena = (!stats->attr->attbyval &&
1919                                                           stats->attr->attlen == -1);
1920         bool            is_varwidth = (!stats->attr->attbyval &&
1921                                                            stats->attr->attlen < 0);
1922         double          corr_xysum;
1923         Oid                     cmpFn;
1924         int                     cmpFlags;
1925         FmgrInfo        f_cmpfn;
1926         ScalarItem *values;
1927         int                     values_cnt = 0;
1928         int                *tupnoLink;
1929         ScalarMCVItem *track;
1930         int                     track_cnt = 0;
1931         int                     num_mcv = stats->attr->attstattarget;
1932         int                     num_bins = stats->attr->attstattarget;
1933         StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
1934
1935         values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
1936         tupnoLink = (int *) palloc(samplerows * sizeof(int));
1937         track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
1938
1939         SelectSortFunction(mystats->ltopr, false, &cmpFn, &cmpFlags);
1940         fmgr_info(cmpFn, &f_cmpfn);
1941
1942         /* Initial scan to find sortable values */
1943         for (i = 0; i < samplerows; i++)
1944         {
1945                 Datum           value;
1946                 bool            isnull;
1947
1948                 vacuum_delay_point();
1949
1950                 value = fetchfunc(stats, i, &isnull);
1951
1952                 /* Check for null/nonnull */
1953                 if (isnull)
1954                 {
1955                         null_cnt++;
1956                         continue;
1957                 }
1958                 nonnull_cnt++;
1959
1960                 /*
1961                  * If it's a variable-width field, add up widths for average width
1962                  * calculation.  Note that if the value is toasted, we use the toasted
1963                  * width.  We don't bother with this calculation if it's a fixed-width
1964                  * type.
1965                  */
1966                 if (is_varlena)
1967                 {
1968                         total_width += VARSIZE_ANY(DatumGetPointer(value));
1969
1970                         /*
1971                          * If the value is toasted, we want to detoast it just once to
1972                          * avoid repeated detoastings and resultant excess memory usage
1973                          * during the comparisons.      Also, check to see if the value is
1974                          * excessively wide, and if so don't detoast at all --- just
1975                          * ignore the value.
1976                          */
1977                         if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1978                         {
1979                                 toowide_cnt++;
1980                                 continue;
1981                         }
1982                         value = PointerGetDatum(PG_DETOAST_DATUM(value));
1983                 }
1984                 else if (is_varwidth)
1985                 {
1986                         /* must be cstring */
1987                         total_width += strlen(DatumGetCString(value)) + 1;
1988                 }
1989
1990                 /* Add it to the list to be sorted */
1991                 values[values_cnt].value = value;
1992                 values[values_cnt].tupno = values_cnt;
1993                 tupnoLink[values_cnt] = values_cnt;
1994                 values_cnt++;
1995         }
1996
1997         /* We can only compute real stats if we found some sortable values. */
1998         if (values_cnt > 0)
1999         {
2000                 int                     ndistinct,      /* # distinct values in sample */
2001                                         nmultiple,      /* # that appear multiple times */
2002                                         num_hist,
2003                                         dups_cnt;
2004                 int                     slot_idx = 0;
2005                 CompareScalarsContext cxt;
2006
2007                 /* Sort the collected values */
2008                 cxt.cmpFn = &f_cmpfn;
2009                 cxt.cmpFlags = cmpFlags;
2010                 cxt.tupnoLink = tupnoLink;
2011                 qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
2012                                   compare_scalars, (void *) &cxt);
2013
2014                 /*
2015                  * Now scan the values in order, find the most common ones, and also
2016                  * accumulate ordering-correlation statistics.
2017                  *
2018                  * To determine which are most common, we first have to count the
2019                  * number of duplicates of each value.  The duplicates are adjacent in
2020                  * the sorted list, so a brute-force approach is to compare successive
2021                  * datum values until we find two that are not equal. However, that
2022                  * requires N-1 invocations of the datum comparison routine, which are
2023                  * completely redundant with work that was done during the sort.  (The
2024                  * sort algorithm must at some point have compared each pair of items
2025                  * that are adjacent in the sorted order; otherwise it could not know
2026                  * that it's ordered the pair correctly.) We exploit this by having
2027                  * compare_scalars remember the highest tupno index that each
2028                  * ScalarItem has been found equal to.  At the end of the sort, a
2029                  * ScalarItem's tupnoLink will still point to itself if and only if it
2030                  * is the last item of its group of duplicates (since the group will
2031                  * be ordered by tupno).
2032                  */
2033                 corr_xysum = 0;
2034                 ndistinct = 0;
2035                 nmultiple = 0;
2036                 dups_cnt = 0;
2037                 for (i = 0; i < values_cnt; i++)
2038                 {
2039                         int                     tupno = values[i].tupno;
2040
2041                         corr_xysum += ((double) i) * ((double) tupno);
2042                         dups_cnt++;
2043                         if (tupnoLink[tupno] == tupno)
2044                         {
2045                                 /* Reached end of duplicates of this value */
2046                                 ndistinct++;
2047                                 if (dups_cnt > 1)
2048                                 {
2049                                         nmultiple++;
2050                                         if (track_cnt < num_mcv ||
2051                                                 dups_cnt > track[track_cnt - 1].count)
2052                                         {
2053                                                 /*
2054                                                  * Found a new item for the mcv list; find its
2055                                                  * position, bubbling down old items if needed. Loop
2056                                                  * invariant is that j points at an empty/ replaceable
2057                                                  * slot.
2058                                                  */
2059                                                 int                     j;
2060
2061                                                 if (track_cnt < num_mcv)
2062                                                         track_cnt++;
2063                                                 for (j = track_cnt - 1; j > 0; j--)
2064                                                 {
2065                                                         if (dups_cnt <= track[j - 1].count)
2066                                                                 break;
2067                                                         track[j].count = track[j - 1].count;
2068                                                         track[j].first = track[j - 1].first;
2069                                                 }
2070                                                 track[j].count = dups_cnt;
2071                                                 track[j].first = i + 1 - dups_cnt;
2072                                         }
2073                                 }
2074                                 dups_cnt = 0;
2075                         }
2076                 }
2077
2078                 stats->stats_valid = true;
2079                 /* Do the simple null-frac and width stats */
2080                 stats->stanullfrac = (double) null_cnt / (double) samplerows;
2081                 if (is_varwidth)
2082                         stats->stawidth = total_width / (double) nonnull_cnt;
2083                 else
2084                         stats->stawidth = stats->attrtype->typlen;
2085
2086                 if (nmultiple == 0)
2087                 {
2088                         /* If we found no repeated values, assume it's a unique column */
2089                         stats->stadistinct = -1.0;
2090                 }
2091                 else if (toowide_cnt == 0 && nmultiple == ndistinct)
2092                 {
2093                         /*
2094                          * Every value in the sample appeared more than once.  Assume the
2095                          * column has just these values.
2096                          */
2097                         stats->stadistinct = ndistinct;
2098                 }
2099                 else
2100                 {
2101                         /*----------
2102                          * Estimate the number of distinct values using the estimator
2103                          * proposed by Haas and Stokes in IBM Research Report RJ 10025:
2104                          *              n*d / (n - f1 + f1*n/N)
2105                          * where f1 is the number of distinct values that occurred
2106                          * exactly once in our sample of n rows (from a total of N),
2107                          * and d is the total number of distinct values in the sample.
2108                          * This is their Duj1 estimator; the other estimators they
2109                          * recommend are considerably more complex, and are numerically
2110                          * very unstable when n is much smaller than N.
2111                          *
2112                          * Overwidth values are assumed to have been distinct.
2113                          *----------
2114                          */
2115                         int                     f1 = ndistinct - nmultiple + toowide_cnt;
2116                         int                     d = f1 + nmultiple;
2117                         double          numer,
2118                                                 denom,
2119                                                 stadistinct;
2120
2121                         numer = (double) samplerows *(double) d;
2122
2123                         denom = (double) (samplerows - f1) +
2124                                 (double) f1 *(double) samplerows / totalrows;
2125
2126                         stadistinct = numer / denom;
2127                         /* Clamp to sane range in case of roundoff error */
2128                         if (stadistinct < (double) d)
2129                                 stadistinct = (double) d;
2130                         if (stadistinct > totalrows)
2131                                 stadistinct = totalrows;
2132                         stats->stadistinct = floor(stadistinct + 0.5);
2133                 }
2134
2135                 /*
2136                  * If we estimated the number of distinct values at more than 10% of
2137                  * the total row count (a very arbitrary limit), then assume that
2138                  * stadistinct should scale with the row count rather than be a fixed
2139                  * value.
2140                  */
2141                 if (stats->stadistinct > 0.1 * totalrows)
2142                         stats->stadistinct = -(stats->stadistinct / totalrows);
2143
2144                 /*
2145                  * Decide how many values are worth storing as most-common values. If
2146                  * we are able to generate a complete MCV list (all the values in the
2147                  * sample will fit, and we think these are all the ones in the table),
2148                  * then do so.  Otherwise, store only those values that are
2149                  * significantly more common than the (estimated) average. We set the
2150                  * threshold rather arbitrarily at 25% more than average, with at
2151                  * least 2 instances in the sample.  Also, we won't suppress values
2152                  * that have a frequency of at least 1/K where K is the intended
2153                  * number of histogram bins; such values might otherwise cause us to
2154                  * emit duplicate histogram bin boundaries.
2155                  */
2156                 if (track_cnt == ndistinct && toowide_cnt == 0 &&
2157                         stats->stadistinct > 0 &&
2158                         track_cnt <= num_mcv)
2159                 {
2160                         /* Track list includes all values seen, and all will fit */
2161                         num_mcv = track_cnt;
2162                 }
2163                 else
2164                 {
2165                         double          ndistinct = stats->stadistinct;
2166                         double          avgcount,
2167                                                 mincount,
2168                                                 maxmincount;
2169
2170                         if (ndistinct < 0)
2171                                 ndistinct = -ndistinct * totalrows;
2172                         /* estimate # of occurrences in sample of a typical value */
2173                         avgcount = (double) samplerows / ndistinct;
2174                         /* set minimum threshold count to store a value */
2175                         mincount = avgcount * 1.25;
2176                         if (mincount < 2)
2177                                 mincount = 2;
2178                         /* don't let threshold exceed 1/K, however */
2179                         maxmincount = (double) samplerows / (double) num_bins;
2180                         if (mincount > maxmincount)
2181                                 mincount = maxmincount;
2182                         if (num_mcv > track_cnt)
2183                                 num_mcv = track_cnt;
2184                         for (i = 0; i < num_mcv; i++)
2185                         {
2186                                 if (track[i].count < mincount)
2187                                 {
2188                                         num_mcv = i;
2189                                         break;
2190                                 }
2191                         }
2192                 }
2193
2194                 /* Generate MCV slot entry */
2195                 if (num_mcv > 0)
2196                 {
2197                         MemoryContext old_context;
2198                         Datum      *mcv_values;
2199                         float4     *mcv_freqs;
2200
2201                         /* Must copy the target values into anl_context */
2202                         old_context = MemoryContextSwitchTo(stats->anl_context);
2203                         mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
2204                         mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
2205                         for (i = 0; i < num_mcv; i++)
2206                         {
2207                                 mcv_values[i] = datumCopy(values[track[i].first].value,
2208                                                                                   stats->attr->attbyval,
2209                                                                                   stats->attr->attlen);
2210                                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
2211                         }
2212                         MemoryContextSwitchTo(old_context);
2213
2214                         stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
2215                         stats->staop[slot_idx] = mystats->eqopr;
2216                         stats->stanumbers[slot_idx] = mcv_freqs;
2217                         stats->numnumbers[slot_idx] = num_mcv;
2218                         stats->stavalues[slot_idx] = mcv_values;
2219                         stats->numvalues[slot_idx] = num_mcv;
2220                         /*
2221                          * Accept the defaults for stats->statypid and others.
2222                          * They have been set before we were called (see vacuum.h)
2223                          */
2224                         slot_idx++;
2225                 }
2226
2227                 /*
2228                  * Generate a histogram slot entry if there are at least two distinct
2229                  * values not accounted for in the MCV list.  (This ensures the
2230                  * histogram won't collapse to empty or a singleton.)
2231                  */
2232                 num_hist = ndistinct - num_mcv;
2233                 if (num_hist > num_bins)
2234                         num_hist = num_bins + 1;
2235                 if (num_hist >= 2)
2236                 {
2237                         MemoryContext old_context;
2238                         Datum      *hist_values;
2239                         int                     nvals;
2240
2241                         /* Sort the MCV items into position order to speed next loop */
2242                         qsort((void *) track, num_mcv,
2243                                   sizeof(ScalarMCVItem), compare_mcvs);
2244
2245                         /*
2246                          * Collapse out the MCV items from the values[] array.
2247                          *
2248                          * Note we destroy the values[] array here... but we don't need it
2249                          * for anything more.  We do, however, still need values_cnt.
2250                          * nvals will be the number of remaining entries in values[].
2251                          */
2252                         if (num_mcv > 0)
2253                         {
2254                                 int                     src,
2255                                                         dest;
2256                                 int                     j;
2257
2258                                 src = dest = 0;
2259                                 j = 0;                  /* index of next interesting MCV item */
2260                                 while (src < values_cnt)
2261                                 {
2262                                         int                     ncopy;
2263
2264                                         if (j < num_mcv)
2265                                         {
2266                                                 int                     first = track[j].first;
2267
2268                                                 if (src >= first)
2269                                                 {
2270                                                         /* advance past this MCV item */
2271                                                         src = first + track[j].count;
2272                                                         j++;
2273                                                         continue;
2274                                                 }
2275                                                 ncopy = first - src;
2276                                         }
2277                                         else
2278                                                 ncopy = values_cnt - src;
2279                                         memmove(&values[dest], &values[src],
2280                                                         ncopy * sizeof(ScalarItem));
2281                                         src += ncopy;
2282                                         dest += ncopy;
2283                                 }
2284                                 nvals = dest;
2285                         }
2286                         else
2287                                 nvals = values_cnt;
2288                         Assert(nvals >= num_hist);
2289
2290                         /* Must copy the target values into anl_context */
2291                         old_context = MemoryContextSwitchTo(stats->anl_context);
2292                         hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
2293                         for (i = 0; i < num_hist; i++)
2294                         {
2295                                 int                     pos;
2296
2297                                 pos = (i * (nvals - 1)) / (num_hist - 1);
2298                                 hist_values[i] = datumCopy(values[pos].value,
2299                                                                                    stats->attr->attbyval,
2300                                                                                    stats->attr->attlen);
2301                         }
2302                         MemoryContextSwitchTo(old_context);
2303
2304                         stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
2305                         stats->staop[slot_idx] = mystats->ltopr;
2306                         stats->stavalues[slot_idx] = hist_values;
2307                         stats->numvalues[slot_idx] = num_hist;
2308                         /*
2309                          * Accept the defaults for stats->statypid and others.
2310                          * They have been set before we were called (see vacuum.h)
2311                          */
2312                         slot_idx++;
2313                 }
2314
2315                 /* Generate a correlation entry if there are multiple values */
2316                 if (values_cnt > 1)
2317                 {
2318                         MemoryContext old_context;
2319                         float4     *corrs;
2320                         double          corr_xsum,
2321                                                 corr_x2sum;
2322
2323                         /* Must copy the target values into anl_context */
2324                         old_context = MemoryContextSwitchTo(stats->anl_context);
2325                         corrs = (float4 *) palloc(sizeof(float4));
2326                         MemoryContextSwitchTo(old_context);
2327
2328                         /*----------
2329                          * Since we know the x and y value sets are both
2330                          *              0, 1, ..., values_cnt-1
2331                          * we have sum(x) = sum(y) =
2332                          *              (values_cnt-1)*values_cnt / 2
2333                          * and sum(x^2) = sum(y^2) =
2334                          *              (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
2335                          *----------
2336                          */
2337                         corr_xsum = ((double) (values_cnt - 1)) *
2338                                 ((double) values_cnt) / 2.0;
2339                         corr_x2sum = ((double) (values_cnt - 1)) *
2340                                 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
2341
2342                         /* And the correlation coefficient reduces to */
2343                         corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
2344                                 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
2345
2346                         stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
2347                         stats->staop[slot_idx] = mystats->ltopr;
2348                         stats->stanumbers[slot_idx] = corrs;
2349                         stats->numnumbers[slot_idx] = 1;
2350                         slot_idx++;
2351                 }
2352         }
2353         else if (nonnull_cnt == 0 && null_cnt > 0)
2354         {
2355                 /* We found only nulls; assume the column is entirely null */
2356                 stats->stats_valid = true;
2357                 stats->stanullfrac = 1.0;
2358                 if (is_varwidth)
2359                         stats->stawidth = 0;    /* "unknown" */
2360                 else
2361                         stats->stawidth = stats->attrtype->typlen;
2362                 stats->stadistinct = 0.0;               /* "unknown" */
2363         }
2364
2365         /* We don't need to bother cleaning up any of our temporary palloc's */
2366 }
2367
2368 /*
2369  * qsort_arg comparator for sorting ScalarItems
2370  *
2371  * Aside from sorting the items, we update the tupnoLink[] array
2372  * whenever two ScalarItems are found to contain equal datums.  The array
2373  * is indexed by tupno; for each ScalarItem, it contains the highest
2374  * tupno that that item's datum has been found to be equal to.  This allows
2375  * us to avoid additional comparisons in compute_scalar_stats().
2376  */
2377 static int
2378 compare_scalars(const void *a, const void *b, void *arg)
2379 {
2380         Datum           da = ((ScalarItem *) a)->value;
2381         int                     ta = ((ScalarItem *) a)->tupno;
2382         Datum           db = ((ScalarItem *) b)->value;
2383         int                     tb = ((ScalarItem *) b)->tupno;
2384         CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
2385         int32           compare;
2386
2387         compare = ApplySortFunction(cxt->cmpFn, cxt->cmpFlags,
2388                                                                 da, false, db, false);
2389         if (compare != 0)
2390                 return compare;
2391
2392         /*
2393          * The two datums are equal, so update cxt->tupnoLink[].
2394          */
2395         if (cxt->tupnoLink[ta] < tb)
2396                 cxt->tupnoLink[ta] = tb;
2397         if (cxt->tupnoLink[tb] < ta)
2398                 cxt->tupnoLink[tb] = ta;
2399
2400         /*
2401          * For equal datums, sort by tupno
2402          */
2403         return ta - tb;
2404 }
2405
2406 /*
2407  * qsort comparator for sorting ScalarMCVItems by position
2408  */
2409 static int
2410 compare_mcvs(const void *a, const void *b)
2411 {
2412         int                     da = ((ScalarMCVItem *) a)->first;
2413         int                     db = ((ScalarMCVItem *) b)->first;
2414
2415         return da - db;
2416 }