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