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