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