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