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