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