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