PostgreSQL Source Code  git master
pg_amcheck.c File Reference
#include "postgres_fe.h"
#include <limits.h>
#include <time.h>
#include "catalog/pg_am_d.h"
#include "catalog/pg_namespace_d.h"
#include "common/logging.h"
#include "common/username.h"
#include "fe_utils/cancel.h"
#include "fe_utils/option_utils.h"
#include "fe_utils/parallel_slot.h"
#include "fe_utils/query_utils.h"
#include "fe_utils/simple_list.h"
#include "fe_utils/string_utils.h"
#include "getopt_long.h"
#include "pgtime.h"
#include "storage/block.h"
Include dependency graph for pg_amcheck.c:

Go to the source code of this file.

Data Structures

struct  PatternInfo
 
struct  PatternInfoArray
 
struct  AmcheckOptions
 
struct  DatabaseInfo
 
struct  RelationInfo
 

Macros

#define log_no_match(...)
 
#define FREE_AND_SET_NULL(x)
 
#define VERBOSE_DATNAME_LENGTH   35
 

Typedefs

typedef struct PatternInfo PatternInfo
 
typedef struct PatternInfoArray PatternInfoArray
 
typedef struct AmcheckOptions AmcheckOptions
 
typedef struct DatabaseInfo DatabaseInfo
 
typedef struct RelationInfo RelationInfo
 

Functions

static void prepare_heap_command (PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
 
static void prepare_btree_command (PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
 
static void run_command (ParallelSlot *slot, const char *sql)
 
static bool verify_heap_slot_handler (PGresult *res, PGconn *conn, void *context)
 
static bool verify_btree_slot_handler (PGresult *res, PGconn *conn, void *context)
 
static void help (const char *progname)
 
static void progress_report (uint64 relations_total, uint64 relations_checked, uint64 relpages_total, uint64 relpages_checked, const char *datname, bool force, bool finished)
 
static void append_database_pattern (PatternInfoArray *pia, const char *pattern, int encoding)
 
static void append_schema_pattern (PatternInfoArray *pia, const char *pattern, int encoding)
 
static void append_relation_pattern (PatternInfoArray *pia, const char *pattern, int encoding)
 
static void append_heap_pattern (PatternInfoArray *pia, const char *pattern, int encoding)
 
static void append_btree_pattern (PatternInfoArray *pia, const char *pattern, int encoding)
 
static void compile_database_list (PGconn *conn, SimplePtrList *databases, const char *initial_dbname)
 
static void compile_relation_list_one_db (PGconn *conn, SimplePtrList *relations, const DatabaseInfo *dat, uint64 *pagecount)
 
int main (int argc, char *argv[])
 
static bool should_processing_continue (PGresult *res)
 
static char * indent_lines (const char *str)
 
static PatternInfoextend_pattern_info_array (PatternInfoArray *pia)
 
static void append_relation_pattern_helper (PatternInfoArray *pia, const char *pattern, int encoding, bool heap_only, bool btree_only)
 
static bool append_db_pattern_cte (PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn, bool inclusive)
 
static void append_rel_pattern_raw_cte (PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn)
 
static void append_rel_pattern_filtered_cte (PQExpBuffer buf, const char *raw, const char *filtered, PGconn *conn)
 

Variables

static AmcheckOptions opts
 
static const char * progname = NULL
 
static bool all_checks_pass = true
 
static pg_time_t last_progress_report = 0
 
static bool progress_since_last_stderr = false
 
static const char *const amcheck_sql
 

Macro Definition Documentation

◆ FREE_AND_SET_NULL

#define FREE_AND_SET_NULL (   x)
Value:
do { \
pg_free(x); \
(x) = NULL; \
} while (0)
int x
Definition: isn.c:71

Definition at line 213 of file pg_amcheck.c.

◆ log_no_match

#define log_no_match (   ...)
Value:
do { \
pg_log_error(__VA_ARGS__); \
pg_log_warning(__VA_ARGS__); \
} while(0)
static AmcheckOptions opts
Definition: pg_amcheck.c:111
#define pg_log_warning(...)
Definition: pgfnames.c:24
bool strict_names
Definition: pg_amcheck.c:60

Definition at line 206 of file pg_amcheck.c.

◆ VERBOSE_DATNAME_LENGTH

#define VERBOSE_DATNAME_LENGTH   35

Typedef Documentation

◆ AmcheckOptions

◆ DatabaseInfo

typedef struct DatabaseInfo DatabaseInfo

◆ PatternInfo

typedef struct PatternInfo PatternInfo

◆ PatternInfoArray

◆ RelationInfo

typedef struct RelationInfo RelationInfo

Function Documentation

◆ append_btree_pattern()

static void append_btree_pattern ( PatternInfoArray pia,
const char *  pattern,
int  encoding 
)
static

Definition at line 1509 of file pg_amcheck.c.

1510 {
1511  append_relation_pattern_helper(pia, pattern, encoding, false, true);
1512 }
static void append_relation_pattern_helper(PatternInfoArray *pia, const char *pattern, int encoding, bool heap_only, bool btree_only)
Definition: pg_amcheck.c:1427
int32 encoding
Definition: pg_database.h:41

References append_relation_pattern_helper(), and encoding.

Referenced by main().

◆ append_database_pattern()

static void append_database_pattern ( PatternInfoArray pia,
const char *  pattern,
int  encoding 
)
static

Definition at line 1355 of file pg_amcheck.c.

1356 {
1358  int dotcnt;
1360 
1361  initPQExpBuffer(&buf);
1362  patternToSQLRegex(encoding, NULL, NULL, &buf, pattern, false, false,
1363  &dotcnt);
1364  if (dotcnt > 0)
1365  {
1366  pg_log_error("improper qualified name (too many dotted names): %s", pattern);
1367  exit(2);
1368  }
1369  info->pattern = pattern;
1370  info->db_regex = pstrdup(buf.data);
1371 
1372  termPQExpBuffer(&buf);
1373 }
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
char * pstrdup(const char *in)
Definition: mcxt.c:1683
static PatternInfo * extend_pattern_info_array(PatternInfoArray *pia)
Definition: pg_amcheck.c:1333
static char * buf
Definition: pg_test_fsync.c:73
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
void patternToSQLRegex(int encoding, PQExpBuffer dbnamebuf, PQExpBuffer schemabuf, PQExpBuffer namebuf, const char *pattern, bool force_escape, bool want_literal_dbname, int *dotcnt)
const char * pattern
Definition: pg_amcheck.c:34
char * db_regex
Definition: pg_amcheck.c:35

References buf, PatternInfo::db_regex, encoding, exit(), extend_pattern_info_array(), initPQExpBuffer(), PatternInfo::pattern, patternToSQLRegex(), pg_log_error, pstrdup(), and termPQExpBuffer().

Referenced by main().

◆ append_db_pattern_cte()

static bool append_db_pattern_cte ( PQExpBuffer  buf,
const PatternInfoArray pia,
PGconn conn,
bool  inclusive 
)
static

Definition at line 1536 of file pg_amcheck.c.

1538 {
1539  int pattern_id;
1540  const char *comma;
1541  bool have_values;
1542 
1543  comma = "";
1544  have_values = false;
1545  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1546  {
1547  PatternInfo *info = &pia->data[pattern_id];
1548 
1549  if (info->db_regex != NULL &&
1550  (inclusive || (info->nsp_regex == NULL && info->rel_regex == NULL)))
1551  {
1552  if (!have_values)
1553  appendPQExpBufferStr(buf, "\nVALUES");
1554  have_values = true;
1555  appendPQExpBuffer(buf, "%s\n(%d, ", comma, pattern_id);
1557  appendPQExpBufferChar(buf, ')');
1558  comma = ",";
1559  }
1560  }
1561 
1562  if (!have_values)
1563  appendPQExpBufferStr(buf, "\nSELECT NULL, NULL, NULL WHERE false");
1564 
1565  return have_values;
1566 }
#define comma
Definition: indent_codes.h:48
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
PGconn * conn
Definition: streamutil.c:54
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
PatternInfo * data
Definition: pg_amcheck.c:49
char * rel_regex
Definition: pg_amcheck.c:38
char * nsp_regex
Definition: pg_amcheck.c:37

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendStringLiteralConn(), buf, comma, conn, PatternInfoArray::data, PatternInfo::db_regex, PatternInfoArray::len, PatternInfo::nsp_regex, and PatternInfo::rel_regex.

Referenced by compile_database_list().

◆ append_heap_pattern()

static void append_heap_pattern ( PatternInfoArray pia,
const char *  pattern,
int  encoding 
)
static

Definition at line 1493 of file pg_amcheck.c.

1494 {
1495  append_relation_pattern_helper(pia, pattern, encoding, true, false);
1496 }

References append_relation_pattern_helper(), and encoding.

Referenced by main().

◆ append_rel_pattern_filtered_cte()

static void append_rel_pattern_filtered_cte ( PQExpBuffer  buf,
const char *  raw,
const char *  filtered,
PGconn conn 
)
static

Definition at line 1843 of file pg_amcheck.c.

1845 {
1847  "\n%s (pattern_id, nsp_regex, rel_regex, heap_only, btree_only) AS ("
1848  "\nSELECT pattern_id, nsp_regex, rel_regex, heap_only, btree_only "
1849  "FROM %s r"
1850  "\nWHERE (r.db_regex IS NULL "
1851  "OR ",
1852  filtered, raw);
1854  appendPQExpBufferStr(buf, " ~ r.db_regex)");
1856  " AND (r.nsp_regex IS NOT NULL"
1857  " OR r.rel_regex IS NOT NULL)"
1858  "),");
1859 }
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6794

References appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), buf, conn, and PQdb().

Referenced by compile_relation_list_one_db().

◆ append_rel_pattern_raw_cte()

static void append_rel_pattern_raw_cte ( PQExpBuffer  buf,
const PatternInfoArray pia,
PGconn conn 
)
static

Definition at line 1774 of file pg_amcheck.c.

1776 {
1777  int pattern_id;
1778  const char *comma;
1779  bool have_values;
1780 
1781  comma = "";
1782  have_values = false;
1783  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1784  {
1785  PatternInfo *info = &pia->data[pattern_id];
1786 
1787  if (!have_values)
1788  appendPQExpBufferStr(buf, "\nVALUES");
1789  have_values = true;
1790  appendPQExpBuffer(buf, "%s\n(%d::INTEGER, ", comma, pattern_id);
1791  if (info->db_regex == NULL)
1792  appendPQExpBufferStr(buf, "NULL");
1793  else
1795  appendPQExpBufferStr(buf, "::TEXT, ");
1796  if (info->nsp_regex == NULL)
1797  appendPQExpBufferStr(buf, "NULL");
1798  else
1800  appendPQExpBufferStr(buf, "::TEXT, ");
1801  if (info->rel_regex == NULL)
1802  appendPQExpBufferStr(buf, "NULL");
1803  else
1805  if (info->heap_only)
1806  appendPQExpBufferStr(buf, "::TEXT, true::BOOLEAN");
1807  else
1808  appendPQExpBufferStr(buf, "::TEXT, false::BOOLEAN");
1809  if (info->btree_only)
1810  appendPQExpBufferStr(buf, ", true::BOOLEAN");
1811  else
1812  appendPQExpBufferStr(buf, ", false::BOOLEAN");
1813  appendPQExpBufferChar(buf, ')');
1814  comma = ",";
1815  }
1816 
1817  if (!have_values)
1819  "\nSELECT NULL::INTEGER, NULL::TEXT, NULL::TEXT, "
1820  "NULL::TEXT, NULL::BOOLEAN, NULL::BOOLEAN "
1821  "WHERE false");
1822 }
bool btree_only
Definition: pg_amcheck.c:42
bool heap_only
Definition: pg_amcheck.c:40

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendStringLiteralConn(), PatternInfo::btree_only, buf, comma, conn, PatternInfoArray::data, PatternInfo::db_regex, PatternInfo::heap_only, PatternInfoArray::len, PatternInfo::nsp_regex, and PatternInfo::rel_regex.

Referenced by compile_relation_list_one_db().

◆ append_relation_pattern()

static void append_relation_pattern ( PatternInfoArray pia,
const char *  pattern,
int  encoding 
)
static

Definition at line 1477 of file pg_amcheck.c.

1478 {
1479  append_relation_pattern_helper(pia, pattern, encoding, false, false);
1480 }

References append_relation_pattern_helper(), and encoding.

Referenced by main().

◆ append_relation_pattern_helper()

static void append_relation_pattern_helper ( PatternInfoArray pia,
const char *  pattern,
int  encoding,
bool  heap_only,
bool  btree_only 
)
static

Definition at line 1427 of file pg_amcheck.c.

1429 {
1430  PQExpBufferData dbbuf;
1431  PQExpBufferData nspbuf;
1432  PQExpBufferData relbuf;
1433  int dotcnt;
1435 
1436  initPQExpBuffer(&dbbuf);
1437  initPQExpBuffer(&nspbuf);
1438  initPQExpBuffer(&relbuf);
1439 
1440  patternToSQLRegex(encoding, &dbbuf, &nspbuf, &relbuf, pattern, false,
1441  false, &dotcnt);
1442  if (dotcnt > 2)
1443  {
1444  pg_log_error("improper relation name (too many dotted names): %s", pattern);
1445  exit(2);
1446  }
1447  info->pattern = pattern;
1448  if (dbbuf.data[0])
1449  {
1450  opts.dbpattern = true;
1451  info->db_regex = pstrdup(dbbuf.data);
1452  }
1453  if (nspbuf.data[0])
1454  info->nsp_regex = pstrdup(nspbuf.data);
1455  if (relbuf.data[0])
1456  info->rel_regex = pstrdup(relbuf.data);
1457 
1458  termPQExpBuffer(&dbbuf);
1459  termPQExpBuffer(&nspbuf);
1460  termPQExpBuffer(&relbuf);
1461 
1462  info->heap_only = heap_only;
1463  info->btree_only = btree_only;
1464 }

References PatternInfo::btree_only, PQExpBufferData::data, PatternInfo::db_regex, AmcheckOptions::dbpattern, encoding, exit(), extend_pattern_info_array(), PatternInfo::heap_only, initPQExpBuffer(), PatternInfo::nsp_regex, opts, PatternInfo::pattern, patternToSQLRegex(), pg_log_error, pstrdup(), PatternInfo::rel_regex, and termPQExpBuffer().

Referenced by append_btree_pattern(), append_heap_pattern(), and append_relation_pattern().

◆ append_schema_pattern()

static void append_schema_pattern ( PatternInfoArray pia,
const char *  pattern,
int  encoding 
)
static

Definition at line 1385 of file pg_amcheck.c.

1386 {
1387  PQExpBufferData dbbuf;
1388  PQExpBufferData nspbuf;
1389  int dotcnt;
1391 
1392  initPQExpBuffer(&dbbuf);
1393  initPQExpBuffer(&nspbuf);
1394 
1395  patternToSQLRegex(encoding, NULL, &dbbuf, &nspbuf, pattern, false, false,
1396  &dotcnt);
1397  if (dotcnt > 1)
1398  {
1399  pg_log_error("improper qualified name (too many dotted names): %s", pattern);
1400  exit(2);
1401  }
1402  info->pattern = pattern;
1403  if (dbbuf.data[0])
1404  {
1405  opts.dbpattern = true;
1406  info->db_regex = pstrdup(dbbuf.data);
1407  }
1408  if (nspbuf.data[0])
1409  info->nsp_regex = pstrdup(nspbuf.data);
1410 
1411  termPQExpBuffer(&dbbuf);
1412  termPQExpBuffer(&nspbuf);
1413 }

References PQExpBufferData::data, PatternInfo::db_regex, AmcheckOptions::dbpattern, encoding, exit(), extend_pattern_info_array(), initPQExpBuffer(), PatternInfo::nsp_regex, opts, PatternInfo::pattern, patternToSQLRegex(), pg_log_error, pstrdup(), and termPQExpBuffer().

Referenced by main().

◆ compile_database_list()

static void compile_database_list ( PGconn conn,
SimplePtrList databases,
const char *  initial_dbname 
)
static

Definition at line 1582 of file pg_amcheck.c.

1584 {
1585  PGresult *res;
1586  PQExpBufferData sql;
1587  int ntups;
1588  int i;
1589  bool fatal;
1590 
1591  if (initial_dbname)
1592  {
1593  DatabaseInfo *dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1594 
1595  /* This database is included. Add to list */
1596  if (opts.verbose)
1597  pg_log_info("including database \"%s\"", initial_dbname);
1598 
1599  dat->datname = pstrdup(initial_dbname);
1600  simple_ptr_list_append(databases, dat);
1601  }
1602 
1603  initPQExpBuffer(&sql);
1604 
1605  /* Append the include patterns CTE. */
1606  appendPQExpBufferStr(&sql, "WITH include_raw (pattern_id, rgx) AS (");
1607  if (!append_db_pattern_cte(&sql, &opts.include, conn, true) &&
1608  !opts.alldb)
1609  {
1610  /*
1611  * None of the inclusion patterns (if any) contain database portions,
1612  * so there is no need to query the database to resolve database
1613  * patterns.
1614  *
1615  * Since we're also not operating under --all, we don't need to query
1616  * the exhaustive list of connectable databases, either.
1617  */
1618  termPQExpBuffer(&sql);
1619  return;
1620  }
1621 
1622  /* Append the exclude patterns CTE. */
1623  appendPQExpBufferStr(&sql, "),\nexclude_raw (pattern_id, rgx) AS (");
1624  append_db_pattern_cte(&sql, &opts.exclude, conn, false);
1625  appendPQExpBufferStr(&sql, "),");
1626 
1627  /*
1628  * Append the database CTE, which includes whether each database is
1629  * connectable and also joins against exclude_raw to determine whether
1630  * each database is excluded.
1631  */
1632  appendPQExpBufferStr(&sql,
1633  "\ndatabase (datname) AS ("
1634  "\nSELECT d.datname "
1635  "FROM pg_catalog.pg_database d "
1636  "LEFT OUTER JOIN exclude_raw e "
1637  "ON d.datname ~ e.rgx "
1638  "\nWHERE d.datallowconn AND datconnlimit != -2 "
1639  "AND e.pattern_id IS NULL"
1640  "),"
1641 
1642  /*
1643  * Append the include_pat CTE, which joins the include_raw CTE against the
1644  * databases CTE to determine if all the inclusion patterns had matches,
1645  * and whether each matched pattern had the misfortune of only matching
1646  * excluded or unconnectable databases.
1647  */
1648  "\ninclude_pat (pattern_id, checkable) AS ("
1649  "\nSELECT i.pattern_id, "
1650  "COUNT(*) FILTER ("
1651  "WHERE d IS NOT NULL"
1652  ") AS checkable"
1653  "\nFROM include_raw i "
1654  "LEFT OUTER JOIN database d "
1655  "ON d.datname ~ i.rgx"
1656  "\nGROUP BY i.pattern_id"
1657  "),"
1658 
1659  /*
1660  * Append the filtered_databases CTE, which selects from the database CTE
1661  * optionally joined against the include_raw CTE to only select databases
1662  * that match an inclusion pattern. This appears to duplicate what the
1663  * include_pat CTE already did above, but here we want only databases, and
1664  * there we wanted patterns.
1665  */
1666  "\nfiltered_databases (datname) AS ("
1667  "\nSELECT DISTINCT d.datname "
1668  "FROM database d");
1669  if (!opts.alldb)
1670  appendPQExpBufferStr(&sql,
1671  " INNER JOIN include_raw i "
1672  "ON d.datname ~ i.rgx");
1673  appendPQExpBufferStr(&sql,
1674  ")"
1675 
1676  /*
1677  * Select the checkable databases and the unmatched inclusion patterns.
1678  */
1679  "\nSELECT pattern_id, datname FROM ("
1680  "\nSELECT pattern_id, NULL::TEXT AS datname "
1681  "FROM include_pat "
1682  "WHERE checkable = 0 "
1683  "UNION ALL"
1684  "\nSELECT NULL, datname "
1685  "FROM filtered_databases"
1686  ") AS combined_records"
1687  "\nORDER BY pattern_id NULLS LAST, datname");
1688 
1689  res = executeQuery(conn, sql.data, opts.echo);
1691  {
1692  pg_log_error("query failed: %s", PQerrorMessage(conn));
1693  pg_log_error_detail("Query was: %s", sql.data);
1695  exit(1);
1696  }
1697  termPQExpBuffer(&sql);
1698 
1699  ntups = PQntuples(res);
1700  for (fatal = false, i = 0; i < ntups; i++)
1701  {
1702  int pattern_id = -1;
1703  const char *datname = NULL;
1704 
1705  if (!PQgetisnull(res, i, 0))
1706  pattern_id = atoi(PQgetvalue(res, i, 0));
1707  if (!PQgetisnull(res, i, 1))
1708  datname = PQgetvalue(res, i, 1);
1709 
1710  if (pattern_id >= 0)
1711  {
1712  /*
1713  * Current record pertains to an inclusion pattern that matched no
1714  * checkable databases.
1715  */
1716  fatal = opts.strict_names;
1717  if (pattern_id >= opts.include.len)
1718  pg_fatal("internal error: received unexpected database pattern_id %d",
1719  pattern_id);
1720  log_no_match("no connectable databases to check matching \"%s\"",
1721  opts.include.data[pattern_id].pattern);
1722  }
1723  else
1724  {
1725  DatabaseInfo *dat;
1726 
1727  /* Current record pertains to a database */
1728  Assert(datname != NULL);
1729 
1730  /* Avoid entering a duplicate entry matching the initial_dbname */
1731  if (initial_dbname != NULL && strcmp(initial_dbname, datname) == 0)
1732  continue;
1733 
1734  /* This database is included. Add to list */
1735  if (opts.verbose)
1736  pg_log_info("including database \"%s\"", datname);
1737 
1738  dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1739  dat->datname = pstrdup(datname);
1740  simple_ptr_list_append(databases, dat);
1741  }
1742  }
1743  PQclear(res);
1744 
1745  if (fatal)
1746  {
1747  if (conn != NULL)
1749  exit(1);
1750  }
1751 }
void disconnectDatabase(PGconn *conn)
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6948
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3371
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3441
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3836
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3861
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
int i
Definition: isn.c:73
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:103
Assert(fmt[strlen(fmt) - 1] !='\n')
#define pg_log_info(...)
Definition: logging.h:124
#define pg_log_error_detail(...)
Definition: logging.h:109
#define log_no_match(...)
Definition: pg_amcheck.c:206
static bool append_db_pattern_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn, bool inclusive)
Definition: pg_amcheck.c:1536
#define pg_fatal(...)
NameData datname
Definition: pg_database.h:35
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1882
void simple_ptr_list_append(SimplePtrList *list, void *ptr)
Definition: simple_list.c:162
PatternInfoArray exclude
Definition: pg_amcheck.c:73
PatternInfoArray include
Definition: pg_amcheck.c:72
char * datname
Definition: pg_amcheck.c:151

References AmcheckOptions::alldb, append_db_pattern_cte(), appendPQExpBufferStr(), Assert(), conn, PatternInfoArray::data, PQExpBufferData::data, DatabaseInfo::datname, datname, disconnectDatabase(), AmcheckOptions::echo, AmcheckOptions::exclude, executeQuery(), exit(), i, AmcheckOptions::include, initPQExpBuffer(), PatternInfoArray::len, log_no_match, opts, PatternInfo::pattern, pg_fatal, pg_log_error, pg_log_error_detail, pg_log_info, pg_malloc0(), PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQgetisnull(), PQgetvalue(), PQntuples(), PQresultStatus(), pstrdup(), res, simple_ptr_list_append(), AmcheckOptions::strict_names, termPQExpBuffer(), and AmcheckOptions::verbose.

Referenced by main().

◆ compile_relation_list_one_db()

static void compile_relation_list_one_db ( PGconn conn,
SimplePtrList relations,
const DatabaseInfo dat,
uint64 *  pagecount 
)
static

Definition at line 1882 of file pg_amcheck.c.

1885 {
1886  PGresult *res;
1887  PQExpBufferData sql;
1888  int ntups;
1889  int i;
1890 
1891  initPQExpBuffer(&sql);
1892  appendPQExpBufferStr(&sql, "WITH");
1893 
1894  /* Append CTEs for the relation inclusion patterns, if any */
1895  if (!opts.allrel)
1896  {
1897  appendPQExpBufferStr(&sql,
1898  " include_raw (pattern_id, db_regex, nsp_regex, rel_regex, heap_only, btree_only) AS (");
1900  appendPQExpBufferStr(&sql, "\n),");
1901  append_rel_pattern_filtered_cte(&sql, "include_raw", "include_pat", conn);
1902  }
1903 
1904  /* Append CTEs for the relation exclusion patterns, if any */
1906  {
1907  appendPQExpBufferStr(&sql,
1908  " exclude_raw (pattern_id, db_regex, nsp_regex, rel_regex, heap_only, btree_only) AS (");
1910  appendPQExpBufferStr(&sql, "\n),");
1911  append_rel_pattern_filtered_cte(&sql, "exclude_raw", "exclude_pat", conn);
1912  }
1913 
1914  /* Append the relation CTE. */
1915  appendPQExpBufferStr(&sql,
1916  " relation (pattern_id, oid, nspname, relname, reltoastrelid, relpages, is_heap, is_btree) AS ("
1917  "\nSELECT DISTINCT ON (c.oid");
1918  if (!opts.allrel)
1919  appendPQExpBufferStr(&sql, ", ip.pattern_id) ip.pattern_id,");
1920  else
1921  appendPQExpBufferStr(&sql, ") NULL::INTEGER AS pattern_id,");
1922  appendPQExpBuffer(&sql,
1923  "\nc.oid, n.nspname, c.relname, c.reltoastrelid, c.relpages, "
1924  "c.relam = %u AS is_heap, "
1925  "c.relam = %u AS is_btree"
1926  "\nFROM pg_catalog.pg_class c "
1927  "INNER JOIN pg_catalog.pg_namespace n "
1928  "ON c.relnamespace = n.oid",
1929  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1930  if (!opts.allrel)
1931  appendPQExpBuffer(&sql,
1932  "\nINNER JOIN include_pat ip"
1933  "\nON (n.nspname ~ ip.nsp_regex OR ip.nsp_regex IS NULL)"
1934  "\nAND (c.relname ~ ip.rel_regex OR ip.rel_regex IS NULL)"
1935  "\nAND (c.relam = %u OR NOT ip.heap_only)"
1936  "\nAND (c.relam = %u OR NOT ip.btree_only)",
1937  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1939  appendPQExpBuffer(&sql,
1940  "\nLEFT OUTER JOIN exclude_pat ep"
1941  "\nON (n.nspname ~ ep.nsp_regex OR ep.nsp_regex IS NULL)"
1942  "\nAND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL)"
1943  "\nAND (c.relam = %u OR NOT ep.heap_only OR ep.rel_regex IS NULL)"
1944  "\nAND (c.relam = %u OR NOT ep.btree_only OR ep.rel_regex IS NULL)",
1945  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1946 
1947  /*
1948  * Exclude temporary tables and indexes, which must necessarily belong to
1949  * other sessions. (We don't create any ourselves.) We must ultimately
1950  * exclude indexes marked invalid or not ready, but we delay that decision
1951  * until firing off the amcheck command, as the state of an index may
1952  * change by then.
1953  */
1954  appendPQExpBufferStr(&sql, "\nWHERE c.relpersistence != 't'");
1956  appendPQExpBufferStr(&sql, "\nAND ep.pattern_id IS NULL");
1957 
1958  /*
1959  * We need to be careful not to break the --no-dependent-toast and
1960  * --no-dependent-indexes options. By default, the btree indexes, toast
1961  * tables, and toast table btree indexes associated with primary heap
1962  * tables are included, using their own CTEs below. We implement the
1963  * --exclude-* options by not creating those CTEs, but that's no use if
1964  * we've already selected the toast and indexes here. On the other hand,
1965  * we want inclusion patterns that match indexes or toast tables to be
1966  * honored. So, if inclusion patterns were given, we want to select all
1967  * tables, toast tables, or indexes that match the patterns. But if no
1968  * inclusion patterns were given, and we're simply matching all relations,
1969  * then we only want to match the primary tables here.
1970  */
1971  if (opts.allrel)
1972  appendPQExpBuffer(&sql,
1973  " AND c.relam = %u "
1974  "AND c.relkind IN ('r', 'S', 'm', 't') "
1975  "AND c.relnamespace != %u",
1976  HEAP_TABLE_AM_OID, PG_TOAST_NAMESPACE);
1977  else
1978  appendPQExpBuffer(&sql,
1979  " AND c.relam IN (%u, %u)"
1980  "AND c.relkind IN ('r', 'S', 'm', 't', 'i') "
1981  "AND ((c.relam = %u AND c.relkind IN ('r', 'S', 'm', 't')) OR "
1982  "(c.relam = %u AND c.relkind = 'i'))",
1983  HEAP_TABLE_AM_OID, BTREE_AM_OID,
1984  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1985 
1986  appendPQExpBufferStr(&sql,
1987  "\nORDER BY c.oid)");
1988 
1989  if (!opts.no_toast_expansion)
1990  {
1991  /*
1992  * Include a CTE for toast tables associated with primary heap tables
1993  * selected above, filtering by exclusion patterns (if any) that match
1994  * toast table names.
1995  */
1996  appendPQExpBufferStr(&sql,
1997  ", toast (oid, nspname, relname, relpages) AS ("
1998  "\nSELECT t.oid, 'pg_toast', t.relname, t.relpages"
1999  "\nFROM pg_catalog.pg_class t "
2000  "INNER JOIN relation r "
2001  "ON r.reltoastrelid = t.oid");
2002  if (opts.excludetbl || opts.excludensp)
2003  appendPQExpBufferStr(&sql,
2004  "\nLEFT OUTER JOIN exclude_pat ep"
2005  "\nON ('pg_toast' ~ ep.nsp_regex OR ep.nsp_regex IS NULL)"
2006  "\nAND (t.relname ~ ep.rel_regex OR ep.rel_regex IS NULL)"
2007  "\nAND ep.heap_only"
2008  "\nWHERE ep.pattern_id IS NULL"
2009  "\nAND t.relpersistence != 't'");
2010  appendPQExpBufferStr(&sql,
2011  "\n)");
2012  }
2013  if (!opts.no_btree_expansion)
2014  {
2015  /*
2016  * Include a CTE for btree indexes associated with primary heap tables
2017  * selected above, filtering by exclusion patterns (if any) that match
2018  * btree index names.
2019  */
2020  appendPQExpBufferStr(&sql,
2021  ", index (oid, nspname, relname, relpages) AS ("
2022  "\nSELECT c.oid, r.nspname, c.relname, c.relpages "
2023  "FROM relation r"
2024  "\nINNER JOIN pg_catalog.pg_index i "
2025  "ON r.oid = i.indrelid "
2026  "INNER JOIN pg_catalog.pg_class c "
2027  "ON i.indexrelid = c.oid "
2028  "AND c.relpersistence != 't'");
2029  if (opts.excludeidx || opts.excludensp)
2030  appendPQExpBufferStr(&sql,
2031  "\nINNER JOIN pg_catalog.pg_namespace n "
2032  "ON c.relnamespace = n.oid"
2033  "\nLEFT OUTER JOIN exclude_pat ep "
2034  "ON (n.nspname ~ ep.nsp_regex OR ep.nsp_regex IS NULL) "
2035  "AND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL) "
2036  "AND ep.btree_only"
2037  "\nWHERE ep.pattern_id IS NULL");
2038  else
2039  appendPQExpBufferStr(&sql,
2040  "\nWHERE true");
2041  appendPQExpBuffer(&sql,
2042  " AND c.relam = %u "
2043  "AND c.relkind = 'i'",
2044  BTREE_AM_OID);
2046  appendPQExpBuffer(&sql,
2047  " AND c.relnamespace != %u",
2048  PG_TOAST_NAMESPACE);
2049  appendPQExpBufferStr(&sql, "\n)");
2050  }
2051 
2053  {
2054  /*
2055  * Include a CTE for btree indexes associated with toast tables of
2056  * primary heap tables selected above, filtering by exclusion patterns
2057  * (if any) that match the toast index names.
2058  */
2059  appendPQExpBufferStr(&sql,
2060  ", toast_index (oid, nspname, relname, relpages) AS ("
2061  "\nSELECT c.oid, 'pg_toast', c.relname, c.relpages "
2062  "FROM toast t "
2063  "INNER JOIN pg_catalog.pg_index i "
2064  "ON t.oid = i.indrelid"
2065  "\nINNER JOIN pg_catalog.pg_class c "
2066  "ON i.indexrelid = c.oid "
2067  "AND c.relpersistence != 't'");
2068  if (opts.excludeidx)
2069  appendPQExpBufferStr(&sql,
2070  "\nLEFT OUTER JOIN exclude_pat ep "
2071  "ON ('pg_toast' ~ ep.nsp_regex OR ep.nsp_regex IS NULL) "
2072  "AND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL) "
2073  "AND ep.btree_only "
2074  "WHERE ep.pattern_id IS NULL");
2075  else
2076  appendPQExpBufferStr(&sql,
2077  "\nWHERE true");
2078  appendPQExpBuffer(&sql,
2079  " AND c.relam = %u"
2080  " AND c.relkind = 'i')",
2081  BTREE_AM_OID);
2082  }
2083 
2084  /*
2085  * Roll-up distinct rows from CTEs.
2086  *
2087  * Relations that match more than one pattern may occur more than once in
2088  * the list, and indexes and toast for primary relations may also have
2089  * matched in their own right, so we rely on UNION to deduplicate the
2090  * list.
2091  */
2092  appendPQExpBufferStr(&sql,
2093  "\nSELECT pattern_id, is_heap, is_btree, oid, nspname, relname, relpages "
2094  "FROM (");
2095  appendPQExpBufferStr(&sql,
2096  /* Inclusion patterns that failed to match */
2097  "\nSELECT pattern_id, is_heap, is_btree, "
2098  "NULL::OID AS oid, "
2099  "NULL::TEXT AS nspname, "
2100  "NULL::TEXT AS relname, "
2101  "NULL::INTEGER AS relpages"
2102  "\nFROM relation "
2103  "WHERE pattern_id IS NOT NULL "
2104  "UNION"
2105  /* Primary relations */
2106  "\nSELECT NULL::INTEGER AS pattern_id, "
2107  "is_heap, is_btree, oid, nspname, relname, relpages "
2108  "FROM relation");
2109  if (!opts.no_toast_expansion)
2110  appendPQExpBufferStr(&sql,
2111  " UNION"
2112  /* Toast tables for primary relations */
2113  "\nSELECT NULL::INTEGER AS pattern_id, TRUE AS is_heap, "
2114  "FALSE AS is_btree, oid, nspname, relname, relpages "
2115  "FROM toast");
2116  if (!opts.no_btree_expansion)
2117  appendPQExpBufferStr(&sql,
2118  " UNION"
2119  /* Indexes for primary relations */
2120  "\nSELECT NULL::INTEGER AS pattern_id, FALSE AS is_heap, "
2121  "TRUE AS is_btree, oid, nspname, relname, relpages "
2122  "FROM index");
2124  appendPQExpBufferStr(&sql,
2125  " UNION"
2126  /* Indexes for toast relations */
2127  "\nSELECT NULL::INTEGER AS pattern_id, FALSE AS is_heap, "
2128  "TRUE AS is_btree, oid, nspname, relname, relpages "
2129  "FROM toast_index");
2130  appendPQExpBufferStr(&sql,
2131  "\n) AS combined_records "
2132  "ORDER BY relpages DESC NULLS FIRST, oid");
2133 
2134  res = executeQuery(conn, sql.data, opts.echo);
2136  {
2137  pg_log_error("query failed: %s", PQerrorMessage(conn));
2138  pg_log_error_detail("Query was: %s", sql.data);
2140  exit(1);
2141  }
2142  termPQExpBuffer(&sql);
2143 
2144  ntups = PQntuples(res);
2145  for (i = 0; i < ntups; i++)
2146  {
2147  int pattern_id = -1;
2148  bool is_heap = false;
2149  bool is_btree PG_USED_FOR_ASSERTS_ONLY = false;
2150  Oid oid = InvalidOid;
2151  const char *nspname = NULL;
2152  const char *relname = NULL;
2153  int relpages = 0;
2154 
2155  if (!PQgetisnull(res, i, 0))
2156  pattern_id = atoi(PQgetvalue(res, i, 0));
2157  if (!PQgetisnull(res, i, 1))
2158  is_heap = (PQgetvalue(res, i, 1)[0] == 't');
2159  if (!PQgetisnull(res, i, 2))
2160  is_btree = (PQgetvalue(res, i, 2)[0] == 't');
2161  if (!PQgetisnull(res, i, 3))
2162  oid = atooid(PQgetvalue(res, i, 3));
2163  if (!PQgetisnull(res, i, 4))
2164  nspname = PQgetvalue(res, i, 4);
2165  if (!PQgetisnull(res, i, 5))
2166  relname = PQgetvalue(res, i, 5);
2167  if (!PQgetisnull(res, i, 6))
2168  relpages = atoi(PQgetvalue(res, i, 6));
2169 
2170  if (pattern_id >= 0)
2171  {
2172  /*
2173  * Current record pertains to an inclusion pattern. Record that
2174  * it matched.
2175  */
2176 
2177  if (pattern_id >= opts.include.len)
2178  pg_fatal("internal error: received unexpected relation pattern_id %d",
2179  pattern_id);
2180 
2181  opts.include.data[pattern_id].matched = true;
2182  }
2183  else
2184  {
2185  /* Current record pertains to a relation */
2186 
2187  RelationInfo *rel = (RelationInfo *) pg_malloc0(sizeof(RelationInfo));
2188 
2189  Assert(OidIsValid(oid));
2190  Assert((is_heap && !is_btree) || (is_btree && !is_heap));
2191 
2192  rel->datinfo = dat;
2193  rel->reloid = oid;
2194  rel->is_heap = is_heap;
2195  rel->nspname = pstrdup(nspname);
2196  rel->relname = pstrdup(relname);
2197  rel->relpages = relpages;
2198  rel->blocks_to_check = relpages;
2199  if (is_heap && (opts.startblock >= 0 || opts.endblock >= 0))
2200  {
2201  /*
2202  * We apply --startblock and --endblock to heap tables, but
2203  * not btree indexes, and for progress purposes we need to
2204  * track how many blocks we expect to check.
2205  */
2206  if (opts.endblock >= 0 && rel->blocks_to_check > opts.endblock)
2207  rel->blocks_to_check = opts.endblock + 1;
2208  if (opts.startblock >= 0)
2209  {
2210  if (rel->blocks_to_check > opts.startblock)
2212  else
2213  rel->blocks_to_check = 0;
2214  }
2215  }
2216  *pagecount += rel->blocks_to_check;
2217 
2218  simple_ptr_list_append(relations, rel);
2219  }
2220  }
2221  PQclear(res);
2222 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:169
#define OidIsValid(objectId)
Definition: c.h:762
static void append_rel_pattern_filtered_cte(PQExpBuffer buf, const char *raw, const char *filtered, PGconn *conn)
Definition: pg_amcheck.c:1843
static void append_rel_pattern_raw_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn)
Definition: pg_amcheck.c:1774
NameData relname
Definition: pg_class.h:38
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define atooid(x)
Definition: postgres_ext.h:42
int64 startblock
Definition: pg_amcheck.c:97
bool no_btree_expansion
Definition: pg_amcheck.c:108
bool no_toast_expansion
Definition: pg_amcheck.c:94
int64 endblock
Definition: pg_amcheck.c:98
bool matched
Definition: pg_amcheck.c:44
const DatabaseInfo * datinfo
Definition: pg_amcheck.c:158
char * nspname
Definition: pg_amcheck.c:161
int blocks_to_check
Definition: pg_amcheck.c:164
char * relname
Definition: pg_amcheck.c:162

References AmcheckOptions::allrel, append_rel_pattern_filtered_cte(), append_rel_pattern_raw_cte(), appendPQExpBuffer(), appendPQExpBufferStr(), Assert(), atooid, RelationInfo::blocks_to_check, conn, PatternInfoArray::data, PQExpBufferData::data, RelationInfo::datinfo, disconnectDatabase(), AmcheckOptions::echo, AmcheckOptions::endblock, AmcheckOptions::exclude, AmcheckOptions::excludeidx, AmcheckOptions::excludensp, AmcheckOptions::excludetbl, executeQuery(), exit(), i, AmcheckOptions::include, initPQExpBuffer(), InvalidOid, RelationInfo::is_heap, PatternInfoArray::len, PatternInfo::matched, AmcheckOptions::no_btree_expansion, AmcheckOptions::no_toast_expansion, RelationInfo::nspname, OidIsValid, opts, pg_fatal, pg_log_error, pg_log_error_detail, pg_malloc0(), PG_USED_FOR_ASSERTS_ONLY, PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQgetisnull(), PQgetvalue(), PQntuples(), PQresultStatus(), pstrdup(), RelationInfo::relname, relname, RelationInfo::reloid, RelationInfo::relpages, res, simple_ptr_list_append(), AmcheckOptions::startblock, and termPQExpBuffer().

Referenced by main().

◆ extend_pattern_info_array()

static PatternInfo* extend_pattern_info_array ( PatternInfoArray pia)
static

Definition at line 1333 of file pg_amcheck.c.

1334 {
1335  PatternInfo *result;
1336 
1337  pia->len++;
1338  pia->data = (PatternInfo *) pg_realloc(pia->data, pia->len * sizeof(PatternInfo));
1339  result = &pia->data[pia->len - 1];
1340  memset(result, 0, sizeof(*result));
1341 
1342  return result;
1343 }
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65

References PatternInfoArray::data, PatternInfoArray::len, and pg_realloc().

Referenced by append_database_pattern(), append_relation_pattern_helper(), and append_schema_pattern().

◆ help()

static void help ( const char *  progname)
static

Definition at line 1180 of file pg_amcheck.c.

1181 {
1182  printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
1183  printf(_("Usage:\n"));
1184  printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
1185  printf(_("\nTarget options:\n"));
1186  printf(_(" -a, --all check all databases\n"));
1187  printf(_(" -d, --database=PATTERN check matching database(s)\n"));
1188  printf(_(" -D, --exclude-database=PATTERN do NOT check matching database(s)\n"));
1189  printf(_(" -i, --index=PATTERN check matching index(es)\n"));
1190  printf(_(" -I, --exclude-index=PATTERN do NOT check matching index(es)\n"));
1191  printf(_(" -r, --relation=PATTERN check matching relation(s)\n"));
1192  printf(_(" -R, --exclude-relation=PATTERN do NOT check matching relation(s)\n"));
1193  printf(_(" -s, --schema=PATTERN check matching schema(s)\n"));
1194  printf(_(" -S, --exclude-schema=PATTERN do NOT check matching schema(s)\n"));
1195  printf(_(" -t, --table=PATTERN check matching table(s)\n"));
1196  printf(_(" -T, --exclude-table=PATTERN do NOT check matching table(s)\n"));
1197  printf(_(" --no-dependent-indexes do NOT expand list of relations to include indexes\n"));
1198  printf(_(" --no-dependent-toast do NOT expand list of relations to include TOAST tables\n"));
1199  printf(_(" --no-strict-names do NOT require patterns to match objects\n"));
1200  printf(_("\nTable checking options:\n"));
1201  printf(_(" --exclude-toast-pointers do NOT follow relation TOAST pointers\n"));
1202  printf(_(" --on-error-stop stop checking at end of first corrupt page\n"));
1203  printf(_(" --skip=OPTION do NOT check \"all-frozen\" or \"all-visible\" blocks\n"));
1204  printf(_(" --startblock=BLOCK begin checking table(s) at the given block number\n"));
1205  printf(_(" --endblock=BLOCK check table(s) only up to the given block number\n"));
1206  printf(_("\nB-tree index checking options:\n"));
1207  printf(_(" --heapallindexed check that all heap tuples are found within indexes\n"));
1208  printf(_(" --parent-check check index parent/child relationships\n"));
1209  printf(_(" --rootdescend search from root page to refind tuples\n"));
1210  printf(_(" --checkunique check unique constraint if index is unique\n"));
1211  printf(_("\nConnection options:\n"));
1212  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1213  printf(_(" -p, --port=PORT database server port\n"));
1214  printf(_(" -U, --username=USERNAME user name to connect as\n"));
1215  printf(_(" -w, --no-password never prompt for password\n"));
1216  printf(_(" -W, --password force password prompt\n"));
1217  printf(_(" --maintenance-db=DBNAME alternate maintenance database\n"));
1218  printf(_("\nOther options:\n"));
1219  printf(_(" -e, --echo show the commands being sent to the server\n"));
1220  printf(_(" -j, --jobs=NUM use this many concurrent connections to the server\n"));
1221  printf(_(" -P, --progress show progress information\n"));
1222  printf(_(" -v, --verbose write a lot of output\n"));
1223  printf(_(" -V, --version output version information, then exit\n"));
1224  printf(_(" --install-missing install missing extensions\n"));
1225  printf(_(" -?, --help show this help, then exit\n"));
1226 
1227  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1228  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1229 }
#define _(x)
Definition: elog.c:90
static const char * progname
Definition: pg_amcheck.c:140
#define printf(...)
Definition: port.h:244

References _, printf, and progname.

Referenced by main().

◆ indent_lines()

static char* indent_lines ( const char *  str)
static

Definition at line 1005 of file pg_amcheck.c.

1006 {
1008  const char *c;
1009  char *result;
1010 
1011  initPQExpBuffer(&buf);
1012  appendPQExpBufferStr(&buf, " ");
1013  for (c = str; *c; c++)
1014  {
1016  if (c[0] == '\n' && c[1] != '\0')
1017  appendPQExpBufferStr(&buf, " ");
1018  }
1019  result = pstrdup(buf.data);
1020  termPQExpBuffer(&buf);
1021 
1022  return result;
1023 }
char * c

References appendPQExpBufferChar(), appendPQExpBufferStr(), buf, initPQExpBuffer(), pstrdup(), generate_unaccent_rules::str, and termPQExpBuffer().

Referenced by verify_btree_slot_handler(), and verify_heap_slot_handler().

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 219 of file pg_amcheck.c.

220 {
221  PGconn *conn = NULL;
222  SimplePtrListCell *cell;
223  SimplePtrList databases = {NULL, NULL};
224  SimplePtrList relations = {NULL, NULL};
225  bool failed = false;
226  const char *latest_datname;
227  int parallel_workers;
229  PQExpBufferData sql;
230  uint64 reltotal = 0;
231  uint64 pageschecked = 0;
232  uint64 pagestotal = 0;
233  uint64 relprogress = 0;
234  int pattern_id;
235 
236  static struct option long_options[] = {
237  /* Connection options */
238  {"host", required_argument, NULL, 'h'},
239  {"port", required_argument, NULL, 'p'},
240  {"username", required_argument, NULL, 'U'},
241  {"no-password", no_argument, NULL, 'w'},
242  {"password", no_argument, NULL, 'W'},
243  {"maintenance-db", required_argument, NULL, 1},
244 
245  /* check options */
246  {"all", no_argument, NULL, 'a'},
247  {"database", required_argument, NULL, 'd'},
248  {"exclude-database", required_argument, NULL, 'D'},
249  {"echo", no_argument, NULL, 'e'},
250  {"index", required_argument, NULL, 'i'},
251  {"exclude-index", required_argument, NULL, 'I'},
252  {"jobs", required_argument, NULL, 'j'},
253  {"progress", no_argument, NULL, 'P'},
254  {"relation", required_argument, NULL, 'r'},
255  {"exclude-relation", required_argument, NULL, 'R'},
256  {"schema", required_argument, NULL, 's'},
257  {"exclude-schema", required_argument, NULL, 'S'},
258  {"table", required_argument, NULL, 't'},
259  {"exclude-table", required_argument, NULL, 'T'},
260  {"verbose", no_argument, NULL, 'v'},
261  {"no-dependent-indexes", no_argument, NULL, 2},
262  {"no-dependent-toast", no_argument, NULL, 3},
263  {"exclude-toast-pointers", no_argument, NULL, 4},
264  {"on-error-stop", no_argument, NULL, 5},
265  {"skip", required_argument, NULL, 6},
266  {"startblock", required_argument, NULL, 7},
267  {"endblock", required_argument, NULL, 8},
268  {"rootdescend", no_argument, NULL, 9},
269  {"no-strict-names", no_argument, NULL, 10},
270  {"heapallindexed", no_argument, NULL, 11},
271  {"parent-check", no_argument, NULL, 12},
272  {"install-missing", optional_argument, NULL, 13},
273  {"checkunique", no_argument, NULL, 14},
274 
275  {NULL, 0, NULL, 0}
276  };
277 
278  int optindex;
279  int c;
280 
281  const char *db = NULL;
282  const char *maintenance_db = NULL;
283 
284  const char *host = NULL;
285  const char *port = NULL;
286  const char *username = NULL;
287  enum trivalue prompt_password = TRI_DEFAULT;
288  int encoding = pg_get_encoding_from_locale(NULL, false);
289  ConnParams cparams;
290 
291  pg_logging_init(argv[0]);
292  progname = get_progname(argv[0]);
293  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_amcheck"));
294 
295  handle_help_version_opts(argc, argv, progname, help);
296 
297  /* process command-line options */
298  while ((c = getopt_long(argc, argv, "ad:D:eh:Hi:I:j:p:Pr:R:s:S:t:T:U:vwW",
299  long_options, &optindex)) != -1)
300  {
301  char *endptr;
302  unsigned long optval;
303 
304  switch (c)
305  {
306  case 'a':
307  opts.alldb = true;
308  break;
309  case 'd':
310  opts.dbpattern = true;
312  break;
313  case 'D':
314  opts.dbpattern = true;
316  break;
317  case 'e':
318  opts.echo = true;
319  break;
320  case 'h':
321  host = pg_strdup(optarg);
322  break;
323  case 'i':
324  opts.allrel = false;
326  break;
327  case 'I':
328  opts.excludeidx = true;
330  break;
331  case 'j':
332  if (!option_parse_int(optarg, "-j/--jobs", 1, INT_MAX,
333  &opts.jobs))
334  exit(1);
335  break;
336  case 'p':
337  port = pg_strdup(optarg);
338  break;
339  case 'P':
340  opts.show_progress = true;
341  break;
342  case 'r':
343  opts.allrel = false;
345  break;
346  case 'R':
347  opts.excludeidx = true;
348  opts.excludetbl = true;
350  break;
351  case 's':
352  opts.allrel = false;
354  break;
355  case 'S':
356  opts.excludensp = true;
358  break;
359  case 't':
360  opts.allrel = false;
362  break;
363  case 'T':
364  opts.excludetbl = true;
366  break;
367  case 'U':
369  break;
370  case 'v':
371  opts.verbose = true;
373  break;
374  case 'w':
375  prompt_password = TRI_NO;
376  break;
377  case 'W':
378  prompt_password = TRI_YES;
379  break;
380  case 1:
381  maintenance_db = pg_strdup(optarg);
382  break;
383  case 2:
384  opts.no_btree_expansion = true;
385  break;
386  case 3:
387  opts.no_toast_expansion = true;
388  break;
389  case 4:
390  opts.reconcile_toast = false;
391  break;
392  case 5:
393  opts.on_error_stop = true;
394  break;
395  case 6:
396  if (pg_strcasecmp(optarg, "all-visible") == 0)
397  opts.skip = "all-visible";
398  else if (pg_strcasecmp(optarg, "all-frozen") == 0)
399  opts.skip = "all-frozen";
400  else if (pg_strcasecmp(optarg, "none") == 0)
401  opts.skip = "none";
402  else
403  pg_fatal("invalid argument for option %s", "--skip");
404  break;
405  case 7:
406  errno = 0;
407  optval = strtoul(optarg, &endptr, 10);
408  if (endptr == optarg || *endptr != '\0' || errno != 0)
409  pg_fatal("invalid start block");
410  if (optval > MaxBlockNumber)
411  pg_fatal("start block out of bounds");
412  opts.startblock = optval;
413  break;
414  case 8:
415  errno = 0;
416  optval = strtoul(optarg, &endptr, 10);
417  if (endptr == optarg || *endptr != '\0' || errno != 0)
418  pg_fatal("invalid end block");
419  if (optval > MaxBlockNumber)
420  pg_fatal("end block out of bounds");
421  opts.endblock = optval;
422  break;
423  case 9:
424  opts.rootdescend = true;
425  opts.parent_check = true;
426  break;
427  case 10:
428  opts.strict_names = false;
429  break;
430  case 11:
431  opts.heapallindexed = true;
432  break;
433  case 12:
434  opts.parent_check = true;
435  break;
436  case 13:
437  opts.install_missing = true;
438  if (optarg)
440  break;
441  case 14:
442  opts.checkunique = true;
443  break;
444  default:
445  /* getopt_long already emitted a complaint */
446  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
447  exit(1);
448  }
449  }
450 
451  if (opts.endblock >= 0 && opts.endblock < opts.startblock)
452  pg_fatal("end block precedes start block");
453 
454  /*
455  * A single non-option arguments specifies a database name or connection
456  * string.
457  */
458  if (optind < argc)
459  {
460  db = argv[optind];
461  optind++;
462  }
463 
464  if (optind < argc)
465  {
466  pg_log_error("too many command-line arguments (first is \"%s\")",
467  argv[optind]);
468  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
469  exit(1);
470  }
471 
472  /* fill cparams except for dbname, which is set below */
473  cparams.pghost = host;
474  cparams.pgport = port;
475  cparams.pguser = username;
476  cparams.prompt_password = prompt_password;
477  cparams.dbname = NULL;
478  cparams.override_dbname = NULL;
479 
480  setup_cancel_handler(NULL);
481 
482  /* choose the database for our initial connection */
483  if (opts.alldb)
484  {
485  if (db != NULL)
486  pg_fatal("cannot specify a database name with --all");
487  cparams.dbname = maintenance_db;
488  }
489  else if (db != NULL)
490  {
491  if (opts.dbpattern)
492  pg_fatal("cannot specify both a database name and database patterns");
493  cparams.dbname = db;
494  }
495 
496  if (opts.alldb || opts.dbpattern)
497  {
499  compile_database_list(conn, &databases, NULL);
500  }
501  else
502  {
503  if (cparams.dbname == NULL)
504  {
505  if (getenv("PGDATABASE"))
506  cparams.dbname = getenv("PGDATABASE");
507  else if (getenv("PGUSER"))
508  cparams.dbname = getenv("PGUSER");
509  else
511  }
512  conn = connectDatabase(&cparams, progname, opts.echo, false, true);
513  compile_database_list(conn, &databases, PQdb(conn));
514  }
515 
516  if (databases.head == NULL)
517  {
518  if (conn != NULL)
520  pg_log_warning("no databases to check");
521  exit(0);
522  }
523 
524  /*
525  * Compile a list of all relations spanning all databases to be checked.
526  */
527  for (cell = databases.head; cell; cell = cell->next)
528  {
529  PGresult *result;
530  int ntups;
531  const char *amcheck_schema = NULL;
532  DatabaseInfo *dat = (DatabaseInfo *) cell->ptr;
533 
534  cparams.override_dbname = dat->datname;
535  if (conn == NULL || strcmp(PQdb(conn), dat->datname) != 0)
536  {
537  if (conn != NULL)
539  conn = connectDatabase(&cparams, progname, opts.echo, false, true);
540  }
541 
542  /*
543  * Optionally install amcheck if not already installed in this
544  * database.
545  */
546  if (opts.install_missing)
547  {
548  char *schema;
549  char *install_sql;
550 
551  /*
552  * Must re-escape the schema name for each database, as the
553  * escaping rules may change.
554  */
556  strlen(opts.install_schema));
557  install_sql = psprintf("CREATE EXTENSION IF NOT EXISTS amcheck WITH SCHEMA %s",
558  schema);
559 
560  executeCommand(conn, install_sql, opts.echo);
561  pfree(install_sql);
562  pfree(schema);
563  }
564 
565  /*
566  * Verify that amcheck is installed for this next database. User
567  * error could result in a database not having amcheck that should
568  * have it, but we also could be iterating over multiple databases
569  * where not all of them have amcheck installed (for example,
570  * 'template1').
571  */
572  result = executeQuery(conn, amcheck_sql, opts.echo);
573  if (PQresultStatus(result) != PGRES_TUPLES_OK)
574  {
575  /* Querying the catalog failed. */
576  pg_log_error("database \"%s\": %s",
578  pg_log_error_detail("Query was: %s", amcheck_sql);
579  PQclear(result);
581  exit(1);
582  }
583  ntups = PQntuples(result);
584  if (ntups == 0)
585  {
586  /* Querying the catalog succeeded, but amcheck is missing. */
587  pg_log_warning("skipping database \"%s\": amcheck is not installed",
588  PQdb(conn));
590  conn = NULL;
591  continue;
592  }
593  amcheck_schema = PQgetvalue(result, 0, 0);
594  if (opts.verbose)
595  pg_log_info("in database \"%s\": using amcheck version \"%s\" in schema \"%s\"",
596  PQdb(conn), PQgetvalue(result, 0, 1), amcheck_schema);
597  dat->amcheck_schema = PQescapeIdentifier(conn, amcheck_schema,
598  strlen(amcheck_schema));
599 
600  /*
601  * Check the version of amcheck extension. Skip requested unique
602  * constraint check with warning if it is not yet supported by
603  * amcheck.
604  */
605  if (opts.checkunique == true)
606  {
607  /*
608  * Now amcheck has only major and minor versions in the string but
609  * we also support revision just in case. Now it is expected to be
610  * zero.
611  */
612  int vmaj = 0,
613  vmin = 0,
614  vrev = 0;
615  const char *amcheck_version = PQgetvalue(result, 0, 1);
616 
617  sscanf(amcheck_version, "%d.%d.%d", &vmaj, &vmin, &vrev);
618 
619  /*
620  * checkunique option is supported in amcheck since version 1.4
621  */
622  if ((vmaj == 1 && vmin < 4) || vmaj == 0)
623  {
624  pg_log_warning("--checkunique option is not supported by amcheck "
625  "version \"%s\"", amcheck_version);
626  dat->is_checkunique = false;
627  }
628  else
629  dat->is_checkunique = true;
630  }
631 
632  PQclear(result);
633 
634  compile_relation_list_one_db(conn, &relations, dat, &pagestotal);
635  }
636 
637  /*
638  * Check that all inclusion patterns matched at least one schema or
639  * relation that we can check.
640  */
641  for (pattern_id = 0; pattern_id < opts.include.len; pattern_id++)
642  {
643  PatternInfo *pat = &opts.include.data[pattern_id];
644 
645  if (!pat->matched && (pat->nsp_regex != NULL || pat->rel_regex != NULL))
646  {
647  failed = opts.strict_names;
648 
649  if (pat->heap_only)
650  log_no_match("no heap tables to check matching \"%s\"",
651  pat->pattern);
652  else if (pat->btree_only)
653  log_no_match("no btree indexes to check matching \"%s\"",
654  pat->pattern);
655  else if (pat->rel_regex == NULL)
656  log_no_match("no relations to check in schemas matching \"%s\"",
657  pat->pattern);
658  else
659  log_no_match("no relations to check matching \"%s\"",
660  pat->pattern);
661  }
662  }
663 
664  if (failed)
665  {
666  if (conn != NULL)
668  exit(1);
669  }
670 
671  /*
672  * Set parallel_workers to the lesser of opts.jobs and the number of
673  * relations.
674  */
675  parallel_workers = 0;
676  for (cell = relations.head; cell; cell = cell->next)
677  {
678  reltotal++;
679  if (parallel_workers < opts.jobs)
680  parallel_workers++;
681  }
682 
683  if (reltotal == 0)
684  {
685  if (conn != NULL)
687  pg_fatal("no relations to check");
688  }
689  progress_report(reltotal, relprogress, pagestotal, pageschecked,
690  NULL, true, false);
691 
692  /*
693  * Main event loop.
694  *
695  * We use server-side parallelism to check up to parallel_workers
696  * relations in parallel. The list of relations was computed in database
697  * order, which minimizes the number of connects and disconnects as we
698  * process the list.
699  */
700  latest_datname = NULL;
701  sa = ParallelSlotsSetup(parallel_workers, &cparams, progname, opts.echo,
702  NULL);
703  if (conn != NULL)
704  {
706  conn = NULL;
707  }
708 
709  initPQExpBuffer(&sql);
710  for (relprogress = 0, cell = relations.head; cell; cell = cell->next)
711  {
712  ParallelSlot *free_slot;
713  RelationInfo *rel;
714 
715  rel = (RelationInfo *) cell->ptr;
716 
718  {
719  failed = true;
720  break;
721  }
722 
723  /*
724  * The list of relations is in database sorted order. If this next
725  * relation is in a different database than the last one seen, we are
726  * about to start checking this database. Note that other slots may
727  * still be working on relations from prior databases.
728  */
729  latest_datname = rel->datinfo->datname;
730 
731  progress_report(reltotal, relprogress, pagestotal, pageschecked,
732  latest_datname, false, false);
733 
734  relprogress++;
735  pageschecked += rel->blocks_to_check;
736 
737  /*
738  * Get a parallel slot for the next amcheck command, blocking if
739  * necessary until one is available, or until a previously issued slot
740  * command fails, indicating that we should abort checking the
741  * remaining objects.
742  */
743  free_slot = ParallelSlotsGetIdle(sa, rel->datinfo->datname);
744  if (!free_slot)
745  {
746  /*
747  * Something failed. We don't need to know what it was, because
748  * the handler should already have emitted the necessary error
749  * messages.
750  */
751  failed = true;
752  break;
753  }
754 
755  if (opts.verbose)
757 
758  /*
759  * Execute the appropriate amcheck command for this relation using our
760  * slot's database connection. We do not wait for the command to
761  * complete, nor do we perform any error checking, as that is done by
762  * the parallel slots and our handler callback functions.
763  */
764  if (rel->is_heap)
765  {
766  if (opts.verbose)
767  {
769  fprintf(stderr, "\n");
770  pg_log_info("checking heap table \"%s.%s.%s\"",
771  rel->datinfo->datname, rel->nspname, rel->relname);
773  }
774  prepare_heap_command(&sql, rel, free_slot->connection);
775  rel->sql = pstrdup(sql.data); /* pg_free'd after command */
777  run_command(free_slot, rel->sql);
778  }
779  else
780  {
781  if (opts.verbose)
782  {
784  fprintf(stderr, "\n");
785 
786  pg_log_info("checking btree index \"%s.%s.%s\"",
787  rel->datinfo->datname, rel->nspname, rel->relname);
789  }
790  prepare_btree_command(&sql, rel, free_slot->connection);
791  rel->sql = pstrdup(sql.data); /* pg_free'd after command */
793  run_command(free_slot, rel->sql);
794  }
795  }
796  termPQExpBuffer(&sql);
797 
798  if (!failed)
799  {
800 
801  /*
802  * Wait for all slots to complete, or for one to indicate that an
803  * error occurred. Like above, we rely on the handler emitting the
804  * necessary error messages.
805  */
807  failed = true;
808 
809  progress_report(reltotal, relprogress, pagestotal, pageschecked, NULL, true, true);
810  }
811 
812  if (sa)
813  {
816  }
817 
818  if (failed)
819  exit(1);
820 
821  if (!all_checks_pass)
822  exit(2);
823 }
#define MaxBlockNumber
Definition: block.h:35
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1201
volatile sig_atomic_t CancelRequested
Definition: cancel.c:59
void setup_cancel_handler(void(*query_cancel_callback)(void))
Definition: cancel.c:183
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:448
PGconn * connectMaintenanceDatabase(ConnParams *cparams, const char *progname, bool echo)
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7086
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4270
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:60
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
#define optional_argument
Definition: getopt_long.h:26
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:132
void pg_logging_increase_verbosity(void)
Definition: logging.c:182
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_log_error_hint(...)
Definition: logging.h:112
void pfree(void *pointer)
Definition: mcxt.c:1508
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
void handle_help_version_opts(int argc, char *argv[], const char *fixed_progname, help_handler hlp)
Definition: option_utils.c:24
ParallelSlot * ParallelSlotsGetIdle(ParallelSlotArray *sa, const char *dbname)
bool ParallelSlotsWaitCompletion(ParallelSlotArray *sa)
ParallelSlotArray * ParallelSlotsSetup(int numslots, ConnParams *cparams, const char *progname, bool echo, const char *initcmd)
void ParallelSlotsTerminate(ParallelSlotArray *sa)
void ParallelSlotsAdoptConn(ParallelSlotArray *sa, PGconn *conn)
static void ParallelSlotSetHandler(ParallelSlot *slot, ParallelSlotResultHandler handler, void *context)
Definition: parallel_slot.h:47
static void progress_report(uint64 relations_total, uint64 relations_checked, uint64 relpages_total, uint64 relpages_checked, const char *datname, bool force, bool finished)
Definition: pg_amcheck.c:1241
static void compile_database_list(PGconn *conn, SimplePtrList *databases, const char *initial_dbname)
Definition: pg_amcheck.c:1582
static void prepare_btree_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
Definition: pg_amcheck.c:881
static void help(const char *progname)
Definition: pg_amcheck.c:1180
static void append_database_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1355
static bool verify_heap_slot_handler(PGresult *res, PGconn *conn, void *context)
Definition: pg_amcheck.c:1036
#define FREE_AND_SET_NULL(x)
Definition: pg_amcheck.c:213
static const char *const amcheck_sql
Definition: pg_amcheck.c:172
static void run_command(ParallelSlot *slot, const char *sql)
Definition: pg_amcheck.c:930
static void append_heap_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1493
static void append_schema_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1385
static bool verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
Definition: pg_amcheck.c:1117
static bool progress_since_last_stderr
Definition: pg_amcheck.c:147
static void append_relation_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1477
static void prepare_heap_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
Definition: pg_amcheck.c:841
static bool all_checks_pass
Definition: pg_amcheck.c:143
static void compile_relation_list_one_db(PGconn *conn, SimplePtrList *relations, const DatabaseInfo *dat, uint64 *pagecount)
Definition: pg_amcheck.c:1882
static void append_btree_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1509
static PGconn * connectDatabase(const char *dbname, const char *connection_string, const char *pghost, const char *pgport, const char *pguser, trivalue prompt_password, bool fail_on_error)
Definition: pg_dumpall.c:1662
static void executeCommand(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1905
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
static int port
Definition: pg_regress.c:116
const char * username
Definition: pgbench.c:296
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * get_progname(const char *argv0)
Definition: path.c:574
#define fprintf
Definition: port.h:242
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool install_missing
Definition: pg_amcheck.c:68
char * install_schema
Definition: pg_amcheck.c:69
bool reconcile_toast
Definition: pg_amcheck.c:95
bool show_progress
Definition: pg_amcheck.c:61
bool on_error_stop
Definition: pg_amcheck.c:96
bool heapallindexed
Definition: pg_amcheck.c:104
const char * skip
Definition: pg_amcheck.c:99
char * amcheck_schema
Definition: pg_amcheck.c:152
bool is_checkunique
Definition: pg_amcheck.c:153
PGconn * connection
Definition: parallel_slot.h:23
char * sql
Definition: pg_amcheck.c:165
struct SimplePtrListCell * next
Definition: simple_list.h:48
SimplePtrListCell * head
Definition: simple_list.h:54
const char * pguser
Definition: connect_utils.h:31
char * override_dbname
Definition: pg_backup.h:91
char * pgport
Definition: pg_backup.h:85
char * pghost
Definition: pg_backup.h:86
char * dbname
Definition: pg_backup.h:84
enum trivalue prompt_password
Definition: connect_utils.h:32
const char * get_user_name_or_exit(const char *progname)
Definition: username.c:74
trivalue
Definition: vacuumlo.c:35
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_DEFAULT
Definition: vacuumlo.c:36
@ TRI_NO
Definition: vacuumlo.c:37

References all_checks_pass, AmcheckOptions::alldb, AmcheckOptions::allrel, DatabaseInfo::amcheck_schema, amcheck_sql, append_btree_pattern(), append_database_pattern(), append_heap_pattern(), append_relation_pattern(), append_schema_pattern(), RelationInfo::blocks_to_check, PatternInfo::btree_only, CancelRequested, AmcheckOptions::checkunique, compile_database_list(), compile_relation_list_one_db(), conn, connectDatabase(), ParallelSlot::connection, connectMaintenanceDatabase(), PatternInfoArray::data, PQExpBufferData::data, RelationInfo::datinfo, DatabaseInfo::datname, _connParams::dbname, AmcheckOptions::dbpattern, disconnectDatabase(), AmcheckOptions::echo, encoding, AmcheckOptions::endblock, AmcheckOptions::exclude, AmcheckOptions::excludeidx, AmcheckOptions::excludensp, AmcheckOptions::excludetbl, executeCommand(), executeQuery(), exit(), fprintf, FREE_AND_SET_NULL, get_progname(), get_user_name_or_exit(), getopt_long(), handle_help_version_opts(), SimplePtrList::head, PatternInfo::heap_only, AmcheckOptions::heapallindexed, help(), if(), AmcheckOptions::include, initPQExpBuffer(), AmcheckOptions::install_missing, AmcheckOptions::install_schema, DatabaseInfo::is_checkunique, RelationInfo::is_heap, AmcheckOptions::jobs, PatternInfoArray::len, log_no_match, PatternInfo::matched, MaxBlockNumber, SimplePtrListCell::next, no_argument, AmcheckOptions::no_btree_expansion, AmcheckOptions::no_toast_expansion, PatternInfo::nsp_regex, RelationInfo::nspname, AmcheckOptions::on_error_stop, optarg, optind, option_parse_int(), optional_argument, opts, _connParams::override_dbname, ParallelSlotsAdoptConn(), ParallelSlotSetHandler(), ParallelSlotsGetIdle(), ParallelSlotsSetup(), ParallelSlotsTerminate(), ParallelSlotsWaitCompletion(), AmcheckOptions::parent_check, PatternInfo::pattern, pfree(), pg_fatal, pg_get_encoding_from_locale(), pg_log_error, pg_log_error_detail, pg_log_error_hint, pg_log_info, pg_log_warning, pg_logging_increase_verbosity(), pg_logging_init(), pg_strcasecmp(), pg_strdup(), PG_TEXTDOMAIN, _connParams::pghost, _connParams::pgport, PGRES_TUPLES_OK, _connParams::pguser, port, PQclear(), PQdb(), PQerrorMessage(), PQERRORS_VERBOSE, PQescapeIdentifier(), PQgetvalue(), PQntuples(), PQresultStatus(), PQsetErrorVerbosity(), prepare_btree_command(), prepare_heap_command(), progname, progress_report(), progress_since_last_stderr, _connParams::prompt_password, psprintf(), pstrdup(), SimplePtrListCell::ptr, AmcheckOptions::reconcile_toast, PatternInfo::rel_regex, RelationInfo::relname, required_argument, AmcheckOptions::rootdescend, run_command(), set_pglocale_pgservice(), setup_cancel_handler(), AmcheckOptions::show_progress, AmcheckOptions::skip, RelationInfo::sql, AmcheckOptions::startblock, AmcheckOptions::strict_names, termPQExpBuffer(), TRI_DEFAULT, TRI_NO, TRI_YES, username, AmcheckOptions::verbose, verify_btree_slot_handler(), and verify_heap_slot_handler().

◆ prepare_btree_command()

static void prepare_btree_command ( PQExpBuffer  sql,
RelationInfo rel,
PGconn conn 
)
static

Definition at line 881 of file pg_amcheck.c.

882 {
883  resetPQExpBuffer(sql);
884 
885  if (opts.parent_check)
886  appendPQExpBuffer(sql,
887  "SELECT %s.bt_index_parent_check("
888  "index := c.oid, heapallindexed := %s, rootdescend := %s "
889  "%s)"
890  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_index i "
891  "WHERE c.oid = %u "
892  "AND c.oid = i.indexrelid "
893  "AND c.relpersistence != 't' "
894  "AND i.indisready AND i.indisvalid AND i.indislive",
895  rel->datinfo->amcheck_schema,
896  (opts.heapallindexed ? "true" : "false"),
897  (opts.rootdescend ? "true" : "false"),
898  (rel->datinfo->is_checkunique ? ", checkunique := true" : ""),
899  rel->reloid);
900  else
901  appendPQExpBuffer(sql,
902  "SELECT %s.bt_index_check("
903  "index := c.oid, heapallindexed := %s "
904  "%s)"
905  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_index i "
906  "WHERE c.oid = %u "
907  "AND c.oid = i.indexrelid "
908  "AND c.relpersistence != 't' "
909  "AND i.indisready AND i.indisvalid AND i.indislive",
910  rel->datinfo->amcheck_schema,
911  (opts.heapallindexed ? "true" : "false"),
912  (rel->datinfo->is_checkunique ? ", checkunique := true" : ""),
913  rel->reloid);
914 }
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146

References DatabaseInfo::amcheck_schema, appendPQExpBuffer(), RelationInfo::datinfo, AmcheckOptions::heapallindexed, DatabaseInfo::is_checkunique, opts, AmcheckOptions::parent_check, RelationInfo::reloid, resetPQExpBuffer(), and AmcheckOptions::rootdescend.

Referenced by main().

◆ prepare_heap_command()

static void prepare_heap_command ( PQExpBuffer  sql,
RelationInfo rel,
PGconn conn 
)
static

Definition at line 841 of file pg_amcheck.c.

842 {
843  resetPQExpBuffer(sql);
844  appendPQExpBuffer(sql,
845  "SELECT v.blkno, v.offnum, v.attnum, v.msg "
846  "FROM pg_catalog.pg_class c, %s.verify_heapam("
847  "\nrelation := c.oid, on_error_stop := %s, check_toast := %s, skip := '%s'",
848  rel->datinfo->amcheck_schema,
849  opts.on_error_stop ? "true" : "false",
850  opts.reconcile_toast ? "true" : "false",
851  opts.skip);
852 
853  if (opts.startblock >= 0)
854  appendPQExpBuffer(sql, ", startblock := " INT64_FORMAT, opts.startblock);
855  if (opts.endblock >= 0)
856  appendPQExpBuffer(sql, ", endblock := " INT64_FORMAT, opts.endblock);
857 
858  appendPQExpBuffer(sql,
859  "\n) v WHERE c.oid = %u "
860  "AND c.relpersistence != 't'",
861  rel->reloid);
862 }
#define INT64_FORMAT
Definition: c.h:535

References DatabaseInfo::amcheck_schema, appendPQExpBuffer(), RelationInfo::datinfo, AmcheckOptions::endblock, INT64_FORMAT, AmcheckOptions::on_error_stop, opts, AmcheckOptions::reconcile_toast, RelationInfo::reloid, resetPQExpBuffer(), AmcheckOptions::skip, and AmcheckOptions::startblock.

Referenced by main().

◆ progress_report()

static void progress_report ( uint64  relations_total,
uint64  relations_checked,
uint64  relpages_total,
uint64  relpages_checked,
const char *  datname,
bool  force,
bool  finished 
)
static

Definition at line 1241 of file pg_amcheck.c.

1244 {
1245  int percent_rel = 0;
1246  int percent_pages = 0;
1247  char checked_rel[32];
1248  char total_rel[32];
1249  char checked_pages[32];
1250  char total_pages[32];
1251  pg_time_t now;
1252 
1253  if (!opts.show_progress)
1254  return;
1255 
1256  now = time(NULL);
1257  if (now == last_progress_report && !force && !finished)
1258  return; /* Max once per second */
1259 
1261  if (relations_total)
1262  percent_rel = (int) (relations_checked * 100 / relations_total);
1263  if (relpages_total)
1264  percent_pages = (int) (relpages_checked * 100 / relpages_total);
1265 
1266  snprintf(checked_rel, sizeof(checked_rel), UINT64_FORMAT, relations_checked);
1267  snprintf(total_rel, sizeof(total_rel), UINT64_FORMAT, relations_total);
1268  snprintf(checked_pages, sizeof(checked_pages), UINT64_FORMAT, relpages_checked);
1269  snprintf(total_pages, sizeof(total_pages), UINT64_FORMAT, relpages_total);
1270 
1271 #define VERBOSE_DATNAME_LENGTH 35
1272  if (opts.verbose)
1273  {
1274  if (!datname)
1275 
1276  /*
1277  * No datname given, so clear the status line (used for first and
1278  * last call)
1279  */
1280  fprintf(stderr,
1281  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) %*s"),
1282  (int) strlen(total_rel),
1283  checked_rel, total_rel, percent_rel,
1284  (int) strlen(total_pages),
1285  checked_pages, total_pages, percent_pages,
1286  VERBOSE_DATNAME_LENGTH + 2, "");
1287  else
1288  {
1289  bool truncate = (strlen(datname) > VERBOSE_DATNAME_LENGTH);
1290 
1291  fprintf(stderr,
1292  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) (%s%-*.*s)"),
1293  (int) strlen(total_rel),
1294  checked_rel, total_rel, percent_rel,
1295  (int) strlen(total_pages),
1296  checked_pages, total_pages, percent_pages,
1297  /* Prefix with "..." if we do leading truncation */
1298  truncate ? "..." : "",
1301  /* Truncate datname at beginning if it's too long */
1302  truncate ? datname + strlen(datname) - VERBOSE_DATNAME_LENGTH + 3 : datname);
1303  }
1304  }
1305  else
1306  fprintf(stderr,
1307  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%)"),
1308  (int) strlen(total_rel),
1309  checked_rel, total_rel, percent_rel,
1310  (int) strlen(total_pages),
1311  checked_pages, total_pages, percent_pages);
1312 
1313  /*
1314  * Stay on the same line if reporting to a terminal and we're not done
1315  * yet.
1316  */
1317  if (!finished && isatty(fileno(stderr)))
1318  {
1319  fputc('\r', stderr);
1321  }
1322  else
1323  fputc('\n', stderr);
1324 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
#define UINT64_FORMAT
Definition: c.h:536
#define VERBOSE_DATNAME_LENGTH
static pg_time_t last_progress_report
Definition: pg_amcheck.c:146
int64 pg_time_t
Definition: pgtime.h:23
#define snprintf
Definition: port.h:238

References _, datname, fprintf, last_progress_report, now(), opts, progress_since_last_stderr, AmcheckOptions::show_progress, snprintf, UINT64_FORMAT, AmcheckOptions::verbose, and VERBOSE_DATNAME_LENGTH.

Referenced by main(), and write_target_range().

◆ run_command()

static void run_command ( ParallelSlot slot,
const char *  sql 
)
static

Definition at line 930 of file pg_amcheck.c.

931 {
932  if (opts.echo)
933  printf("%s\n", sql);
934 
935  if (PQsendQuery(slot->connection, sql) == 0)
936  {
937  pg_log_error("error sending command to database \"%s\": %s",
938  PQdb(slot->connection),
939  PQerrorMessage(slot->connection));
940  pg_log_error_detail("Command was: %s", sql);
941  exit(1);
942  }
943 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1425

References ParallelSlot::connection, AmcheckOptions::echo, exit(), opts, pg_log_error, pg_log_error_detail, PQdb(), PQerrorMessage(), PQsendQuery(), and printf.

Referenced by main().

◆ should_processing_continue()

static bool should_processing_continue ( PGresult res)
static

Definition at line 962 of file pg_amcheck.c.

963 {
964  const char *severity;
965 
966  switch (PQresultStatus(res))
967  {
968  /* These are expected and ok */
969  case PGRES_COMMAND_OK:
970  case PGRES_TUPLES_OK:
972  break;
973 
974  /* This is expected but requires closer scrutiny */
975  case PGRES_FATAL_ERROR:
977  if (severity == NULL)
978  return false; /* libpq failure, probably lost connection */
979  if (strcmp(severity, "FATAL") == 0)
980  return false;
981  if (strcmp(severity, "PANIC") == 0)
982  return false;
983  break;
984 
985  /* These are unexpected */
986  case PGRES_BAD_RESPONSE:
987  case PGRES_EMPTY_QUERY:
988  case PGRES_COPY_OUT:
989  case PGRES_COPY_IN:
990  case PGRES_COPY_BOTH:
991  case PGRES_SINGLE_TUPLE:
992  case PGRES_PIPELINE_SYNC:
994  return false;
995  }
996  return true;
997 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3426
@ PGRES_COPY_IN
Definition: libpq-fe.h:107
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:112
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:100
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:111
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:113
@ PGRES_COPY_OUT
Definition: libpq-fe.h:106
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:99
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:114
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:108
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:115
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:110
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:55

References PG_DIAG_SEVERITY_NONLOCALIZED, PGRES_BAD_RESPONSE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, PGRES_PIPELINE_ABORTED, PGRES_PIPELINE_SYNC, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PQresultErrorField(), PQresultStatus(), and res.

Referenced by verify_btree_slot_handler(), and verify_heap_slot_handler().

◆ verify_btree_slot_handler()

static bool verify_btree_slot_handler ( PGresult res,
PGconn conn,
void *  context 
)
static

Definition at line 1117 of file pg_amcheck.c.

1118 {
1119  RelationInfo *rel = (RelationInfo *) context;
1120 
1122  {
1123  int ntups = PQntuples(res);
1124 
1125  if (ntups > 1)
1126  {
1127  /*
1128  * We expect the btree checking functions to return one void row
1129  * each, or zero rows if the check was skipped due to the object
1130  * being in the wrong state to be checked, so we should output
1131  * some sort of warning if we get anything more, not because it
1132  * indicates corruption, but because it suggests a mismatch
1133  * between amcheck and pg_amcheck versions.
1134  *
1135  * In conjunction with --progress, anything written to stderr at
1136  * this time would present strangely to the user without an extra
1137  * newline, so we print one. If we were multithreaded, we'd have
1138  * to avoid splitting this across multiple calls, but we're in an
1139  * event loop, so it doesn't matter.
1140  */
1142  fprintf(stderr, "\n");
1143  pg_log_warning("btree index \"%s.%s.%s\": btree checking function returned unexpected number of rows: %d",
1144  rel->datinfo->datname, rel->nspname, rel->relname, ntups);
1145  if (opts.verbose)
1146  pg_log_warning_detail("Query was: %s", rel->sql);
1147  pg_log_warning_hint("Are %s's and amcheck's versions compatible?",
1148  progname);
1150  }
1151  }
1152  else
1153  {
1154  char *msg = indent_lines(PQerrorMessage(conn));
1155 
1156  all_checks_pass = false;
1157  printf(_("btree index \"%s.%s.%s\":\n"),
1158  rel->datinfo->datname, rel->nspname, rel->relname);
1159  printf("%s", msg);
1160  if (opts.verbose)
1161  printf(_("query was: %s\n"), rel->sql);
1162  FREE_AND_SET_NULL(msg);
1163  }
1164 
1165  FREE_AND_SET_NULL(rel->sql);
1166  FREE_AND_SET_NULL(rel->nspname);
1167  FREE_AND_SET_NULL(rel->relname);
1168 
1170 }
#define pg_log_warning_hint(...)
Definition: logging.h:121
#define pg_log_warning_detail(...)
Definition: logging.h:118
static char * indent_lines(const char *str)
Definition: pg_amcheck.c:1005
static bool should_processing_continue(PGresult *res)
Definition: pg_amcheck.c:962

References _, all_checks_pass, conn, RelationInfo::datinfo, DatabaseInfo::datname, fprintf, FREE_AND_SET_NULL, indent_lines(), RelationInfo::nspname, opts, pg_log_warning, pg_log_warning_detail, pg_log_warning_hint, PGRES_TUPLES_OK, PQerrorMessage(), PQntuples(), PQresultStatus(), printf, progname, progress_since_last_stderr, RelationInfo::relname, res, should_processing_continue(), AmcheckOptions::show_progress, RelationInfo::sql, and AmcheckOptions::verbose.

Referenced by main().

◆ verify_heap_slot_handler()

static bool verify_heap_slot_handler ( PGresult res,
PGconn conn,
void *  context 
)
static

Definition at line 1036 of file pg_amcheck.c.

1037 {
1038  RelationInfo *rel = (RelationInfo *) context;
1039 
1041  {
1042  int i;
1043  int ntups = PQntuples(res);
1044 
1045  if (ntups > 0)
1046  all_checks_pass = false;
1047 
1048  for (i = 0; i < ntups; i++)
1049  {
1050  const char *msg;
1051 
1052  /* The message string should never be null, but check */
1053  if (PQgetisnull(res, i, 3))
1054  msg = "NO MESSAGE";
1055  else
1056  msg = PQgetvalue(res, i, 3);
1057 
1058  if (!PQgetisnull(res, i, 2))
1059  printf(_("heap table \"%s.%s.%s\", block %s, offset %s, attribute %s:\n"),
1060  rel->datinfo->datname, rel->nspname, rel->relname,
1061  PQgetvalue(res, i, 0), /* blkno */
1062  PQgetvalue(res, i, 1), /* offnum */
1063  PQgetvalue(res, i, 2)); /* attnum */
1064 
1065  else if (!PQgetisnull(res, i, 1))
1066  printf(_("heap table \"%s.%s.%s\", block %s, offset %s:\n"),
1067  rel->datinfo->datname, rel->nspname, rel->relname,
1068  PQgetvalue(res, i, 0), /* blkno */
1069  PQgetvalue(res, i, 1)); /* offnum */
1070 
1071  else if (!PQgetisnull(res, i, 0))
1072  printf(_("heap table \"%s.%s.%s\", block %s:\n"),
1073  rel->datinfo->datname, rel->nspname, rel->relname,
1074  PQgetvalue(res, i, 0)); /* blkno */
1075 
1076  else
1077  printf(_("heap table \"%s.%s.%s\":\n"),
1078  rel->datinfo->datname, rel->nspname, rel->relname);
1079 
1080  printf(" %s\n", msg);
1081  }
1082  }
1083  else if (PQresultStatus(res) != PGRES_TUPLES_OK)
1084  {
1085  char *msg = indent_lines(PQerrorMessage(conn));
1086 
1087  all_checks_pass = false;
1088  printf(_("heap table \"%s.%s.%s\":\n"),
1089  rel->datinfo->datname, rel->nspname, rel->relname);
1090  printf("%s", msg);
1091  if (opts.verbose)
1092  printf(_("query was: %s\n"), rel->sql);
1093  FREE_AND_SET_NULL(msg);
1094  }
1095 
1096  FREE_AND_SET_NULL(rel->sql);
1097  FREE_AND_SET_NULL(rel->nspname);
1098  FREE_AND_SET_NULL(rel->relname);
1099 
1101 }

References _, all_checks_pass, conn, RelationInfo::datinfo, DatabaseInfo::datname, FREE_AND_SET_NULL, i, indent_lines(), RelationInfo::nspname, opts, PGRES_TUPLES_OK, PQerrorMessage(), PQgetisnull(), PQgetvalue(), PQntuples(), PQresultStatus(), printf, RelationInfo::relname, res, should_processing_continue(), RelationInfo::sql, and AmcheckOptions::verbose.

Referenced by main().

Variable Documentation

◆ all_checks_pass

bool all_checks_pass = true
static

Definition at line 143 of file pg_amcheck.c.

Referenced by main(), verify_btree_slot_handler(), and verify_heap_slot_handler().

◆ amcheck_sql

const char* const amcheck_sql
static
Initial value:
=
"SELECT n.nspname, x.extversion FROM pg_catalog.pg_extension x"
"\nJOIN pg_catalog.pg_namespace n ON x.extnamespace = n.oid"
"\nWHERE x.extname = 'amcheck'"

Definition at line 172 of file pg_amcheck.c.

Referenced by main().

◆ last_progress_report

pg_time_t last_progress_report = 0
static

Definition at line 146 of file pg_amcheck.c.

Referenced by progress_report().

◆ opts

AmcheckOptions opts
static
Initial value:
= {
.dbpattern = false,
.alldb = false,
.echo = false,
.verbose = false,
.strict_names = true,
.show_progress = false,
.jobs = 1,
.install_missing = false,
.install_schema = "pg_catalog",
.include = {NULL, 0},
.exclude = {NULL, 0},
.excludetbl = false,
.excludeidx = false,
.excludensp = false,
.allrel = true,
.no_toast_expansion = false,
.reconcile_toast = true,
.on_error_stop = false,
.startblock = -1,
.endblock = -1,
.skip = "none",
.parent_check = false,
.rootdescend = false,
.heapallindexed = false,
.checkunique = false,
.no_btree_expansion = false
}

Definition at line 111 of file pg_amcheck.c.

Referenced by AlterSubscription(), append_relation_pattern_helper(), append_schema_pattern(), ArchiveEntry(), BloomFillMetapage(), brin_bloom_add_value(), brin_bloom_get_ndistinct(), brin_minmax_multi_add_value(), brin_minmax_multi_get_values(), build_local_reloptions(), compile_database_list(), compile_relation_list_one_db(), copy_connection(), CopyIndexAttOptions(), CreateSubscription(), get_attribute_options(), get_tablespace(), getFormattedTypeName(), initBloomState(), InitDumpOptions(), libpqrcv_check_conninfo(), libpqrcv_get_dbname_from_conninfo(), main(), makeDefaultBloomOptions(), NewDumpOptions(), NewRestoreOptions(), parse_re_flags(), parse_subscription_options(), parse_test_flags(), prepare_btree_command(), prepare_heap_command(), progress_report(), read_restore_filters(), RelationGetIndexAttOptions(), run_command(), sql_exec_dumpalldbs(), sql_exec_dumpalltables(), sql_exec_dumpalltbspc(), sql_exec_searchtables(), verify_btree_slot_handler(), and verify_heap_slot_handler().

◆ progname

const char* progname = NULL
static

Definition at line 140 of file pg_amcheck.c.

Referenced by help(), main(), and verify_btree_slot_handler().

◆ progress_since_last_stderr

bool progress_since_last_stderr = false
static

Definition at line 147 of file pg_amcheck.c.

Referenced by main(), progress_report(), and verify_btree_slot_handler().