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