PostgreSQL Source Code  git master
vacuum.h File Reference
#include "access/htup.h"
#include "catalog/pg_class.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_type.h"
#include "nodes/parsenodes.h"
#include "storage/buf.h"
#include "storage/lock.h"
#include "utils/relcache.h"
Include dependency graph for vacuum.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  VacAttrStats
 
struct  VacuumParams
 

Typedefs

typedef struct VacAttrStatsVacAttrStatsP
 
typedef Datum(* AnalyzeAttrFetchFunc) (VacAttrStatsP stats, int rownum, bool *isNull)
 
typedef void(* AnalyzeAttrComputeStatsFunc) (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
typedef struct VacAttrStats VacAttrStats
 
typedef enum VacuumOption VacuumOption
 
typedef enum VacOptTernaryValue VacOptTernaryValue
 
typedef struct VacuumParams VacuumParams
 

Enumerations

enum  VacuumOption {
  VACOPT_VACUUM = 1 << 0, VACOPT_ANALYZE = 1 << 1, VACOPT_VERBOSE = 1 << 2, VACOPT_FREEZE = 1 << 3,
  VACOPT_FULL = 1 << 4, VACOPT_SKIP_LOCKED = 1 << 5, VACOPT_SKIPTOAST = 1 << 6, VACOPT_DISABLE_PAGE_SKIPPING = 1 << 7
}
 
enum  VacOptTernaryValue { VACOPT_TERNARY_DEFAULT = 0, VACOPT_TERNARY_DISABLED, VACOPT_TERNARY_ENABLED }
 

Functions

void ExecVacuum (ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)
 
void vacuum (List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
 
void vac_open_indexes (Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
 
void vac_close_indexes (int nindexes, Relation *Irel, LOCKMODE lockmode)
 
double vac_estimate_reltuples (Relation relation, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
 
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)
 
void vacuum_set_xid_limits (Relation rel, int freeze_min_age, int freeze_table_age, int multixact_freeze_min_age, int multixact_freeze_table_age, TransactionId *oldestXmin, TransactionId *freezeLimit, TransactionId *xidFullScanLimit, MultiXactId *multiXactCutoff, MultiXactId *mxactFullScanLimit)
 
void vac_update_datfrozenxid (void)
 
void vacuum_delay_point (void)
 
bool vacuum_is_relation_owner (Oid relid, Form_pg_class reltuple, int options)
 
Relation vacuum_open_relation (Oid relid, RangeVar *relation, int options, bool verbose, LOCKMODE lmode)
 
void analyze_rel (Oid relid, RangeVar *relation, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
 
bool std_typanalyze (VacAttrStats *stats)
 
double anl_random_fract (void)
 
double anl_init_selection_state (int n)
 
double anl_get_next_S (double t, int n, double *stateptr)
 

Variables

PGDLLIMPORT int default_statistics_target
 
int vacuum_freeze_min_age
 
int vacuum_freeze_table_age
 
int vacuum_multixact_freeze_min_age
 
int vacuum_multixact_freeze_table_age
 

Typedef Documentation

◆ AnalyzeAttrComputeStatsFunc

typedef void(* AnalyzeAttrComputeStatsFunc) (VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)

Definition at line 67 of file vacuum.h.

◆ AnalyzeAttrFetchFunc

typedef Datum(* AnalyzeAttrFetchFunc) (VacAttrStatsP stats, int rownum, bool *isNull)

Definition at line 64 of file vacuum.h.

◆ VacAttrStats

typedef struct VacAttrStats VacAttrStats

◆ VacAttrStatsP

typedef struct VacAttrStats* VacAttrStatsP

Definition at line 62 of file vacuum.h.

◆ VacOptTernaryValue

◆ VacuumOption

typedef enum VacuumOption VacuumOption

◆ VacuumParams

typedef struct VacuumParams VacuumParams

Enumeration Type Documentation

◆ VacOptTernaryValue

Enumerator
VACOPT_TERNARY_DEFAULT 
VACOPT_TERNARY_DISABLED 
VACOPT_TERNARY_ENABLED 

Definition at line 157 of file vacuum.h.

◆ VacuumOption

Enumerator
VACOPT_VACUUM 
VACOPT_ANALYZE 
VACOPT_VERBOSE 
VACOPT_FREEZE 
VACOPT_FULL 
VACOPT_SKIP_LOCKED 
VACOPT_SKIPTOAST 
VACOPT_DISABLE_PAGE_SKIPPING 

Definition at line 139 of file vacuum.h.

140 {
141  VACOPT_VACUUM = 1 << 0, /* do VACUUM */
142  VACOPT_ANALYZE = 1 << 1, /* do ANALYZE */
143  VACOPT_VERBOSE = 1 << 2, /* print progress info */
144  VACOPT_FREEZE = 1 << 3, /* FREEZE option */
145  VACOPT_FULL = 1 << 4, /* FULL (non-concurrent) vacuum */
146  VACOPT_SKIP_LOCKED = 1 << 5, /* skip if cannot get lock */
147  VACOPT_SKIPTOAST = 1 << 6, /* don't process the TOAST table, if any */
148  VACOPT_DISABLE_PAGE_SKIPPING = 1 << 7 /* don't skip any pages */
149 } VacuumOption;
VacuumOption
Definition: vacuum.h:139

Function Documentation

◆ analyze_rel()

void analyze_rel ( Oid  relid,
RangeVar relation,
VacuumParams params,
List va_cols,
bool  in_outer_xact,
BufferAccessStrategy  bstrategy 
)

Definition at line 118 of file analyze.c.

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, DEBUG2, do_analyze_rel(), elevel, ereport, errmsg(), GetFdwRoutineForRelation(), INFO, VacuumParams::log_min_duration, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyPgXact, NoLock, VacuumParams::options, PROC_IN_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, relpages, ShareUpdateExclusiveLock, VACOPT_ANALYZE, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum_is_relation_owner(), vacuum_open_relation(), PGXACT::vacuumFlags, and WARNING.

Referenced by vacuum().

121 {
122  Relation onerel;
123  int elevel;
124  AcquireSampleRowsFunc acquirefunc = NULL;
125  BlockNumber relpages = 0;
126 
127  /* Select logging level */
128  if (params->options & VACOPT_VERBOSE)
129  elevel = INFO;
130  else
131  elevel = DEBUG2;
132 
133  /* Set up static variables */
134  vac_strategy = bstrategy;
135 
136  /*
137  * Check for user-requested abort.
138  */
140 
141  /*
142  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
143  * ANALYZEs don't run on it concurrently. (This also locks out a
144  * concurrent VACUUM, which doesn't matter much at the moment but might
145  * matter if we ever try to accumulate stats on dead tuples.) If the rel
146  * has been dropped since we last saw it, we don't need to process it.
147  *
148  * Make sure to generate only logs for ANALYZE in this case.
149  */
150  onerel = vacuum_open_relation(relid, relation, params->options & ~(VACOPT_VACUUM),
151  params->log_min_duration >= 0,
153 
154  /* leave if relation could not be opened or locked */
155  if (!onerel)
156  return;
157 
158  /*
159  * Check if relation needs to be skipped based on ownership. This check
160  * happens also when building the relation list to analyze for a manual
161  * operation, and needs to be done additionally here as ANALYZE could
162  * happen across multiple transactions where relation ownership could have
163  * changed in-between. Make sure to generate only logs for ANALYZE in
164  * this case.
165  */
167  onerel->rd_rel,
168  params->options & VACOPT_ANALYZE))
169  {
171  return;
172  }
173 
174  /*
175  * Silently ignore tables that are temp tables of other backends ---
176  * trying to analyze these is rather pointless, since their contents are
177  * probably not up-to-date on disk. (We don't throw a warning here; it
178  * would just lead to chatter during a database-wide ANALYZE.)
179  */
180  if (RELATION_IS_OTHER_TEMP(onerel))
181  {
183  return;
184  }
185 
186  /*
187  * We can ANALYZE any table except pg_statistic. See update_attstats
188  */
189  if (RelationGetRelid(onerel) == StatisticRelationId)
190  {
192  return;
193  }
194 
195  /*
196  * Check that it's of an analyzable relkind, and set up appropriately.
197  */
198  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
199  onerel->rd_rel->relkind == RELKIND_MATVIEW)
200  {
201  /* Regular table, so we'll use the regular row acquisition function */
202  acquirefunc = acquire_sample_rows;
203  /* Also get regular table's size */
204  relpages = RelationGetNumberOfBlocks(onerel);
205  }
206  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
207  {
208  /*
209  * For a foreign table, call the FDW's hook function to see whether it
210  * supports analysis.
211  */
212  FdwRoutine *fdwroutine;
213  bool ok = false;
214 
215  fdwroutine = GetFdwRoutineForRelation(onerel, false);
216 
217  if (fdwroutine->AnalyzeForeignTable != NULL)
218  ok = fdwroutine->AnalyzeForeignTable(onerel,
219  &acquirefunc,
220  &relpages);
221 
222  if (!ok)
223  {
225  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
226  RelationGetRelationName(onerel))));
228  return;
229  }
230  }
231  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
232  {
233  /*
234  * For partitioned tables, we want to do the recursive ANALYZE below.
235  */
236  }
237  else
238  {
239  /* No need for a WARNING if we already complained during VACUUM */
240  if (!(params->options & VACOPT_VACUUM))
242  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
243  RelationGetRelationName(onerel))));
245  return;
246  }
247 
248  /*
249  * OK, let's do it. First let other backends know I'm in ANALYZE.
250  */
251  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
253  LWLockRelease(ProcArrayLock);
254 
255  /*
256  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
257  * tables, which don't contain any rows.
258  */
259  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
260  do_analyze_rel(onerel, params, va_cols, acquirefunc,
261  relpages, false, in_outer_xact, elevel);
262 
263  /*
264  * If there are child tables, do recursive ANALYZE.
265  */
266  if (onerel->rd_rel->relhassubclass)
267  do_analyze_rel(onerel, params, va_cols, acquirefunc, relpages,
268  true, in_outer_xact, elevel);
269 
270  /*
271  * Close source relation now, but keep lock so that no one deletes it
272  * before we commit. (If someone did, they'd fail to clean up the entries
273  * we made in pg_statistic. Also, releasing the lock before commit would
274  * expose us to concurrent-update failures in update_attstats.)
275  */
276  relation_close(onerel, NoLock);
277 
278  /*
279  * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
280  * because the vacuum flag is cleared by the end-of-xact code.
281  */
282  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
284  LWLockRelease(ProcArrayLock);
285 }
static void do_analyze_rel(Relation onerel, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:295
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:234
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:84
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:83
int32 relpages
Definition: pg_class.h:60
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:233
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, int options)
Definition: vacuum.c:480
#define DEBUG2
Definition: elog.h:24
#define NoLock
Definition: lockdefs.h:34
Relation vacuum_open_relation(Oid relid, RangeVar *relation, int options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:554
#define RelationGetRelationName(relation)
Definition: rel.h:457
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
static int elevel
Definition: vacuumlazy.c:143
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:198
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:553
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int log_min_duration
Definition: vacuum.h:180
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:142
int errmsg(const char *fmt,...)
Definition: elog.c:822
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
int options
Definition: vacuum.h:172
#define PROC_IN_ANALYZE
Definition: proc.h:55
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define RelationGetRelid(relation)
Definition: rel.h:423
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:1022

◆ anl_get_next_S()

double anl_get_next_S ( double  t,
int  n,
double *  stateptr 
)

Definition at line 284 of file sampling.c.

285 {
286  double result;
287 
288  oldrs.W = *stateptr;
289  result = reservoir_get_next_S(&oldrs, t, n);
290  *stateptr = oldrs.W;
291  return result;
292 }
static ReservoirStateData oldrs
Definition: sampling.c:259
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142

◆ anl_init_selection_state()

double anl_init_selection_state ( int  n)

Definition at line 273 of file sampling.c.

274 {
275  /* initialize if first time through */
276  if (oldrs.randstate[0] == 0)
278 
279  /* Initial value of W (for use when Algorithm Z is first applied) */
280  return exp(-log(sampler_random_fract(oldrs.randstate)) / n);
281 }
void sampler_random_init_state(long seed, SamplerRandomState randstate)
Definition: sampling.c:229
long random(void)
Definition: random.c:22
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
static ReservoirStateData oldrs
Definition: sampling.c:259
SamplerRandomState randstate
Definition: sampling.h:50

◆ anl_random_fract()

double anl_random_fract ( void  )

Definition at line 262 of file sampling.c.

263 {
264  /* initialize if first time through */
265  if (oldrs.randstate[0] == 0)
267 
268  /* and compute a random fraction */
270 }
void sampler_random_init_state(long seed, SamplerRandomState randstate)
Definition: sampling.c:229
long random(void)
Definition: random.c:22
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
static ReservoirStateData oldrs
Definition: sampling.c:259
SamplerRandomState randstate
Definition: sampling.h:50

◆ ExecVacuum()

void ExecVacuum ( ParseState pstate,
VacuumStmt vacstmt,
bool  isTopLevel 
)

Definition at line 88 of file vacuum.c.

References analyze(), Assert, defGetBoolean(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, get_vacopt_ternary_value(), VacuumParams::index_cleanup, VacuumStmt::is_vacuumcmd, VacuumParams::is_wraparound, lfirst, lfirst_node, DefElem::location, VacuumParams::log_min_duration, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, NIL, VacuumParams::options, VacuumStmt::options, parser_errposition(), VacuumStmt::rels, VacuumParams::truncate, VacuumRelation::va_cols, VACOPT_ANALYZE, VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_FREEZE, VACOPT_FULL, VACOPT_SKIP_LOCKED, VACOPT_SKIPTOAST, VACOPT_TERNARY_DEFAULT, VACOPT_VACUUM, VACOPT_VERBOSE, vacuum(), and verbose.

Referenced by standard_ProcessUtility().

89 {
90  VacuumParams params;
91  bool verbose = false;
92  bool skip_locked = false;
93  bool analyze = false;
94  bool freeze = false;
95  bool full = false;
96  bool disable_page_skipping = false;
97  ListCell *lc;
98 
99  /* Set default value */
102 
103  /* Parse options list */
104  foreach(lc, vacstmt->options)
105  {
106  DefElem *opt = (DefElem *) lfirst(lc);
107 
108  /* Parse common options for VACUUM and ANALYZE */
109  if (strcmp(opt->defname, "verbose") == 0)
110  verbose = defGetBoolean(opt);
111  else if (strcmp(opt->defname, "skip_locked") == 0)
112  skip_locked = defGetBoolean(opt);
113  else if (!vacstmt->is_vacuumcmd)
114  ereport(ERROR,
115  (errcode(ERRCODE_SYNTAX_ERROR),
116  errmsg("unrecognized ANALYZE option \"%s\"", opt->defname),
117  parser_errposition(pstate, opt->location)));
118 
119  /* Parse options available on VACUUM */
120  else if (strcmp(opt->defname, "analyze") == 0)
121  analyze = defGetBoolean(opt);
122  else if (strcmp(opt->defname, "freeze") == 0)
123  freeze = defGetBoolean(opt);
124  else if (strcmp(opt->defname, "full") == 0)
125  full = defGetBoolean(opt);
126  else if (strcmp(opt->defname, "disable_page_skipping") == 0)
127  disable_page_skipping = defGetBoolean(opt);
128  else if (strcmp(opt->defname, "index_cleanup") == 0)
130  else if (strcmp(opt->defname, "truncate") == 0)
131  params.truncate = get_vacopt_ternary_value(opt);
132  else
133  ereport(ERROR,
134  (errcode(ERRCODE_SYNTAX_ERROR),
135  errmsg("unrecognized VACUUM option \"%s\"", opt->defname),
136  parser_errposition(pstate, opt->location)));
137  }
138 
139  /* Set vacuum options */
140  params.options =
141  (vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE) |
142  (verbose ? VACOPT_VERBOSE : 0) |
143  (skip_locked ? VACOPT_SKIP_LOCKED : 0) |
144  (analyze ? VACOPT_ANALYZE : 0) |
145  (freeze ? VACOPT_FREEZE : 0) |
146  (full ? VACOPT_FULL : 0) |
147  (disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0);
148 
149  /* sanity checks on options */
150  Assert(params.options & (VACOPT_VACUUM | VACOPT_ANALYZE));
151  Assert((params.options & VACOPT_VACUUM) ||
152  !(params.options & (VACOPT_FULL | VACOPT_FREEZE)));
153  Assert(!(params.options & VACOPT_SKIPTOAST));
154 
155  /*
156  * Make sure VACOPT_ANALYZE is specified if any column lists are present.
157  */
158  if (!(params.options & VACOPT_ANALYZE))
159  {
160  ListCell *lc;
161 
162  foreach(lc, vacstmt->rels)
163  {
165 
166  if (vrel->va_cols != NIL)
167  ereport(ERROR,
168  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
169  errmsg("ANALYZE option must be specified when a column list is provided")));
170  }
171  }
172 
173  /*
174  * All freeze ages are zero if the FREEZE option is given; otherwise pass
175  * them as -1 which means to use the default values.
176  */
177  if (params.options & VACOPT_FREEZE)
178  {
179  params.freeze_min_age = 0;
180  params.freeze_table_age = 0;
181  params.multixact_freeze_min_age = 0;
182  params.multixact_freeze_table_age = 0;
183  }
184  else
185  {
186  params.freeze_min_age = -1;
187  params.freeze_table_age = -1;
188  params.multixact_freeze_min_age = -1;
189  params.multixact_freeze_table_age = -1;
190  }
191 
192  /* user-invoked vacuum is never "for wraparound" */
193  params.is_wraparound = false;
194 
195  /* user-invoked vacuum never uses this parameter */
196  params.log_min_duration = -1;
197 
198  /* Now go through the common routine */
199  vacuum(vacstmt->rels, &params, NULL, isTopLevel);
200 }
#define NIL
Definition: pg_list.h:65
int multixact_freeze_table_age
Definition: vacuum.h:177
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:222
bool is_vacuumcmd
Definition: parsenodes.h:3191
int errcode(int sqlerrcode)
Definition: elog.c:608
int freeze_table_age
Definition: vacuum.h:174
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:43
int freeze_min_age
Definition: vacuum.h:173
bool is_wraparound
Definition: vacuum.h:179
#define lfirst_node(type, lc)
Definition: pg_list.h:193
int location
Definition: parsenodes.h:733
#define ereport(elevel, rest)
Definition: elog.h:141
VacOptTernaryValue index_cleanup
Definition: vacuum.h:183
static int verbose
Definition: pg_basebackup.c:90
VacOptTernaryValue truncate
Definition: vacuum.h:185
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int log_min_duration
Definition: vacuum.h:180
int errmsg(const char *fmt,...)
Definition: elog.c:822
List * options
Definition: parsenodes.h:3189
int options
Definition: vacuum.h:172
char * defname
Definition: parsenodes.h:730
int multixact_freeze_min_age
Definition: vacuum.h:175
static long analyze(struct nfa *nfa)
Definition: regc_nfa.c:2816
List * rels
Definition: parsenodes.h:3190
static VacOptTernaryValue get_vacopt_ternary_value(DefElem *def)
Definition: vacuum.c:1976

◆ std_typanalyze()

bool std_typanalyze ( VacAttrStats stats)

Definition at line 1660 of file analyze.c.

References VacAttrStats::attr, VacAttrStats::attrtypid, compute_distinct_stats(), compute_scalar_stats(), VacAttrStats::compute_stats, compute_trivial_stats(), default_statistics_target, StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, get_opcode(), get_sort_group_operators(), InvalidOid, StdAnalyzeData::ltopr, VacAttrStats::minrows, OidIsValid, and palloc().

Referenced by array_typanalyze(), and examine_attribute().

1661 {
1662  Form_pg_attribute attr = stats->attr;
1663  Oid ltopr;
1664  Oid eqopr;
1665  StdAnalyzeData *mystats;
1666 
1667  /* If the attstattarget column is negative, use the default value */
1668  /* NB: it is okay to scribble on stats->attr since it's a copy */
1669  if (attr->attstattarget < 0)
1670  attr->attstattarget = default_statistics_target;
1671 
1672  /* Look for default "<" and "=" operators for column's type */
1674  false, false, false,
1675  &ltopr, &eqopr, NULL,
1676  NULL);
1677 
1678  /* Save the operator info for compute_stats routines */
1679  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1680  mystats->eqopr = eqopr;
1681  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1682  mystats->ltopr = ltopr;
1683  stats->extra_data = mystats;
1684 
1685  /*
1686  * Determine which standard statistics algorithm to use
1687  */
1688  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1689  {
1690  /* Seems to be a scalar datatype */
1692  /*--------------------
1693  * The following choice of minrows is based on the paper
1694  * "Random sampling for histogram construction: how much is enough?"
1695  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1696  * Proceedings of ACM SIGMOD International Conference on Management
1697  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1698  * says that for table size n, histogram size k, maximum relative
1699  * error in bin size f, and error probability gamma, the minimum
1700  * random sample size is
1701  * r = 4 * k * ln(2*n/gamma) / f^2
1702  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1703  * r = 305.82 * k
1704  * Note that because of the log function, the dependence on n is
1705  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1706  * bin size error with probability 0.99. So there's no real need to
1707  * scale for n, which is a good thing because we don't necessarily
1708  * know it at this point.
1709  *--------------------
1710  */
1711  stats->minrows = 300 * attr->attstattarget;
1712  }
1713  else if (OidIsValid(eqopr))
1714  {
1715  /* We can still recognize distinct values */
1717  /* Might as well use the same minrows as above */
1718  stats->minrows = 300 * attr->attstattarget;
1719  }
1720  else
1721  {
1722  /* Can't do much but the trivial stuff */
1724  /* Might as well use the same minrows as above */
1725  stats->minrows = 300 * attr->attstattarget;
1726  }
1727 
1728  return true;
1729 }
int minrows
Definition: vacuum.h:97
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2173
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:639
Form_pg_attribute attr
Definition: vacuum.h:85
Oid attrtypid
Definition: vacuum.h:86
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1830
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1092
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1740
void * palloc(Size size)
Definition: mcxt.c:949
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:96
void * extra_data
Definition: vacuum.h:98
int default_statistics_target
Definition: analyze.c:80

◆ vac_close_indexes()

void vac_close_indexes ( int  nindexes,
Relation Irel,
LOCKMODE  lockmode 
)

Definition at line 1921 of file vacuum.c.

References index_close(), and pfree().

Referenced by do_analyze_rel(), and heap_vacuum_rel().

1922 {
1923  if (Irel == NULL)
1924  return;
1925 
1926  while (nindexes--)
1927  {
1928  Relation ind = Irel[nindexes];
1929 
1930  index_close(ind, lockmode);
1931  }
1932  pfree(Irel);
1933 }
void pfree(void *pointer)
Definition: mcxt.c:1056
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152

◆ vac_estimate_reltuples()

double vac_estimate_reltuples ( Relation  relation,
BlockNumber  total_pages,
BlockNumber  scanned_pages,
double  scanned_tuples 
)

Definition at line 1068 of file vacuum.c.

References RelationData::rd_rel.

Referenced by lazy_scan_heap(), and statapprox_heap().

1072 {
1073  BlockNumber old_rel_pages = relation->rd_rel->relpages;
1074  double old_rel_tuples = relation->rd_rel->reltuples;
1075  double old_density;
1076  double unscanned_pages;
1077  double total_tuples;
1078 
1079  /* If we did scan the whole table, just use the count as-is */
1080  if (scanned_pages >= total_pages)
1081  return scanned_tuples;
1082 
1083  /*
1084  * If scanned_pages is zero but total_pages isn't, keep the existing value
1085  * of reltuples. (Note: callers should avoid updating the pg_class
1086  * statistics in this situation, since no new information has been
1087  * provided.)
1088  */
1089  if (scanned_pages == 0)
1090  return old_rel_tuples;
1091 
1092  /*
1093  * If old value of relpages is zero, old density is indeterminate; we
1094  * can't do much except scale up scanned_tuples to match total_pages.
1095  */
1096  if (old_rel_pages == 0)
1097  return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
1098 
1099  /*
1100  * Okay, we've covered the corner cases. The normal calculation is to
1101  * convert the old measurement to a density (tuples per page), then
1102  * estimate the number of tuples in the unscanned pages using that figure,
1103  * and finally add on the number of tuples in the scanned pages.
1104  */
1105  old_density = old_rel_tuples / old_rel_pages;
1106  unscanned_pages = (double) total_pages - (double) scanned_pages;
1107  total_tuples = old_density * unscanned_pages + scanned_tuples;
1108  return floor(total_tuples + 0.5);
1109 }
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:83

◆ vac_open_indexes()

void vac_open_indexes ( Relation  relation,
LOCKMODE  lockmode,
int *  nindexes,
Relation **  Irel 
)

Definition at line 1878 of file vacuum.c.

References Assert, i, index_close(), index_open(), lfirst_oid, list_free(), list_length(), NoLock, palloc(), RelationData::rd_index, and RelationGetIndexList().

Referenced by do_analyze_rel(), and heap_vacuum_rel().

1880 {
1881  List *indexoidlist;
1882  ListCell *indexoidscan;
1883  int i;
1884 
1885  Assert(lockmode != NoLock);
1886 
1887  indexoidlist = RelationGetIndexList(relation);
1888 
1889  /* allocate enough memory for all indexes */
1890  i = list_length(indexoidlist);
1891 
1892  if (i > 0)
1893  *Irel = (Relation *) palloc(i * sizeof(Relation));
1894  else
1895  *Irel = NULL;
1896 
1897  /* collect just the ready indexes */
1898  i = 0;
1899  foreach(indexoidscan, indexoidlist)
1900  {
1901  Oid indexoid = lfirst_oid(indexoidscan);
1902  Relation indrel;
1903 
1904  indrel = index_open(indexoid, lockmode);
1905  if (indrel->rd_index->indisready)
1906  (*Irel)[i++] = indrel;
1907  else
1908  index_close(indrel, lockmode);
1909  }
1910 
1911  *nindexes = i;
1912 
1913  list_free(indexoidlist);
1914 }
unsigned int Oid
Definition: postgres_ext.h:31
Form_pg_index rd_index
Definition: rel.h:143
#define NoLock
Definition: lockdefs.h:34
#define Assert(condition)
Definition: c.h:733
static int list_length(const List *l)
Definition: pg_list.h:169
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4347
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
void * palloc(Size size)
Definition: mcxt.c:949
void list_free(List *list)
Definition: list.c:1377
int i
Definition: pg_list.h:50
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ vac_update_datfrozenxid()

void vac_update_datfrozenxid ( void  )

Definition at line 1280 of file vacuum.c.

References AccessShareLock, Assert, DATABASEOID, elog, ERROR, ForceTransactionIdLimitUpdate(), GetOldestMultiXactId(), GetOldestXmin(), GETSTRUCT, heap_freetuple(), heap_inplace_update(), HeapTupleIsValid, InvalidOid, MultiXactIdIsValid, MultiXactIdPrecedes(), MyDatabaseId, ObjectIdGetDatum, PROCARRAY_FLAGS_VACUUM, ReadNewTransactionId(), ReadNextMultiXactId(), RowExclusiveLock, SearchSysCacheCopy1, systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), and vac_truncate_clog().

Referenced by do_autovacuum(), and vacuum().

1281 {
1282  HeapTuple tuple;
1283  Form_pg_database dbform;
1284  Relation relation;
1285  SysScanDesc scan;
1286  HeapTuple classTup;
1287  TransactionId newFrozenXid;
1288  MultiXactId newMinMulti;
1289  TransactionId lastSaneFrozenXid;
1290  MultiXactId lastSaneMinMulti;
1291  bool bogus = false;
1292  bool dirty = false;
1293 
1294  /*
1295  * Initialize the "min" calculation with GetOldestXmin, which is a
1296  * reasonable approximation to the minimum relfrozenxid for not-yet-
1297  * committed pg_class entries for new tables; see AddNewRelationTuple().
1298  * So we cannot produce a wrong minimum by starting with this.
1299  */
1300  newFrozenXid = GetOldestXmin(NULL, PROCARRAY_FLAGS_VACUUM);
1301 
1302  /*
1303  * Similarly, initialize the MultiXact "min" with the value that would be
1304  * used on pg_class for new tables. See AddNewRelationTuple().
1305  */
1306  newMinMulti = GetOldestMultiXactId();
1307 
1308  /*
1309  * Identify the latest relfrozenxid and relminmxid values that we could
1310  * validly see during the scan. These are conservative values, but it's
1311  * not really worth trying to be more exact.
1312  */
1313  lastSaneFrozenXid = ReadNewTransactionId();
1314  lastSaneMinMulti = ReadNextMultiXactId();
1315 
1316  /*
1317  * We must seqscan pg_class to find the minimum Xid, because there is no
1318  * index that can help us here.
1319  */
1320  relation = table_open(RelationRelationId, AccessShareLock);
1321 
1322  scan = systable_beginscan(relation, InvalidOid, false,
1323  NULL, 0, NULL);
1324 
1325  while ((classTup = systable_getnext(scan)) != NULL)
1326  {
1327  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
1328 
1329  /*
1330  * Only consider relations able to hold unfrozen XIDs (anything else
1331  * should have InvalidTransactionId in relfrozenxid anyway).
1332  */
1333  if (classForm->relkind != RELKIND_RELATION &&
1334  classForm->relkind != RELKIND_MATVIEW &&
1335  classForm->relkind != RELKIND_TOASTVALUE)
1336  {
1337  Assert(!TransactionIdIsValid(classForm->relfrozenxid));
1338  Assert(!MultiXactIdIsValid(classForm->relminmxid));
1339  continue;
1340  }
1341 
1342  /*
1343  * Some table AMs might not need per-relation xid / multixid horizons.
1344  * It therefore seems reasonable to allow relfrozenxid and relminmxid
1345  * to not be set (i.e. set to their respective Invalid*Id)
1346  * independently. Thus validate and compute horizon for each only if
1347  * set.
1348  *
1349  * If things are working properly, no relation should have a
1350  * relfrozenxid or relminmxid that is "in the future". However, such
1351  * cases have been known to arise due to bugs in pg_upgrade. If we
1352  * see any entries that are "in the future", chicken out and don't do
1353  * anything. This ensures we won't truncate clog & multixact SLRUs
1354  * before those relations have been scanned and cleaned up.
1355  */
1356 
1357  if (TransactionIdIsValid(classForm->relfrozenxid))
1358  {
1359  Assert(TransactionIdIsNormal(classForm->relfrozenxid));
1360 
1361  /* check for values in the future */
1362  if (TransactionIdPrecedes(lastSaneFrozenXid, classForm->relfrozenxid))
1363  {
1364  bogus = true;
1365  break;
1366  }
1367 
1368  /* determine new horizon */
1369  if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
1370  newFrozenXid = classForm->relfrozenxid;
1371  }
1372 
1373  if (MultiXactIdIsValid(classForm->relminmxid))
1374  {
1375  /* check for values in the future */
1376  if (MultiXactIdPrecedes(lastSaneMinMulti, classForm->relminmxid))
1377  {
1378  bogus = true;
1379  break;
1380  }
1381 
1382  /* determine new horizon */
1383  if (MultiXactIdPrecedes(classForm->relminmxid, newMinMulti))
1384  newMinMulti = classForm->relminmxid;
1385  }
1386  }
1387 
1388  /* we're done with pg_class */
1389  systable_endscan(scan);
1390  table_close(relation, AccessShareLock);
1391 
1392  /* chicken out if bogus data found */
1393  if (bogus)
1394  return;
1395 
1396  Assert(TransactionIdIsNormal(newFrozenXid));
1397  Assert(MultiXactIdIsValid(newMinMulti));
1398 
1399  /* Now fetch the pg_database tuple we need to update. */
1400  relation = table_open(DatabaseRelationId, RowExclusiveLock);
1401 
1402  /* Fetch a copy of the tuple to scribble on */
1404  if (!HeapTupleIsValid(tuple))
1405  elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
1406  dbform = (Form_pg_database) GETSTRUCT(tuple);
1407 
1408  /*
1409  * As in vac_update_relstats(), we ordinarily don't want to let
1410  * datfrozenxid go backward; but if it's "in the future" then it must be
1411  * corrupt and it seems best to overwrite it.
1412  */
1413  if (dbform->datfrozenxid != newFrozenXid &&
1414  (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
1415  TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
1416  {
1417  dbform->datfrozenxid = newFrozenXid;
1418  dirty = true;
1419  }
1420  else
1421  newFrozenXid = dbform->datfrozenxid;
1422 
1423  /* Ditto for datminmxid */
1424  if (dbform->datminmxid != newMinMulti &&
1425  (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
1426  MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
1427  {
1428  dbform->datminmxid = newMinMulti;
1429  dirty = true;
1430  }
1431  else
1432  newMinMulti = dbform->datminmxid;
1433 
1434  if (dirty)
1435  heap_inplace_update(relation, tuple);
1436 
1437  heap_freetuple(tuple);
1438  table_close(relation, RowExclusiveLock);
1439 
1440  /*
1441  * If we were able to advance datfrozenxid or datminmxid, see if we can
1442  * truncate pg_xact and/or pg_multixact. Also do it if the shared
1443  * XID-wrap-limit info is stale, since this action will update that too.
1444  */
1445  if (dirty || ForceTransactionIdLimitUpdate())
1446  vac_truncate_clog(newFrozenXid, newMinMulti,
1447  lastSaneFrozenXid, lastSaneMinMulti);
1448 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
uint32 TransactionId
Definition: c.h:508
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
#define AccessShareLock
Definition: lockdefs.h:36
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:52
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
bool ForceTransactionIdLimitUpdate(void)
Definition: varsup.c:471
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
#define MultiXactIdIsValid(multi)
Definition: multixact.h:27
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2493
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1306
TransactionId MultiXactId
Definition: c.h:518
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:733
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3142
static void vac_truncate_clog(TransactionId frozenXID, MultiXactId minMulti, TransactionId lastSaneFrozenXid, MultiXactId lastSaneMinMulti)
Definition: vacuum.c:1469
static TransactionId ReadNewTransactionId(void)
Definition: transam.h:244
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5707
#define elog(elevel,...)
Definition: elog.h:228
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

◆ vac_update_relstats()

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 at line 1153 of file vacuum.c.

References elog, ERROR, GETSTRUCT, heap_inplace_update(), HeapTupleIsValid, MultiXactIdIsValid, MultiXactIdPrecedes(), ObjectIdGetDatum, RelationData::rd_rules, ReadNewTransactionId(), ReadNextMultiXactId(), RelationGetRelid, RELOID, RowExclusiveLock, SearchSysCacheCopy1, table_close(), table_open(), TransactionIdIsNormal, TransactionIdPrecedes(), and RelationData::trigdesc.

Referenced by do_analyze_rel(), heap_vacuum_rel(), and lazy_cleanup_index().

1159 {
1160  Oid relid = RelationGetRelid(relation);
1161  Relation rd;
1162  HeapTuple ctup;
1163  Form_pg_class pgcform;
1164  bool dirty;
1165 
1166  rd = table_open(RelationRelationId, RowExclusiveLock);
1167 
1168  /* Fetch a copy of the tuple to scribble on */
1170  if (!HeapTupleIsValid(ctup))
1171  elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
1172  relid);
1173  pgcform = (Form_pg_class) GETSTRUCT(ctup);
1174 
1175  /* Apply statistical updates, if any, to copied tuple */
1176 
1177  dirty = false;
1178  if (pgcform->relpages != (int32) num_pages)
1179  {
1180  pgcform->relpages = (int32) num_pages;
1181  dirty = true;
1182  }
1183  if (pgcform->reltuples != (float4) num_tuples)
1184  {
1185  pgcform->reltuples = (float4) num_tuples;
1186  dirty = true;
1187  }
1188  if (pgcform->relallvisible != (int32) num_all_visible_pages)
1189  {
1190  pgcform->relallvisible = (int32) num_all_visible_pages;
1191  dirty = true;
1192  }
1193 
1194  /* Apply DDL updates, but not inside an outer transaction (see above) */
1195 
1196  if (!in_outer_xact)
1197  {
1198  /*
1199  * If we didn't find any indexes, reset relhasindex.
1200  */
1201  if (pgcform->relhasindex && !hasindex)
1202  {
1203  pgcform->relhasindex = false;
1204  dirty = true;
1205  }
1206 
1207  /* We also clear relhasrules and relhastriggers if needed */
1208  if (pgcform->relhasrules && relation->rd_rules == NULL)
1209  {
1210  pgcform->relhasrules = false;
1211  dirty = true;
1212  }
1213  if (pgcform->relhastriggers && relation->trigdesc == NULL)
1214  {
1215  pgcform->relhastriggers = false;
1216  dirty = true;
1217  }
1218  }
1219 
1220  /*
1221  * Update relfrozenxid, unless caller passed InvalidTransactionId
1222  * indicating it has no new data.
1223  *
1224  * Ordinarily, we don't let relfrozenxid go backwards: if things are
1225  * working correctly, the only way the new frozenxid could be older would
1226  * be if a previous VACUUM was done with a tighter freeze_min_age, in
1227  * which case we don't want to forget the work it already did. However,
1228  * if the stored relfrozenxid is "in the future", then it must be corrupt
1229  * and it seems best to overwrite it with the cutoff we used this time.
1230  * This should match vac_update_datfrozenxid() concerning what we consider
1231  * to be "in the future".
1232  */
1233  if (TransactionIdIsNormal(frozenxid) &&
1234  pgcform->relfrozenxid != frozenxid &&
1235  (TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid) ||
1237  pgcform->relfrozenxid)))
1238  {
1239  pgcform->relfrozenxid = frozenxid;
1240  dirty = true;
1241  }
1242 
1243  /* Similarly for relminmxid */
1244  if (MultiXactIdIsValid(minmulti) &&
1245  pgcform->relminmxid != minmulti &&
1246  (MultiXactIdPrecedes(pgcform->relminmxid, minmulti) ||
1247  MultiXactIdPrecedes(ReadNextMultiXactId(), pgcform->relminmxid)))
1248  {
1249  pgcform->relminmxid = minmulti;
1250  dirty = true;
1251  }
1252 
1253  /* If anything changed, write out the tuple. */
1254  if (dirty)
1255  heap_inplace_update(rd, ctup);
1256 
1258 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:347
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:89
#define RowExclusiveLock
Definition: lockdefs.h:38
#define MultiXactIdIsValid(multi)
Definition: multixact.h:27
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
float float4
Definition: c.h:491
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
RuleLock * rd_rules
Definition: rel.h:87
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3142
static TransactionId ReadNewTransactionId(void)
Definition: transam.h:244
FormData_pg_class * Form_pg_class
Definition: pg_class.h:150
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5707
#define elog(elevel,...)
Definition: elog.h:228
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:423
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

◆ vacuum()

void vacuum ( List relations,
VacuumParams params,
BufferAccessStrategy  bstrategy,
bool  isTopLevel 
)

Definition at line 222 of file vacuum.c.

References ActiveSnapshotSet(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_rel(), Assert, BAS_VACUUM, CommandCounterIncrement(), CommitTransactionCommand(), cur, ereport, errcode(), errmsg(), ERROR, expand_vacuum_rel(), get_all_vacuum_rels(), GetAccessStrategy(), GetTransactionSnapshot(), IsAutoVacuumWorkerProcess(), IsInTransactionBlock(), lfirst_node, list_concat(), list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), NIL, VacuumRelation::oid, VacuumParams::options, PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_vacuum_stat(), PopActiveSnapshot(), PortalContext, PreventInTransactionBlock(), PushActiveSnapshot(), VacuumRelation::relation, StartTransactionCommand(), VacuumRelation::va_cols, vac_update_datfrozenxid(), VACOPT_ANALYZE, VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_FULL, VACOPT_VACUUM, vacuum_rel(), VacuumCostActive, VacuumCostBalance, VacuumCostDelay, VacuumPageDirty, VacuumPageHit, and VacuumPageMiss.

Referenced by autovacuum_do_vac_analyze(), and ExecVacuum().

224 {
225  static bool in_vacuum = false;
226 
227  const char *stmttype;
228  volatile bool in_outer_xact,
229  use_own_xacts;
230 
231  Assert(params != NULL);
232 
233  stmttype = (params->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
234 
235  /*
236  * We cannot run VACUUM inside a user transaction block; if we were inside
237  * a transaction, then our commit- and start-transaction-command calls
238  * would not have the intended effect! There are numerous other subtle
239  * dependencies on this, too.
240  *
241  * ANALYZE (without VACUUM) can run either way.
242  */
243  if (params->options & VACOPT_VACUUM)
244  {
245  PreventInTransactionBlock(isTopLevel, stmttype);
246  in_outer_xact = false;
247  }
248  else
249  in_outer_xact = IsInTransactionBlock(isTopLevel);
250 
251  /*
252  * Due to static variables vac_context, anl_context and vac_strategy,
253  * vacuum() is not reentrant. This matters when VACUUM FULL or ANALYZE
254  * calls a hostile index expression that itself calls ANALYZE.
255  */
256  if (in_vacuum)
257  ereport(ERROR,
258  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
259  errmsg("%s cannot be executed from VACUUM or ANALYZE",
260  stmttype)));
261 
262  /*
263  * Sanity check DISABLE_PAGE_SKIPPING option.
264  */
265  if ((params->options & VACOPT_FULL) != 0 &&
266  (params->options & VACOPT_DISABLE_PAGE_SKIPPING) != 0)
267  ereport(ERROR,
268  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
269  errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL")));
270 
271  /*
272  * Send info about dead objects to the statistics collector, unless we are
273  * in autovacuum --- autovacuum.c does this for itself.
274  */
275  if ((params->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
277 
278  /*
279  * Create special memory context for cross-transaction storage.
280  *
281  * Since it is a child of PortalContext, it will go away eventually even
282  * if we suffer an error; there's no need for special abort cleanup logic.
283  */
285  "Vacuum",
287 
288  /*
289  * If caller didn't give us a buffer strategy object, make one in the
290  * cross-transaction memory context.
291  */
292  if (bstrategy == NULL)
293  {
295 
296  bstrategy = GetAccessStrategy(BAS_VACUUM);
297  MemoryContextSwitchTo(old_context);
298  }
299  vac_strategy = bstrategy;
300 
301  /*
302  * Build list of relation(s) to process, putting any new data in
303  * vac_context for safekeeping.
304  */
305  if (relations != NIL)
306  {
307  List *newrels = NIL;
308  ListCell *lc;
309 
310  foreach(lc, relations)
311  {
313  List *sublist;
314  MemoryContext old_context;
315 
316  sublist = expand_vacuum_rel(vrel, params->options);
317  old_context = MemoryContextSwitchTo(vac_context);
318  newrels = list_concat(newrels, sublist);
319  MemoryContextSwitchTo(old_context);
320  }
321  relations = newrels;
322  }
323  else
324  relations = get_all_vacuum_rels(params->options);
325 
326  /*
327  * Decide whether we need to start/commit our own transactions.
328  *
329  * For VACUUM (with or without ANALYZE): always do so, so that we can
330  * release locks as soon as possible. (We could possibly use the outer
331  * transaction for a one-table VACUUM, but handling TOAST tables would be
332  * problematic.)
333  *
334  * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
335  * start/commit our own transactions. Also, there's no need to do so if
336  * only processing one relation. For multiple relations when not within a
337  * transaction block, and also in an autovacuum worker, use own
338  * transactions so we can release locks sooner.
339  */
340  if (params->options & VACOPT_VACUUM)
341  use_own_xacts = true;
342  else
343  {
344  Assert(params->options & VACOPT_ANALYZE);
346  use_own_xacts = true;
347  else if (in_outer_xact)
348  use_own_xacts = false;
349  else if (list_length(relations) > 1)
350  use_own_xacts = true;
351  else
352  use_own_xacts = false;
353  }
354 
355  /*
356  * vacuum_rel expects to be entered with no transaction active; it will
357  * start and commit its own transaction. But we are called by an SQL
358  * command, and so we are executing inside a transaction already. We
359  * commit the transaction started in PostgresMain() here, and start
360  * another one before exiting to match the commit waiting for us back in
361  * PostgresMain().
362  */
363  if (use_own_xacts)
364  {
365  Assert(!in_outer_xact);
366 
367  /* ActiveSnapshot is not set by autovacuum */
368  if (ActiveSnapshotSet())
370 
371  /* matches the StartTransaction in PostgresMain() */
373  }
374 
375  /* Turn vacuum cost accounting on or off, and set/clear in_vacuum */
376  PG_TRY();
377  {
378  ListCell *cur;
379 
380  in_vacuum = true;
382  VacuumCostBalance = 0;
383  VacuumPageHit = 0;
384  VacuumPageMiss = 0;
385  VacuumPageDirty = 0;
386 
387  /*
388  * Loop to process each selected relation.
389  */
390  foreach(cur, relations)
391  {
393 
394  if (params->options & VACOPT_VACUUM)
395  {
396  if (!vacuum_rel(vrel->oid, vrel->relation, params))
397  continue;
398  }
399 
400  if (params->options & VACOPT_ANALYZE)
401  {
402  /*
403  * If using separate xacts, start one for analyze. Otherwise,
404  * we can use the outer transaction.
405  */
406  if (use_own_xacts)
407  {
409  /* functions in indexes may want a snapshot set */
411  }
412 
413  analyze_rel(vrel->oid, vrel->relation, params,
414  vrel->va_cols, in_outer_xact, vac_strategy);
415 
416  if (use_own_xacts)
417  {
420  }
421  else
422  {
423  /*
424  * If we're not using separate xacts, better separate the
425  * ANALYZE actions with CCIs. This avoids trouble if user
426  * says "ANALYZE t, t".
427  */
429  }
430  }
431  }
432  }
433  PG_FINALLY();
434  {
435  in_vacuum = false;
436  VacuumCostActive = false;
437  }
438  PG_END_TRY();
439 
440  /*
441  * Finish up processing.
442  */
443  if (use_own_xacts)
444  {
445  /* here, we are not in a transaction */
446 
447  /*
448  * This matches the CommitTransaction waiting for us in
449  * PostgresMain().
450  */
452  }
453 
454  if ((params->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
455  {
456  /*
457  * Update pg_database.datfrozenxid, and truncate pg_xact if possible.
458  * (autovacuum.c does this for itself.)
459  */
461  }
462 
463  /*
464  * Clean up working storage --- note we must do this after
465  * StartTransactionCommand, else we might be trying to delete the active
466  * context!
467  */
469  vac_context = NULL;
470 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:542
#define NIL
Definition: pg_list.h:65
void analyze_rel(Oid relid, RangeVar *relation, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
Definition: analyze.c:118
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
int VacuumCostBalance
Definition: globals.c:147
static bool vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params)
Definition: vacuum.c:1615
RangeVar * relation
Definition: parsenodes.h:3204
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1280
int VacuumPageHit
Definition: globals.c:143
void CommitTransactionCommand(void)
Definition: xact.c:2897
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static BufferAccessStrategy vac_strategy
Definition: vacuum.c:68
struct cursor * cur
Definition: ecpg.c:28
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
static List * expand_vacuum_rel(VacuumRelation *vrel, int options)
Definition: vacuum.c:666
MemoryContext PortalContext
Definition: mcxt.c:53
#define ERROR
Definition: elog.h:43
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
static MemoryContext vac_context
Definition: vacuum.c:67
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3330
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:853
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3281
#define ereport(elevel, rest)
Definition: elog.h:141
void pgstat_vacuum_stat(void)
Definition: pgstat.c:1021
bool IsInTransactionBlock(bool isTopLevel)
Definition: xact.c:3444
#define PG_FINALLY()
Definition: elog.h:339
int VacuumPageDirty
Definition: globals.c:145
void CommandCounterIncrement(void)
Definition: xact.c:1005
#define Assert(condition)
Definition: c.h:733
void StartTransactionCommand(void)
Definition: xact.c:2796
static int list_length(const List *l)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:822
double VacuumCostDelay
Definition: globals.c:141
int options
Definition: vacuum.h:172
int VacuumPageMiss
Definition: globals.c:144
#define PG_TRY()
Definition: elog.h:322
Definition: pg_list.h:50
#define PG_END_TRY()
Definition: elog.h:347
bool VacuumCostActive
Definition: globals.c:148
static List * get_all_vacuum_rels(int options)
Definition: vacuum.c:805

◆ vacuum_delay_point()

void vacuum_delay_point ( void  )

Definition at line 1942 of file vacuum.c.

References AutoVacuumUpdateDelay(), CHECK_FOR_INTERRUPTS, InterruptPending, pg_usleep(), VacuumCostActive, VacuumCostBalance, VacuumCostDelay, and VacuumCostLimit.

Referenced by acquire_sample_rows(), blbulkdelete(), blvacuumcleanup(), btvacuumpage(), compute_array_stats(), compute_distinct_stats(), compute_index_stats(), compute_range_stats(), compute_scalar_stats(), compute_trivial_stats(), compute_tsvector_stats(), file_acquire_sample_rows(), ginbulkdelete(), ginInsertCleanup(), ginvacuumcleanup(), gistvacuumpage(), hashbucketcleanup(), lazy_scan_heap(), lazy_vacuum_heap(), spgprocesspending(), and spgvacuumpage().

1943 {
1944  /* Always check for interrupts */
1946 
1947  /* Nap if appropriate */
1950  {
1951  double msec;
1952 
1954  if (msec > VacuumCostDelay * 4)
1955  msec = VacuumCostDelay * 4;
1956 
1957  pg_usleep((long) (msec * 1000));
1958 
1959  VacuumCostBalance = 0;
1960 
1961  /* update balance values for workers */
1963 
1964  /* Might have gotten an interrupt while sleeping */
1966  }
1967 }
int VacuumCostBalance
Definition: globals.c:147
void pg_usleep(long microsec)
Definition: signal.c:53
int VacuumCostLimit
Definition: globals.c:140
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
double VacuumCostDelay
Definition: globals.c:141
void AutoVacuumUpdateDelay(void)
Definition: autovacuum.c:1763
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
bool VacuumCostActive
Definition: globals.c:148

◆ vacuum_is_relation_owner()

bool vacuum_is_relation_owner ( Oid  relid,
Form_pg_class  reltuple,
int  options 
)

Definition at line 480 of file vacuum.c.

References Assert, ereport, errmsg(), GetUserId(), MyDatabaseId, NameStr, pg_class_ownercheck(), pg_database_ownercheck(), relname, VACOPT_ANALYZE, VACOPT_VACUUM, and WARNING.

Referenced by analyze_rel(), expand_vacuum_rel(), get_all_vacuum_rels(), and vacuum_rel().

481 {
482  char *relname;
483 
485 
486  /*
487  * Check permissions.
488  *
489  * We allow the user to vacuum or analyze a table if he is superuser, the
490  * table owner, or the database owner (but in the latter case, only if
491  * it's not a shared relation). pg_class_ownercheck includes the
492  * superuser case.
493  *
494  * Note we choose to treat permissions failure as a WARNING and keep
495  * trying to vacuum or analyze the rest of the DB --- is this appropriate?
496  */
497  if (pg_class_ownercheck(relid, GetUserId()) ||
498  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !reltuple->relisshared))
499  return true;
500 
501  relname = NameStr(reltuple->relname);
502 
503  if ((options & VACOPT_VACUUM) != 0)
504  {
505  if (reltuple->relisshared)
507  (errmsg("skipping \"%s\" --- only superuser can vacuum it",
508  relname)));
509  else if (reltuple->relnamespace == PG_CATALOG_NAMESPACE)
511  (errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
512  relname)));
513  else
515  (errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
516  relname)));
517 
518  /*
519  * For VACUUM ANALYZE, both logs could show up, but just generate
520  * information for VACUUM as that would be the first one to be
521  * processed.
522  */
523  return false;
524  }
525 
526  if ((options & VACOPT_ANALYZE) != 0)
527  {
528  if (reltuple->relisshared)
530  (errmsg("skipping \"%s\" --- only superuser can analyze it",
531  relname)));
532  else if (reltuple->relnamespace == PG_CATALOG_NAMESPACE)
534  (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
535  relname)));
536  else
538  (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
539  relname)));
540  }
541 
542  return false;
543 }
Oid GetUserId(void)
Definition: miscinit.c:380
NameData relname
Definition: pg_class.h:35
#define ereport(elevel, rest)
Definition: elog.h:141
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5172
#define WARNING
Definition: elog.h:40
Oid MyDatabaseId
Definition: globals.c:85
#define Assert(condition)
Definition: c.h:733
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4754
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define NameStr(name)
Definition: c.h:610

◆ vacuum_open_relation()

Relation vacuum_open_relation ( Oid  relid,
RangeVar relation,
int  options,
bool  verbose,
LOCKMODE  lmode 
)

Definition at line 554 of file vacuum.c.

References Assert, ConditionalLockRelationOid(), elevel, ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), IsAutoVacuumWorkerProcess(), LOG, NoLock, RangeVar::relname, try_relation_open(), VACOPT_ANALYZE, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, and WARNING.

Referenced by analyze_rel(), and vacuum_rel().

556 {
557  Relation onerel;
558  bool rel_lock = true;
559  int elevel;
560 
562 
563  /*
564  * Open the relation and get the appropriate lock on it.
565  *
566  * There's a race condition here: the relation may have gone away since
567  * the last time we saw it. If so, we don't need to vacuum or analyze it.
568  *
569  * If we've been asked not to wait for the relation lock, acquire it first
570  * in non-blocking mode, before calling try_relation_open().
571  */
572  if (!(options & VACOPT_SKIP_LOCKED))
573  onerel = try_relation_open(relid, lmode);
574  else if (ConditionalLockRelationOid(relid, lmode))
575  onerel = try_relation_open(relid, NoLock);
576  else
577  {
578  onerel = NULL;
579  rel_lock = false;
580  }
581 
582  /* if relation is opened, leave */
583  if (onerel)
584  return onerel;
585 
586  /*
587  * Relation could not be opened, hence generate if possible a log
588  * informing on the situation.
589  *
590  * If the RangeVar is not defined, we do not have enough information to
591  * provide a meaningful log statement. Chances are that the caller has
592  * intentionally not provided this information so that this logging is
593  * skipped, anyway.
594  */
595  if (relation == NULL)
596  return NULL;
597 
598  /*
599  * Determine the log level.
600  *
601  * For manual VACUUM or ANALYZE, we emit a WARNING to match the log
602  * statements in the permission checks; otherwise, only log if the caller
603  * so requested.
604  */
606  elevel = WARNING;
607  else if (verbose)
608  elevel = LOG;
609  else
610  return NULL;
611 
612  if ((options & VACOPT_VACUUM) != 0)
613  {
614  if (!rel_lock)
615  ereport(elevel,
616  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
617  errmsg("skipping vacuum of \"%s\" --- lock not available",
618  relation->relname)));
619  else
620  ereport(elevel,
622  errmsg("skipping vacuum of \"%s\" --- relation no longer exists",
623  relation->relname)));
624 
625  /*
626  * For VACUUM ANALYZE, both logs could show up, but just generate
627  * information for VACUUM as that would be the first one to be
628  * processed.
629  */
630  return NULL;
631  }
632 
633  if ((options & VACOPT_ANALYZE) != 0)
634  {
635  if (!rel_lock)
636  ereport(elevel,
637  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
638  errmsg("skipping analyze of \"%s\" --- lock not available",
639  relation->relname)));
640  else
641  ereport(elevel,
643  errmsg("skipping analyze of \"%s\" --- relation no longer exists",
644  relation->relname)));
645  }
646 
647  return NULL;
648 }
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:73
int errcode(int sqlerrcode)
Definition: elog.c:608
#define LOG
Definition: elog.h:26
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89
char * relname
Definition: primnodes.h:68
#define NoLock
Definition: lockdefs.h:34
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3281
#define ereport(elevel, rest)
Definition: elog.h:141
static int verbose
Definition: pg_basebackup.c:90
#define WARNING
Definition: elog.h:40
static int elevel
Definition: vacuumlazy.c:143
#define Assert(condition)
Definition: c.h:733
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ vacuum_set_xid_limits()

void vacuum_set_xid_limits ( Relation  rel,
int  freeze_min_age,
int  freeze_table_age,
int  multixact_freeze_min_age,
int  multixact_freeze_table_age,
TransactionId oldestXmin,
TransactionId freezeLimit,
TransactionId xidFullScanLimit,
MultiXactId multiXactCutoff,
MultiXactId mxactFullScanLimit 
)

Definition at line 876 of file vacuum.c.

References Assert, autovacuum_freeze_max_age, ereport, errhint(), errmsg(), FirstMultiXactId, FirstNormalTransactionId, GetOldestMultiXactId(), GetOldestXmin(), Min, MultiXactIdPrecedes(), MultiXactMemberFreezeThreshold(), PROCARRAY_FLAGS_VACUUM, ReadNewTransactionId(), ReadNextMultiXactId(), TransactionIdIsNormal, TransactionIdLimitedForOldSnapshots(), TransactionIdPrecedes(), vacuum_freeze_min_age, vacuum_freeze_table_age, vacuum_multixact_freeze_min_age, vacuum_multixact_freeze_table_age, and WARNING.

Referenced by copy_table_data(), and heap_vacuum_rel().

886 {
887  int freezemin;
888  int mxid_freezemin;
889  int effective_multixact_freeze_max_age;
890  TransactionId limit;
891  TransactionId safeLimit;
892  MultiXactId oldestMxact;
893  MultiXactId mxactLimit;
894  MultiXactId safeMxactLimit;
895 
896  /*
897  * We can always ignore processes running lazy vacuum. This is because we
898  * use these values only for deciding which tuples we must keep in the
899  * tables. Since lazy vacuum doesn't write its XID anywhere, it's safe to
900  * ignore it. In theory it could be problematic to ignore lazy vacuums in
901  * a full vacuum, but keep in mind that only one vacuum process can be
902  * working on a particular table at any time, and that each vacuum is
903  * always an independent transaction.
904  */
905  *oldestXmin =
907 
908  Assert(TransactionIdIsNormal(*oldestXmin));
909 
910  /*
911  * Determine the minimum freeze age to use: as specified by the caller, or
912  * vacuum_freeze_min_age, but in any case not more than half
913  * autovacuum_freeze_max_age, so that autovacuums to prevent XID
914  * wraparound won't occur too frequently.
915  */
916  freezemin = freeze_min_age;
917  if (freezemin < 0)
918  freezemin = vacuum_freeze_min_age;
919  freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
920  Assert(freezemin >= 0);
921 
922  /*
923  * Compute the cutoff XID, being careful not to generate a "permanent" XID
924  */
925  limit = *oldestXmin - freezemin;
926  if (!TransactionIdIsNormal(limit))
927  limit = FirstNormalTransactionId;
928 
929  /*
930  * If oldestXmin is very far back (in practice, more than
931  * autovacuum_freeze_max_age / 2 XIDs old), complain and force a minimum
932  * freeze age of zero.
933  */
935  if (!TransactionIdIsNormal(safeLimit))
936  safeLimit = FirstNormalTransactionId;
937 
938  if (TransactionIdPrecedes(limit, safeLimit))
939  {
941  (errmsg("oldest xmin is far in the past"),
942  errhint("Close open transactions soon to avoid wraparound problems.\n"
943  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
944  limit = *oldestXmin;
945  }
946 
947  *freezeLimit = limit;
948 
949  /*
950  * Compute the multixact age for which freezing is urgent. This is
951  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
952  * short of multixact member space.
953  */
954  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
955 
956  /*
957  * Determine the minimum multixact freeze age to use: as specified by
958  * caller, or vacuum_multixact_freeze_min_age, but in any case not more
959  * than half effective_multixact_freeze_max_age, so that autovacuums to
960  * prevent MultiXact wraparound won't occur too frequently.
961  */
962  mxid_freezemin = multixact_freeze_min_age;
963  if (mxid_freezemin < 0)
964  mxid_freezemin = vacuum_multixact_freeze_min_age;
965  mxid_freezemin = Min(mxid_freezemin,
966  effective_multixact_freeze_max_age / 2);
967  Assert(mxid_freezemin >= 0);
968 
969  /* compute the cutoff multi, being careful to generate a valid value */
970  oldestMxact = GetOldestMultiXactId();
971  mxactLimit = oldestMxact - mxid_freezemin;
972  if (mxactLimit < FirstMultiXactId)
973  mxactLimit = FirstMultiXactId;
974 
975  safeMxactLimit =
976  ReadNextMultiXactId() - effective_multixact_freeze_max_age;
977  if (safeMxactLimit < FirstMultiXactId)
978  safeMxactLimit = FirstMultiXactId;
979 
980  if (MultiXactIdPrecedes(mxactLimit, safeMxactLimit))
981  {
983  (errmsg("oldest multixact is far in the past"),
984  errhint("Close open transactions with multixacts soon to avoid wraparound problems.")));
985  /* Use the safe limit, unless an older mxact is still running */
986  if (MultiXactIdPrecedes(oldestMxact, safeMxactLimit))
987  mxactLimit = oldestMxact;
988  else
989  mxactLimit = safeMxactLimit;
990  }
991 
992  *multiXactCutoff = mxactLimit;
993 
994  if (xidFullScanLimit != NULL)
995  {
996  int freezetable;
997 
998  Assert(mxactFullScanLimit != NULL);
999 
1000  /*
1001  * Determine the table freeze age to use: as specified by the caller,
1002  * or vacuum_freeze_table_age, but in any case not more than
1003  * autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
1004  * VACUUM schedule, the nightly VACUUM gets a chance to freeze tuples
1005  * before anti-wraparound autovacuum is launched.
1006  */
1007  freezetable = freeze_table_age;
1008  if (freezetable < 0)
1009  freezetable = vacuum_freeze_table_age;
1010  freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
1011  Assert(freezetable >= 0);
1012 
1013  /*
1014  * Compute XID limit causing a full-table vacuum, being careful not to
1015  * generate a "permanent" XID.
1016  */
1017  limit = ReadNewTransactionId() - freezetable;
1018  if (!TransactionIdIsNormal(limit))
1019  limit = FirstNormalTransactionId;
1020 
1021  *xidFullScanLimit = limit;
1022 
1023  /*
1024  * Similar to the above, determine the table freeze age to use for
1025  * multixacts: as specified by the caller, or
1026  * vacuum_multixact_freeze_table_age, but in any case not more than
1027  * autovacuum_multixact_freeze_table_age * 0.95, so that if you have
1028  * e.g. nightly VACUUM schedule, the nightly VACUUM gets a chance to
1029  * freeze multixacts before anti-wraparound autovacuum is launched.
1030  */
1031  freezetable = multixact_freeze_table_age;
1032  if (freezetable < 0)
1033  freezetable = vacuum_multixact_freeze_table_age;
1034  freezetable = Min(freezetable,
1035  effective_multixact_freeze_max_age * 0.95);
1036  Assert(freezetable >= 0);
1037 
1038  /*
1039  * Compute MultiXact limit causing a full-table vacuum, being careful
1040  * to generate a valid MultiXact value.
1041  */
1042  mxactLimit = ReadNextMultiXactId() - freezetable;
1043  if (mxactLimit < FirstMultiXactId)
1044  mxactLimit = FirstMultiXactId;
1045 
1046  *mxactFullScanLimit = mxactLimit;
1047  }
1048  else
1049  {
1050  Assert(mxactFullScanLimit == NULL);
1051  }
1052 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:63
uint32 TransactionId
Definition: c.h:508
#define Min(x, y)
Definition: c.h:905
TransactionId TransactionIdLimitedForOldSnapshots(TransactionId recentXmin, Relation relation)
Definition: snapmgr.c:1775
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:52
#define FirstNormalTransactionId
Definition: transam.h:34
int autovacuum_freeze_max_age
Definition: autovacuum.c:121
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:62
#define FirstMultiXactId
Definition: multixact.h:24
#define ereport(elevel, rest)
Definition: elog.h:141
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2819
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define WARNING
Definition: elog.h:40
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2493
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1306
TransactionId MultiXactId
Definition: c.h:518
#define Assert(condition)
Definition: c.h:733
int vacuum_freeze_min_age
Definition: vacuum.c:60
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3142
int vacuum_freeze_table_age
Definition: vacuum.c:61
static TransactionId ReadNewTransactionId(void)
Definition: transam.h:244
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

Variable Documentation

◆ default_statistics_target

PGDLLIMPORT int default_statistics_target

◆ vacuum_freeze_min_age

int vacuum_freeze_min_age

Definition at line 60 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ vacuum_freeze_table_age

int vacuum_freeze_table_age

Definition at line 61 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ vacuum_multixact_freeze_min_age

int vacuum_multixact_freeze_min_age

Definition at line 62 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ vacuum_multixact_freeze_table_age

int vacuum_multixact_freeze_table_age

Definition at line 63 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().