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