OSDN Git Service

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