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-2021, 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_generic(PG_LOG_ERROR, __VA_ARGS__); \
206  else \
207  pg_log_generic(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  {
400  pg_log_error("invalid argument for option %s", "--skip");
401  exit(1);
402  }
403  break;
404  case 7:
405  errno = 0;
406  optval = strtoul(optarg, &endptr, 10);
407  if (endptr == optarg || *endptr != '\0' || errno != 0)
408  {
409  pg_log_error("invalid start block");
410  exit(1);
411  }
412  if (optval > MaxBlockNumber)
413  {
414  pg_log_error("start block out of bounds");
415  exit(1);
416  }
417  opts.startblock = optval;
418  break;
419  case 8:
420  errno = 0;
421  optval = strtoul(optarg, &endptr, 10);
422  if (endptr == optarg || *endptr != '\0' || errno != 0)
423  {
424  pg_log_error("invalid end block");
425  exit(1);
426  }
427  if (optval > MaxBlockNumber)
428  {
429  pg_log_error("end block out of bounds");
430  exit(1);
431  }
432  opts.endblock = optval;
433  break;
434  case 9:
435  opts.rootdescend = true;
436  opts.parent_check = true;
437  break;
438  case 10:
439  opts.strict_names = false;
440  break;
441  case 11:
442  opts.heapallindexed = true;
443  break;
444  case 12:
445  opts.parent_check = true;
446  break;
447  case 13:
448  opts.install_missing = true;
449  if (optarg)
451  break;
452  default:
453  fprintf(stderr,
454  _("Try \"%s --help\" for more information.\n"),
455  progname);
456  exit(1);
457  }
458  }
459 
460  if (opts.endblock >= 0 && opts.endblock < opts.startblock)
461  {
462  pg_log_error("end block precedes start block");
463  exit(1);
464  }
465 
466  /*
467  * A single non-option arguments specifies a database name or connection
468  * string.
469  */
470  if (optind < argc)
471  {
472  db = argv[optind];
473  optind++;
474  }
475 
476  if (optind < argc)
477  {
478  pg_log_error("too many command-line arguments (first is \"%s\")",
479  argv[optind]);
480  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
481  exit(1);
482  }
483 
484  /* fill cparams except for dbname, which is set below */
485  cparams.pghost = host;
486  cparams.pgport = port;
487  cparams.pguser = username;
488  cparams.prompt_password = prompt_password;
489  cparams.dbname = NULL;
490  cparams.override_dbname = NULL;
491 
492  setup_cancel_handler(NULL);
493 
494  /* choose the database for our initial connection */
495  if (opts.alldb)
496  {
497  if (db != NULL)
498  {
499  pg_log_error("cannot specify a database name with --all");
500  exit(1);
501  }
502  cparams.dbname = maintenance_db;
503  }
504  else if (db != NULL)
505  {
506  if (opts.dbpattern)
507  {
508  pg_log_error("cannot specify both a database name and database patterns");
509  exit(1);
510  }
511  cparams.dbname = db;
512  }
513 
514  if (opts.alldb || opts.dbpattern)
515  {
517  compile_database_list(conn, &databases, NULL);
518  }
519  else
520  {
521  if (cparams.dbname == NULL)
522  {
523  if (getenv("PGDATABASE"))
524  cparams.dbname = getenv("PGDATABASE");
525  else if (getenv("PGUSER"))
526  cparams.dbname = getenv("PGUSER");
527  else
529  }
530  conn = connectDatabase(&cparams, progname, opts.echo, false, true);
531  compile_database_list(conn, &databases, PQdb(conn));
532  }
533 
534  if (databases.head == NULL)
535  {
536  if (conn != NULL)
538  pg_log_error("no databases to check");
539  exit(0);
540  }
541 
542  /*
543  * Compile a list of all relations spanning all databases to be checked.
544  */
545  for (cell = databases.head; cell; cell = cell->next)
546  {
547  PGresult *result;
548  int ntups;
549  const char *amcheck_schema = NULL;
550  DatabaseInfo *dat = (DatabaseInfo *) cell->ptr;
551 
552  cparams.override_dbname = dat->datname;
553  if (conn == NULL || strcmp(PQdb(conn), dat->datname) != 0)
554  {
555  if (conn != NULL)
557  conn = connectDatabase(&cparams, progname, opts.echo, false, true);
558  }
559 
560  /*
561  * Optionally install amcheck if not already installed in this
562  * database.
563  */
564  if (opts.install_missing)
565  {
566  char *schema;
567  char *install_sql;
568 
569  /*
570  * Must re-escape the schema name for each database, as the
571  * escaping rules may change.
572  */
574  strlen(opts.install_schema));
575  install_sql = psprintf("CREATE EXTENSION IF NOT EXISTS amcheck WITH SCHEMA %s",
576  schema);
577 
578  executeCommand(conn, install_sql, opts.echo);
579  pfree(install_sql);
580  pfree(schema);
581  }
582 
583  /*
584  * Verify that amcheck is installed for this next database. User
585  * error could result in a database not having amcheck that should
586  * have it, but we also could be iterating over multiple databases
587  * where not all of them have amcheck installed (for example,
588  * 'template1').
589  */
590  result = executeQuery(conn, amcheck_sql, opts.echo);
591  if (PQresultStatus(result) != PGRES_TUPLES_OK)
592  {
593  /* Querying the catalog failed. */
594  pg_log_error("database \"%s\": %s",
596  pg_log_info("query was: %s", amcheck_sql);
597  PQclear(result);
599  exit(1);
600  }
601  ntups = PQntuples(result);
602  if (ntups == 0)
603  {
604  /* Querying the catalog succeeded, but amcheck is missing. */
605  pg_log_warning("skipping database \"%s\": amcheck is not installed",
606  PQdb(conn));
608  conn = NULL;
609  continue;
610  }
611  amcheck_schema = PQgetvalue(result, 0, 0);
612  if (opts.verbose)
613  pg_log_info("in database \"%s\": using amcheck version \"%s\" in schema \"%s\"",
614  PQdb(conn), PQgetvalue(result, 0, 1), amcheck_schema);
615  dat->amcheck_schema = PQescapeIdentifier(conn, amcheck_schema,
616  strlen(amcheck_schema));
617  PQclear(result);
618 
619  compile_relation_list_one_db(conn, &relations, dat, &pagestotal);
620  }
621 
622  /*
623  * Check that all inclusion patterns matched at least one schema or
624  * relation that we can check.
625  */
626  for (pattern_id = 0; pattern_id < opts.include.len; pattern_id++)
627  {
628  PatternInfo *pat = &opts.include.data[pattern_id];
629 
630  if (!pat->matched && (pat->nsp_regex != NULL || pat->rel_regex != NULL))
631  {
632  failed = opts.strict_names;
633 
634  if (pat->heap_only)
635  log_no_match("no heap tables to check matching \"%s\"",
636  pat->pattern);
637  else if (pat->btree_only)
638  log_no_match("no btree indexes to check matching \"%s\"",
639  pat->pattern);
640  else if (pat->rel_regex == NULL)
641  log_no_match("no relations to check in schemas matching \"%s\"",
642  pat->pattern);
643  else
644  log_no_match("no relations to check matching \"%s\"",
645  pat->pattern);
646  }
647  }
648 
649  if (failed)
650  {
651  if (conn != NULL)
653  exit(1);
654  }
655 
656  /*
657  * Set parallel_workers to the lesser of opts.jobs and the number of
658  * relations.
659  */
660  parallel_workers = 0;
661  for (cell = relations.head; cell; cell = cell->next)
662  {
663  reltotal++;
664  if (parallel_workers < opts.jobs)
665  parallel_workers++;
666  }
667 
668  if (reltotal == 0)
669  {
670  if (conn != NULL)
672  pg_log_error("no relations to check");
673  exit(1);
674  }
675  progress_report(reltotal, relprogress, pagestotal, pageschecked,
676  NULL, true, false);
677 
678  /*
679  * Main event loop.
680  *
681  * We use server-side parallelism to check up to parallel_workers
682  * relations in parallel. The list of relations was computed in database
683  * order, which minimizes the number of connects and disconnects as we
684  * process the list.
685  */
686  latest_datname = NULL;
687  sa = ParallelSlotsSetup(parallel_workers, &cparams, progname, opts.echo,
688  NULL);
689  if (conn != NULL)
690  {
692  conn = NULL;
693  }
694 
695  initPQExpBuffer(&sql);
696  for (relprogress = 0, cell = relations.head; cell; cell = cell->next)
697  {
698  ParallelSlot *free_slot;
699  RelationInfo *rel;
700 
701  rel = (RelationInfo *) cell->ptr;
702 
704  {
705  failed = true;
706  break;
707  }
708 
709  /*
710  * The list of relations is in database sorted order. If this next
711  * relation is in a different database than the last one seen, we are
712  * about to start checking this database. Note that other slots may
713  * still be working on relations from prior databases.
714  */
715  latest_datname = rel->datinfo->datname;
716 
717  progress_report(reltotal, relprogress, pagestotal, pageschecked,
718  latest_datname, false, false);
719 
720  relprogress++;
721  pageschecked += rel->blocks_to_check;
722 
723  /*
724  * Get a parallel slot for the next amcheck command, blocking if
725  * necessary until one is available, or until a previously issued slot
726  * command fails, indicating that we should abort checking the
727  * remaining objects.
728  */
729  free_slot = ParallelSlotsGetIdle(sa, rel->datinfo->datname);
730  if (!free_slot)
731  {
732  /*
733  * Something failed. We don't need to know what it was, because
734  * the handler should already have emitted the necessary error
735  * messages.
736  */
737  failed = true;
738  break;
739  }
740 
741  if (opts.verbose)
743 
744  /*
745  * Execute the appropriate amcheck command for this relation using our
746  * slot's database connection. We do not wait for the command to
747  * complete, nor do we perform any error checking, as that is done by
748  * the parallel slots and our handler callback functions.
749  */
750  if (rel->is_heap)
751  {
752  if (opts.verbose)
753  {
755  fprintf(stderr, "\n");
756  pg_log_info("checking heap table \"%s.%s.%s\"",
757  rel->datinfo->datname, rel->nspname, rel->relname);
759  }
760  prepare_heap_command(&sql, rel, free_slot->connection);
761  rel->sql = pstrdup(sql.data); /* pg_free'd after command */
763  run_command(free_slot, rel->sql);
764  }
765  else
766  {
767  if (opts.verbose)
768  {
770  fprintf(stderr, "\n");
771 
772  pg_log_info("checking btree index \"%s.%s.%s\"",
773  rel->datinfo->datname, rel->nspname, rel->relname);
775  }
776  prepare_btree_command(&sql, rel, free_slot->connection);
777  rel->sql = pstrdup(sql.data); /* pg_free'd after command */
779  run_command(free_slot, rel->sql);
780  }
781  }
782  termPQExpBuffer(&sql);
783 
784  if (!failed)
785  {
786 
787  /*
788  * Wait for all slots to complete, or for one to indicate that an
789  * error occurred. Like above, we rely on the handler emitting the
790  * necessary error messages.
791  */
793  failed = true;
794 
795  progress_report(reltotal, relprogress, pagestotal, pageschecked, NULL, true, true);
796  }
797 
798  if (sa)
799  {
802  }
803 
804  if (failed)
805  exit(1);
806 
807  if (!all_checks_pass)
808  exit(2);
809 }
810 
811 /*
812  * prepare_heap_command
813  *
814  * Creates a SQL command for running amcheck checking on the given heap
815  * relation. The command is phrased as a SQL query, with column order and
816  * names matching the expectations of verify_heap_slot_handler, which will
817  * receive and handle each row returned from the verify_heapam() function.
818  *
819  * The constructed SQL command will silently skip temporary tables, as checking
820  * them would needlessly draw errors from the underlying amcheck function.
821  *
822  * sql: buffer into which the heap table checking command will be written
823  * rel: relation information for the heap table to be checked
824  * conn: the connection to be used, for string escaping purposes
825  */
826 static void
828 {
829  resetPQExpBuffer(sql);
830  appendPQExpBuffer(sql,
831  "SELECT v.blkno, v.offnum, v.attnum, v.msg "
832  "FROM pg_catalog.pg_class c, %s.verify_heapam("
833  "\nrelation := c.oid, on_error_stop := %s, check_toast := %s, skip := '%s'",
834  rel->datinfo->amcheck_schema,
835  opts.on_error_stop ? "true" : "false",
836  opts.reconcile_toast ? "true" : "false",
837  opts.skip);
838 
839  if (opts.startblock >= 0)
840  appendPQExpBuffer(sql, ", startblock := " INT64_FORMAT, opts.startblock);
841  if (opts.endblock >= 0)
842  appendPQExpBuffer(sql, ", endblock := " INT64_FORMAT, opts.endblock);
843 
844  appendPQExpBuffer(sql,
845  "\n) v WHERE c.oid = %u "
846  "AND c.relpersistence != 't'",
847  rel->reloid);
848 }
849 
850 /*
851  * prepare_btree_command
852  *
853  * Creates a SQL command for running amcheck checking on the given btree index
854  * relation. The command does not select any columns, as btree checking
855  * functions do not return any, but rather return corruption information by
856  * raising errors, which verify_btree_slot_handler expects.
857  *
858  * The constructed SQL command will silently skip temporary indexes, and
859  * indexes being reindexed concurrently, as checking them would needlessly draw
860  * errors from the underlying amcheck functions.
861  *
862  * sql: buffer into which the heap table checking command will be written
863  * rel: relation information for the index to be checked
864  * conn: the connection to be used, for string escaping purposes
865  */
866 static void
868 {
869  resetPQExpBuffer(sql);
870 
871  if (opts.parent_check)
872  appendPQExpBuffer(sql,
873  "SELECT %s.bt_index_parent_check("
874  "index := c.oid, heapallindexed := %s, rootdescend := %s)"
875  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_index i "
876  "WHERE c.oid = %u "
877  "AND c.oid = i.indexrelid "
878  "AND c.relpersistence != 't' "
879  "AND i.indisready AND i.indisvalid AND i.indislive",
880  rel->datinfo->amcheck_schema,
881  (opts.heapallindexed ? "true" : "false"),
882  (opts.rootdescend ? "true" : "false"),
883  rel->reloid);
884  else
885  appendPQExpBuffer(sql,
886  "SELECT %s.bt_index_check("
887  "index := c.oid, heapallindexed := %s)"
888  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_index i "
889  "WHERE c.oid = %u "
890  "AND c.oid = i.indexrelid "
891  "AND c.relpersistence != 't' "
892  "AND i.indisready AND i.indisvalid AND i.indislive",
893  rel->datinfo->amcheck_schema,
894  (opts.heapallindexed ? "true" : "false"),
895  rel->reloid);
896 }
897 
898 /*
899  * run_command
900  *
901  * Sends a command to the server without waiting for the command to complete.
902  * Logs an error if the command cannot be sent, but otherwise any errors are
903  * expected to be handled by a ParallelSlotHandler.
904  *
905  * If reconnecting to the database is necessary, the cparams argument may be
906  * modified.
907  *
908  * slot: slot with connection to the server we should use for the command
909  * sql: query to send
910  */
911 static void
912 run_command(ParallelSlot *slot, const char *sql)
913 {
914  if (opts.echo)
915  printf("%s\n", sql);
916 
917  if (PQsendQuery(slot->connection, sql) == 0)
918  {
919  pg_log_error("error sending command to database \"%s\": %s",
920  PQdb(slot->connection),
921  PQerrorMessage(slot->connection));
922  pg_log_error("command was: %s", sql);
923  exit(1);
924  }
925 }
926 
927 /*
928  * should_processing_continue
929  *
930  * Checks a query result returned from a query (presumably issued on a slot's
931  * connection) to determine if parallel slots should continue issuing further
932  * commands.
933  *
934  * Note: Heap relation corruption is reported by verify_heapam() via the result
935  * set, rather than an ERROR, but running verify_heapam() on a corrupted heap
936  * table may still result in an error being returned from the server due to
937  * missing relation files, bad checksums, etc. The btree corruption checking
938  * functions always use errors to communicate corruption messages. We can't
939  * just abort processing because we got a mere ERROR.
940  *
941  * res: result from an executed sql query
942  */
943 static bool
945 {
946  const char *severity;
947 
948  switch (PQresultStatus(res))
949  {
950  /* These are expected and ok */
951  case PGRES_COMMAND_OK:
952  case PGRES_TUPLES_OK:
954  break;
955 
956  /* This is expected but requires closer scrutiny */
957  case PGRES_FATAL_ERROR:
959  if (strcmp(severity, "FATAL") == 0)
960  return false;
961  if (strcmp(severity, "PANIC") == 0)
962  return false;
963  break;
964 
965  /* These are unexpected */
966  case PGRES_BAD_RESPONSE:
967  case PGRES_EMPTY_QUERY:
968  case PGRES_COPY_OUT:
969  case PGRES_COPY_IN:
970  case PGRES_COPY_BOTH:
971  case PGRES_SINGLE_TUPLE:
972  case PGRES_PIPELINE_SYNC:
974  return false;
975  }
976  return true;
977 }
978 
979 /*
980  * Returns a copy of the argument string with all lines indented four spaces.
981  *
982  * The caller should pg_free the result when finished with it.
983  */
984 static char *
985 indent_lines(const char *str)
986 {
988  const char *c;
989  char *result;
990 
992  appendPQExpBufferStr(&buf, " ");
993  for (c = str; *c; c++)
994  {
996  if (c[0] == '\n' && c[1] != '\0')
997  appendPQExpBufferStr(&buf, " ");
998  }
999  result = pstrdup(buf.data);
1000  termPQExpBuffer(&buf);
1001 
1002  return result;
1003 }
1004 
1005 /*
1006  * verify_heap_slot_handler
1007  *
1008  * ParallelSlotHandler that receives results from a heap table checking command
1009  * created by prepare_heap_command and outputs the results for the user.
1010  *
1011  * res: result from an executed sql query
1012  * conn: connection on which the sql query was executed
1013  * context: the sql query being handled, as a cstring
1014  */
1015 static bool
1017 {
1018  RelationInfo *rel = (RelationInfo *) context;
1019 
1021  {
1022  int i;
1023  int ntups = PQntuples(res);
1024 
1025  if (ntups > 0)
1026  all_checks_pass = false;
1027 
1028  for (i = 0; i < ntups; i++)
1029  {
1030  const char *msg;
1031 
1032  /* The message string should never be null, but check */
1033  if (PQgetisnull(res, i, 3))
1034  msg = "NO MESSAGE";
1035  else
1036  msg = PQgetvalue(res, i, 3);
1037 
1038  if (!PQgetisnull(res, i, 2))
1039  printf(_("heap table \"%s.%s.%s\", block %s, offset %s, attribute %s:\n"),
1040  rel->datinfo->datname, rel->nspname, rel->relname,
1041  PQgetvalue(res, i, 0), /* blkno */
1042  PQgetvalue(res, i, 1), /* offnum */
1043  PQgetvalue(res, i, 2)); /* attnum */
1044 
1045  else if (!PQgetisnull(res, i, 1))
1046  printf(_("heap table \"%s.%s.%s\", block %s, offset %s:\n"),
1047  rel->datinfo->datname, rel->nspname, rel->relname,
1048  PQgetvalue(res, i, 0), /* blkno */
1049  PQgetvalue(res, i, 1)); /* offnum */
1050 
1051  else if (!PQgetisnull(res, i, 0))
1052  printf(_("heap table \"%s.%s.%s\", block %s:\n"),
1053  rel->datinfo->datname, rel->nspname, rel->relname,
1054  PQgetvalue(res, i, 0)); /* blkno */
1055 
1056  else
1057  printf(_("heap table \"%s.%s.%s\":\n"),
1058  rel->datinfo->datname, rel->nspname, rel->relname);
1059 
1060  printf(" %s\n", msg);
1061  }
1062  }
1063  else if (PQresultStatus(res) != PGRES_TUPLES_OK)
1064  {
1065  char *msg = indent_lines(PQerrorMessage(conn));
1066 
1067  all_checks_pass = false;
1068  printf(_("heap table \"%s.%s.%s\":\n"),
1069  rel->datinfo->datname, rel->nspname, rel->relname);
1070  printf("%s", msg);
1071  if (opts.verbose)
1072  printf(_("query was: %s\n"), rel->sql);
1073  FREE_AND_SET_NULL(msg);
1074  }
1075 
1076  FREE_AND_SET_NULL(rel->sql);
1077  FREE_AND_SET_NULL(rel->nspname);
1078  FREE_AND_SET_NULL(rel->relname);
1079 
1081 }
1082 
1083 /*
1084  * verify_btree_slot_handler
1085  *
1086  * ParallelSlotHandler that receives results from a btree checking command
1087  * created by prepare_btree_command and outputs them for the user. The results
1088  * from the btree checking command is assumed to be empty, but when the results
1089  * are an error code, the useful information about the corruption is expected
1090  * in the connection's error message.
1091  *
1092  * res: result from an executed sql query
1093  * conn: connection on which the sql query was executed
1094  * context: unused
1095  */
1096 static bool
1098 {
1099  RelationInfo *rel = (RelationInfo *) context;
1100 
1102  {
1103  int ntups = PQntuples(res);
1104 
1105  if (ntups > 1)
1106  {
1107  /*
1108  * We expect the btree checking functions to return one void row
1109  * each, or zero rows if the check was skipped due to the object
1110  * being in the wrong state to be checked, so we should output some
1111  * sort of warning if we get anything more, not because it
1112  * indicates corruption, but because it suggests a mismatch between
1113  * amcheck and pg_amcheck versions.
1114  *
1115  * In conjunction with --progress, anything written to stderr at
1116  * this time would present strangely to the user without an extra
1117  * newline, so we print one. If we were multithreaded, we'd have
1118  * to avoid splitting this across multiple calls, but we're in an
1119  * event loop, so it doesn't matter.
1120  */
1122  fprintf(stderr, "\n");
1123  pg_log_warning("btree index \"%s.%s.%s\": btree checking function returned unexpected number of rows: %d",
1124  rel->datinfo->datname, rel->nspname, rel->relname, ntups);
1125  if (opts.verbose)
1126  pg_log_info("query was: %s", rel->sql);
1127  pg_log_warning("Are %s's and amcheck's versions compatible?",
1128  progname);
1130  }
1131  }
1132  else
1133  {
1134  char *msg = indent_lines(PQerrorMessage(conn));
1135 
1136  all_checks_pass = false;
1137  printf(_("btree index \"%s.%s.%s\":\n"),
1138  rel->datinfo->datname, rel->nspname, rel->relname);
1139  printf("%s", msg);
1140  if (opts.verbose)
1141  printf(_("query was: %s\n"), rel->sql);
1142  FREE_AND_SET_NULL(msg);
1143  }
1144 
1145  FREE_AND_SET_NULL(rel->sql);
1146  FREE_AND_SET_NULL(rel->nspname);
1147  FREE_AND_SET_NULL(rel->relname);
1148 
1150 }
1151 
1152 /*
1153  * help
1154  *
1155  * Prints help page for the program
1156  *
1157  * progname: the name of the executed program, such as "pg_amcheck"
1158  */
1159 static void
1160 help(const char *progname)
1161 {
1162  printf(_("%s checks objects in a PostgreSQL database for corruption.\n\n"), progname);
1163  printf(_("Usage:\n"));
1164  printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
1165  printf(_("\nTarget options:\n"));
1166  printf(_(" -a, --all check all databases\n"));
1167  printf(_(" -d, --database=PATTERN check matching database(s)\n"));
1168  printf(_(" -D, --exclude-database=PATTERN do NOT check matching database(s)\n"));
1169  printf(_(" -i, --index=PATTERN check matching index(es)\n"));
1170  printf(_(" -I, --exclude-index=PATTERN do NOT check matching index(es)\n"));
1171  printf(_(" -r, --relation=PATTERN check matching relation(s)\n"));
1172  printf(_(" -R, --exclude-relation=PATTERN do NOT check matching relation(s)\n"));
1173  printf(_(" -s, --schema=PATTERN check matching schema(s)\n"));
1174  printf(_(" -S, --exclude-schema=PATTERN do NOT check matching schema(s)\n"));
1175  printf(_(" -t, --table=PATTERN check matching table(s)\n"));
1176  printf(_(" -T, --exclude-table=PATTERN do NOT check matching table(s)\n"));
1177  printf(_(" --no-dependent-indexes do NOT expand list of relations to include indexes\n"));
1178  printf(_(" --no-dependent-toast do NOT expand list of relations to include TOAST tables\n"));
1179  printf(_(" --no-strict-names do NOT require patterns to match objects\n"));
1180  printf(_("\nTable checking options:\n"));
1181  printf(_(" --exclude-toast-pointers do NOT follow relation TOAST pointers\n"));
1182  printf(_(" --on-error-stop stop checking at end of first corrupt page\n"));
1183  printf(_(" --skip=OPTION do NOT check \"all-frozen\" or \"all-visible\" blocks\n"));
1184  printf(_(" --startblock=BLOCK begin checking table(s) at the given block number\n"));
1185  printf(_(" --endblock=BLOCK check table(s) only up to the given block number\n"));
1186  printf(_("\nB-tree index checking options:\n"));
1187  printf(_(" --heapallindexed check that all heap tuples are found within indexes\n"));
1188  printf(_(" --parent-check check index parent/child relationships\n"));
1189  printf(_(" --rootdescend search from root page to refind tuples\n"));
1190  printf(_("\nConnection options:\n"));
1191  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1192  printf(_(" -p, --port=PORT database server port\n"));
1193  printf(_(" -U, --username=USERNAME user name to connect as\n"));
1194  printf(_(" -w, --no-password never prompt for password\n"));
1195  printf(_(" -W, --password force password prompt\n"));
1196  printf(_(" --maintenance-db=DBNAME alternate maintenance database\n"));
1197  printf(_("\nOther options:\n"));
1198  printf(_(" -e, --echo show the commands being sent to the server\n"));
1199  printf(_(" -j, --jobs=NUM use this many concurrent connections to the server\n"));
1200  printf(_(" -P, --progress show progress information\n"));
1201  printf(_(" -v, --verbose write a lot of output\n"));
1202  printf(_(" -V, --version output version information, then exit\n"));
1203  printf(_(" --install-missing install missing extensions\n"));
1204  printf(_(" -?, --help show this help, then exit\n"));
1205 
1206  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1207  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1208 }
1209 
1210 /*
1211  * Print a progress report based on the global variables.
1212  *
1213  * Progress report is written at maximum once per second, unless the force
1214  * parameter is set to true.
1215  *
1216  * If finished is set to true, this is the last progress report. The cursor
1217  * is moved to the next line.
1218  */
1219 static void
1220 progress_report(uint64 relations_total, uint64 relations_checked,
1221  uint64 relpages_total, uint64 relpages_checked,
1222  const char *datname, bool force, bool finished)
1223 {
1224  int percent_rel = 0;
1225  int percent_pages = 0;
1226  char checked_rel[32];
1227  char total_rel[32];
1228  char checked_pages[32];
1229  char total_pages[32];
1230  pg_time_t now;
1231 
1232  if (!opts.show_progress)
1233  return;
1234 
1235  now = time(NULL);
1236  if (now == last_progress_report && !force && !finished)
1237  return; /* Max once per second */
1238 
1240  if (relations_total)
1241  percent_rel = (int) (relations_checked * 100 / relations_total);
1242  if (relpages_total)
1243  percent_pages = (int) (relpages_checked * 100 / relpages_total);
1244 
1245  snprintf(checked_rel, sizeof(checked_rel), UINT64_FORMAT, relations_checked);
1246  snprintf(total_rel, sizeof(total_rel), UINT64_FORMAT, relations_total);
1247  snprintf(checked_pages, sizeof(checked_pages), UINT64_FORMAT, relpages_checked);
1248  snprintf(total_pages, sizeof(total_pages), UINT64_FORMAT, relpages_total);
1249 
1250 #define VERBOSE_DATNAME_LENGTH 35
1251  if (opts.verbose)
1252  {
1253  if (!datname)
1254 
1255  /*
1256  * No datname given, so clear the status line (used for first and
1257  * last call)
1258  */
1259  fprintf(stderr,
1260  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) %*s"),
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  VERBOSE_DATNAME_LENGTH + 2, "");
1266  else
1267  {
1268  bool truncate = (strlen(datname) > VERBOSE_DATNAME_LENGTH);
1269 
1270  fprintf(stderr,
1271  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%) (%s%-*.*s)"),
1272  (int) strlen(total_rel),
1273  checked_rel, total_rel, percent_rel,
1274  (int) strlen(total_pages),
1275  checked_pages, total_pages, percent_pages,
1276  /* Prefix with "..." if we do leading truncation */
1277  truncate ? "..." : "",
1280  /* Truncate datname at beginning if it's too long */
1281  truncate ? datname + strlen(datname) - VERBOSE_DATNAME_LENGTH + 3 : datname);
1282  }
1283  }
1284  else
1285  fprintf(stderr,
1286  _("%*s/%s relations (%d%%), %*s/%s pages (%d%%)"),
1287  (int) strlen(total_rel),
1288  checked_rel, total_rel, percent_rel,
1289  (int) strlen(total_pages),
1290  checked_pages, total_pages, percent_pages);
1291 
1292  /*
1293  * Stay on the same line if reporting to a terminal and we're not done
1294  * yet.
1295  */
1296  if (!finished && isatty(fileno(stderr)))
1297  {
1298  fputc('\r', stderr);
1300  }
1301  else
1302  fputc('\n', stderr);
1303 }
1304 
1305 /*
1306  * Extend the pattern info array to hold one additional initialized pattern
1307  * info entry.
1308  *
1309  * Returns a pointer to the new entry.
1310  */
1311 static PatternInfo *
1313 {
1314  PatternInfo *result;
1315 
1316  pia->len++;
1317  pia->data = (PatternInfo *) pg_realloc(pia->data, pia->len * sizeof(PatternInfo));
1318  result = &pia->data[pia->len - 1];
1319  memset(result, 0, sizeof(*result));
1320 
1321  return result;
1322 }
1323 
1324 /*
1325  * append_database_pattern
1326  *
1327  * Adds the given pattern interpreted as a database name pattern.
1328  *
1329  * pia: the pattern info array to be appended
1330  * pattern: the database name pattern
1331  * encoding: client encoding for parsing the pattern
1332  */
1333 static void
1334 append_database_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1335 {
1338 
1339  initPQExpBuffer(&buf);
1340  patternToSQLRegex(encoding, NULL, NULL, &buf, pattern, false);
1341  info->pattern = pattern;
1342  info->db_regex = pstrdup(buf.data);
1343 
1344  termPQExpBuffer(&buf);
1345 }
1346 
1347 /*
1348  * append_schema_pattern
1349  *
1350  * Adds the given pattern interpreted as a schema name pattern.
1351  *
1352  * pia: the pattern info array to be appended
1353  * pattern: the schema name pattern
1354  * encoding: client encoding for parsing the pattern
1355  */
1356 static void
1357 append_schema_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1358 {
1359  PQExpBufferData dbbuf;
1360  PQExpBufferData nspbuf;
1362 
1363  initPQExpBuffer(&dbbuf);
1364  initPQExpBuffer(&nspbuf);
1365 
1366  patternToSQLRegex(encoding, NULL, &dbbuf, &nspbuf, pattern, false);
1367  info->pattern = pattern;
1368  if (dbbuf.data[0])
1369  {
1370  opts.dbpattern = true;
1371  info->db_regex = pstrdup(dbbuf.data);
1372  }
1373  if (nspbuf.data[0])
1374  info->nsp_regex = pstrdup(nspbuf.data);
1375 
1376  termPQExpBuffer(&dbbuf);
1377  termPQExpBuffer(&nspbuf);
1378 }
1379 
1380 /*
1381  * append_relation_pattern_helper
1382  *
1383  * Adds to a list the given pattern interpreted as a relation pattern.
1384  *
1385  * pia: the pattern info array to be appended
1386  * pattern: the relation name pattern
1387  * encoding: client encoding for parsing the pattern
1388  * heap_only: whether the pattern should only be matched against heap tables
1389  * btree_only: whether the pattern should only be matched against btree indexes
1390  */
1391 static void
1393  int encoding, bool heap_only, bool btree_only)
1394 {
1395  PQExpBufferData dbbuf;
1396  PQExpBufferData nspbuf;
1397  PQExpBufferData relbuf;
1399 
1400  initPQExpBuffer(&dbbuf);
1401  initPQExpBuffer(&nspbuf);
1402  initPQExpBuffer(&relbuf);
1403 
1404  patternToSQLRegex(encoding, &dbbuf, &nspbuf, &relbuf, pattern, false);
1405  info->pattern = pattern;
1406  if (dbbuf.data[0])
1407  {
1408  opts.dbpattern = true;
1409  info->db_regex = pstrdup(dbbuf.data);
1410  }
1411  if (nspbuf.data[0])
1412  info->nsp_regex = pstrdup(nspbuf.data);
1413  if (relbuf.data[0])
1414  info->rel_regex = pstrdup(relbuf.data);
1415 
1416  termPQExpBuffer(&dbbuf);
1417  termPQExpBuffer(&nspbuf);
1418  termPQExpBuffer(&relbuf);
1419 
1420  info->heap_only = heap_only;
1421  info->btree_only = btree_only;
1422 }
1423 
1424 /*
1425  * append_relation_pattern
1426  *
1427  * Adds the given pattern interpreted as a relation pattern, to be matched
1428  * against both heap tables and btree indexes.
1429  *
1430  * pia: the pattern info array to be appended
1431  * pattern: the relation name pattern
1432  * encoding: client encoding for parsing the pattern
1433  */
1434 static void
1435 append_relation_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1436 {
1437  append_relation_pattern_helper(pia, pattern, encoding, false, false);
1438 }
1439 
1440 /*
1441  * append_heap_pattern
1442  *
1443  * Adds the given pattern interpreted as a relation pattern, to be matched only
1444  * against heap tables.
1445  *
1446  * pia: the pattern info array to be appended
1447  * pattern: the relation name pattern
1448  * encoding: client encoding for parsing the pattern
1449  */
1450 static void
1451 append_heap_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1452 {
1453  append_relation_pattern_helper(pia, pattern, encoding, true, false);
1454 }
1455 
1456 /*
1457  * append_btree_pattern
1458  *
1459  * Adds the given pattern interpreted as a relation pattern, to be matched only
1460  * against btree indexes.
1461  *
1462  * pia: the pattern info array to be appended
1463  * pattern: the relation name pattern
1464  * encoding: client encoding for parsing the pattern
1465  */
1466 static void
1467 append_btree_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
1468 {
1469  append_relation_pattern_helper(pia, pattern, encoding, false, true);
1470 }
1471 
1472 /*
1473  * append_db_pattern_cte
1474  *
1475  * Appends to the buffer the body of a Common Table Expression (CTE) containing
1476  * the database portions filtered from the list of patterns expressed as two
1477  * columns:
1478  *
1479  * pattern_id: the index of this pattern in pia->data[]
1480  * rgx: the database regular expression parsed from the pattern
1481  *
1482  * Patterns without a database portion are skipped. Patterns with more than
1483  * just a database portion are optionally skipped, depending on argument
1484  * 'inclusive'.
1485  *
1486  * buf: the buffer to be appended
1487  * pia: the array of patterns to be inserted into the CTE
1488  * conn: the database connection
1489  * inclusive: whether to include patterns with schema and/or relation parts
1490  *
1491  * Returns whether any database patterns were appended.
1492  */
1493 static bool
1495  PGconn *conn, bool inclusive)
1496 {
1497  int pattern_id;
1498  const char *comma;
1499  bool have_values;
1500 
1501  comma = "";
1502  have_values = false;
1503  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1504  {
1505  PatternInfo *info = &pia->data[pattern_id];
1506 
1507  if (info->db_regex != NULL &&
1508  (inclusive || (info->nsp_regex == NULL && info->rel_regex == NULL)))
1509  {
1510  if (!have_values)
1511  appendPQExpBufferStr(buf, "\nVALUES");
1512  have_values = true;
1513  appendPQExpBuffer(buf, "%s\n(%d, ", comma, pattern_id);
1515  appendPQExpBufferStr(buf, ")");
1516  comma = ",";
1517  }
1518  }
1519 
1520  if (!have_values)
1521  appendPQExpBufferStr(buf, "\nSELECT NULL, NULL, NULL WHERE false");
1522 
1523  return have_values;
1524 }
1525 
1526 /*
1527  * compile_database_list
1528  *
1529  * If any database patterns exist, or if --all was given, compiles a distinct
1530  * list of databases to check using a SQL query based on the patterns plus the
1531  * literal initial database name, if given. If no database patterns exist and
1532  * --all was not given, the query is not necessary, and only the initial
1533  * database name (if any) is added to the list.
1534  *
1535  * conn: connection to the initial database
1536  * databases: the list onto which databases should be appended
1537  * initial_dbname: an optional extra database name to include in the list
1538  */
1539 static void
1541  const char *initial_dbname)
1542 {
1543  PGresult *res;
1544  PQExpBufferData sql;
1545  int ntups;
1546  int i;
1547  bool fatal;
1548 
1549  if (initial_dbname)
1550  {
1551  DatabaseInfo *dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1552 
1553  /* This database is included. Add to list */
1554  if (opts.verbose)
1555  pg_log_info("including database \"%s\"", initial_dbname);
1556 
1557  dat->datname = pstrdup(initial_dbname);
1558  simple_ptr_list_append(databases, dat);
1559  }
1560 
1561  initPQExpBuffer(&sql);
1562 
1563  /* Append the include patterns CTE. */
1564  appendPQExpBufferStr(&sql, "WITH include_raw (pattern_id, rgx) AS (");
1565  if (!append_db_pattern_cte(&sql, &opts.include, conn, true) &&
1566  !opts.alldb)
1567  {
1568  /*
1569  * None of the inclusion patterns (if any) contain database portions,
1570  * so there is no need to query the database to resolve database
1571  * patterns.
1572  *
1573  * Since we're also not operating under --all, we don't need to query
1574  * the exhaustive list of connectable databases, either.
1575  */
1576  termPQExpBuffer(&sql);
1577  return;
1578  }
1579 
1580  /* Append the exclude patterns CTE. */
1581  appendPQExpBufferStr(&sql, "),\nexclude_raw (pattern_id, rgx) AS (");
1582  append_db_pattern_cte(&sql, &opts.exclude, conn, false);
1583  appendPQExpBufferStr(&sql, "),");
1584 
1585  /*
1586  * Append the database CTE, which includes whether each database is
1587  * connectable and also joins against exclude_raw to determine whether
1588  * each database is excluded.
1589  */
1590  appendPQExpBufferStr(&sql,
1591  "\ndatabase (datname) AS ("
1592  "\nSELECT d.datname "
1593  "FROM pg_catalog.pg_database d "
1594  "LEFT OUTER JOIN exclude_raw e "
1595  "ON d.datname ~ e.rgx "
1596  "\nWHERE d.datallowconn "
1597  "AND e.pattern_id IS NULL"
1598  "),"
1599 
1600  /*
1601  * Append the include_pat CTE, which joins the include_raw CTE against the
1602  * databases CTE to determine if all the inclusion patterns had matches,
1603  * and whether each matched pattern had the misfortune of only matching
1604  * excluded or unconnectable databases.
1605  */
1606  "\ninclude_pat (pattern_id, checkable) AS ("
1607  "\nSELECT i.pattern_id, "
1608  "COUNT(*) FILTER ("
1609  "WHERE d IS NOT NULL"
1610  ") AS checkable"
1611  "\nFROM include_raw i "
1612  "LEFT OUTER JOIN database d "
1613  "ON d.datname ~ i.rgx"
1614  "\nGROUP BY i.pattern_id"
1615  "),"
1616 
1617  /*
1618  * Append the filtered_databases CTE, which selects from the database CTE
1619  * optionally joined against the include_raw CTE to only select databases
1620  * that match an inclusion pattern. This appears to duplicate what the
1621  * include_pat CTE already did above, but here we want only databases, and
1622  * there we wanted patterns.
1623  */
1624  "\nfiltered_databases (datname) AS ("
1625  "\nSELECT DISTINCT d.datname "
1626  "FROM database d");
1627  if (!opts.alldb)
1628  appendPQExpBufferStr(&sql,
1629  " INNER JOIN include_raw i "
1630  "ON d.datname ~ i.rgx");
1631  appendPQExpBufferStr(&sql,
1632  ")"
1633 
1634  /*
1635  * Select the checkable databases and the unmatched inclusion patterns.
1636  */
1637  "\nSELECT pattern_id, datname FROM ("
1638  "\nSELECT pattern_id, NULL::TEXT AS datname "
1639  "FROM include_pat "
1640  "WHERE checkable = 0 "
1641  "UNION ALL"
1642  "\nSELECT NULL, datname "
1643  "FROM filtered_databases"
1644  ") AS combined_records"
1645  "\nORDER BY pattern_id NULLS LAST, datname");
1646 
1647  res = executeQuery(conn, sql.data, opts.echo);
1649  {
1650  pg_log_error("query failed: %s", PQerrorMessage(conn));
1651  pg_log_info("query was: %s", sql.data);
1653  exit(1);
1654  }
1655  termPQExpBuffer(&sql);
1656 
1657  ntups = PQntuples(res);
1658  for (fatal = false, i = 0; i < ntups; i++)
1659  {
1660  int pattern_id = -1;
1661  const char *datname = NULL;
1662 
1663  if (!PQgetisnull(res, i, 0))
1664  pattern_id = atoi(PQgetvalue(res, i, 0));
1665  if (!PQgetisnull(res, i, 1))
1666  datname = PQgetvalue(res, i, 1);
1667 
1668  if (pattern_id >= 0)
1669  {
1670  /*
1671  * Current record pertains to an inclusion pattern that matched no
1672  * checkable databases.
1673  */
1675  if (pattern_id >= opts.include.len)
1676  {
1677  pg_log_error("internal error: received unexpected database pattern_id %d",
1678  pattern_id);
1679  exit(1);
1680  }
1681  log_no_match("no connectable databases to check matching \"%s\"",
1682  opts.include.data[pattern_id].pattern);
1683  }
1684  else
1685  {
1686  DatabaseInfo *dat;
1687 
1688  /* Current record pertains to a database */
1689  Assert(datname != NULL);
1690 
1691  /* Avoid entering a duplicate entry matching the initial_dbname */
1692  if (initial_dbname != NULL && strcmp(initial_dbname, datname) == 0)
1693  continue;
1694 
1695  /* This database is included. Add to list */
1696  if (opts.verbose)
1697  pg_log_info("including database \"%s\"", datname);
1698 
1699  dat = (DatabaseInfo *) pg_malloc0(sizeof(DatabaseInfo));
1700  dat->datname = pstrdup(datname);
1701  simple_ptr_list_append(databases, dat);
1702  }
1703  }
1704  PQclear(res);
1705 
1706  if (fatal)
1707  {
1708  if (conn != NULL)
1710  exit(1);
1711  }
1712 }
1713 
1714 /*
1715  * append_rel_pattern_raw_cte
1716  *
1717  * Appends to the buffer the body of a Common Table Expression (CTE) containing
1718  * the given patterns as six columns:
1719  *
1720  * pattern_id: the index of this pattern in pia->data[]
1721  * db_regex: the database regexp parsed from the pattern, or NULL if the
1722  * pattern had no database part
1723  * nsp_regex: the namespace regexp parsed from the pattern, or NULL if the
1724  * pattern had no namespace part
1725  * rel_regex: the relname regexp parsed from the pattern, or NULL if the
1726  * pattern had no relname part
1727  * heap_only: true if the pattern applies only to heap tables (not indexes)
1728  * btree_only: true if the pattern applies only to btree indexes (not tables)
1729  *
1730  * buf: the buffer to be appended
1731  * patterns: the array of patterns to be inserted into the CTE
1732  * conn: the database connection
1733  */
1734 static void
1736  PGconn *conn)
1737 {
1738  int pattern_id;
1739  const char *comma;
1740  bool have_values;
1741 
1742  comma = "";
1743  have_values = false;
1744  for (pattern_id = 0; pattern_id < pia->len; pattern_id++)
1745  {
1746  PatternInfo *info = &pia->data[pattern_id];
1747 
1748  if (!have_values)
1749  appendPQExpBufferStr(buf, "\nVALUES");
1750  have_values = true;
1751  appendPQExpBuffer(buf, "%s\n(%d::INTEGER, ", comma, pattern_id);
1752  if (info->db_regex == NULL)
1753  appendPQExpBufferStr(buf, "NULL");
1754  else
1756  appendPQExpBufferStr(buf, "::TEXT, ");
1757  if (info->nsp_regex == NULL)
1758  appendPQExpBufferStr(buf, "NULL");
1759  else
1761  appendPQExpBufferStr(buf, "::TEXT, ");
1762  if (info->rel_regex == NULL)
1763  appendPQExpBufferStr(buf, "NULL");
1764  else
1766  if (info->heap_only)
1767  appendPQExpBufferStr(buf, "::TEXT, true::BOOLEAN");
1768  else
1769  appendPQExpBufferStr(buf, "::TEXT, false::BOOLEAN");
1770  if (info->btree_only)
1771  appendPQExpBufferStr(buf, ", true::BOOLEAN");
1772  else
1773  appendPQExpBufferStr(buf, ", false::BOOLEAN");
1774  appendPQExpBufferStr(buf, ")");
1775  comma = ",";
1776  }
1777 
1778  if (!have_values)
1780  "\nSELECT NULL::INTEGER, NULL::TEXT, NULL::TEXT, "
1781  "NULL::TEXT, NULL::BOOLEAN, NULL::BOOLEAN "
1782  "WHERE false");
1783 }
1784 
1785 /*
1786  * append_rel_pattern_filtered_cte
1787  *
1788  * Appends to the buffer a Common Table Expression (CTE) which selects
1789  * all patterns from the named raw CTE, filtered by database. All patterns
1790  * which have no database portion or whose database portion matches our
1791  * connection's database name are selected, with other patterns excluded.
1792  *
1793  * The basic idea here is that if we're connected to database "foo" and we have
1794  * patterns "foo.bar.baz", "alpha.beta" and "one.two.three", we only want to
1795  * use the first two while processing relations in this database, as the third
1796  * one is not relevant.
1797  *
1798  * buf: the buffer to be appended
1799  * raw: the name of the CTE to select from
1800  * filtered: the name of the CTE to create
1801  * conn: the database connection
1802  */
1803 static void
1805  const char *filtered, PGconn *conn)
1806 {
1808  "\n%s (pattern_id, nsp_regex, rel_regex, heap_only, btree_only) AS ("
1809  "\nSELECT pattern_id, nsp_regex, rel_regex, heap_only, btree_only "
1810  "FROM %s r"
1811  "\nWHERE (r.db_regex IS NULL "
1812  "OR ",
1813  filtered, raw);
1815  appendPQExpBufferStr(buf, " ~ r.db_regex)");
1817  " AND (r.nsp_regex IS NOT NULL"
1818  " OR r.rel_regex IS NOT NULL)"
1819  "),");
1820 }
1821 
1822 /*
1823  * compile_relation_list_one_db
1824  *
1825  * Compiles a list of relations to check within the currently connected
1826  * database based on the user supplied options, sorted by descending size,
1827  * and appends them to the given list of relations.
1828  *
1829  * The cells of the constructed list contain all information about the relation
1830  * necessary to connect to the database and check the object, including which
1831  * database to connect to, where contrib/amcheck is installed, and the Oid and
1832  * type of object (heap table vs. btree index). Rather than duplicating the
1833  * database details per relation, the relation structs use references to the
1834  * same database object, provided by the caller.
1835  *
1836  * conn: connection to this next database, which should be the same as in 'dat'
1837  * relations: list onto which the relations information should be appended
1838  * dat: the database info struct for use by each relation
1839  * pagecount: gets incremented by the number of blocks to check in all
1840  * relations added
1841  */
1842 static void
1844  const DatabaseInfo *dat,
1845  uint64 *pagecount)
1846 {
1847  PGresult *res;
1848  PQExpBufferData sql;
1849  int ntups;
1850  int i;
1851 
1852  initPQExpBuffer(&sql);
1853  appendPQExpBufferStr(&sql, "WITH");
1854 
1855  /* Append CTEs for the relation inclusion patterns, if any */
1856  if (!opts.allrel)
1857  {
1858  appendPQExpBufferStr(&sql,
1859  " include_raw (pattern_id, db_regex, nsp_regex, rel_regex, heap_only, btree_only) AS (");
1861  appendPQExpBufferStr(&sql, "\n),");
1862  append_rel_pattern_filtered_cte(&sql, "include_raw", "include_pat", conn);
1863  }
1864 
1865  /* Append CTEs for the relation exclusion patterns, if any */
1867  {
1868  appendPQExpBufferStr(&sql,
1869  " exclude_raw (pattern_id, db_regex, nsp_regex, rel_regex, heap_only, btree_only) AS (");
1871  appendPQExpBufferStr(&sql, "\n),");
1872  append_rel_pattern_filtered_cte(&sql, "exclude_raw", "exclude_pat", conn);
1873  }
1874 
1875  /* Append the relation CTE. */
1876  appendPQExpBufferStr(&sql,
1877  " relation (pattern_id, oid, nspname, relname, reltoastrelid, relpages, is_heap, is_btree) AS ("
1878  "\nSELECT DISTINCT ON (c.oid");
1879  if (!opts.allrel)
1880  appendPQExpBufferStr(&sql, ", ip.pattern_id) ip.pattern_id,");
1881  else
1882  appendPQExpBufferStr(&sql, ") NULL::INTEGER AS pattern_id,");
1883  appendPQExpBuffer(&sql,
1884  "\nc.oid, n.nspname, c.relname, c.reltoastrelid, c.relpages, "
1885  "c.relam = %u AS is_heap, "
1886  "c.relam = %u AS is_btree"
1887  "\nFROM pg_catalog.pg_class c "
1888  "INNER JOIN pg_catalog.pg_namespace n "
1889  "ON c.relnamespace = n.oid",
1890  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1891  if (!opts.allrel)
1892  appendPQExpBuffer(&sql,
1893  "\nINNER JOIN include_pat ip"
1894  "\nON (n.nspname ~ ip.nsp_regex OR ip.nsp_regex IS NULL)"
1895  "\nAND (c.relname ~ ip.rel_regex OR ip.rel_regex IS NULL)"
1896  "\nAND (c.relam = %u OR NOT ip.heap_only)"
1897  "\nAND (c.relam = %u OR NOT ip.btree_only)",
1898  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1900  appendPQExpBuffer(&sql,
1901  "\nLEFT OUTER JOIN exclude_pat ep"
1902  "\nON (n.nspname ~ ep.nsp_regex OR ep.nsp_regex IS NULL)"
1903  "\nAND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL)"
1904  "\nAND (c.relam = %u OR NOT ep.heap_only OR ep.rel_regex IS NULL)"
1905  "\nAND (c.relam = %u OR NOT ep.btree_only OR ep.rel_regex IS NULL)",
1906  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1907 
1908  /*
1909  * Exclude temporary tables and indexes, which must necessarily belong to
1910  * other sessions. (We don't create any ourselves.) We must ultimately
1911  * exclude indexes marked invalid or not ready, but we delay that decision
1912  * until firing off the amcheck command, as the state of an index may
1913  * change by then.
1914  */
1915  appendPQExpBufferStr(&sql, "\nWHERE c.relpersistence != 't'");
1917  appendPQExpBufferStr(&sql, "\nAND ep.pattern_id IS NULL");
1918 
1919  /*
1920  * We need to be careful not to break the --no-dependent-toast and
1921  * --no-dependent-indexes options. By default, the btree indexes, toast
1922  * tables, and toast table btree indexes associated with primary heap
1923  * tables are included, using their own CTEs below. We implement the
1924  * --exclude-* options by not creating those CTEs, but that's no use if
1925  * we've already selected the toast and indexes here. On the other hand,
1926  * we want inclusion patterns that match indexes or toast tables to be
1927  * honored. So, if inclusion patterns were given, we want to select all
1928  * tables, toast tables, or indexes that match the patterns. But if no
1929  * inclusion patterns were given, and we're simply matching all relations,
1930  * then we only want to match the primary tables here.
1931  */
1932  if (opts.allrel)
1933  appendPQExpBuffer(&sql,
1934  " AND c.relam = %u "
1935  "AND c.relkind IN ('r', 'S', 'm', 't') "
1936  "AND c.relnamespace != %u",
1937  HEAP_TABLE_AM_OID, PG_TOAST_NAMESPACE);
1938  else
1939  appendPQExpBuffer(&sql,
1940  " AND c.relam IN (%u, %u)"
1941  "AND c.relkind IN ('r', 'S', 'm', 't', 'i') "
1942  "AND ((c.relam = %u AND c.relkind IN ('r', 'S', 'm', 't')) OR "
1943  "(c.relam = %u AND c.relkind = 'i'))",
1944  HEAP_TABLE_AM_OID, BTREE_AM_OID,
1945  HEAP_TABLE_AM_OID, BTREE_AM_OID);
1946 
1947  appendPQExpBufferStr(&sql,
1948  "\nORDER BY c.oid)");
1949 
1950  if (!opts.no_toast_expansion)
1951  {
1952  /*
1953  * Include a CTE for toast tables associated with primary heap tables
1954  * selected above, filtering by exclusion patterns (if any) that match
1955  * toast table names.
1956  */
1957  appendPQExpBufferStr(&sql,
1958  ", toast (oid, nspname, relname, relpages) AS ("
1959  "\nSELECT t.oid, 'pg_toast', t.relname, t.relpages"
1960  "\nFROM pg_catalog.pg_class t "
1961  "INNER JOIN relation r "
1962  "ON r.reltoastrelid = t.oid");
1963  if (opts.excludetbl || opts.excludensp)
1964  appendPQExpBufferStr(&sql,
1965  "\nLEFT OUTER JOIN exclude_pat ep"
1966  "\nON ('pg_toast' ~ ep.nsp_regex OR ep.nsp_regex IS NULL)"
1967  "\nAND (t.relname ~ ep.rel_regex OR ep.rel_regex IS NULL)"
1968  "\nAND ep.heap_only"
1969  "\nWHERE ep.pattern_id IS NULL"
1970  "\nAND t.relpersistence != 't'");
1971  appendPQExpBufferStr(&sql,
1972  "\n)");
1973  }
1974  if (!opts.no_btree_expansion)
1975  {
1976  /*
1977  * Include a CTE for btree indexes associated with primary heap tables
1978  * selected above, filtering by exclusion patterns (if any) that match
1979  * btree index names.
1980  */
1981  appendPQExpBuffer(&sql,
1982  ", index (oid, nspname, relname, relpages) AS ("
1983  "\nSELECT c.oid, r.nspname, c.relname, c.relpages "
1984  "FROM relation r"
1985  "\nINNER JOIN pg_catalog.pg_index i "
1986  "ON r.oid = i.indrelid "
1987  "INNER JOIN pg_catalog.pg_class c "
1988  "ON i.indexrelid = c.oid "
1989  "AND c.relpersistence != 't'");
1990  if (opts.excludeidx || opts.excludensp)
1991  appendPQExpBufferStr(&sql,
1992  "\nINNER JOIN pg_catalog.pg_namespace n "
1993  "ON c.relnamespace = n.oid"
1994  "\nLEFT OUTER JOIN exclude_pat ep "
1995  "ON (n.nspname ~ ep.nsp_regex OR ep.nsp_regex IS NULL) "
1996  "AND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL) "
1997  "AND ep.btree_only"
1998  "\nWHERE ep.pattern_id IS NULL");
1999  else
2000  appendPQExpBufferStr(&sql,
2001  "\nWHERE true");
2002  appendPQExpBuffer(&sql,
2003  " AND c.relam = %u "
2004  "AND c.relkind = 'i'",
2005  BTREE_AM_OID);
2007  appendPQExpBuffer(&sql,
2008  " AND c.relnamespace != %u",
2009  PG_TOAST_NAMESPACE);
2010  appendPQExpBufferStr(&sql, "\n)");
2011  }
2012 
2014  {
2015  /*
2016  * Include a CTE for btree indexes associated with toast tables of
2017  * primary heap tables selected above, filtering by exclusion patterns
2018  * (if any) that match the toast index names.
2019  */
2020  appendPQExpBuffer(&sql,
2021  ", toast_index (oid, nspname, relname, relpages) AS ("
2022  "\nSELECT c.oid, 'pg_toast', c.relname, c.relpages "
2023  "FROM toast t "
2024  "INNER JOIN pg_catalog.pg_index i "
2025  "ON t.oid = i.indrelid"
2026  "\nINNER JOIN pg_catalog.pg_class c "
2027  "ON i.indexrelid = c.oid "
2028  "AND c.relpersistence != 't'");
2029  if (opts.excludeidx)
2030  appendPQExpBufferStr(&sql,
2031  "\nLEFT OUTER JOIN exclude_pat ep "
2032  "ON ('pg_toast' ~ ep.nsp_regex OR ep.nsp_regex IS NULL) "
2033  "AND (c.relname ~ ep.rel_regex OR ep.rel_regex IS NULL) "
2034  "AND ep.btree_only "
2035  "WHERE ep.pattern_id IS NULL");
2036  else
2037  appendPQExpBufferStr(&sql,
2038  "\nWHERE true");
2039  appendPQExpBuffer(&sql,
2040  " AND c.relam = %u"
2041  " AND c.relkind = 'i')",
2042  BTREE_AM_OID);
2043  }
2044 
2045  /*
2046  * Roll-up distinct rows from CTEs.
2047  *
2048  * Relations that match more than one pattern may occur more than once in
2049  * the list, and indexes and toast for primary relations may also have
2050  * matched in their own right, so we rely on UNION to deduplicate the
2051  * list.
2052  */
2053  appendPQExpBuffer(&sql,
2054  "\nSELECT pattern_id, is_heap, is_btree, oid, nspname, relname, relpages "
2055  "FROM (");
2056  appendPQExpBufferStr(&sql,
2057  /* Inclusion patterns that failed to match */
2058  "\nSELECT pattern_id, is_heap, is_btree, "
2059  "NULL::OID AS oid, "
2060  "NULL::TEXT AS nspname, "
2061  "NULL::TEXT AS relname, "
2062  "NULL::INTEGER AS relpages"
2063  "\nFROM relation "
2064  "WHERE pattern_id IS NOT NULL "
2065  "UNION"
2066  /* Primary relations */
2067  "\nSELECT NULL::INTEGER AS pattern_id, "
2068  "is_heap, is_btree, oid, nspname, relname, relpages "
2069  "FROM relation");
2070  if (!opts.no_toast_expansion)
2071  appendPQExpBufferStr(&sql,
2072  " UNION"
2073  /* Toast tables for primary relations */
2074  "\nSELECT NULL::INTEGER AS pattern_id, TRUE AS is_heap, "
2075  "FALSE AS is_btree, oid, nspname, relname, relpages "
2076  "FROM toast");
2077  if (!opts.no_btree_expansion)
2078  appendPQExpBufferStr(&sql,
2079  " UNION"
2080  /* Indexes for primary relations */
2081  "\nSELECT NULL::INTEGER AS pattern_id, FALSE AS is_heap, "
2082  "TRUE AS is_btree, oid, nspname, relname, relpages "
2083  "FROM index");
2085  appendPQExpBufferStr(&sql,
2086  " UNION"
2087  /* Indexes for toast relations */
2088  "\nSELECT NULL::INTEGER AS pattern_id, FALSE AS is_heap, "
2089  "TRUE AS is_btree, oid, nspname, relname, relpages "
2090  "FROM toast_index");
2091  appendPQExpBufferStr(&sql,
2092  "\n) AS combined_records "
2093  "ORDER BY relpages DESC NULLS FIRST, oid");
2094 
2095  res = executeQuery(conn, sql.data, opts.echo);
2097  {
2098  pg_log_error("query failed: %s", PQerrorMessage(conn));
2099  pg_log_info("query was: %s", sql.data);
2101  exit(1);
2102  }
2103  termPQExpBuffer(&sql);
2104 
2105  ntups = PQntuples(res);
2106  for (i = 0; i < ntups; i++)
2107  {
2108  int pattern_id = -1;
2109  bool is_heap = false;
2110  bool is_btree PG_USED_FOR_ASSERTS_ONLY = false;
2111  Oid oid = InvalidOid;
2112  const char *nspname = NULL;
2113  const char *relname = NULL;
2114  int relpages = 0;
2115 
2116  if (!PQgetisnull(res, i, 0))
2117  pattern_id = atoi(PQgetvalue(res, i, 0));
2118  if (!PQgetisnull(res, i, 1))
2119  is_heap = (PQgetvalue(res, i, 1)[0] == 't');
2120  if (!PQgetisnull(res, i, 2))
2121  is_btree = (PQgetvalue(res, i, 2)[0] == 't');
2122  if (!PQgetisnull(res, i, 3))
2123  oid = atooid(PQgetvalue(res, i, 3));
2124  if (!PQgetisnull(res, i, 4))
2125  nspname = PQgetvalue(res, i, 4);
2126  if (!PQgetisnull(res, i, 5))
2127  relname = PQgetvalue(res, i, 5);
2128  if (!PQgetisnull(res, i, 6))
2129  relpages = atoi(PQgetvalue(res, i, 6));
2130 
2131  if (pattern_id >= 0)
2132  {
2133  /*
2134  * Current record pertains to an inclusion pattern. Record that
2135  * it matched.
2136  */
2137 
2138  if (pattern_id >= opts.include.len)
2139  {
2140  pg_log_error("internal error: received unexpected relation pattern_id %d",
2141  pattern_id);
2142  exit(1);
2143  }
2144 
2145  opts.include.data[pattern_id].matched = true;
2146  }
2147  else
2148  {
2149  /* Current record pertains to a relation */
2150 
2151  RelationInfo *rel = (RelationInfo *) pg_malloc0(sizeof(RelationInfo));
2152 
2153  Assert(OidIsValid(oid));
2154  Assert((is_heap && !is_btree) || (is_btree && !is_heap));
2155 
2156  rel->datinfo = dat;
2157  rel->reloid = oid;
2158  rel->is_heap = is_heap;
2159  rel->nspname = pstrdup(nspname);
2160  rel->relname = pstrdup(relname);
2161  rel->relpages = relpages;
2162  rel->blocks_to_check = relpages;
2163  if (is_heap && (opts.startblock >= 0 || opts.endblock >= 0))
2164  {
2165  /*
2166  * We apply --startblock and --endblock to heap tables, but
2167  * not btree indexes, and for progress purposes we need to
2168  * track how many blocks we expect to check.
2169  */
2170  if (opts.endblock >= 0 && rel->blocks_to_check > opts.endblock)
2171  rel->blocks_to_check = opts.endblock + 1;
2172  if (opts.startblock >= 0)
2173  {
2174  if (rel->blocks_to_check > opts.startblock)
2176  else
2177  rel->blocks_to_check = 0;
2178  }
2179  }
2180  *pagecount += rel->blocks_to_check;
2181 
2182  simple_ptr_list_append(relations, rel);
2183  }
2184  }
2185  PQclear(res);
2186 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
static void setup_cancel_handler(void)
Definition: parallel.c:613
#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:52
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:433
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:6616
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6770
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:6897
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4075
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3178
void PQclear(PGresult *res)
Definition: fe-exec.c:694
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3248
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3642
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3667
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1326
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3233
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:102
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:107
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:95
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:106
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:108
@ PGRES_COPY_OUT
Definition: libpq-fe.h:101
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:94
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:109
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:103
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:110
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:105
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:98
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:127
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void pg_logging_increase_verbosity(void)
Definition: logging.c:174
void pg_logging_init(const char *argv0)
Definition: logging.c:81
#define pg_log_error(...)
Definition: logging.h:80
#define pg_log_info(...)
Definition: logging.h:88
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void pfree(void *pointer)
Definition: mcxt.c:1169
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:985
static bool should_processing_continue(PGresult *res)
Definition: pg_amcheck.c:944
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:1220
static void append_rel_pattern_filtered_cte(PQExpBuffer buf, const char *raw, const char *filtered, PGconn *conn)
Definition: pg_amcheck.c:1804
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:1540
struct DatabaseInfo DatabaseInfo
static PatternInfo * extend_pattern_info_array(PatternInfoArray *pia)
Definition: pg_amcheck.c:1312
static void prepare_btree_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
Definition: pg_amcheck.c:867
static void help(const char *progname)
Definition: pg_amcheck.c:1160
struct PatternInfoArray PatternInfoArray
static void append_database_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1334
static void append_rel_pattern_raw_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn)
Definition: pg_amcheck.c:1735
static bool verify_heap_slot_handler(PGresult *res, PGconn *conn, void *context)
Definition: pg_amcheck.c:1016
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:1392
struct RelationInfo RelationInfo
static void run_command(ParallelSlot *slot, const char *sql)
Definition: pg_amcheck.c:912
static void append_heap_pattern(PatternInfoArray *pia, const char *pattern, int encoding)
Definition: pg_amcheck.c:1451
#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:1357
static bool verify_btree_slot_handler(PGresult *res, PGconn *conn, void *context)
Definition: pg_amcheck.c:1097
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:1843
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:1435
static bool append_db_pattern_cte(PQExpBuffer buf, const PatternInfoArray *pia, PGconn *conn, bool inclusive)
Definition: pg_amcheck.c:1494
static void prepare_heap_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
Definition: pg_amcheck.c:827
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:1467
#define 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:1600
static void executeCommand(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1861
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1838
int optind
Definition: getopt.c:50
char * optarg
Definition: getopt.c:52
static int port
Definition: pg_regress.c:92
static char * buf
Definition: pg_test_fsync.c:70
const char * username
Definition: pgbench.c:282
#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:453
#define snprintf
Definition: port.h:222
#define fprintf
Definition: port.h:226
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:452
#define printf(...)
Definition: port.h:228
#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)
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