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 * 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 210 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:110
#define pg_log_warning(...)
Definition: pgfnames.c:24
bool strict_names
Definition: pg_amcheck.c:60

Definition at line 203 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 1464 of file pg_amcheck.c.

1465 {
1466  append_relation_pattern_helper(pia, pattern, encoding, false, true);
1467 }
static void append_relation_pattern_helper(PatternInfoArray *pia, const char *pattern, int encoding, bool heap_only, bool btree_only)
Definition: pg_amcheck.c:1382
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 1310 of file pg_amcheck.c.

1311 {
1313  int dotcnt;
1315 
1316  initPQExpBuffer(&buf);
1317  patternToSQLRegex(encoding, NULL, NULL, &buf, pattern, false, false,
1318  &dotcnt);
1319  if (dotcnt > 0)
1320  {
1321  pg_log_error("improper qualified name (too many dotted names): %s", pattern);
1322  exit(2);
1323  }
1324  info->pattern = pattern;
1325  info->db_regex = pstrdup(buf.data);
1326 
1327  termPQExpBuffer(&buf);
1328 }
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
char * pstrdup(const char *in)
Definition: mcxt.c:1624
static PatternInfo * extend_pattern_info_array(PatternInfoArray *pia)
Definition: pg_amcheck.c:1288
static char * buf
Definition: pg_test_fsync.c:67
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 1491 of file pg_amcheck.c.

1493 {
1494  int pattern_id;
1495  const char *comma;
1496  bool have_values;
1497 
1498  comma = "";
1499  have_values = false;
1500  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1501  {
1502  PatternInfo *info = &pia->data[pattern_id];
1503 
1504  if (info->db_regex != NULL &&
1505  (inclusive || (info->nsp_regex == NULL && info->rel_regex == NULL)))
1506  {
1507  if (!have_values)
1508  appendPQExpBufferStr(buf, "\nVALUES");
1509  have_values = true;
1510  appendPQExpBuffer(buf, "%s\n(%d, ", comma, pattern_id);
1512  appendPQExpBufferChar(buf, ')');
1513  comma = ",";
1514  }
1515  }
1516 
1517  if (!have_values)
1518  appendPQExpBufferStr(buf, "\nSELECT NULL, NULL, NULL WHERE false");
1519 
1520  return have_values;
1521 }
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, 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 1448 of file pg_amcheck.c.

1449 {
1450  append_relation_pattern_helper(pia, pattern, encoding, true, false);
1451 }

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 1798 of file pg_amcheck.c.

1800 {
1802  "\n%s (pattern_id, nsp_regex, rel_regex, heap_only, btree_only) AS ("
1803  "\nSELECT pattern_id, nsp_regex, rel_regex, heap_only, btree_only "
1804  "FROM %s r"
1805  "\nWHERE (r.db_regex IS NULL "
1806  "OR ",
1807  filtered, raw);
1809  appendPQExpBufferStr(buf, " ~ r.db_regex)");
1811  " AND (r.nsp_regex IS NOT NULL"
1812  " OR r.rel_regex IS NOT NULL)"
1813  "),");
1814 }
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6589

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 1729 of file pg_amcheck.c.

1731 {
1732  int pattern_id;
1733  const char *comma;
1734  bool have_values;
1735 
1736  comma = "";
1737  have_values = false;
1738  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1739  {
1740  PatternInfo *info = &pia->data[pattern_id];
1741 
1742  if (!have_values)
1743  appendPQExpBufferStr(buf, "\nVALUES");
1744  have_values = true;
1745  appendPQExpBuffer(buf, "%s\n(%d::INTEGER, ", comma, pattern_id);
1746  if (info->db_regex == NULL)
1747  appendPQExpBufferStr(buf, "NULL");
1748  else
1750  appendPQExpBufferStr(buf, "::TEXT, ");
1751  if (info->nsp_regex == NULL)
1752  appendPQExpBufferStr(buf, "NULL");
1753  else
1755  appendPQExpBufferStr(buf, "::TEXT, ");
1756  if (info->rel_regex == NULL)
1757  appendPQExpBufferStr(buf, "NULL");
1758  else
1760  if (info->heap_only)
1761  appendPQExpBufferStr(buf, "::TEXT, true::BOOLEAN");
1762  else
1763  appendPQExpBufferStr(buf, "::TEXT, false::BOOLEAN");
1764  if (info->btree_only)
1765  appendPQExpBufferStr(buf, ", true::BOOLEAN");
1766  else
1767  appendPQExpBufferStr(buf, ", false::BOOLEAN");
1768  appendPQExpBufferChar(buf, ')');
1769  comma = ",";
1770  }
1771 
1772  if (!have_values)
1774  "\nSELECT NULL::INTEGER, NULL::TEXT, NULL::TEXT, "
1775  "NULL::TEXT, NULL::BOOLEAN, NULL::BOOLEAN "
1776  "WHERE false");
1777 }
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, 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 1432 of file pg_amcheck.c.

1433 {
1434  append_relation_pattern_helper(pia, pattern, encoding, false, false);
1435 }

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 1382 of file pg_amcheck.c.

1384 {
1385  PQExpBufferData dbbuf;
1386  PQExpBufferData nspbuf;
1387  PQExpBufferData relbuf;
1388  int dotcnt;
1390 
1391  initPQExpBuffer(&dbbuf);
1392  initPQExpBuffer(&nspbuf);
1393  initPQExpBuffer(&relbuf);
1394 
1395  patternToSQLRegex(encoding, &dbbuf, &nspbuf, &relbuf, pattern, false,
1396  false, &dotcnt);
1397  if (dotcnt > 2)
1398  {
1399  pg_log_error("improper relation 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  if (relbuf.data[0])
1411  info->rel_regex = pstrdup(relbuf.data);
1412 
1413  termPQExpBuffer(&dbbuf);
1414  termPQExpBuffer(&nspbuf);
1415  termPQExpBuffer(&relbuf);
1416 
1417  info->heap_only = heap_only;
1418  info->btree_only = btree_only;
1419 }

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 1340 of file pg_amcheck.c.

1341 {
1342  PQExpBufferData dbbuf;
1343  PQExpBufferData nspbuf;
1344  int dotcnt;
1346 
1347  initPQExpBuffer(&dbbuf);
1348  initPQExpBuffer(&nspbuf);
1349 
1350  patternToSQLRegex(encoding, NULL, &dbbuf, &nspbuf, pattern, false, false,
1351  &dotcnt);
1352  if (dotcnt > 1)
1353  {
1354  pg_log_error("improper qualified name (too many dotted names): %s", pattern);
1355  exit(2);
1356  }
1357  info->pattern = pattern;
1358  if (dbbuf.data[0])
1359  {
1360  opts.dbpattern = true;
1361  info->db_regex = pstrdup(dbbuf.data);
1362  }
1363  if (nspbuf.data[0])
1364  info->nsp_regex = pstrdup(nspbuf.data);
1365 
1366  termPQExpBuffer(&dbbuf);
1367  termPQExpBuffer(&nspbuf);
1368 }

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 1537 of file pg_amcheck.c.

1539 {
1540  PGresult *res;
1541  PQExpBufferData sql;
1542  int ntups;
1543  int i;
1544  bool fatal;
1545 
1546  if (initial_dbname)
1547  {
1548  DatabaseInfo *dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1549 
1550  /* This database is included. Add to list */
1551  if (opts.verbose)
1552  pg_log_info("including database \"%s\"", initial_dbname);
1553 
1554  dat->datname = pstrdup(initial_dbname);
1555  simple_ptr_list_append(databases, dat);
1556  }
1557 
1558  initPQExpBuffer(&sql);
1559 
1560  /* Append the include patterns CTE. */
1561  appendPQExpBufferStr(&sql, "WITH include_raw (pattern_id, rgx) AS (");
1562  if (!append_db_pattern_cte(&sql, &opts.include, conn, true) &&
1563  !opts.alldb)
1564  {
1565  /*
1566  * None of the inclusion patterns (if any) contain database portions,
1567  * so there is no need to query the database to resolve database
1568  * patterns.
1569  *
1570  * Since we're also not operating under --all, we don't need to query
1571  * the exhaustive list of connectable databases, either.
1572  */
1573  termPQExpBuffer(&sql);
1574  return;
1575  }
1576 
1577  /* Append the exclude patterns CTE. */
1578  appendPQExpBufferStr(&sql, "),\nexclude_raw (pattern_id, rgx) AS (");
1579  append_db_pattern_cte(&sql, &opts.exclude, conn, false);
1580  appendPQExpBufferStr(&sql, "),");
1581 
1582  /*
1583  * Append the database CTE, which includes whether each database is
1584  * connectable and also joins against exclude_raw to determine whether
1585  * each database is excluded.
1586  */
1587  appendPQExpBufferStr(&sql,
1588  "\ndatabase (datname) AS ("
1589  "\nSELECT d.datname "
1590  "FROM pg_catalog.pg_database d "
1591  "LEFT OUTER JOIN exclude_raw e "
1592  "ON d.datname ~ e.rgx "
1593  "\nWHERE d.datallowconn "
1594  "AND e.pattern_id IS NULL"
1595  "),"
1596 
1597  /*
1598  * Append the include_pat CTE, which joins the include_raw CTE against the
1599  * databases CTE to determine if all the inclusion patterns had matches,
1600  * and whether each matched pattern had the misfortune of only matching
1601  * excluded or unconnectable databases.
1602  */
1603  "\ninclude_pat (pattern_id, checkable) AS ("
1604  "\nSELECT i.pattern_id, "
1605  "COUNT(*) FILTER ("
1606  "WHERE d IS NOT NULL"
1607  ") AS checkable"
1608  "\nFROM include_raw i "
1609  "LEFT OUTER JOIN database d "
1610  "ON d.datname ~ i.rgx"
1611  "\nGROUP BY i.pattern_id"
1612  "),"
1613 
1614  /*
1615  * Append the filtered_databases CTE, which selects from the database CTE
1616  * optionally joined against the include_raw CTE to only select databases
1617  * that match an inclusion pattern. This appears to duplicate what the
1618  * include_pat CTE already did above, but here we want only databases, and
1619  * there we wanted patterns.
1620  */
1621  "\nfiltered_databases (datname) AS ("
1622  "\nSELECT DISTINCT d.datname "
1623  "FROM database d");
1624  if (!opts.alldb)
1625  appendPQExpBufferStr(&sql,
1626  " INNER JOIN include_raw i "
1627  "ON d.datname ~ i.rgx");
1628  appendPQExpBufferStr(&sql,
1629  ")"
1630 
1631  /*
1632  * Select the checkable databases and the unmatched inclusion patterns.
1633  */
1634  "\nSELECT pattern_id, datname FROM ("
1635  "\nSELECT pattern_id, NULL::TEXT AS datname "
1636  "FROM include_pat "
1637  "WHERE checkable = 0 "
1638  "UNION ALL"
1639  "\nSELECT NULL, datname "
1640  "FROM filtered_databases"
1641  ") AS combined_records"
1642  "\nORDER BY pattern_id NULLS LAST, datname");
1643 
1644  res = executeQuery(conn, sql.data, opts.echo);
1646  {
1647  pg_log_error("query failed: %s", PQerrorMessage(conn));
1648  pg_log_error_detail("Query was: %s", sql.data);
1650  exit(1);
1651  }
1652  termPQExpBuffer(&sql);
1653 
1654  ntups = PQntuples(res);
1655  for (fatal = false, i = 0; i < ntups; i++)
1656  {
1657  int pattern_id = -1;
1658  const char *datname = NULL;
1659 
1660  if (!PQgetisnull(res, i, 0))
1661  pattern_id = atoi(PQgetvalue(res, i, 0));
1662  if (!PQgetisnull(res, i, 1))
1663  datname = PQgetvalue(res, i, 1);
1664 
1665  if (pattern_id >= 0)
1666  {
1667  /*
1668  * Current record pertains to an inclusion pattern that matched no
1669  * checkable databases.
1670  */
1671  fatal = opts.strict_names;
1672  if (pattern_id >= opts.include.len)
1673  pg_fatal("internal error: received unexpected database pattern_id %d",
1674  pattern_id);
1675  log_no_match("no connectable databases to check matching \"%s\"",
1676  opts.include.data[pattern_id].pattern);
1677  }
1678  else
1679  {
1680  DatabaseInfo *dat;
1681 
1682  /* Current record pertains to a database */
1683  Assert(datname != NULL);
1684 
1685  /* Avoid entering a duplicate entry matching the initial_dbname */
1686  if (initial_dbname != NULL && strcmp(initial_dbname, datname) == 0)
1687  continue;
1688 
1689  /* This database is included. Add to list */
1690  if (opts.verbose)
1691  pg_log_info("including database \"%s\"", datname);
1692 
1693  dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1694  dat->datname = pstrdup(datname);
1695  simple_ptr_list_append(databases, dat);
1696  }
1697  }
1698  PQclear(res);
1699 
1700  if (fatal)
1701  {
1702  if (conn != NULL)
1704  exit(1);
1705  }
1706 }
void disconnectDatabase(PGconn *conn)
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6743
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3730
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
int i
Definition: isn.c:73
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
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:203
static bool append_db_pattern_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn, bool inclusive)
Definition: pg_amcheck.c:1491
#define pg_fatal(...)
NameData datname
Definition: pg_database.h:35
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1869
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:149

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 1837 of file pg_amcheck.c.

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

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 1288 of file pg_amcheck.c.

1289 {
1290  PatternInfo *result;
1291 
1292  pia->len++;
1293  pia->data = (PatternInfo *) pg_realloc(pia->data, pia->len * sizeof(PatternInfo));
1294  result = &pia->data[pia->len - 1];
1295  memset(result, 0, sizeof(*result));
1296 
1297  return result;
1298 }
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 1136 of file pg_amcheck.c.

1137 {
1138  printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
1139  printf(_("Usage:\n"));
1140  printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
1141  printf(_("\nTarget options:\n"));
1142  printf(_(" -a, --all check all databases\n"));
1143  printf(_(" -d, --database=PATTERN check matching database(s)\n"));
1144  printf(_(" -D, --exclude-database=PATTERN do NOT check matching database(s)\n"));
1145  printf(_(" -i, --index=PATTERN check matching index(es)\n"));
1146  printf(_(" -I, --exclude-index=PATTERN do NOT check matching index(es)\n"));
1147  printf(_(" -r, --relation=PATTERN check matching relation(s)\n"));
1148  printf(_(" -R, --exclude-relation=PATTERN do NOT check matching relation(s)\n"));
1149  printf(_(" -s, --schema=PATTERN check matching schema(s)\n"));
1150  printf(_(" -S, --exclude-schema=PATTERN do NOT check matching schema(s)\n"));
1151  printf(_(" -t, --table=PATTERN check matching table(s)\n"));
1152  printf(_(" -T, --exclude-table=PATTERN do NOT check matching table(s)\n"));
1153  printf(_(" --no-dependent-indexes do NOT expand list of relations to include indexes\n"));
1154  printf(_(" --no-dependent-toast do NOT expand list of relations to include TOAST tables\n"));
1155  printf(_(" --no-strict-names do NOT require patterns to match objects\n"));
1156  printf(_("\nTable checking options:\n"));
1157  printf(_(" --exclude-toast-pointers do NOT follow relation TOAST pointers\n"));
1158  printf(_(" --on-error-stop stop checking at end of first corrupt page\n"));
1159  printf(_(" --skip=OPTION do NOT check \"all-frozen\" or \"all-visible\" blocks\n"));
1160  printf(_(" --startblock=BLOCK begin checking table(s) at the given block number\n"));
1161  printf(_(" --endblock=BLOCK check table(s) only up to the given block number\n"));
1162  printf(_("\nB-tree index checking options:\n"));
1163  printf(_(" --heapallindexed check that all heap tuples are found within indexes\n"));
1164  printf(_(" --parent-check check index parent/child relationships\n"));
1165  printf(_(" --rootdescend search from root page to refind tuples\n"));
1166  printf(_("\nConnection options:\n"));
1167  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1168  printf(_(" -p, --port=PORT database server port\n"));
1169  printf(_(" -U, --username=USERNAME user name to connect as\n"));
1170  printf(_(" -w, --no-password never prompt for password\n"));
1171  printf(_(" -W, --password force password prompt\n"));
1172  printf(_(" --maintenance-db=DBNAME alternate maintenance database\n"));
1173  printf(_("\nOther options:\n"));
1174  printf(_(" -e, --echo show the commands being sent to the server\n"));
1175  printf(_(" -j, --jobs=NUM use this many concurrent connections to the server\n"));
1176  printf(_(" -P, --progress show progress information\n"));
1177  printf(_(" -v, --verbose write a lot of output\n"));
1178  printf(_(" -V, --version output version information, then exit\n"));
1179  printf(_(" --install-missing install missing extensions\n"));
1180  printf(_(" -?, --help show this help, then exit\n"));
1181 
1182  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1183  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1184 }
#define _(x)
Definition: elog.c:91
static const char * progname
Definition: pg_amcheck.c:138
#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 961 of file pg_amcheck.c.

962 {
964  const char *c;
965  char *result;
966 
968  appendPQExpBufferStr(&buf, " ");
969  for (c = str; *c; c++)
970  {
972  if (c[0] == '\n' && c[1] != '\0')
973  appendPQExpBufferStr(&buf, " ");
974  }
975  result = pstrdup(buf.data);
977 
978  return result;
979 }
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 216 of file pg_amcheck.c.

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

842 {
843  resetPQExpBuffer(sql);
844 
845  if (opts.parent_check)
846  appendPQExpBuffer(sql,
847  "SELECT %s.bt_index_parent_check("
848  "index := c.oid, heapallindexed := %s, rootdescend := %s)"
849  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_index i "
850  "WHERE c.oid = %u "
851  "AND c.oid = i.indexrelid "
852  "AND c.relpersistence != 't' "
853  "AND i.indisready AND i.indisvalid AND i.indislive",
854  rel->datinfo->amcheck_schema,
855  (opts.heapallindexed ? "true" : "false"),
856  (opts.rootdescend ? "true" : "false"),
857  rel->reloid);
858  else
859  appendPQExpBuffer(sql,
860  "SELECT %s.bt_index_check("
861  "index := c.oid, heapallindexed := %s)"
862  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_index i "
863  "WHERE c.oid = %u "
864  "AND c.oid = i.indexrelid "
865  "AND c.relpersistence != 't' "
866  "AND i.indisready AND i.indisvalid AND i.indislive",
867  rel->datinfo->amcheck_schema,
868  (opts.heapallindexed ? "true" : "false"),
869  rel->reloid);
870 }
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146

References DatabaseInfo::amcheck_schema, appendPQExpBuffer(), RelationInfo::datinfo, AmcheckOptions::heapallindexed, 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 801 of file pg_amcheck.c.

802 {
803  resetPQExpBuffer(sql);
804  appendPQExpBuffer(sql,
805  "SELECT v.blkno, v.offnum, v.attnum, v.msg "
806  "FROM pg_catalog.pg_class c, %s.verify_heapam("
807  "\nrelation := c.oid, on_error_stop := %s, check_toast := %s, skip := '%s'",
808  rel->datinfo->amcheck_schema,
809  opts.on_error_stop ? "true" : "false",
810  opts.reconcile_toast ? "true" : "false",
811  opts.skip);
812 
813  if (opts.startblock >= 0)
814  appendPQExpBuffer(sql, ", startblock := " INT64_FORMAT, opts.startblock);
815  if (opts.endblock >= 0)
816  appendPQExpBuffer(sql, ", endblock := " INT64_FORMAT, opts.endblock);
817 
818  appendPQExpBuffer(sql,
819  "\n) v WHERE c.oid = %u "
820  "AND c.relpersistence != 't'",
821  rel->reloid);
822 }
#define INT64_FORMAT
Definition: c.h:532

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 1196 of file pg_amcheck.c.

1199 {
1200  int percent_rel = 0;
1201  int percent_pages = 0;
1202  char checked_rel[32];
1203  char total_rel[32];
1204  char checked_pages[32];
1205  char total_pages[32];
1206  pg_time_t now;
1207 
1208  if (!opts.show_progress)
1209  return;
1210 
1211  now = time(NULL);
1212  if (now == last_progress_report && !force && !finished)
1213  return; /* Max once per second */
1214 
1216  if (relations_total)
1217  percent_rel = (int) (relations_checked * 100 / relations_total);
1218  if (relpages_total)
1219  percent_pages = (int) (relpages_checked * 100 / relpages_total);
1220 
1221  snprintf(checked_rel, sizeof(checked_rel), UINT64_FORMAT, relations_checked);
1222  snprintf(total_rel, sizeof(total_rel), UINT64_FORMAT, relations_total);
1223  snprintf(checked_pages, sizeof(checked_pages), UINT64_FORMAT, relpages_checked);
1224  snprintf(total_pages, sizeof(total_pages), UINT64_FORMAT, relpages_total);
1225 
1226 #define VERBOSE_DATNAME_LENGTH 35
1227  if (opts.verbose)
1228  {
1229  if (!datname)
1230 
1231  /*
1232  * No datname given, so clear the status line (used for first and
1233  * last call)
1234  */
1235  fprintf(stderr,
1236  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) %*s"),
1237  (int) strlen(total_rel),
1238  checked_rel, total_rel, percent_rel,
1239  (int) strlen(total_pages),
1240  checked_pages, total_pages, percent_pages,
1241  VERBOSE_DATNAME_LENGTH + 2, "");
1242  else
1243  {
1244  bool truncate = (strlen(datname) > VERBOSE_DATNAME_LENGTH);
1245 
1246  fprintf(stderr,
1247  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) (%s%-*.*s)"),
1248  (int) strlen(total_rel),
1249  checked_rel, total_rel, percent_rel,
1250  (int) strlen(total_pages),
1251  checked_pages, total_pages, percent_pages,
1252  /* Prefix with "..." if we do leading truncation */
1253  truncate ? "..." : "",
1256  /* Truncate datname at beginning if it's too long */
1257  truncate ? datname + strlen(datname) - VERBOSE_DATNAME_LENGTH + 3 : datname);
1258  }
1259  }
1260  else
1261  fprintf(stderr,
1262  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%)"),
1263  (int) strlen(total_rel),
1264  checked_rel, total_rel, percent_rel,
1265  (int) strlen(total_pages),
1266  checked_pages, total_pages, percent_pages);
1267 
1268  /*
1269  * Stay on the same line if reporting to a terminal and we're not done
1270  * yet.
1271  */
1272  if (!finished && isatty(fileno(stderr)))
1273  {
1274  fputc('\r', stderr);
1276  }
1277  else
1278  fputc('\n', stderr);
1279 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1549
#define UINT64_FORMAT
Definition: c.h:533
#define VERBOSE_DATNAME_LENGTH
static pg_time_t last_progress_report
Definition: pg_amcheck.c:144
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 886 of file pg_amcheck.c.

887 {
888  if (opts.echo)
889  printf("%s\n", sql);
890 
891  if (PQsendQuery(slot->connection, sql) == 0)
892  {
893  pg_log_error("error sending command to database \"%s\": %s",
894  PQdb(slot->connection),
895  PQerrorMessage(slot->connection));
896  pg_log_error_detail("Command was: %s", sql);
897  exit(1);
898  }
899 }
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1418

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 918 of file pg_amcheck.c.

919 {
920  const char *severity;
921 
922  switch (PQresultStatus(res))
923  {
924  /* These are expected and ok */
925  case PGRES_COMMAND_OK:
926  case PGRES_TUPLES_OK:
928  break;
929 
930  /* This is expected but requires closer scrutiny */
931  case PGRES_FATAL_ERROR:
933  if (severity == NULL)
934  return false; /* libpq failure, probably lost connection */
935  if (strcmp(severity, "FATAL") == 0)
936  return false;
937  if (strcmp(severity, "PANIC") == 0)
938  return false;
939  break;
940 
941  /* These are unexpected */
942  case PGRES_BAD_RESPONSE:
943  case PGRES_EMPTY_QUERY:
944  case PGRES_COPY_OUT:
945  case PGRES_COPY_IN:
946  case PGRES_COPY_BOTH:
947  case PGRES_SINGLE_TUPLE:
948  case PGRES_PIPELINE_SYNC:
950  return false;
951  }
952  return true;
953 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3295
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:110
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:105
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
#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 1073 of file pg_amcheck.c.

1074 {
1075  RelationInfo *rel = (RelationInfo *) context;
1076 
1078  {
1079  int ntups = PQntuples(res);
1080 
1081  if (ntups > 1)
1082  {
1083  /*
1084  * We expect the btree checking functions to return one void row
1085  * each, or zero rows if the check was skipped due to the object
1086  * being in the wrong state to be checked, so we should output
1087  * some sort of warning if we get anything more, not because it
1088  * indicates corruption, but because it suggests a mismatch
1089  * between amcheck and pg_amcheck versions.
1090  *
1091  * In conjunction with --progress, anything written to stderr at
1092  * this time would present strangely to the user without an extra
1093  * newline, so we print one. If we were multithreaded, we'd have
1094  * to avoid splitting this across multiple calls, but we're in an
1095  * event loop, so it doesn't matter.
1096  */
1098  fprintf(stderr, "\n");
1099  pg_log_warning("btree index \"%s.%s.%s\": btree checking function returned unexpected number of rows: %d",
1100  rel->datinfo->datname, rel->nspname, rel->relname, ntups);
1101  if (opts.verbose)
1102  pg_log_warning_detail("Query was: %s", rel->sql);
1103  pg_log_warning_hint("Are %s's and amcheck's versions compatible?",
1104  progname);
1106  }
1107  }
1108  else
1109  {
1110  char *msg = indent_lines(PQerrorMessage(conn));
1111 
1112  all_checks_pass = false;
1113  printf(_("btree index \"%s.%s.%s\":\n"),
1114  rel->datinfo->datname, rel->nspname, rel->relname);
1115  printf("%s", msg);
1116  if (opts.verbose)
1117  printf(_("query was: %s\n"), rel->sql);
1118  FREE_AND_SET_NULL(msg);
1119  }
1120 
1121  FREE_AND_SET_NULL(rel->sql);
1122  FREE_AND_SET_NULL(rel->nspname);
1123  FREE_AND_SET_NULL(rel->relname);
1124 
1126 }
#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:961
static bool should_processing_continue(PGresult *res)
Definition: pg_amcheck.c:918

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 992 of file pg_amcheck.c.

993 {
994  RelationInfo *rel = (RelationInfo *) context;
995 
997  {
998  int i;
999  int ntups = PQntuples(res);
1000 
1001  if (ntups > 0)
1002  all_checks_pass = false;
1003 
1004  for (i = 0; i < ntups; i++)
1005  {
1006  const char *msg;
1007 
1008  /* The message string should never be null, but check */
1009  if (PQgetisnull(res, i, 3))
1010  msg = "NO MESSAGE";
1011  else
1012  msg = PQgetvalue(res, i, 3);
1013 
1014  if (!PQgetisnull(res, i, 2))
1015  printf(_("heap table \"%s.%s.%s\", block %s, offset %s, attribute %s:\n"),
1016  rel->datinfo->datname, rel->nspname, rel->relname,
1017  PQgetvalue(res, i, 0), /* blkno */
1018  PQgetvalue(res, i, 1), /* offnum */
1019  PQgetvalue(res, i, 2)); /* attnum */
1020 
1021  else if (!PQgetisnull(res, i, 1))
1022  printf(_("heap table \"%s.%s.%s\", block %s, offset %s:\n"),
1023  rel->datinfo->datname, rel->nspname, rel->relname,
1024  PQgetvalue(res, i, 0), /* blkno */
1025  PQgetvalue(res, i, 1)); /* offnum */
1026 
1027  else if (!PQgetisnull(res, i, 0))
1028  printf(_("heap table \"%s.%s.%s\", block %s:\n"),
1029  rel->datinfo->datname, rel->nspname, rel->relname,
1030  PQgetvalue(res, i, 0)); /* blkno */
1031 
1032  else
1033  printf(_("heap table \"%s.%s.%s\":\n"),
1034  rel->datinfo->datname, rel->nspname, rel->relname);
1035 
1036  printf(" %s\n", msg);
1037  }
1038  }
1039  else if (PQresultStatus(res) != PGRES_TUPLES_OK)
1040  {
1041  char *msg = indent_lines(PQerrorMessage(conn));
1042 
1043  all_checks_pass = false;
1044  printf(_("heap table \"%s.%s.%s\":\n"),
1045  rel->datinfo->datname, rel->nspname, rel->relname);
1046  printf("%s", msg);
1047  if (opts.verbose)
1048  printf(_("query was: %s\n"), rel->sql);
1049  FREE_AND_SET_NULL(msg);
1050  }
1051 
1052  FREE_AND_SET_NULL(rel->sql);
1053  FREE_AND_SET_NULL(rel->nspname);
1054  FREE_AND_SET_NULL(rel->relname);
1055 
1057 }

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 141 of file pg_amcheck.c.

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

◆ amcheck_sql

const char* 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 169 of file pg_amcheck.c.

Referenced by main().

◆ last_progress_report

pg_time_t last_progress_report = 0
static

Definition at line 144 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,
.no_btree_expansion = false
}

Definition at line 110 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(), CopyIndexAttOptions(), CreateSubscription(), get_attribute_options(), get_tablespace(), getFormattedTypeName(), initBloomState(), InitDumpOptions(), libpqrcv_check_conninfo(), main(), makeDefaultBloomOptions(), NewDumpOptions(), NewRestoreOptions(), parse_re_flags(), parse_subscription_options(), parse_test_flags(), prepare_btree_command(), prepare_heap_command(), progress_report(), 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 138 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 145 of file pg_amcheck.c.

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