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