PostgreSQL Source Code  git master
pg_amcheck.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_amcheck.c
4  * Detects corruption within database relations.
5  *
6  * Copyright (c) 2017-2022, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * src/bin/pg_amcheck/pg_amcheck.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 #include "postgres_fe.h"
14 
15 #include <limits.h>
16 #include <time.h>
17 
18 #include "catalog/pg_am_d.h"
19 #include "catalog/pg_namespace_d.h"
20 #include "common/logging.h"
21 #include "common/username.h"
22 #include "fe_utils/cancel.h"
23 #include "fe_utils/option_utils.h"
24 #include "fe_utils/parallel_slot.h"
25 #include "fe_utils/query_utils.h"
26 #include "fe_utils/simple_list.h"
27 #include "fe_utils/string_utils.h"
28 #include "getopt_long.h" /* pgrminclude ignore */
29 #include "pgtime.h"
30 #include "storage/block.h"
31 
32 typedef struct PatternInfo
33 {
34  const char *pattern; /* Unaltered pattern from the command line */
35  char *db_regex; /* Database regexp parsed from pattern, or
36  * NULL */
37  char *nsp_regex; /* Schema regexp parsed from pattern, or NULL */
38  char *rel_regex; /* Relation regexp parsed from pattern, or
39  * NULL */
40  bool heap_only; /* true if rel_regex should only match heap
41  * tables */
42  bool btree_only; /* true if rel_regex should only match btree
43  * indexes */
44  bool matched; /* true if the pattern matched in any database */
46 
47 typedef struct PatternInfoArray
48 {
50  size_t len;
52 
53 /* pg_amcheck command line options controlled by user flags */
54 typedef struct AmcheckOptions
55 {
56  bool dbpattern;
57  bool alldb;
58  bool echo;
59  bool verbose;
62  int jobs;
63 
64  /*
65  * Whether to install missing extensions, and optionally the name of the
66  * schema in which to install the extension's objects.
67  */
70 
71  /* Objects to check or not to check, as lists of PatternInfo structs. */
74 
75  /*
76  * As an optimization, if any pattern in the exclude list applies to heap
77  * tables, or similarly if any such pattern applies to btree indexes, or
78  * to schemas, then these will be true, otherwise false. These should
79  * always agree with what you'd conclude by grep'ing through the exclude
80  * list.
81  */
82  bool excludetbl;
83  bool excludeidx;
84  bool excludensp;
85 
86  /*
87  * If any inclusion pattern exists, then we should only be checking
88  * matching relations rather than all relations, so this is true iff
89  * include is empty.
90  */
91  bool allrel;
92 
93  /* heap table checking options */
97  int64 startblock;
98  int64 endblock;
99  const char *skip;
100 
101  /* btree index checking options */
105 
106  /* heap and btree hybrid option */
109 
111  .dbpattern = false,
112  .alldb = false,
113  .echo = false,
114  .verbose = false,
115  .strict_names = true,
116  .show_progress = false,
117  .jobs = 1,
118  .install_missing = false,
119  .install_schema = "pg_catalog",
120  .include = {NULL, 0},
121  .exclude = {NULL, 0},
122  .excludetbl = false,
123  .excludeidx = false,
124  .excludensp = false,
125  .allrel = true,
126  .no_toast_expansion = false,
127  .reconcile_toast = true,
128  .on_error_stop = false,
129  .startblock = -1,
130  .endblock = -1,
131  .skip = "none",
132  .parent_check = false,
133  .rootdescend = false,
134  .heapallindexed = false,
135  .no_btree_expansion = false
136 };
137 
138 static const char *progname = NULL;
139 
140 /* Whether all relations have so far passed their corruption checks */
141 static bool all_checks_pass = true;
142 
143 /* Time last progress report was displayed */
145 static bool progress_since_last_stderr = false;
146 
147 typedef struct DatabaseInfo
148 {
149  char *datname;
150  char *amcheck_schema; /* escaped, quoted literal */
152 
153 typedef struct RelationInfo
154 {
155  const DatabaseInfo *datinfo; /* shared by other relinfos */
157  bool is_heap; /* true if heap, false if btree */
158  char *nspname;
159  char *relname;
160  int relpages;
162  char *sql; /* set during query run, pg_free'd after */
164 
165 /*
166  * Query for determining if contrib's amcheck is installed. If so, selects the
167  * namespace name where amcheck's functions can be found.
168  */
169 static const char *amcheck_sql =
170 "SELECT n.nspname, x.extversion FROM pg_catalog.pg_extension x"
171 "\nJOIN pg_catalog.pg_namespace n ON x.extnamespace = n.oid"
172 "\nWHERE x.extname = 'amcheck'";
173 
174 static void prepare_heap_command(PQExpBuffer sql, RelationInfo *rel,
175  PGconn *conn);
176 static void prepare_btree_command(PQExpBuffer sql, RelationInfo *rel,
177  PGconn *conn);
178 static void run_command(ParallelSlot *slot, const char *sql);
180  void *context);
181 static bool verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context);
182 static void help(const char *progname);
183 static void progress_report(uint64 relations_total, uint64 relations_checked,
184  uint64 relpages_total, uint64 relpages_checked,
185  const char *datname, bool force, bool finished);
186 
187 static void append_database_pattern(PatternInfoArray *pia, const char *pattern,
188  int encoding);
189 static void append_schema_pattern(PatternInfoArray *pia, const char *pattern,
190  int encoding);
191 static void append_relation_pattern(PatternInfoArray *pia, const char *pattern,
192  int encoding);
193 static void append_heap_pattern(PatternInfoArray *pia, const char *pattern,
194  int encoding);
195 static void append_btree_pattern(PatternInfoArray *pia, const char *pattern,
196  int encoding);
197 static void compile_database_list(PGconn *conn, SimplePtrList *databases,
198  const char *initial_dbname);
199 static void compile_relation_list_one_db(PGconn *conn, SimplePtrList *relations,
200  const DatabaseInfo *datinfo,
201  uint64 *pagecount);
202 
203 #define log_no_match(...) do { \
204  if (opts.strict_names) \
205  pg_log_error(__VA_ARGS__); \
206  else \
207  pg_log_warning(__VA_ARGS__); \
208  } while(0)
209 
210 #define FREE_AND_SET_NULL(x) do { \
211  pg_free(x); \
212  (x) = NULL; \
213  } while (0)
214 
215 int
216 main(int argc, char *argv[])
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:wWv",
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 'w':
367  prompt_password = TRI_NO;
368  break;
369  case 'W':
370  prompt_password = TRI_YES;
371  break;
372  case 'v':
373  opts.verbose = true;
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 }
784 
785 /*
786  * prepare_heap_command
787  *
788  * Creates a SQL command for running amcheck checking on the given heap
789  * relation. The command is phrased as a SQL query, with column order and
790  * names matching the expectations of verify_heap_slot_handler, which will
791  * receive and handle each row returned from the verify_heapam() function.
792  *
793  * The constructed SQL command will silently skip temporary tables, as checking
794  * them would needlessly draw errors from the underlying amcheck function.
795  *
796  * sql: buffer into which the heap table checking command will be written
797  * rel: relation information for the heap table to be checked
798  * conn: the connection to be used, for string escaping purposes
799  */
800 static void
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 }
823 
824 /*
825  * prepare_btree_command
826  *
827  * Creates a SQL command for running amcheck checking on the given btree index
828  * relation. The command does not select any columns, as btree checking
829  * functions do not return any, but rather return corruption information by
830  * raising errors, which verify_btree_slot_handler expects.
831  *
832  * The constructed SQL command will silently skip temporary indexes, and
833  * indexes being reindexed concurrently, as checking them would needlessly draw
834  * errors from the underlying amcheck functions.
835  *
836  * sql: buffer into which the heap table checking command will be written
837  * rel: relation information for the index to be checked
838  * conn: the connection to be used, for string escaping purposes
839  */
840 static void
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 }
871 
872 /*
873  * run_command
874  *
875  * Sends a command to the server without waiting for the command to complete.
876  * Logs an error if the command cannot be sent, but otherwise any errors are
877  * expected to be handled by a ParallelSlotHandler.
878  *
879  * If reconnecting to the database is necessary, the cparams argument may be
880  * modified.
881  *
882  * slot: slot with connection to the server we should use for the command
883  * sql: query to send
884  */
885 static void
886 run_command(ParallelSlot *slot, const char *sql)
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 }
900 
901 /*
902  * should_processing_continue
903  *
904  * Checks a query result returned from a query (presumably issued on a slot's
905  * connection) to determine if parallel slots should continue issuing further
906  * commands.
907  *
908  * Note: Heap relation corruption is reported by verify_heapam() via the result
909  * set, rather than an ERROR, but running verify_heapam() on a corrupted heap
910  * table may still result in an error being returned from the server due to
911  * missing relation files, bad checksums, etc. The btree corruption checking
912  * functions always use errors to communicate corruption messages. We can't
913  * just abort processing because we got a mere ERROR.
914  *
915  * res: result from an executed sql query
916  */
917 static bool
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 (strcmp(severity, "FATAL") == 0)
934  return false;
935  if (strcmp(severity, "PANIC") == 0)
936  return false;
937  break;
938 
939  /* These are unexpected */
940  case PGRES_BAD_RESPONSE:
941  case PGRES_EMPTY_QUERY:
942  case PGRES_COPY_OUT:
943  case PGRES_COPY_IN:
944  case PGRES_COPY_BOTH:
945  case PGRES_SINGLE_TUPLE:
946  case PGRES_PIPELINE_SYNC:
948  return false;
949  }
950  return true;
951 }
952 
953 /*
954  * Returns a copy of the argument string with all lines indented four spaces.
955  *
956  * The caller should pg_free the result when finished with it.
957  */
958 static char *
959 indent_lines(const char *str)
960 {
962  const char *c;
963  char *result;
964 
966  appendPQExpBufferStr(&buf, " ");
967  for (c = str; *c; c++)
968  {
970  if (c[0] == '\n' && c[1] != '\0')
971  appendPQExpBufferStr(&buf, " ");
972  }
973  result = pstrdup(buf.data);
975 
976  return result;
977 }
978 
979 /*
980  * verify_heap_slot_handler
981  *
982  * ParallelSlotHandler that receives results from a heap table checking command
983  * created by prepare_heap_command and outputs the results for the user.
984  *
985  * res: result from an executed sql query
986  * conn: connection on which the sql query was executed
987  * context: the sql query being handled, as a cstring
988  */
989 static bool
991 {
992  RelationInfo *rel = (RelationInfo *) context;
993 
995  {
996  int i;
997  int ntups = PQntuples(res);
998 
999  if (ntups > 0)
1000  all_checks_pass = false;
1001 
1002  for (i = 0; i < ntups; i++)
1003  {
1004  const char *msg;
1005 
1006  /* The message string should never be null, but check */
1007  if (PQgetisnull(res, i, 3))
1008  msg = "NO MESSAGE";
1009  else
1010  msg = PQgetvalue(res, i, 3);
1011 
1012  if (!PQgetisnull(res, i, 2))
1013  printf(_("heap table \"%s.%s.%s\", block %s, offset %s, attribute %s:\n"),
1014  rel->datinfo->datname, rel->nspname, rel->relname,
1015  PQgetvalue(res, i, 0), /* blkno */
1016  PQgetvalue(res, i, 1), /* offnum */
1017  PQgetvalue(res, i, 2)); /* attnum */
1018 
1019  else if (!PQgetisnull(res, i, 1))
1020  printf(_("heap table \"%s.%s.%s\", block %s, offset %s:\n"),
1021  rel->datinfo->datname, rel->nspname, rel->relname,
1022  PQgetvalue(res, i, 0), /* blkno */
1023  PQgetvalue(res, i, 1)); /* offnum */
1024 
1025  else if (!PQgetisnull(res, i, 0))
1026  printf(_("heap table \"%s.%s.%s\", block %s:\n"),
1027  rel->datinfo->datname, rel->nspname, rel->relname,
1028  PQgetvalue(res, i, 0)); /* blkno */
1029 
1030  else
1031  printf(_("heap table \"%s.%s.%s\":\n"),
1032  rel->datinfo->datname, rel->nspname, rel->relname);
1033 
1034  printf(" %s\n", msg);
1035  }
1036  }
1037  else if (PQresultStatus(res) != PGRES_TUPLES_OK)
1038  {
1039  char *msg = indent_lines(PQerrorMessage(conn));
1040 
1041  all_checks_pass = false;
1042  printf(_("heap table \"%s.%s.%s\":\n"),
1043  rel->datinfo->datname, rel->nspname, rel->relname);
1044  printf("%s", msg);
1045  if (opts.verbose)
1046  printf(_("query was: %s\n"), rel->sql);
1047  FREE_AND_SET_NULL(msg);
1048  }
1049 
1050  FREE_AND_SET_NULL(rel->sql);
1051  FREE_AND_SET_NULL(rel->nspname);
1052  FREE_AND_SET_NULL(rel->relname);
1053 
1055 }
1056 
1057 /*
1058  * verify_btree_slot_handler
1059  *
1060  * ParallelSlotHandler that receives results from a btree checking command
1061  * created by prepare_btree_command and outputs them for the user. The results
1062  * from the btree checking command is assumed to be empty, but when the results
1063  * are an error code, the useful information about the corruption is expected
1064  * in the connection's error message.
1065  *
1066  * res: result from an executed sql query
1067  * conn: connection on which the sql query was executed
1068  * context: unused
1069  */
1070 static bool
1072 {
1073  RelationInfo *rel = (RelationInfo *) context;
1074 
1076  {
1077  int ntups = PQntuples(res);
1078 
1079  if (ntups > 1)
1080  {
1081  /*
1082  * We expect the btree checking functions to return one void row
1083  * each, or zero rows if the check was skipped due to the object
1084  * being in the wrong state to be checked, so we should output
1085  * some sort of warning if we get anything more, not because it
1086  * indicates corruption, but because it suggests a mismatch
1087  * between amcheck and pg_amcheck versions.
1088  *
1089  * In conjunction with --progress, anything written to stderr at
1090  * this time would present strangely to the user without an extra
1091  * newline, so we print one. If we were multithreaded, we'd have
1092  * to avoid splitting this across multiple calls, but we're in an
1093  * event loop, so it doesn't matter.
1094  */
1096  fprintf(stderr, "\n");
1097  pg_log_warning("btree index \"%s.%s.%s\": btree checking function returned unexpected number of rows: %d",
1098  rel->datinfo->datname, rel->nspname, rel->relname, ntups);
1099  if (opts.verbose)
1100  pg_log_warning_detail("Query was: %s", rel->sql);
1101  pg_log_warning_hint("Are %s's and amcheck's versions compatible?",
1102  progname);
1104  }
1105  }
1106  else
1107  {
1108  char *msg = indent_lines(PQerrorMessage(conn));
1109 
1110  all_checks_pass = false;
1111  printf(_("btree index \"%s.%s.%s\":\n"),
1112  rel->datinfo->datname, rel->nspname, rel->relname);
1113  printf("%s", msg);
1114  if (opts.verbose)
1115  printf(_("query was: %s\n"), rel->sql);
1116  FREE_AND_SET_NULL(msg);
1117  }
1118 
1119  FREE_AND_SET_NULL(rel->sql);
1120  FREE_AND_SET_NULL(rel->nspname);
1121  FREE_AND_SET_NULL(rel->relname);
1122 
1124 }
1125 
1126 /*
1127  * help
1128  *
1129  * Prints help page for the program
1130  *
1131  * progname: the name of the executed program, such as "pg_amcheck"
1132  */
1133 static void
1134 help(const char *progname)
1135 {
1136  printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
1137  printf(_("Usage:\n"));
1138  printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
1139  printf(_("\nTarget options:\n"));
1140  printf(_(" -a, --all check all databases\n"));
1141  printf(_(" -d, --database=PATTERN check matching database(s)\n"));
1142  printf(_(" -D, --exclude-database=PATTERN do NOT check matching database(s)\n"));
1143  printf(_(" -i, --index=PATTERN check matching index(es)\n"));
1144  printf(_(" -I, --exclude-index=PATTERN do NOT check matching index(es)\n"));
1145  printf(_(" -r, --relation=PATTERN check matching relation(s)\n"));
1146  printf(_(" -R, --exclude-relation=PATTERN do NOT check matching relation(s)\n"));
1147  printf(_(" -s, --schema=PATTERN check matching schema(s)\n"));
1148  printf(_(" -S, --exclude-schema=PATTERN do NOT check matching schema(s)\n"));
1149  printf(_(" -t, --table=PATTERN check matching table(s)\n"));
1150  printf(_(" -T, --exclude-table=PATTERN do NOT check matching table(s)\n"));
1151  printf(_(" --no-dependent-indexes do NOT expand list of relations to include indexes\n"));
1152  printf(_(" --no-dependent-toast do NOT expand list of relations to include TOAST tables\n"));
1153  printf(_(" --no-strict-names do NOT require patterns to match objects\n"));
1154  printf(_("\nTable checking options:\n"));
1155  printf(_(" --exclude-toast-pointers do NOT follow relation TOAST pointers\n"));
1156  printf(_(" --on-error-stop stop checking at end of first corrupt page\n"));
1157  printf(_(" --skip=OPTION do NOT check \"all-frozen\" or \"all-visible\" blocks\n"));
1158  printf(_(" --startblock=BLOCK begin checking table(s) at the given block number\n"));
1159  printf(_(" --endblock=BLOCK check table(s) only up to the given block number\n"));
1160  printf(_("\nB-tree index checking options:\n"));
1161  printf(_(" --heapallindexed check that all heap tuples are found within indexes\n"));
1162  printf(_(" --parent-check check index parent/child relationships\n"));
1163  printf(_(" --rootdescend search from root page to refind tuples\n"));
1164  printf(_("\nConnection options:\n"));
1165  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1166  printf(_(" -p, --port=PORT database server port\n"));
1167  printf(_(" -U, --username=USERNAME user name to connect as\n"));
1168  printf(_(" -w, --no-password never prompt for password\n"));
1169  printf(_(" -W, --password force password prompt\n"));
1170  printf(_(" --maintenance-db=DBNAME alternate maintenance database\n"));
1171  printf(_("\nOther options:\n"));
1172  printf(_(" -e, --echo show the commands being sent to the server\n"));
1173  printf(_(" -j, --jobs=NUM use this many concurrent connections to the server\n"));
1174  printf(_(" -P, --progress show progress information\n"));
1175  printf(_(" -v, --verbose write a lot of output\n"));
1176  printf(_(" -V, --version output version information, then exit\n"));
1177  printf(_(" --install-missing install missing extensions\n"));
1178  printf(_(" -?, --help show this help, then exit\n"));
1179 
1180  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1181  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1182 }
1183 
1184 /*
1185  * Print a progress report based on the global variables.
1186  *
1187  * Progress report is written at maximum once per second, unless the force
1188  * parameter is set to true.
1189  *
1190  * If finished is set to true, this is the last progress report. The cursor
1191  * is moved to the next line.
1192  */
1193 static void
1194 progress_report(uint64 relations_total, uint64 relations_checked,
1195  uint64 relpages_total, uint64 relpages_checked,
1196  const char *datname, bool force, bool finished)
1197 {
1198  int percent_rel = 0;
1199  int percent_pages = 0;
1200  char checked_rel[32];
1201  char total_rel[32];
1202  char checked_pages[32];
1203  char total_pages[32];
1204  pg_time_t now;
1205 
1206  if (!opts.show_progress)
1207  return;
1208 
1209  now = time(NULL);
1210  if (now == last_progress_report && !force && !finished)
1211  return; /* Max once per second */
1212 
1214  if (relations_total)
1215  percent_rel = (int) (relations_checked * 100 / relations_total);
1216  if (relpages_total)
1217  percent_pages = (int) (relpages_checked * 100 / relpages_total);
1218 
1219  snprintf(checked_rel, sizeof(checked_rel), UINT64_FORMAT, relations_checked);
1220  snprintf(total_rel, sizeof(total_rel), UINT64_FORMAT, relations_total);
1221  snprintf(checked_pages, sizeof(checked_pages), UINT64_FORMAT, relpages_checked);
1222  snprintf(total_pages, sizeof(total_pages), UINT64_FORMAT, relpages_total);
1223 
1224 #define VERBOSE_DATNAME_LENGTH 35
1225  if (opts.verbose)
1226  {
1227  if (!datname)
1228 
1229  /*
1230  * No datname given, so clear the status line (used for first and
1231  * last call)
1232  */
1233  fprintf(stderr,
1234  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) %*s"),
1235  (int) strlen(total_rel),
1236  checked_rel, total_rel, percent_rel,
1237  (int) strlen(total_pages),
1238  checked_pages, total_pages, percent_pages,
1239  VERBOSE_DATNAME_LENGTH + 2, "");
1240  else
1241  {
1242  bool truncate = (strlen(datname) > VERBOSE_DATNAME_LENGTH);
1243 
1244  fprintf(stderr,
1245  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) (%s%-*.*s)"),
1246  (int) strlen(total_rel),
1247  checked_rel, total_rel, percent_rel,
1248  (int) strlen(total_pages),
1249  checked_pages, total_pages, percent_pages,
1250  /* Prefix with "..." if we do leading truncation */
1251  truncate ? "..." : "",
1254  /* Truncate datname at beginning if it's too long */
1255  truncate ? datname + strlen(datname) - VERBOSE_DATNAME_LENGTH + 3 : datname);
1256  }
1257  }
1258  else
1259  fprintf(stderr,
1260  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%)"),
1261  (int) strlen(total_rel),
1262  checked_rel, total_rel, percent_rel,
1263  (int) strlen(total_pages),
1264  checked_pages, total_pages, percent_pages);
1265 
1266  /*
1267  * Stay on the same line if reporting to a terminal and we're not done
1268  * yet.
1269  */
1270  if (!finished && isatty(fileno(stderr)))
1271  {
1272  fputc('\r', stderr);
1274  }
1275  else
1276  fputc('\n', stderr);
1277 }
1278 
1279 /*
1280  * Extend the pattern info array to hold one additional initialized pattern
1281  * info entry.
1282  *
1283  * Returns a pointer to the new entry.
1284  */
1285 static PatternInfo *
1287 {
1288  PatternInfo *result;
1289 
1290  pia->len++;
1291  pia->data = (PatternInfo *) pg_realloc(pia->data, pia->len * sizeof(PatternInfo));
1292  result = &pia->data[pia->len - 1];
1293  memset(result, 0, sizeof(*result));
1294 
1295  return result;
1296 }
1297 
1298 /*
1299  * append_database_pattern
1300  *
1301  * Adds the given pattern interpreted as a database name pattern.
1302  *
1303  * pia: the pattern info array to be appended
1304  * pattern: the database name pattern
1305  * encoding: client encoding for parsing the pattern
1306  */
1307 static void
1308 append_database_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1309 {
1311  int dotcnt;
1313 
1314  initPQExpBuffer(&buf);
1315  patternToSQLRegex(encoding, NULL, NULL, &buf, pattern, false, false,
1316  &dotcnt);
1317  if (dotcnt > 0)
1318  {
1319  pg_log_error("improper qualified name (too many dotted names): %s", pattern);
1320  exit(2);
1321  }
1322  info->pattern = pattern;
1323  info->db_regex = pstrdup(buf.data);
1324 
1325  termPQExpBuffer(&buf);
1326 }
1327 
1328 /*
1329  * append_schema_pattern
1330  *
1331  * Adds the given pattern interpreted as a schema name pattern.
1332  *
1333  * pia: the pattern info array to be appended
1334  * pattern: the schema name pattern
1335  * encoding: client encoding for parsing the pattern
1336  */
1337 static void
1338 append_schema_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1339 {
1340  PQExpBufferData dbbuf;
1341  PQExpBufferData nspbuf;
1342  int dotcnt;
1344 
1345  initPQExpBuffer(&dbbuf);
1346  initPQExpBuffer(&nspbuf);
1347 
1348  patternToSQLRegex(encoding, NULL, &dbbuf, &nspbuf, pattern, false, false,
1349  &dotcnt);
1350  if (dotcnt > 1)
1351  {
1352  pg_log_error("improper qualified name (too many dotted names): %s", pattern);
1353  exit(2);
1354  }
1355  info->pattern = pattern;
1356  if (dbbuf.data[0])
1357  {
1358  opts.dbpattern = true;
1359  info->db_regex = pstrdup(dbbuf.data);
1360  }
1361  if (nspbuf.data[0])
1362  info->nsp_regex = pstrdup(nspbuf.data);
1363 
1364  termPQExpBuffer(&dbbuf);
1365  termPQExpBuffer(&nspbuf);
1366 }
1367 
1368 /*
1369  * append_relation_pattern_helper
1370  *
1371  * Adds to a list the given pattern interpreted as a relation pattern.
1372  *
1373  * pia: the pattern info array to be appended
1374  * pattern: the relation name pattern
1375  * encoding: client encoding for parsing the pattern
1376  * heap_only: whether the pattern should only be matched against heap tables
1377  * btree_only: whether the pattern should only be matched against btree indexes
1378  */
1379 static void
1381  int encoding, bool heap_only, bool btree_only)
1382 {
1383  PQExpBufferData dbbuf;
1384  PQExpBufferData nspbuf;
1385  PQExpBufferData relbuf;
1386  int dotcnt;
1388 
1389  initPQExpBuffer(&dbbuf);
1390  initPQExpBuffer(&nspbuf);
1391  initPQExpBuffer(&relbuf);
1392 
1393  patternToSQLRegex(encoding, &dbbuf, &nspbuf, &relbuf, pattern, false,
1394  false, &dotcnt);
1395  if (dotcnt > 2)
1396  {
1397  pg_log_error("improper relation name (too many dotted names): %s", pattern);
1398  exit(2);
1399  }
1400  info->pattern = pattern;
1401  if (dbbuf.data[0])
1402  {
1403  opts.dbpattern = true;
1404  info->db_regex = pstrdup(dbbuf.data);
1405  }
1406  if (nspbuf.data[0])
1407  info->nsp_regex = pstrdup(nspbuf.data);
1408  if (relbuf.data[0])
1409  info->rel_regex = pstrdup(relbuf.data);
1410 
1411  termPQExpBuffer(&dbbuf);
1412  termPQExpBuffer(&nspbuf);
1413  termPQExpBuffer(&relbuf);
1414 
1415  info->heap_only = heap_only;
1416  info->btree_only = btree_only;
1417 }
1418 
1419 /*
1420  * append_relation_pattern
1421  *
1422  * Adds the given pattern interpreted as a relation pattern, to be matched
1423  * against both heap tables and btree indexes.
1424  *
1425  * pia: the pattern info array to be appended
1426  * pattern: the relation name pattern
1427  * encoding: client encoding for parsing the pattern
1428  */
1429 static void
1430 append_relation_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1431 {
1432  append_relation_pattern_helper(pia, pattern, encoding, false, false);
1433 }
1434 
1435 /*
1436  * append_heap_pattern
1437  *
1438  * Adds the given pattern interpreted as a relation pattern, to be matched only
1439  * against heap tables.
1440  *
1441  * pia: the pattern info array to be appended
1442  * pattern: the relation name pattern
1443  * encoding: client encoding for parsing the pattern
1444  */
1445 static void
1446 append_heap_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1447 {
1448  append_relation_pattern_helper(pia, pattern, encoding, true, false);
1449 }
1450 
1451 /*
1452  * append_btree_pattern
1453  *
1454  * Adds the given pattern interpreted as a relation pattern, to be matched only
1455  * against btree indexes.
1456  *
1457  * pia: the pattern info array to be appended
1458  * pattern: the relation name pattern
1459  * encoding: client encoding for parsing the pattern
1460  */
1461 static void
1462 append_btree_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1463 {
1464  append_relation_pattern_helper(pia, pattern, encoding, false, true);
1465 }
1466 
1467 /*
1468  * append_db_pattern_cte
1469  *
1470  * Appends to the buffer the body of a Common Table Expression (CTE) containing
1471  * the database portions filtered from the list of patterns expressed as two
1472  * columns:
1473  *
1474  * pattern_id: the index of this pattern in pia->data[]
1475  * rgx: the database regular expression parsed from the pattern
1476  *
1477  * Patterns without a database portion are skipped. Patterns with more than
1478  * just a database portion are optionally skipped, depending on argument
1479  * 'inclusive'.
1480  *
1481  * buf: the buffer to be appended
1482  * pia: the array of patterns to be inserted into the CTE
1483  * conn: the database connection
1484  * inclusive: whether to include patterns with schema and/or relation parts
1485  *
1486  * Returns whether any database patterns were appended.
1487  */
1488 static bool
1490  PGconn *conn, bool inclusive)
1491 {
1492  int pattern_id;
1493  const char *comma;
1494  bool have_values;
1495 
1496  comma = "";
1497  have_values = false;
1498  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1499  {
1500  PatternInfo *info = &pia->data[pattern_id];
1501 
1502  if (info->db_regex != NULL &&
1503  (inclusive || (info->nsp_regex == NULL && info->rel_regex == NULL)))
1504  {
1505  if (!have_values)
1506  appendPQExpBufferStr(buf, "\nVALUES");
1507  have_values = true;
1508  appendPQExpBuffer(buf, "%s\n(%d, ", comma, pattern_id);
1510  appendPQExpBufferStr(buf, ")");
1511  comma = ",";
1512  }
1513  }
1514 
1515  if (!have_values)
1516  appendPQExpBufferStr(buf, "\nSELECT NULL, NULL, NULL WHERE false");
1517 
1518  return have_values;
1519 }
1520 
1521 /*
1522  * compile_database_list
1523  *
1524  * If any database patterns exist, or if --all was given, compiles a distinct
1525  * list of databases to check using a SQL query based on the patterns plus the
1526  * literal initial database name, if given. If no database patterns exist and
1527  * --all was not given, the query is not necessary, and only the initial
1528  * database name (if any) is added to the list.
1529  *
1530  * conn: connection to the initial database
1531  * databases: the list onto which databases should be appended
1532  * initial_dbname: an optional extra database name to include in the list
1533  */
1534 static void
1536  const char *initial_dbname)
1537 {
1538  PGresult *res;
1539  PQExpBufferData sql;
1540  int ntups;
1541  int i;
1542  bool fatal;
1543 
1544  if (initial_dbname)
1545  {
1546  DatabaseInfo *dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1547 
1548  /* This database is included. Add to list */
1549  if (opts.verbose)
1550  pg_log_info("including database \"%s\"", initial_dbname);
1551 
1552  dat->datname = pstrdup(initial_dbname);
1553  simple_ptr_list_append(databases, dat);
1554  }
1555 
1556  initPQExpBuffer(&sql);
1557 
1558  /* Append the include patterns CTE. */
1559  appendPQExpBufferStr(&sql, "WITH include_raw (pattern_id, rgx) AS (");
1560  if (!append_db_pattern_cte(&sql, &opts.include, conn, true) &&
1561  !opts.alldb)
1562  {
1563  /*
1564  * None of the inclusion patterns (if any) contain database portions,
1565  * so there is no need to query the database to resolve database
1566  * patterns.
1567  *
1568  * Since we're also not operating under --all, we don't need to query
1569  * the exhaustive list of connectable databases, either.
1570  */
1571  termPQExpBuffer(&sql);
1572  return;
1573  }
1574 
1575  /* Append the exclude patterns CTE. */
1576  appendPQExpBufferStr(&sql, "),\nexclude_raw (pattern_id, rgx) AS (");
1577  append_db_pattern_cte(&sql, &opts.exclude, conn, false);
1578  appendPQExpBufferStr(&sql, "),");
1579 
1580  /*
1581  * Append the database CTE, which includes whether each database is
1582  * connectable and also joins against exclude_raw to determine whether
1583  * each database is excluded.
1584  */
1585  appendPQExpBufferStr(&sql,
1586  "\ndatabase (datname) AS ("
1587  "\nSELECT d.datname "
1588  "FROM pg_catalog.pg_database d "
1589  "LEFT OUTER JOIN exclude_raw e "
1590  "ON d.datname ~ e.rgx "
1591  "\nWHERE d.datallowconn "
1592  "AND e.pattern_id IS NULL"
1593  "),"
1594 
1595  /*
1596  * Append the include_pat CTE, which joins the include_raw CTE against the
1597  * databases CTE to determine if all the inclusion patterns had matches,
1598  * and whether each matched pattern had the misfortune of only matching
1599  * excluded or unconnectable databases.
1600  */
1601  "\ninclude_pat (pattern_id, checkable) AS ("
1602  "\nSELECT i.pattern_id, "
1603  "COUNT(*) FILTER ("
1604  "WHERE d IS NOT NULL"
1605  ") AS checkable"
1606  "\nFROM include_raw i "
1607  "LEFT OUTER JOIN database d "
1608  "ON d.datname ~ i.rgx"
1609  "\nGROUP BY i.pattern_id"
1610  "),"
1611 
1612  /*
1613  * Append the filtered_databases CTE, which selects from the database CTE
1614  * optionally joined against the include_raw CTE to only select databases
1615  * that match an inclusion pattern. This appears to duplicate what the
1616  * include_pat CTE already did above, but here we want only databases, and
1617  * there we wanted patterns.
1618  */
1619  "\nfiltered_databases (datname) AS ("
1620  "\nSELECT DISTINCT d.datname "
1621  "FROM database d");
1622  if (!opts.alldb)
1623  appendPQExpBufferStr(&sql,
1624  " INNER JOIN include_raw i "
1625  "ON d.datname ~ i.rgx");
1626  appendPQExpBufferStr(&sql,
1627  ")"
1628 
1629  /*
1630  * Select the checkable databases and the unmatched inclusion patterns.
1631  */
1632  "\nSELECT pattern_id, datname FROM ("
1633  "\nSELECT pattern_id, NULL::TEXT AS datname "
1634  "FROM include_pat "
1635  "WHERE checkable = 0 "
1636  "UNION ALL"
1637  "\nSELECT NULL, datname "
1638  "FROM filtered_databases"
1639  ") AS combined_records"
1640  "\nORDER BY pattern_id NULLS LAST, datname");
1641 
1642  res = executeQuery(conn, sql.data, opts.echo);
1644  {
1645  pg_log_error("query failed: %s", PQerrorMessage(conn));
1646  pg_log_error_detail("Query was: %s", sql.data);
1648  exit(1);
1649  }
1650  termPQExpBuffer(&sql);
1651 
1652  ntups = PQntuples(res);
1653  for (fatal = false, i = 0; i < ntups; i++)
1654  {
1655  int pattern_id = -1;
1656  const char *datname = NULL;
1657 
1658  if (!PQgetisnull(res, i, 0))
1659  pattern_id = atoi(PQgetvalue(res, i, 0));
1660  if (!PQgetisnull(res, i, 1))
1661  datname = PQgetvalue(res, i, 1);
1662 
1663  if (pattern_id >= 0)
1664  {
1665  /*
1666  * Current record pertains to an inclusion pattern that matched no
1667  * checkable databases.
1668  */
1669  fatal = opts.strict_names;
1670  if (pattern_id >= opts.include.len)
1671  pg_fatal("internal error: received unexpected database pattern_id %d",
1672  pattern_id);
1673  log_no_match("no connectable databases to check matching \"%s\"",
1674  opts.include.data[pattern_id].pattern);
1675  }
1676  else
1677  {
1678  DatabaseInfo *dat;
1679 
1680  /* Current record pertains to a database */
1681  Assert(datname != NULL);
1682 
1683  /* Avoid entering a duplicate entry matching the initial_dbname */
1684  if (initial_dbname != NULL && strcmp(initial_dbname, datname) == 0)
1685  continue;
1686 
1687  /* This database is included. Add to list */
1688  if (opts.verbose)
1689  pg_log_info("including database \"%s\"", datname);
1690 
1691  dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1692  dat->datname = pstrdup(datname);
1693  simple_ptr_list_append(databases, dat);
1694  }
1695  }
1696  PQclear(res);
1697 
1698  if (fatal)
1699  {
1700  if (conn != NULL)
1702  exit(1);
1703  }
1704 }
1705 
1706 /*
1707  * append_rel_pattern_raw_cte
1708  *
1709  * Appends to the buffer the body of a Common Table Expression (CTE) containing
1710  * the given patterns as six columns:
1711  *
1712  * pattern_id: the index of this pattern in pia->data[]
1713  * db_regex: the database regexp parsed from the pattern, or NULL if the
1714  * pattern had no database part
1715  * nsp_regex: the namespace regexp parsed from the pattern, or NULL if the
1716  * pattern had no namespace part
1717  * rel_regex: the relname regexp parsed from the pattern, or NULL if the
1718  * pattern had no relname part
1719  * heap_only: true if the pattern applies only to heap tables (not indexes)
1720  * btree_only: true if the pattern applies only to btree indexes (not tables)
1721  *
1722  * buf: the buffer to be appended
1723  * patterns: the array of patterns to be inserted into the CTE
1724  * conn: the database connection
1725  */
1726 static void
1728  PGconn *conn)
1729 {
1730  int pattern_id;
1731  const char *comma;
1732  bool have_values;
1733 
1734  comma = "";
1735  have_values = false;
1736  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1737  {
1738  PatternInfo *info = &pia->data[pattern_id];
1739 
1740  if (!have_values)
1741  appendPQExpBufferStr(buf, "\nVALUES");
1742  have_values = true;
1743  appendPQExpBuffer(buf, "%s\n(%d::INTEGER, ", comma, pattern_id);
1744  if (info->db_regex == NULL)
1745  appendPQExpBufferStr(buf, "NULL");
1746  else
1748  appendPQExpBufferStr(buf, "::TEXT, ");
1749  if (info->nsp_regex == NULL)
1750  appendPQExpBufferStr(buf, "NULL");
1751  else
1753  appendPQExpBufferStr(buf, "::TEXT, ");
1754  if (info->rel_regex == NULL)
1755  appendPQExpBufferStr(buf, "NULL");
1756  else
1758  if (info->heap_only)
1759  appendPQExpBufferStr(buf, "::TEXT, true::BOOLEAN");
1760  else
1761  appendPQExpBufferStr(buf, "::TEXT, false::BOOLEAN");
1762  if (info->btree_only)
1763  appendPQExpBufferStr(buf, ", true::BOOLEAN");
1764  else
1765  appendPQExpBufferStr(buf, ", false::BOOLEAN");
1766  appendPQExpBufferStr(buf, ")");
1767  comma = ",";
1768  }
1769 
1770  if (!have_values)
1772  "\nSELECT NULL::INTEGER, NULL::TEXT, NULL::TEXT, "
1773  "NULL::TEXT, NULL::BOOLEAN, NULL::BOOLEAN "
1774  "WHERE false");
1775 }
1776 
1777 /*
1778  * append_rel_pattern_filtered_cte
1779  *
1780  * Appends to the buffer a Common Table Expression (CTE) which selects
1781  * all patterns from the named raw CTE, filtered by database. All patterns
1782  * which have no database portion or whose database portion matches our
1783  * connection's database name are selected, with other patterns excluded.
1784  *
1785  * The basic idea here is that if we're connected to database "foo" and we have
1786  * patterns "foo.bar.baz", "alpha.beta" and "one.two.three", we only want to
1787  * use the first two while processing relations in this database, as the third
1788  * one is not relevant.
1789  *
1790  * buf: the buffer to be appended
1791  * raw: the name of the CTE to select from
1792  * filtered: the name of the CTE to create
1793  * conn: the database connection
1794  */
1795 static void
1797  const char *filtered, PGconn *conn)
1798 {
1800  "\n%s (pattern_id, nsp_regex, rel_regex, heap_only, btree_only) AS ("
1801  "\nSELECT pattern_id, nsp_regex, rel_regex, heap_only, btree_only "
1802  "FROM %s r"
1803  "\nWHERE (r.db_regex IS NULL "
1804  "OR ",
1805  filtered, raw);
1807  appendPQExpBufferStr(buf, " ~ r.db_regex)");
1809  " AND (r.nsp_regex IS NOT NULL"
1810  " OR r.rel_regex IS NOT NULL)"
1811  "),");
1812 }
1813 
1814 /*
1815  * compile_relation_list_one_db
1816  *
1817  * Compiles a list of relations to check within the currently connected
1818  * database based on the user supplied options, sorted by descending size,
1819  * and appends them to the given list of relations.
1820  *
1821  * The cells of the constructed list contain all information about the relation
1822  * necessary to connect to the database and check the object, including which
1823  * database to connect to, where contrib/amcheck is installed, and the Oid and
1824  * type of object (heap table vs. btree index). Rather than duplicating the
1825  * database details per relation, the relation structs use references to the
1826  * same database object, provided by the caller.
1827  *
1828  * conn: connection to this next database, which should be the same as in 'dat'
1829  * relations: list onto which the relations information should be appended
1830  * dat: the database info struct for use by each relation
1831  * pagecount: gets incremented by the number of blocks to check in all
1832  * relations added
1833  */
1834 static void
1836  const DatabaseInfo *dat,
1837  uint64 *pagecount)
1838 {
1839  PGresult *res;
1840  PQExpBufferData sql;
1841  int ntups;
1842  int i;
1843 
1844  initPQExpBuffer(&sql);
1845  appendPQExpBufferStr(&sql, "WITH");
1846 
1847  /* Append CTEs for the relation inclusion patterns, if any */
1848  if (!opts.allrel)
1849  {
1850  appendPQExpBufferStr(&sql,
1851  " include_raw (pattern_id, db_regex, nsp_regex, rel_regex, heap_only, btree_only) AS (");
1853  appendPQExpBufferStr(&sql, "\n),");
1854  append_rel_pattern_filtered_cte(&sql, "include_raw", "include_pat", conn);
1855  }
1856 
1857  /* Append CTEs for the relation exclusion patterns, if any */
1859  {
1860  appendPQExpBufferStr(&sql,
1861  " exclude_raw (pattern_id, db_regex, nsp_regex, rel_regex, heap_only, btree_only) AS (");
1863  appendPQExpBufferStr(&sql, "\n),");
1864  append_rel_pattern_filtered_cte(&sql, "exclude_raw", "exclude_pat", conn);
1865  }
1866 
1867  /* Append the relation CTE. */
1868  appendPQExpBufferStr(&sql,
1869  " relation (pattern_id, oid, nspname, relname, reltoastrelid, relpages, is_heap, is_btree) AS ("
1870  "\nSELECT DISTINCT ON (c.oid");
1871  if (!opts.allrel)
1872  appendPQExpBufferStr(&sql, ", ip.pattern_id) ip.pattern_id,");
1873  else
1874  appendPQExpBufferStr(&sql, ") NULL::INTEGER AS pattern_id,");
1875  appendPQExpBuffer(&sql,
1876  "\nc.oid, n.nspname, c.relname, c.reltoastrelid, c.relpages, "
1877  "c.relam = %u AS is_heap, "
1878  "c.relam = %u AS is_btree"
1879  "\nFROM pg_catalog.pg_class c "
1880  "INNER JOIN pg_catalog.pg_namespace n "
1881  "ON c.relnamespace = n.oid",
1882  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1883  if (!opts.allrel)
1884  appendPQExpBuffer(&sql,
1885  "\nINNER JOIN include_pat ip"
1886  "\nON (n.nspname ~ ip.nsp_regex OR ip.nsp_regex IS NULL)"
1887  "\nAND (c.relname ~ ip.rel_regex OR ip.rel_regex IS NULL)"
1888  "\nAND (c.relam = %u OR NOT ip.heap_only)"
1889  "\nAND (c.relam = %u OR NOT ip.btree_only)",
1890  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1892  appendPQExpBuffer(&sql,
1893  "\nLEFT OUTER JOIN exclude_pat ep"
1894  "\nON (n.nspname ~ ep.nsp_regex OR ep.nsp_regex IS NULL)"
1895  "\nAND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL)"
1896  "\nAND (c.relam = %u OR NOT ep.heap_only OR ep.rel_regex IS NULL)"
1897  "\nAND (c.relam = %u OR NOT ep.btree_only OR ep.rel_regex IS NULL)",
1898  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1899 
1900  /*
1901  * Exclude temporary tables and indexes, which must necessarily belong to
1902  * other sessions. (We don't create any ourselves.) We must ultimately
1903  * exclude indexes marked invalid or not ready, but we delay that decision
1904  * until firing off the amcheck command, as the state of an index may
1905  * change by then.
1906  */
1907  appendPQExpBufferStr(&sql, "\nWHERE c.relpersistence != 't'");
1909  appendPQExpBufferStr(&sql, "\nAND ep.pattern_id IS NULL");
1910 
1911  /*
1912  * We need to be careful not to break the --no-dependent-toast and
1913  * --no-dependent-indexes options. By default, the btree indexes, toast
1914  * tables, and toast table btree indexes associated with primary heap
1915  * tables are included, using their own CTEs below. We implement the
1916  * --exclude-* options by not creating those CTEs, but that's no use if
1917  * we've already selected the toast and indexes here. On the other hand,
1918  * we want inclusion patterns that match indexes or toast tables to be
1919  * honored. So, if inclusion patterns were given, we want to select all
1920  * tables, toast tables, or indexes that match the patterns. But if no
1921  * inclusion patterns were given, and we're simply matching all relations,
1922  * then we only want to match the primary tables here.
1923  */
1924  if (opts.allrel)
1925  appendPQExpBuffer(&sql,
1926  " AND c.relam = %u "
1927  "AND c.relkind IN ('r', 'S', 'm', 't') "
1928  "AND c.relnamespace != %u",
1929  HEAP_TABLE_AM_OID, PG_TOAST_NAMESPACE);
1930  else
1931  appendPQExpBuffer(&sql,
1932  " AND c.relam IN (%u, %u)"
1933  "AND c.relkind IN ('r', 'S', 'm', 't', 'i') "
1934  "AND ((c.relam = %u AND c.relkind IN ('r', 'S', 'm', 't')) OR "
1935  "(c.relam = %u AND c.relkind = 'i'))",
1936  HEAP_TABLE_AM_OID, BTREE_AM_OID,
1937  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1938 
1939  appendPQExpBufferStr(&sql,
1940  "\nORDER BY c.oid)");
1941 
1942  if (!opts.no_toast_expansion)
1943  {
1944  /*
1945  * Include a CTE for toast tables associated with primary heap tables
1946  * selected above, filtering by exclusion patterns (if any) that match
1947  * toast table names.
1948  */
1949  appendPQExpBufferStr(&sql,
1950  ", toast (oid, nspname, relname, relpages) AS ("
1951  "\nSELECT t.oid, 'pg_toast', t.relname, t.relpages"
1952  "\nFROM pg_catalog.pg_class t "
1953  "INNER JOIN relation r "
1954  "ON r.reltoastrelid = t.oid");
1955  if (opts.excludetbl || opts.excludensp)
1956  appendPQExpBufferStr(&sql,
1957  "\nLEFT OUTER JOIN exclude_pat ep"
1958  "\nON ('pg_toast' ~ ep.nsp_regex OR ep.nsp_regex IS NULL)"
1959  "\nAND (t.relname ~ ep.rel_regex OR ep.rel_regex IS NULL)"
1960  "\nAND ep.heap_only"
1961  "\nWHERE ep.pattern_id IS NULL"
1962  "\nAND t.relpersistence != 't'");
1963  appendPQExpBufferStr(&sql,
1964  "\n)");
1965  }
1966  if (!opts.no_btree_expansion)
1967  {
1968  /*
1969  * Include a CTE for btree indexes associated with primary heap tables
1970  * selected above, filtering by exclusion patterns (if any) that match
1971  * btree index names.
1972  */
1973  appendPQExpBuffer(&sql,
1974  ", index (oid, nspname, relname, relpages) AS ("
1975  "\nSELECT c.oid, r.nspname, c.relname, c.relpages "
1976  "FROM relation r"
1977  "\nINNER JOIN pg_catalog.pg_index i "
1978  "ON r.oid = i.indrelid "
1979  "INNER JOIN pg_catalog.pg_class c "
1980  "ON i.indexrelid = c.oid "
1981  "AND c.relpersistence != 't'");
1982  if (opts.excludeidx || opts.excludensp)
1983  appendPQExpBufferStr(&sql,
1984  "\nINNER JOIN pg_catalog.pg_namespace n "
1985  "ON c.relnamespace = n.oid"
1986  "\nLEFT OUTER JOIN exclude_pat ep "
1987  "ON (n.nspname ~ ep.nsp_regex OR ep.nsp_regex IS NULL) "
1988  "AND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL) "
1989  "AND ep.btree_only"
1990  "\nWHERE ep.pattern_id IS NULL");
1991  else
1992  appendPQExpBufferStr(&sql,
1993  "\nWHERE true");
1994  appendPQExpBuffer(&sql,
1995  " AND c.relam = %u "
1996  "AND c.relkind = 'i'",
1997  BTREE_AM_OID);
1999  appendPQExpBuffer(&sql,
2000  " AND c.relnamespace != %u",
2001  PG_TOAST_NAMESPACE);
2002  appendPQExpBufferStr(&sql, "\n)");
2003  }
2004 
2006  {
2007  /*
2008  * Include a CTE for btree indexes associated with toast tables of
2009  * primary heap tables selected above, filtering by exclusion patterns
2010  * (if any) that match the toast index names.
2011  */
2012  appendPQExpBuffer(&sql,
2013  ", toast_index (oid, nspname, relname, relpages) AS ("
2014  "\nSELECT c.oid, 'pg_toast', c.relname, c.relpages "
2015  "FROM toast t "
2016  "INNER JOIN pg_catalog.pg_index i "
2017  "ON t.oid = i.indrelid"
2018  "\nINNER JOIN pg_catalog.pg_class c "
2019  "ON i.indexrelid = c.oid "
2020  "AND c.relpersistence != 't'");
2021  if (opts.excludeidx)
2022  appendPQExpBufferStr(&sql,
2023  "\nLEFT OUTER JOIN exclude_pat ep "
2024  "ON ('pg_toast' ~ ep.nsp_regex OR ep.nsp_regex IS NULL) "
2025  "AND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL) "
2026  "AND ep.btree_only "
2027  "WHERE ep.pattern_id IS NULL");
2028  else
2029  appendPQExpBufferStr(&sql,
2030  "\nWHERE true");
2031  appendPQExpBuffer(&sql,
2032  " AND c.relam = %u"
2033  " AND c.relkind = 'i')",
2034  BTREE_AM_OID);
2035  }
2036 
2037  /*
2038  * Roll-up distinct rows from CTEs.
2039  *
2040  * Relations that match more than one pattern may occur more than once in
2041  * the list, and indexes and toast for primary relations may also have
2042  * matched in their own right, so we rely on UNION to deduplicate the
2043  * list.
2044  */
2045  appendPQExpBuffer(&sql,
2046  "\nSELECT pattern_id, is_heap, is_btree, oid, nspname, relname, relpages "
2047  "FROM (");
2048  appendPQExpBufferStr(&sql,
2049  /* Inclusion patterns that failed to match */
2050  "\nSELECT pattern_id, is_heap, is_btree, "
2051  "NULL::OID AS oid, "
2052  "NULL::TEXT AS nspname, "
2053  "NULL::TEXT AS relname, "
2054  "NULL::INTEGER AS relpages"
2055  "\nFROM relation "
2056  "WHERE pattern_id IS NOT NULL "
2057  "UNION"
2058  /* Primary relations */
2059  "\nSELECT NULL::INTEGER AS pattern_id, "
2060  "is_heap, is_btree, oid, nspname, relname, relpages "
2061  "FROM relation");
2062  if (!opts.no_toast_expansion)
2063  appendPQExpBufferStr(&sql,
2064  " UNION"
2065  /* Toast tables for primary relations */
2066  "\nSELECT NULL::INTEGER AS pattern_id, TRUE AS is_heap, "
2067  "FALSE AS is_btree, oid, nspname, relname, relpages "
2068  "FROM toast");
2069  if (!opts.no_btree_expansion)
2070  appendPQExpBufferStr(&sql,
2071  " UNION"
2072  /* Indexes for primary relations */
2073  "\nSELECT NULL::INTEGER AS pattern_id, FALSE AS is_heap, "
2074  "TRUE AS is_btree, oid, nspname, relname, relpages "
2075  "FROM index");
2077  appendPQExpBufferStr(&sql,
2078  " UNION"
2079  /* Indexes for toast relations */
2080  "\nSELECT NULL::INTEGER AS pattern_id, FALSE AS is_heap, "
2081  "TRUE AS is_btree, oid, nspname, relname, relpages "
2082  "FROM toast_index");
2083  appendPQExpBufferStr(&sql,
2084  "\n) AS combined_records "
2085  "ORDER BY relpages DESC NULLS FIRST, oid");
2086 
2087  res = executeQuery(conn, sql.data, opts.echo);
2089  {
2090  pg_log_error("query failed: %s", PQerrorMessage(conn));
2091  pg_log_error_detail("Query was: %s", sql.data);
2093  exit(1);
2094  }
2095  termPQExpBuffer(&sql);
2096 
2097  ntups = PQntuples(res);
2098  for (i = 0; i < ntups; i++)
2099  {
2100  int pattern_id = -1;
2101  bool is_heap = false;
2102  bool is_btree PG_USED_FOR_ASSERTS_ONLY = false;
2103  Oid oid = InvalidOid;
2104  const char *nspname = NULL;
2105  const char *relname = NULL;
2106  int relpages = 0;
2107 
2108  if (!PQgetisnull(res, i, 0))
2109  pattern_id = atoi(PQgetvalue(res, i, 0));
2110  if (!PQgetisnull(res, i, 1))
2111  is_heap = (PQgetvalue(res, i, 1)[0] == 't');
2112  if (!PQgetisnull(res, i, 2))
2113  is_btree = (PQgetvalue(res, i, 2)[0] == 't');
2114  if (!PQgetisnull(res, i, 3))
2115  oid = atooid(PQgetvalue(res, i, 3));
2116  if (!PQgetisnull(res, i, 4))
2117  nspname = PQgetvalue(res, i, 4);
2118  if (!PQgetisnull(res, i, 5))
2119  relname = PQgetvalue(res, i, 5);
2120  if (!PQgetisnull(res, i, 6))
2121  relpages = atoi(PQgetvalue(res, i, 6));
2122 
2123  if (pattern_id >= 0)
2124  {
2125  /*
2126  * Current record pertains to an inclusion pattern. Record that
2127  * it matched.
2128  */
2129 
2130  if (pattern_id >= opts.include.len)
2131  pg_fatal("internal error: received unexpected relation pattern_id %d",
2132  pattern_id);
2133 
2134  opts.include.data[pattern_id].matched = true;
2135  }
2136  else
2137  {
2138  /* Current record pertains to a relation */
2139 
2140  RelationInfo *rel = (RelationInfo *) pg_malloc0(sizeof(RelationInfo));
2141 
2142  Assert(OidIsValid(oid));
2143  Assert((is_heap && !is_btree) || (is_btree && !is_heap));
2144 
2145  rel->datinfo = dat;
2146  rel->reloid = oid;
2147  rel->is_heap = is_heap;
2148  rel->nspname = pstrdup(nspname);
2149  rel->relname = pstrdup(relname);
2150  rel->relpages = relpages;
2151  rel->blocks_to_check = relpages;
2152  if (is_heap && (opts.startblock >= 0 || opts.endblock >= 0))
2153  {
2154  /*
2155  * We apply --startblock and --endblock to heap tables, but
2156  * not btree indexes, and for progress purposes we need to
2157  * track how many blocks we expect to check.
2158  */
2159  if (opts.endblock >= 0 && rel->blocks_to_check > opts.endblock)
2160  rel->blocks_to_check = opts.endblock + 1;
2161  if (opts.startblock >= 0)
2162  {
2163  if (rel->blocks_to_check > opts.startblock)
2165  else
2166  rel->blocks_to_check = 0;
2167  }
2168  }
2169  *pagecount += rel->blocks_to_check;
2170 
2171  simple_ptr_list_append(relations, rel);
2172  }
2173  }
2174  PQclear(res);
2175 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
static void setup_cancel_handler(void)
Definition: parallel.c:610
#define MaxBlockNumber
Definition: block.h:35
#define INT64_FORMAT
Definition: c.h:483
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1212
#define UINT64_FORMAT
Definition: c.h:484
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
#define OidIsValid(objectId)
Definition: c.h:710
volatile sig_atomic_t CancelRequested
Definition: cancel.c:59
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:446
void disconnectDatabase(PGconn *conn)
PGconn * connectMaintenanceDatabase(ConnParams *cparams, const char *progname, bool echo)
#define _(x)
Definition: elog.c:89
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:6754
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6908
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:7035
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4172
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3270
void PQclear(PGresult *res)
Definition: fe-exec.c:718
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3340
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3735
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3760
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1424
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3325
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
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
int i
Definition: isn.c:73
@ 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
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
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(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
#define pg_log_info(...)
Definition: logging.h:124
#define pg_log_warning_hint(...)
Definition: logging.h:121
#define pg_log_warning_detail(...)
Definition: logging.h:118
#define pg_log_error_detail(...)
Definition: logging.h:109
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void pfree(void *pointer)
Definition: mcxt.c:1175
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
#define VERBOSE_DATNAME_LENGTH
static char * indent_lines(const char *str)
Definition: pg_amcheck.c:959
static bool should_processing_continue(PGresult *res)
Definition: pg_amcheck.c:918
int main(int argc, char *argv[])
Definition: pg_amcheck.c:216
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:1194
static void append_rel_pattern_filtered_cte(PQExpBuffer buf, const char *raw, const char *filtered, PGconn *conn)
Definition: pg_amcheck.c:1796
static AmcheckOptions opts
Definition: pg_amcheck.c:110
static void compile_database_list(PGconn *conn, SimplePtrList *databases, const char *initial_dbname)
Definition: pg_amcheck.c:1535
struct DatabaseInfo DatabaseInfo
static PatternInfo * extend_pattern_info_array(PatternInfoArray *pia)
Definition: pg_amcheck.c:1286
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:1134
struct PatternInfoArray PatternInfoArray
static void append_database_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1308
static void append_rel_pattern_raw_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn)
Definition: pg_amcheck.c:1727
static bool verify_heap_slot_handler(PGresult *res, PGconn *conn, void *context)
Definition: pg_amcheck.c:990
struct PatternInfo PatternInfo
static pg_time_t last_progress_report
Definition: pg_amcheck.c:144
#define FREE_AND_SET_NULL(x)
Definition: pg_amcheck.c:210
static void append_relation_pattern_helper(PatternInfoArray *pia, const char *pattern, int encoding, bool heap_only, bool btree_only)
Definition: pg_amcheck.c:1380
struct RelationInfo RelationInfo
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:1446
#define log_no_match(...)
Definition: pg_amcheck.c:203
static void append_schema_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1338
static bool verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
Definition: pg_amcheck.c:1071
struct AmcheckOptions AmcheckOptions
static bool progress_since_last_stderr
Definition: pg_amcheck.c:145
static void compile_relation_list_one_db(PGconn *conn, SimplePtrList *relations, const DatabaseInfo *datinfo, uint64 *pagecount)
Definition: pg_amcheck.c:1835
static const char * progname
Definition: pg_amcheck.c:138
static void append_relation_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1430
static bool append_db_pattern_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn, bool inclusive)
Definition: pg_amcheck.c:1489
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 append_btree_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1462
#define pg_fatal(...)
NameData relname
Definition: pg_class.h:38
NameData datname
Definition: pg_database.h:35
int32 encoding
Definition: pg_database.h:41
static PGconn * connectDatabase(const char *dbname, const char *connstr, const char *pghost, const char *pgport, const char *pguser, trivalue prompt_password, bool fail_on_error)
Definition: pg_dumpall.c:1476
static void executeCommand(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1722
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1699
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
static int port
Definition: pg_regress.c:92
static char * buf
Definition: pg_test_fsync.c:67
const char * username
Definition: pgbench.c:309
#define pg_log_warning(...)
Definition: pgfnames.c:24
int64 pg_time_t
Definition: pgtime.h:23
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 snprintf
Definition: port.h:225
#define fprintf
Definition: port.h:229
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:451
#define printf(...)
Definition: port.h:231
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define atooid(x)
Definition: postgres_ext.h:42
#define PG_DIAG_SEVERITY_NONLOCALIZED
Definition: postgres_ext.h:56
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:380
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
char * c
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void simple_ptr_list_append(SimplePtrList *list, void *ptr)
Definition: simple_list.c:162
PGconn * conn
Definition: streamutil.c:54
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
void patternToSQLRegex(int encoding, PQExpBuffer dbnamebuf, PQExpBuffer schemabuf, PQExpBuffer namebuf, const char *pattern, bool force_escape, bool want_literal_dbname, int *dotcnt)
int64 startblock
Definition: pg_amcheck.c:97
bool no_btree_expansion
Definition: pg_amcheck.c:107
bool install_missing
Definition: pg_amcheck.c:68
bool no_toast_expansion
Definition: pg_amcheck.c:94
char * install_schema
Definition: pg_amcheck.c:69
bool reconcile_toast
Definition: pg_amcheck.c:95
PatternInfoArray exclude
Definition: pg_amcheck.c:73
bool strict_names
Definition: pg_amcheck.c:60
int64 endblock
Definition: pg_amcheck.c:98
bool show_progress
Definition: pg_amcheck.c:61
bool on_error_stop
Definition: pg_amcheck.c:96
bool heapallindexed
Definition: pg_amcheck.c:104
PatternInfoArray include
Definition: pg_amcheck.c:72
const char * skip
Definition: pg_amcheck.c:99
char * amcheck_schema
Definition: pg_amcheck.c:150
char * datname
Definition: pg_amcheck.c:149
PGconn * connection
Definition: parallel_slot.h:23
PatternInfo * data
Definition: pg_amcheck.c:49
const char * pattern
Definition: pg_amcheck.c:34
char * rel_regex
Definition: pg_amcheck.c:38
char * db_regex
Definition: pg_amcheck.c:35
char * nsp_regex
Definition: pg_amcheck.c:37
bool btree_only
Definition: pg_amcheck.c:42
bool matched
Definition: pg_amcheck.c:44
bool heap_only
Definition: pg_amcheck.c:40
char * sql
Definition: pg_amcheck.c:162
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
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:89
char * pgport
Definition: pg_backup.h:83
char * pghost
Definition: pg_backup.h:84
char * dbname
Definition: pg_backup.h:82
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