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