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