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