Debian Codegraph @

src/bin/pg_upgrade/check.c

raw
1 /*
2 * check.c
3 *
4 * server checks and output routines
5 *
6 * Copyright (c) 2010-2025, PostgreSQL Global Development Group
7 * src/bin/pg_upgrade/check.c
8 */
9
10 #include "postgres_fe.h"
11
12 #include "catalog/pg_authid_d.h"
13 #include "catalog/pg_class_d.h"
14 #include "fe_utils/string_utils.h"
15 #include "pg_upgrade.h"
16 #include "common/unicode_version.h"
17
18 static void check_new_cluster_is_empty(void);
19 static void check_is_install_user(ClusterInfo *cluster);
20 static void check_for_connection_status(ClusterInfo *cluster);
21 static void check_for_prepared_transactions(ClusterInfo *cluster);
22 static void check_for_isn_and_int8_passing_mismatch(ClusterInfo *cluster);
23 static void check_for_user_defined_postfix_ops(ClusterInfo *cluster);
24 static void check_for_incompatible_polymorphics(ClusterInfo *cluster);
25 static void check_for_tables_with_oids(ClusterInfo *cluster);
26 static void check_for_not_null_inheritance(ClusterInfo *cluster);
27 static void check_for_pg_role_prefix(ClusterInfo *cluster);
28 static void check_for_new_tablespace_dir(void);
29 static void check_for_user_defined_encoding_conversions(ClusterInfo *cluster);
30 static void check_for_unicode_update(ClusterInfo *cluster);
31 static void check_new_cluster_logical_replication_slots(void);
32 static void check_new_cluster_subscription_configuration(void);
33 static void check_old_cluster_for_valid_slots(void);
34 static void check_old_cluster_subscription_state(void);
35
36 /*
37 * DataTypesUsageChecks - definitions of data type checks for the old cluster
38 * in order to determine if an upgrade can be performed. See the comment on
39 * data_types_usage_checks below for a more detailed description.
40 */
41 typedef struct
42 {
43 /* Status line to print to the user */
44 const char *status;
45 /* Filename to store report to */
46 const char *report_filename;
47 /* Query to extract the oid of the datatype */
48 const char *base_query;
49 /* Text to store to report in case of error */
50 const char *report_text;
51 /* The latest version where the check applies */
52 int threshold_version;
53 /* A function pointer for determining if the check applies */
54 DataTypesUsageVersionCheck version_hook;
55 } DataTypesUsageChecks;
56
57 /*
58 * Special values for threshold_version for indicating that a check applies to
59 * all versions, or that a custom function needs to be invoked to determine
60 * if the check applies.
61 */
62 #define MANUAL_CHECK 1
63 #define ALL_VERSIONS -1
64
65 /*--
66 * Data type usage checks. Each check for problematic data type usage is
67 * defined in this array with metadata, SQL query for finding the data type
68 * and functionality for deciding if the check is applicable to the version
69 * of the old cluster. The struct members are described in detail below:
70 *
71 * status A oneline string which can be printed to the user to
72 * inform about progress. Should not end with newline.
73 * report_filename The filename in which the list of problems detected by
74 * the check will be printed.
75 * base_query A query which extracts the Oid of the datatype checked
76 * for.
77 * report_text The text which will be printed to the user to explain
78 * what the check did, and why it failed. The text should
79 * end with a newline, and does not need to refer to the
80 * report_filename as that is automatically appended to
81 * the report with the path to the log folder.
82 * threshold_version The major version of PostgreSQL for which to run the
83 * check. Iff the old cluster is less than, or equal to,
84 * the threshold version then the check will be executed.
85 * If the old version is greater than the threshold then
86 * the check is skipped. If the threshold_version is set
87 * to ALL_VERSIONS then it will be run unconditionally,
88 * if set to MANUAL_CHECK then the version_hook function
89 * will be executed in order to determine whether or not
90 * to run.
91 * version_hook A function pointer to a version check function of type
92 * DataTypesUsageVersionCheck which is used to determine
93 * if the check is applicable to the old cluster. If the
94 * version_hook returns true then the check will be run,
95 * else it will be skipped. The function will only be
96 * executed iff threshold_version is set to MANUAL_CHECK.
97 */
98 static DataTypesUsageChecks data_types_usage_checks[] =
99 {
100 /*
101 * Look for composite types that were made during initdb *or* belong to
102 * information_schema; that's important in case information_schema was
103 * dropped and reloaded.
104 *
105 * The cutoff OID here should match the source cluster's value of
106 * FirstNormalObjectId. We hardcode it rather than using that C #define
107 * because, if that #define is ever changed, our own version's value is
108 * NOT what to use. Eventually we may need a test on the source cluster's
109 * version to select the correct value.
110 */
111 {
112 .status = gettext_noop("Checking for system-defined composite types in user tables"),
113 .report_filename = "tables_using_composite.txt",
114 .base_query =
115 "SELECT t.oid FROM pg_catalog.pg_type t "
116 "LEFT JOIN pg_catalog.pg_namespace n ON t.typnamespace = n.oid "
117 " WHERE typtype = 'c' AND (t.oid < 16384 OR nspname = 'information_schema')",
118 .report_text =
119 gettext_noop("Your installation contains system-defined composite types in user tables.\n"
120 "These type OIDs are not stable across PostgreSQL versions,\n"
121 "so this cluster cannot currently be upgraded. You can drop the\n"
122 "problem columns and restart the upgrade.\n"),
123 .threshold_version = ALL_VERSIONS
124 },
125
126 /*
127 * 9.3 -> 9.4 Fully implement the 'line' data type in 9.4, which
128 * previously returned "not enabled" by default and was only functionally
129 * enabled with a compile-time switch; as of 9.4 "line" has a different
130 * on-disk representation format.
131 */
132 {
133 .status = gettext_noop("Checking for incompatible \"line\" data type"),
134 .report_filename = "tables_using_line.txt",
135 .base_query =
136 "SELECT 'pg_catalog.line'::pg_catalog.regtype AS oid",
137 .report_text =
138 gettext_noop("Your installation contains the \"line\" data type in user tables.\n"
139 "This data type changed its internal and input/output format\n"
140 "between your old and new versions so this\n"
141 "cluster cannot currently be upgraded. You can\n"
142 "drop the problem columns and restart the upgrade.\n"),
143 .threshold_version = 903
144 },
145
146 /*
147 * pg_upgrade only preserves these system values: pg_class.oid pg_type.oid
148 * pg_enum.oid
149 *
150 * Many of the reg* data types reference system catalog info that is not
151 * preserved, and hence these data types cannot be used in user tables
152 * upgraded by pg_upgrade.
153 */
154 {
155 .status = gettext_noop("Checking for reg* data types in user tables"),
156 .report_filename = "tables_using_reg.txt",
157
158 /*
159 * Note: older servers will not have all of these reg* types, so we
160 * have to write the query like this rather than depending on casts to
161 * regtype.
162 */
163 .base_query =
164 "SELECT oid FROM pg_catalog.pg_type t "
165 "WHERE t.typnamespace = "
166 " (SELECT oid FROM pg_catalog.pg_namespace "
167 " WHERE nspname = 'pg_catalog') "
168 " AND t.typname IN ( "
169 /* pg_class.oid is preserved, so 'regclass' is OK */
170 " 'regcollation', "
171 " 'regconfig', "
172 " 'regdictionary', "
173 " 'regnamespace', "
174 " 'regoper', "
175 " 'regoperator', "
176 " 'regproc', "
177 " 'regprocedure' "
178 /* pg_authid.oid is preserved, so 'regrole' is OK */
179 /* pg_type.oid is (mostly) preserved, so 'regtype' is OK */
180 " )",
181 .report_text =
182 gettext_noop("Your installation contains one of the reg* data types in user tables.\n"
183 "These data types reference system OIDs that are not preserved by\n"
184 "pg_upgrade, so this cluster cannot currently be upgraded. You can\n"
185 "drop the problem columns and restart the upgrade.\n"),
186 .threshold_version = ALL_VERSIONS
187 },
188
189 /*
190 * PG 16 increased the size of the 'aclitem' type, which breaks the
191 * on-disk format for existing data.
192 */
193 {
194 .status = gettext_noop("Checking for incompatible \"aclitem\" data type"),
195 .report_filename = "tables_using_aclitem.txt",
196 .base_query =
197 "SELECT 'pg_catalog.aclitem'::pg_catalog.regtype AS oid",
198 .report_text =
199 gettext_noop("Your installation contains the \"aclitem\" data type in user tables.\n"
200 "The internal format of \"aclitem\" changed in PostgreSQL version 16\n"
201 "so this cluster cannot currently be upgraded. You can drop the\n"
202 "problem columns and restart the upgrade.\n"),
203 .threshold_version = 1500
204 },
205
206 /*
207 * It's no longer allowed to create tables or views with "unknown"-type
208 * columns. We do not complain about views with such columns, because
209 * they should get silently converted to "text" columns during the DDL
210 * dump and reload; it seems unlikely to be worth making users do that by
211 * hand. However, if there's a table with such a column, the DDL reload
212 * will fail, so we should pre-detect that rather than failing
213 * mid-upgrade. Worse, if there's a matview with such a column, the DDL
214 * reload will silently change it to "text" which won't match the on-disk
215 * storage (which is like "cstring"). So we *must* reject that.
216 */
217 {
218 .status = gettext_noop("Checking for invalid \"unknown\" user columns"),
219 .report_filename = "tables_using_unknown.txt",
220 .base_query =
221 "SELECT 'pg_catalog.unknown'::pg_catalog.regtype AS oid",
222 .report_text =
223 gettext_noop("Your installation contains the \"unknown\" data type in user tables.\n"
224 "This data type is no longer allowed in tables, so this cluster\n"
225 "cannot currently be upgraded. You can drop the problem columns\n"
226 "and restart the upgrade.\n"),
227 .threshold_version = 906
228 },
229
230 /*
231 * PG 12 changed the 'sql_identifier' type storage to be based on name,
232 * not varchar, which breaks on-disk format for existing data. So we need
233 * to prevent upgrade when used in user objects (tables, indexes, ...). In
234 * 12, the sql_identifier data type was switched from name to varchar,
235 * which does affect the storage (name is by-ref, but not varlena). This
236 * means user tables using sql_identifier for columns are broken because
237 * the on-disk format is different.
238 */
239 {
240 .status = gettext_noop("Checking for invalid \"sql_identifier\" user columns"),
241 .report_filename = "tables_using_sql_identifier.txt",
242 .base_query =
243 "SELECT 'information_schema.sql_identifier'::pg_catalog.regtype AS oid",
244 .report_text =
245 gettext_noop("Your installation contains the \"sql_identifier\" data type in user tables.\n"
246 "The on-disk format for this data type has changed, so this\n"
247 "cluster cannot currently be upgraded. You can drop the problem\n"
248 "columns and restart the upgrade.\n"),
249 .threshold_version = 1100
250 },
251
252 /*
253 * JSONB changed its storage format during 9.4 beta, so check for it.
254 */
255 {
256 .status = gettext_noop("Checking for incompatible \"jsonb\" data type in user tables"),
257 .report_filename = "tables_using_jsonb.txt",
258 .base_query =
259 "SELECT 'pg_catalog.jsonb'::pg_catalog.regtype AS oid",
260 .report_text =
261 gettext_noop("Your installation contains the \"jsonb\" data type in user tables.\n"
262 "The internal format of \"jsonb\" changed during 9.4 beta so this\n"
263 "cluster cannot currently be upgraded. You can drop the problem \n"
264 "columns and restart the upgrade.\n"),
265 .threshold_version = MANUAL_CHECK,
266 .version_hook = jsonb_9_4_check_applicable
267 },
268
269 /*
270 * PG 12 removed types abstime, reltime, tinterval.
271 */
272 {
273 .status = gettext_noop("Checking for removed \"abstime\" data type in user tables"),
274 .report_filename = "tables_using_abstime.txt",
275 .base_query =
276 "SELECT 'pg_catalog.abstime'::pg_catalog.regtype AS oid",
277 .report_text =
278 gettext_noop("Your installation contains the \"abstime\" data type in user tables.\n"
279 "The \"abstime\" type has been removed in PostgreSQL version 12,\n"
280 "so this cluster cannot currently be upgraded. You can drop the\n"
281 "problem columns, or change them to another data type, and restart\n"
282 "the upgrade.\n"),
283 .threshold_version = 1100
284 },
285 {
286 .status = gettext_noop("Checking for removed \"reltime\" data type in user tables"),
287 .report_filename = "tables_using_reltime.txt",
288 .base_query =
289 "SELECT 'pg_catalog.reltime'::pg_catalog.regtype AS oid",
290 .report_text =
291 gettext_noop("Your installation contains the \"reltime\" data type in user tables.\n"
292 "The \"reltime\" type has been removed in PostgreSQL version 12,\n"
293 "so this cluster cannot currently be upgraded. You can drop the\n"
294 "problem columns, or change them to another data type, and restart\n"
295 "the upgrade.\n"),
296 .threshold_version = 1100
297 },
298 {
299 .status = gettext_noop("Checking for removed \"tinterval\" data type in user tables"),
300 .report_filename = "tables_using_tinterval.txt",
301 .base_query =
302 "SELECT 'pg_catalog.tinterval'::pg_catalog.regtype AS oid",
303 .report_text =
304 gettext_noop("Your installation contains the \"tinterval\" data type in user tables.\n"
305 "The \"tinterval\" type has been removed in PostgreSQL version 12,\n"
306 "so this cluster cannot currently be upgraded. You can drop the\n"
307 "problem columns, or change them to another data type, and restart\n"
308 "the upgrade.\n"),
309 .threshold_version = 1100
310 },
311
312 /* End of checks marker, must remain last */
313 {
314 NULL, NULL, NULL, NULL, 0, NULL
315 }
316 };
317
318 /*
319 * Private state for check_for_data_types_usage()'s UpgradeTask.
320 */
321 struct data_type_check_state
322 {
323 DataTypesUsageChecks *check; /* the check for this step */
324 bool result; /* true if check failed for any database */
325 PQExpBuffer *report; /* buffer for report on failed checks */
326 };
327
328 /*
329 * Returns a palloc'd query string for the data type check, for use by
330 * check_for_data_types_usage()'s UpgradeTask.
331 */
332 static char *
333 data_type_check_query(int checknum)
334 {
335 DataTypesUsageChecks *check = &data_types_usage_checks[checknum];
336
337 return psprintf("WITH RECURSIVE oids AS ( "
338 /* start with the type(s) returned by base_query */
339 " %s "
340 " UNION ALL "
341 " SELECT * FROM ( "
342 /* inner WITH because we can only reference the CTE once */
343 " WITH x AS (SELECT oid FROM oids) "
344 /* domains on any type selected so far */
345 " SELECT t.oid FROM pg_catalog.pg_type t, x WHERE typbasetype = x.oid AND typtype = 'd' "
346 " UNION ALL "
347 /* arrays over any type selected so far */
348 " SELECT t.oid FROM pg_catalog.pg_type t, x WHERE typelem = x.oid AND typtype = 'b' "
349 " UNION ALL "
350 /* composite types containing any type selected so far */
351 " SELECT t.oid FROM pg_catalog.pg_type t, pg_catalog.pg_class c, pg_catalog.pg_attribute a, x "
352 " WHERE t.typtype = 'c' AND "
353 " t.oid = c.reltype AND "
354 " c.oid = a.attrelid AND "
355 " NOT a.attisdropped AND "
356 " a.atttypid = x.oid "
357 " UNION ALL "
358 /* ranges containing any type selected so far */
359 " SELECT t.oid FROM pg_catalog.pg_type t, pg_catalog.pg_range r, x "
360 " WHERE t.typtype = 'r' AND r.rngtypid = t.oid AND r.rngsubtype = x.oid"
361 " ) foo "
362 ") "
363 /* now look for stored columns of any such type */
364 "SELECT n.nspname, c.relname, a.attname "
365 "FROM pg_catalog.pg_class c, "
366 " pg_catalog.pg_namespace n, "
367 " pg_catalog.pg_attribute a "
368 "WHERE c.oid = a.attrelid AND "
369 " NOT a.attisdropped AND "
370 " a.atttypid IN (SELECT oid FROM oids) AND "
371 " c.relkind IN ("
372 CppAsString2(RELKIND_RELATION) ", "
373 CppAsString2(RELKIND_MATVIEW) ", "
374 CppAsString2(RELKIND_INDEX) ") AND "
375 " c.relnamespace = n.oid AND "
376 /* exclude possible orphaned temp tables */
377 " n.nspname !~ '^pg_temp_' AND "
378 " n.nspname !~ '^pg_toast_temp_' AND "
379 /* exclude system catalogs, too */
380 " n.nspname NOT IN ('pg_catalog', 'information_schema')",
381 check->base_query);
382 }
383
384 /*
385 * Callback function for processing results of queries for
386 * check_for_data_types_usage()'s UpgradeTask. If the query returned any rows
387 * (i.e., the check failed), write the details to the report file.
388 */
389 static void
390 process_data_type_check(DbInfo *dbinfo, PGresult *res, void *arg)
391 {
392 struct data_type_check_state *state = (struct data_type_check_state *) arg;
393 int ntups = PQntuples(res);
394 char output_path[MAXPGPATH];
395 int i_nspname = PQfnumber(res, "nspname");
396 int i_relname = PQfnumber(res, "relname");
397 int i_attname = PQfnumber(res, "attname");
398 FILE *script = NULL;
399
400 AssertVariableIsOfType(&process_data_type_check, UpgradeTaskProcessCB);
401
402 if (ntups == 0)
403 return;
404
405 snprintf(output_path, sizeof(output_path), "%s/%s",
406 log_opts.basedir,
407 state->check->report_filename);
408
409 /*
410 * Make sure we have a buffer to save reports to now that we found a first
411 * failing check.
412 */
413 if (*state->report == NULL)
414 *state->report = createPQExpBuffer();
415
416 /*
417 * If this is the first time we see an error for the check in question
418 * then print a status message of the failure.
419 */
420 if (!state->result)
421 {
422 pg_log(PG_REPORT, "failed check: %s", _(state->check->status));
423 appendPQExpBuffer(*state->report, "\n%s\n%s\n %s\n",
424 _(state->check->report_text),
425 _("A list of the problem columns is in the file:"),
426 output_path);
427 }
428 state->result = true;
429
430 if ((script = fopen_priv(output_path, "a")) == NULL)
431 pg_fatal("could not open file \"%s\": %m", output_path);
432
433 fprintf(script, "In database: %s\n", dbinfo->db_name);
434
435 for (int rowno = 0; rowno < ntups; rowno++)
436 fprintf(script, " %s.%s.%s\n",
437 PQgetvalue(res, rowno, i_nspname),
438 PQgetvalue(res, rowno, i_relname),
439 PQgetvalue(res, rowno, i_attname));
440
441 fclose(script);
442 }
443
444 /*
445 * check_for_data_types_usage()
446 * Detect whether there are any stored columns depending on given type(s)
447 *
448 * If so, write a report to the given file name and signal a failure to the
449 * user.
450 *
451 * The checks to run are defined in a DataTypesUsageChecks structure where
452 * each check has a metadata for explaining errors to the user, a base_query,
453 * a report filename and a function pointer hook for validating if the check
454 * should be executed given the cluster at hand.
455 *
456 * base_query should be a SELECT yielding a single column named "oid",
457 * containing the pg_type OIDs of one or more types that are known to have
458 * inconsistent on-disk representations across server versions.
459 *
460 * We check for the type(s) in tables, matviews, and indexes, but not views;
461 * there's no storage involved in a view.
462 */
463 static void
464 check_for_data_types_usage(ClusterInfo *cluster)
465 {
466 PQExpBuffer report = NULL;
467 DataTypesUsageChecks *tmp = data_types_usage_checks;
468 int n_data_types_usage_checks = 0;
469 UpgradeTask *task = upgrade_task_create();
470 char **queries = NULL;
471 struct data_type_check_state *states;
472
473 prep_status("Checking data type usage");
474
475 /* Gather number of checks to perform */
476 while (tmp->status != NULL)
477 {
478 n_data_types_usage_checks++;
479 tmp++;
480 }
481
482 /* Allocate memory for queries and for task states */
483 queries = pg_malloc0(sizeof(char *) * n_data_types_usage_checks);
484 states = pg_malloc0(sizeof(struct data_type_check_state) * n_data_types_usage_checks);
485
486 for (int i = 0; i < n_data_types_usage_checks; i++)
487 {
488 DataTypesUsageChecks *check = &data_types_usage_checks[i];
489
490 if (check->threshold_version == MANUAL_CHECK)
491 {
492 Assert(check->version_hook);
493
494 /*
495 * Make sure that the check applies to the current cluster version
496 * and skip it if not.
497 */
498 if (!check->version_hook(cluster))
499 continue;
500 }
501 else if (check->threshold_version != ALL_VERSIONS)
502 {
503 if (GET_MAJOR_VERSION(cluster->major_version) > check->threshold_version)
504 continue;
505 }
506 else
507 Assert(check->threshold_version == ALL_VERSIONS);
508
509 queries[i] = data_type_check_query(i);
510
511 states[i].check = check;
512 states[i].report = &report;
513
514 upgrade_task_add_step(task, queries[i], process_data_type_check,
515 true, &states[i]);
516 }
517
518 /*
519 * Connect to each database in the cluster and run all defined checks
520 * against that database before trying the next one.
521 */
522 upgrade_task_run(task, cluster);
523 upgrade_task_free(task);
524
525 if (report)
526 {
527 pg_fatal("Data type checks failed: %s", report->data);
528 destroyPQExpBuffer(report);
529 }
530
531 for (int i = 0; i < n_data_types_usage_checks; i++)
532 {
533 if (queries[i])
534 pg_free(queries[i]);
535 }
536 pg_free(queries);
537 pg_free(states);
538
539 check_ok();
540 }
541
542 /*
543 * fix_path_separator
544 * For non-Windows, just return the argument.
545 * For Windows convert any forward slash to a backslash
546 * such as is suitable for arguments to builtin commands
547 * like RMDIR and DEL.
548 */
549 static char *
550 fix_path_separator(char *path)
551 {
552 #ifdef WIN32
553
554 char *result;
555 char *c;
556
557 result = pg_strdup(path);
558
559 for (c = result; *c != '\0'; c++)
560 if (*c == '/')
561 *c = '\\';
562
563 return result;
564 #else
565
566 return path;
567 #endif
568 }
569
570 void
571 output_check_banner(void)
572 {
573 if (user_opts.live_check)
574 {
575 pg_log(PG_REPORT,
576 "Performing Consistency Checks on Old Live Server\n"
577 "------------------------------------------------");
578 }
579 else
580 {
581 pg_log(PG_REPORT,
582 "Performing Consistency Checks\n"
583 "-----------------------------");
584 }
585 }
586
587
588 void
589 check_and_dump_old_cluster(void)
590 {
591 /* -- OLD -- */
592
593 if (!user_opts.live_check)
594 start_postmaster(&old_cluster, true);
595
596 /*
597 * First check that all databases allow connections since we'll otherwise
598 * fail in later stages.
599 */
600 check_for_connection_status(&old_cluster);
601
602 /*
603 * Extract a list of databases, tables, and logical replication slots from
604 * the old cluster.
605 */
606 get_db_rel_and_slot_infos(&old_cluster);
607
608 init_tablespaces();
609
610 get_loadable_libraries();
611
612
613 /*
614 * Check for various failure cases
615 */
616 check_is_install_user(&old_cluster);
617 check_for_prepared_transactions(&old_cluster);
618 check_for_isn_and_int8_passing_mismatch(&old_cluster);
619
620 if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1700)
621 {
622 /*
623 * Logical replication slots can be migrated since PG17. See comments
624 * atop get_old_cluster_logical_slot_infos().
625 */
626 check_old_cluster_for_valid_slots();
627
628 /*
629 * Subscriptions and their dependencies can be migrated since PG17.
630 * Before that the logical slots are not upgraded, so we will not be
631 * able to upgrade the logical replication clusters completely.
632 */
633 get_subscription_count(&old_cluster);
634 check_old_cluster_subscription_state();
635 }
636
637 check_for_data_types_usage(&old_cluster);
638
639 /*
640 * Unicode updates can affect some objects that use expressions with
641 * functions dependent on Unicode.
642 */
643 check_for_unicode_update(&old_cluster);
644
645 /*
646 * PG 14 changed the function signature of encoding conversion functions.
647 * Conversions from older versions cannot be upgraded automatically
648 * because the user-defined functions used by the encoding conversions
649 * need to be changed to match the new signature.
650 */
651 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1300)
652 check_for_user_defined_encoding_conversions(&old_cluster);
653
654 /*
655 * Pre-PG 14 allowed user defined postfix operators, which are not
656 * supported anymore. Verify there are none, iff applicable.
657 */
658 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1300)
659 check_for_user_defined_postfix_ops(&old_cluster);
660
661 /*
662 * PG 14 changed polymorphic functions from anyarray to
663 * anycompatiblearray.
664 */
665 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1300)
666 check_for_incompatible_polymorphics(&old_cluster);
667
668 /*
669 * Pre-PG 12 allowed tables to be declared WITH OIDS, which is not
670 * supported anymore. Verify there are none, iff applicable.
671 */
672 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1100)
673 check_for_tables_with_oids(&old_cluster);
674
675 /*
676 * Pre-PG 18 allowed child tables to omit not-null constraints that their
677 * parents columns have, but schema restore fails for them. Verify there
678 * are none, iff applicable.
679 */
680 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1800)
681 check_for_not_null_inheritance(&old_cluster);
682
683 /*
684 * Pre-PG 10 allowed tables with 'unknown' type columns and non WAL logged
685 * hash indexes
686 */
687 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 906)
688 {
689 if (user_opts.check)
690 old_9_6_invalidate_hash_indexes(&old_cluster, true);
691 }
692
693 /* 9.5 and below should not have roles starting with pg_ */
694 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 905)
695 check_for_pg_role_prefix(&old_cluster);
696
697 /*
698 * While not a check option, we do this now because this is the only time
699 * the old server is running.
700 */
701 if (!user_opts.check)
702 generate_old_dump();
703
704 if (!user_opts.live_check)
705 stop_postmaster(false);
706 }
707
708
709 void
710 check_new_cluster(void)
711 {
712 get_db_rel_and_slot_infos(&new_cluster);
713
714 check_new_cluster_is_empty();
715
716 check_loadable_libraries();
717
718 switch (user_opts.transfer_mode)
719 {
720 case TRANSFER_MODE_CLONE:
721 check_file_clone();
722 break;
723 case TRANSFER_MODE_COPY:
724 break;
725 case TRANSFER_MODE_COPY_FILE_RANGE:
726 check_copy_file_range();
727 break;
728 case TRANSFER_MODE_LINK:
729 check_hard_link(TRANSFER_MODE_LINK);
730 break;
731 case TRANSFER_MODE_SWAP:
732
733 /*
734 * We do the hard link check for --swap, too, since it's an easy
735 * way to verify the clusters are in the same file system. This
736 * allows us to take some shortcuts in the file synchronization
737 * step. With some more effort, we could probably support the
738 * separate-file-system use case, but this mode is unlikely to
739 * offer much benefit if we have to copy the files across file
740 * system boundaries.
741 */
742 check_hard_link(TRANSFER_MODE_SWAP);
743
744 /*
745 * There are a few known issues with using --swap to upgrade from
746 * versions older than 10. For example, the sequence tuple format
747 * changed in v10, and the visibility map format changed in 9.6.
748 * While such problems are not insurmountable (and we may have to
749 * deal with similar problems in the future, anyway), it doesn't
750 * seem worth the effort to support swap mode for upgrades from
751 * long-unsupported versions.
752 */
753 if (GET_MAJOR_VERSION(old_cluster.major_version) < 1000)
754 pg_fatal("Swap mode can only upgrade clusters from PostgreSQL version %s and later.",
755 "10");
756
757 break;
758 }
759
760 check_is_install_user(&new_cluster);
761
762 check_for_prepared_transactions(&new_cluster);
763
764 check_for_new_tablespace_dir();
765
766 check_new_cluster_logical_replication_slots();
767
768 check_new_cluster_subscription_configuration();
769 }
770
771
772 void
773 report_clusters_compatible(void)
774 {
775 if (user_opts.check)
776 {
777 pg_log(PG_REPORT, "\n*Clusters are compatible*");
778 /* stops new cluster */
779 stop_postmaster(false);
780
781 cleanup_output_dirs();
782 exit(0);
783 }
784
785 pg_log(PG_REPORT, "\n"
786 "If pg_upgrade fails after this point, you must re-initdb the\n"
787 "new cluster before continuing.");
788 }
789
790
791 void
792 issue_warnings_and_set_wal_level(void)
793 {
794 /*
795 * We unconditionally start/stop the new server because pg_resetwal -o set
796 * wal_level to 'minimum'. If the user is upgrading standby servers using
797 * the rsync instructions, they will need pg_upgrade to write its final
798 * WAL record showing wal_level as 'replica'.
799 */
800 start_postmaster(&new_cluster, true);
801
802 /* Reindex hash indexes for old < 10.0 */
803 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 906)
804 old_9_6_invalidate_hash_indexes(&new_cluster, false);
805
806 report_extension_updates(&new_cluster);
807
808 stop_postmaster(false);
809 }
810
811
812 void
813 output_completion_banner(char *deletion_script_file_name)
814 {
815 PQExpBufferData user_specification;
816
817 initPQExpBuffer(&user_specification);
818 if (os_info.user_specified)
819 {
820 appendPQExpBufferStr(&user_specification, "-U ");
821 appendShellString(&user_specification, os_info.user);
822 appendPQExpBufferChar(&user_specification, ' ');
823 }
824
825 pg_log(PG_REPORT,
826 "Some statistics are not transferred by pg_upgrade.\n"
827 "Once you start the new server, consider running these two commands:\n"
828 " %s/vacuumdb %s--all --analyze-in-stages --missing-stats-only\n"
829 " %s/vacuumdb %s--all --analyze-only",
830 new_cluster.bindir, user_specification.data,
831 new_cluster.bindir, user_specification.data);
832
833 if (deletion_script_file_name)
834 pg_log(PG_REPORT,
835 "Running this script will delete the old cluster's data files:\n"
836 " %s",
837 deletion_script_file_name);
838 else
839 pg_log(PG_REPORT,
840 "Could not create a script to delete the old cluster's data files\n"
841 "because user-defined tablespaces or the new cluster's data directory\n"
842 "exist in the old cluster directory. The old cluster's contents must\n"
843 "be deleted manually.");
844
845 termPQExpBuffer(&user_specification);
846 }
847
848
849 void
850 check_cluster_versions(void)
851 {
852 prep_status("Checking cluster versions");
853
854 /* cluster versions should already have been obtained */
855 Assert(old_cluster.major_version != 0);
856 Assert(new_cluster.major_version != 0);
857
858 /*
859 * We allow upgrades from/to the same major version for alpha/beta
860 * upgrades
861 */
862
863 if (GET_MAJOR_VERSION(old_cluster.major_version) < 902)
864 pg_fatal("This utility can only upgrade from PostgreSQL version %s and later.",
865 "9.2");
866
867 /* Only current PG version is supported as a target */
868 if (GET_MAJOR_VERSION(new_cluster.major_version) != GET_MAJOR_VERSION(PG_VERSION_NUM))
869 pg_fatal("This utility can only upgrade to PostgreSQL version %s.",
870 PG_MAJORVERSION);
871
872 /*
873 * We can't allow downgrading because we use the target pg_dump, and
874 * pg_dump cannot operate on newer database versions, only current and
875 * older versions.
876 */
877 if (old_cluster.major_version > new_cluster.major_version)
878 pg_fatal("This utility cannot be used to downgrade to older major PostgreSQL versions.");
879
880 /* Ensure binaries match the designated data directories */
881 if (GET_MAJOR_VERSION(old_cluster.major_version) !=
882 GET_MAJOR_VERSION(old_cluster.bin_version))
883 pg_fatal("Old cluster data and binary directories are from different major versions.");
884 if (GET_MAJOR_VERSION(new_cluster.major_version) !=
885 GET_MAJOR_VERSION(new_cluster.bin_version))
886 pg_fatal("New cluster data and binary directories are from different major versions.");
887
888 /*
889 * Since from version 18, newly created database clusters always have
890 * 'signed' default char-signedness, it makes less sense to use
891 * --set-char-signedness option for upgrading from version 18 or later.
892 * Users who want to change the default char signedness of the new
893 * cluster, they can use pg_resetwal manually before the upgrade.
894 */
895 if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1800 &&
896 user_opts.char_signedness != -1)
897 pg_fatal("The option %s cannot be used for upgrades from PostgreSQL %s and later.",
898 "--set-char-signedness", "18");
899
900 check_ok();
901 }
902
903
904 void
905 check_cluster_compatibility(void)
906 {
907 /* get/check pg_control data of servers */
908 get_control_data(&old_cluster);
909 get_control_data(&new_cluster);
910 check_control_data(&old_cluster.controldata, &new_cluster.controldata);
911
912 if (user_opts.live_check && old_cluster.port == new_cluster.port)
913 pg_fatal("When checking a live server, "
914 "the old and new port numbers must be different.");
915 }
916
917
918 static void
919 check_new_cluster_is_empty(void)
920 {
921 int dbnum;
922
923 for (dbnum = 0; dbnum < new_cluster.dbarr.ndbs; dbnum++)
924 {
925 int relnum;
926 RelInfoArr *rel_arr = &new_cluster.dbarr.dbs[dbnum].rel_arr;
927
928 for (relnum = 0; relnum < rel_arr->nrels;
929 relnum++)
930 {
931 /* pg_largeobject and its index should be skipped */
932 if (strcmp(rel_arr->rels[relnum].nspname, "pg_catalog") != 0)
933 pg_fatal("New cluster database \"%s\" is not empty: found relation \"%s.%s\"",
934 new_cluster.dbarr.dbs[dbnum].db_name,
935 rel_arr->rels[relnum].nspname,
936 rel_arr->rels[relnum].relname);
937 }
938 }
939 }
940
941 /*
942 * A previous run of pg_upgrade might have failed and the new cluster
943 * directory recreated, but they might have forgotten to remove
944 * the new cluster's tablespace directories. Therefore, check that
945 * new cluster tablespace directories do not already exist. If
946 * they do, it would cause an error while restoring global objects.
947 * This allows the failure to be detected at check time, rather than
948 * during schema restore.
949 */
950 static void
951 check_for_new_tablespace_dir(void)
952 {
953 int tblnum;
954 char new_tablespace_dir[MAXPGPATH];
955
956 prep_status("Checking for new cluster tablespace directories");
957
958 for (tblnum = 0; tblnum < os_info.num_old_tablespaces; tblnum++)
959 {
960 struct stat statbuf;
961
962 snprintf(new_tablespace_dir, MAXPGPATH, "%s%s",
963 os_info.old_tablespaces[tblnum],
964 new_cluster.tablespace_suffix);
965
966 if (stat(new_tablespace_dir, &statbuf) == 0 || errno != ENOENT)
967 pg_fatal("new cluster tablespace directory already exists: \"%s\"",
968 new_tablespace_dir);
969 }
970
971 check_ok();
972 }
973
974 /*
975 * create_script_for_old_cluster_deletion()
976 *
977 * This is particularly useful for tablespace deletion.
978 */
979 void
980 create_script_for_old_cluster_deletion(char **deletion_script_file_name)
981 {
982 FILE *script = NULL;
983 int tblnum;
984 char old_cluster_pgdata[MAXPGPATH],
985 new_cluster_pgdata[MAXPGPATH];
986 char *old_tblspc_suffix;
987
988 *deletion_script_file_name = psprintf("%sdelete_old_cluster.%s",
989 SCRIPT_PREFIX, SCRIPT_EXT);
990
991 strlcpy(old_cluster_pgdata, old_cluster.pgdata, MAXPGPATH);
992 canonicalize_path(old_cluster_pgdata);
993
994 strlcpy(new_cluster_pgdata, new_cluster.pgdata, MAXPGPATH);
995 canonicalize_path(new_cluster_pgdata);
996
997 /* Some people put the new data directory inside the old one. */
998 if (path_is_prefix_of_path(old_cluster_pgdata, new_cluster_pgdata))
999 {
1000 pg_log(PG_WARNING,
1001 "\nWARNING: new data directory should not be inside the old data directory, i.e. %s", old_cluster_pgdata);
1002
1003 /* Unlink file in case it is left over from a previous run. */
1004 unlink(*deletion_script_file_name);
1005 pg_free(*deletion_script_file_name);
1006 *deletion_script_file_name = NULL;
1007 return;
1008 }
1009
1010 /*
1011 * Some users (oddly) create tablespaces inside the cluster data
1012 * directory. We can't create a proper old cluster delete script in that
1013 * case.
1014 */
1015 for (tblnum = 0; tblnum < os_info.num_old_tablespaces; tblnum++)
1016 {
1017 char old_tablespace_dir[MAXPGPATH];
1018
1019 strlcpy(old_tablespace_dir, os_info.old_tablespaces[tblnum], MAXPGPATH);
1020 canonicalize_path(old_tablespace_dir);
1021 if (path_is_prefix_of_path(old_cluster_pgdata, old_tablespace_dir))
1022 {
1023 /* reproduce warning from CREATE TABLESPACE that is in the log */
1024 pg_log(PG_WARNING,
1025 "\nWARNING: user-defined tablespace locations should not be inside the data directory, i.e. %s", old_tablespace_dir);
1026
1027 /* Unlink file in case it is left over from a previous run. */
1028 unlink(*deletion_script_file_name);
1029 pg_free(*deletion_script_file_name);
1030 *deletion_script_file_name = NULL;
1031 return;
1032 }
1033 }
1034
1035 prep_status("Creating script to delete old cluster");
1036
1037 if ((script = fopen_priv(*deletion_script_file_name, "w")) == NULL)
1038 pg_fatal("could not open file \"%s\": %m",
1039 *deletion_script_file_name);
1040
1041 #ifndef WIN32
1042 /* add shebang header */
1043 fprintf(script, "#!/bin/sh\n\n");
1044 #endif
1045
1046 /* delete old cluster's default tablespace */
1047 fprintf(script, RMDIR_CMD " %c%s%c\n", PATH_QUOTE,
1048 fix_path_separator(old_cluster.pgdata), PATH_QUOTE);
1049
1050 /* delete old cluster's alternate tablespaces */
1051 old_tblspc_suffix = pg_strdup(old_cluster.tablespace_suffix);
1052 fix_path_separator(old_tblspc_suffix);
1053 for (tblnum = 0; tblnum < os_info.num_old_tablespaces; tblnum++)
1054 fprintf(script, RMDIR_CMD " %c%s%s%c\n", PATH_QUOTE,
1055 fix_path_separator(os_info.old_tablespaces[tblnum]),
1056 old_tblspc_suffix, PATH_QUOTE);
1057 pfree(old_tblspc_suffix);
1058
1059 fclose(script);
1060
1061 #ifndef WIN32
1062 if (chmod(*deletion_script_file_name, S_IRWXU) != 0)
1063 pg_fatal("could not add execute permission to file \"%s\": %m",
1064 *deletion_script_file_name);
1065 #endif
1066
1067 check_ok();
1068 }
1069
1070
1071 /*
1072 * check_is_install_user()
1073 *
1074 * Check we are the install user, and that the new cluster
1075 * has no other users.
1076 */
1077 static void
1078 check_is_install_user(ClusterInfo *cluster)
1079 {
1080 PGresult *res;
1081 PGconn *conn = connectToServer(cluster, "template1");
1082
1083 prep_status("Checking database user is the install user");
1084
1085 /* Can't use pg_authid because only superusers can view it. */
1086 res = executeQueryOrDie(conn,
1087 "SELECT rolsuper, oid "
1088 "FROM pg_catalog.pg_roles "
1089 "WHERE rolname = current_user "
1090 "AND rolname !~ '^pg_'");
1091
1092 /*
1093 * We only allow the install user in the new cluster (see comment below)
1094 * and we preserve pg_authid.oid, so this must be the install user in the
1095 * old cluster too.
1096 */
1097 if (PQntuples(res) != 1 ||
1098 atooid(PQgetvalue(res, 0, 1)) != BOOTSTRAP_SUPERUSERID)
1099 pg_fatal("database user \"%s\" is not the install user",
1100 os_info.user);
1101
1102 PQclear(res);
1103
1104 res = executeQueryOrDie(conn,
1105 "SELECT COUNT(*) "
1106 "FROM pg_catalog.pg_roles "
1107 "WHERE rolname !~ '^pg_'");
1108
1109 if (PQntuples(res) != 1)
1110 pg_fatal("could not determine the number of users");
1111
1112 /*
1113 * We only allow the install user in the new cluster because other defined
1114 * users might match users defined in the old cluster and generate an
1115 * error during pg_dump restore.
1116 */
1117 if (cluster == &new_cluster && strcmp(PQgetvalue(res, 0, 0), "1") != 0)
1118 pg_fatal("Only the install user can be defined in the new cluster.");
1119
1120 PQclear(res);
1121
1122 PQfinish(conn);
1123
1124 check_ok();
1125 }
1126
1127
1128 /*
1129 * check_for_connection_status
1130 *
1131 * Ensure that all non-template0 databases allow connections since they
1132 * otherwise won't be restored; and that template0 explicitly doesn't allow
1133 * connections since it would make pg_dumpall --globals restore fail.
1134 */
1135 static void
1136 check_for_connection_status(ClusterInfo *cluster)
1137 {
1138 int dbnum;
1139 PGconn *conn_template1;
1140 PGresult *dbres;
1141 int ntups;
1142 int i_datname;
1143 int i_datallowconn;
1144 int i_datconnlimit;
1145 FILE *script = NULL;
1146 char output_path[MAXPGPATH];
1147
1148 prep_status("Checking database connection settings");
1149
1150 snprintf(output_path, sizeof(output_path), "%s/%s",
1151 log_opts.basedir,
1152 "databases_cannot_connect_to.txt");
1153
1154 conn_template1 = connectToServer(cluster, "template1");
1155
1156 /* get database names */
1157 dbres = executeQueryOrDie(conn_template1,
1158 "SELECT datname, datallowconn, datconnlimit "
1159 "FROM pg_catalog.pg_database");
1160
1161 i_datname = PQfnumber(dbres, "datname");
1162 i_datallowconn = PQfnumber(dbres, "datallowconn");
1163 i_datconnlimit = PQfnumber(dbres, "datconnlimit");
1164
1165 ntups = PQntuples(dbres);
1166 for (dbnum = 0; dbnum < ntups; dbnum++)
1167 {
1168 char *datname = PQgetvalue(dbres, dbnum, i_datname);
1169 char *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
1170 char *datconnlimit = PQgetvalue(dbres, dbnum, i_datconnlimit);
1171
1172 if (strcmp(datname, "template0") == 0)
1173 {
1174 /* avoid restore failure when pg_dumpall tries to create template0 */
1175 if (strcmp(datallowconn, "t") == 0)
1176 pg_fatal("template0 must not allow connections, "
1177 "i.e. its pg_database.datallowconn must be false");
1178 }
1179 else
1180 {
1181 /*
1182 * Avoid datallowconn == false databases from being skipped on
1183 * restore, and ensure that no databases are marked invalid with
1184 * datconnlimit == -2.
1185 */
1186 if ((strcmp(datallowconn, "f") == 0) || strcmp(datconnlimit, "-2") == 0)
1187 {
1188 if (script == NULL && (script = fopen_priv(output_path, "w")) == NULL)
1189 pg_fatal("could not open file \"%s\": %m", output_path);
1190
1191 fprintf(script, "%s\n", datname);
1192 }
1193 }
1194 }
1195
1196 PQclear(dbres);
1197
1198 PQfinish(conn_template1);
1199
1200 if (script)
1201 {
1202 fclose(script);
1203 pg_log(PG_REPORT, "fatal");
1204 pg_fatal("All non-template0 databases must allow connections, i.e. their\n"
1205 "pg_database.datallowconn must be true and pg_database.datconnlimit\n"
1206 "must not be -2. Your installation contains non-template0 databases\n"
1207 "which cannot be connected to. Consider allowing connection for all\n"
1208 "non-template0 databases or drop the databases which do not allow\n"
1209 "connections. A list of databases with the problem is in the file:\n"
1210 " %s", output_path);
1211 }
1212 else
1213 check_ok();
1214 }
1215
1216
1217 /*
1218 * check_for_prepared_transactions()
1219 *
1220 * Make sure there are no prepared transactions because the storage format
1221 * might have changed.
1222 */
1223 static void
1224 check_for_prepared_transactions(ClusterInfo *cluster)
1225 {
1226 PGresult *res;
1227 PGconn *conn = connectToServer(cluster, "template1");
1228
1229 prep_status("Checking for prepared transactions");
1230
1231 res = executeQueryOrDie(conn,
1232 "SELECT * "
1233 "FROM pg_catalog.pg_prepared_xacts");
1234
1235 if (PQntuples(res) != 0)
1236 {
1237 if (cluster == &old_cluster)
1238 pg_fatal("The source cluster contains prepared transactions");
1239 else
1240 pg_fatal("The target cluster contains prepared transactions");
1241 }
1242
1243 PQclear(res);
1244
1245 PQfinish(conn);
1246
1247 check_ok();
1248 }
1249
1250 /*
1251 * Callback function for processing result of query for
1252 * check_for_isn_and_int8_passing_mismatch()'s UpgradeTask. If the query
1253 * returned any rows (i.e., the check failed), write the details to the report
1254 * file.
1255 */
1256 static void
1257 process_isn_and_int8_passing_mismatch(DbInfo *dbinfo, PGresult *res, void *arg)
1258 {
1259 int ntups = PQntuples(res);
1260 int i_nspname = PQfnumber(res, "nspname");
1261 int i_proname = PQfnumber(res, "proname");
1262 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1263
1264 AssertVariableIsOfType(&process_isn_and_int8_passing_mismatch,
1265 UpgradeTaskProcessCB);
1266
1267 if (ntups == 0)
1268 return;
1269
1270 if (report->file == NULL &&
1271 (report->file = fopen_priv(report->path, "w")) == NULL)
1272 pg_fatal("could not open file \"%s\": %m", report->path);
1273
1274 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1275
1276 for (int rowno = 0; rowno < ntups; rowno++)
1277 fprintf(report->file, " %s.%s\n",
1278 PQgetvalue(res, rowno, i_nspname),
1279 PQgetvalue(res, rowno, i_proname));
1280 }
1281
1282 /*
1283 * check_for_isn_and_int8_passing_mismatch()
1284 *
1285 * contrib/isn relies on data type int8, and in 8.4 int8 can now be passed
1286 * by value. The schema dumps the CREATE TYPE PASSEDBYVALUE setting so
1287 * it must match for the old and new servers.
1288 */
1289 static void
1290 check_for_isn_and_int8_passing_mismatch(ClusterInfo *cluster)
1291 {
1292 UpgradeTask *task;
1293 UpgradeTaskReport report;
1294 const char *query = "SELECT n.nspname, p.proname "
1295 "FROM pg_catalog.pg_proc p, "
1296 " pg_catalog.pg_namespace n "
1297 "WHERE p.pronamespace = n.oid AND "
1298 " p.probin = '$libdir/isn'";
1299
1300 prep_status("Checking for contrib/isn with bigint-passing mismatch");
1301
1302 if (old_cluster.controldata.float8_pass_by_value ==
1303 new_cluster.controldata.float8_pass_by_value)
1304 {
1305 /* no mismatch */
1306 check_ok();
1307 return;
1308 }
1309
1310 report.file = NULL;
1311 snprintf(report.path, sizeof(report.path), "%s/%s",
1312 log_opts.basedir,
1313 "contrib_isn_and_int8_pass_by_value.txt");
1314
1315 task = upgrade_task_create();
1316 upgrade_task_add_step(task, query, process_isn_and_int8_passing_mismatch,
1317 true, &report);
1318 upgrade_task_run(task, cluster);
1319 upgrade_task_free(task);
1320
1321 if (report.file)
1322 {
1323 fclose(report.file);
1324 pg_log(PG_REPORT, "fatal");
1325 pg_fatal("Your installation contains \"contrib/isn\" functions which rely on the\n"
1326 "bigint data type. Your old and new clusters pass bigint values\n"
1327 "differently so this cluster cannot currently be upgraded. You can\n"
1328 "manually dump databases in the old cluster that use \"contrib/isn\"\n"
1329 "facilities, drop them, perform the upgrade, and then restore them. A\n"
1330 "list of the problem functions is in the file:\n"
1331 " %s", report.path);
1332 }
1333 else
1334 check_ok();
1335 }
1336
1337 /*
1338 * Callback function for processing result of query for
1339 * check_for_user_defined_postfix_ops()'s UpgradeTask. If the query returned
1340 * any rows (i.e., the check failed), write the details to the report file.
1341 */
1342 static void
1343 process_user_defined_postfix_ops(DbInfo *dbinfo, PGresult *res, void *arg)
1344 {
1345 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1346 int ntups = PQntuples(res);
1347 int i_oproid = PQfnumber(res, "oproid");
1348 int i_oprnsp = PQfnumber(res, "oprnsp");
1349 int i_oprname = PQfnumber(res, "oprname");
1350 int i_typnsp = PQfnumber(res, "typnsp");
1351 int i_typname = PQfnumber(res, "typname");
1352
1353 AssertVariableIsOfType(&process_user_defined_postfix_ops,
1354 UpgradeTaskProcessCB);
1355
1356 if (ntups == 0)
1357 return;
1358
1359 if (report->file == NULL &&
1360 (report->file = fopen_priv(report->path, "w")) == NULL)
1361 pg_fatal("could not open file \"%s\": %m", report->path);
1362
1363 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1364
1365 for (int rowno = 0; rowno < ntups; rowno++)
1366 fprintf(report->file, " (oid=%s) %s.%s (%s.%s, NONE)\n",
1367 PQgetvalue(res, rowno, i_oproid),
1368 PQgetvalue(res, rowno, i_oprnsp),
1369 PQgetvalue(res, rowno, i_oprname),
1370 PQgetvalue(res, rowno, i_typnsp),
1371 PQgetvalue(res, rowno, i_typname));
1372 }
1373
1374 /*
1375 * Verify that no user defined postfix operators exist.
1376 */
1377 static void
1378 check_for_user_defined_postfix_ops(ClusterInfo *cluster)
1379 {
1380 UpgradeTaskReport report;
1381 UpgradeTask *task = upgrade_task_create();
1382 const char *query;
1383
1384 /*
1385 * The query below hardcodes FirstNormalObjectId as 16384 rather than
1386 * interpolating that C #define into the query because, if that #define is
1387 * ever changed, the cutoff we want to use is the value used by
1388 * pre-version 14 servers, not that of some future version.
1389 */
1390 query = "SELECT o.oid AS oproid, "
1391 " n.nspname AS oprnsp, "
1392 " o.oprname, "
1393 " tn.nspname AS typnsp, "
1394 " t.typname "
1395 "FROM pg_catalog.pg_operator o, "
1396 " pg_catalog.pg_namespace n, "
1397 " pg_catalog.pg_type t, "
1398 " pg_catalog.pg_namespace tn "
1399 "WHERE o.oprnamespace = n.oid AND "
1400 " o.oprleft = t.oid AND "
1401 " t.typnamespace = tn.oid AND "
1402 " o.oprright = 0 AND "
1403 " o.oid >= 16384";
1404
1405 prep_status("Checking for user-defined postfix operators");
1406
1407 report.file = NULL;
1408 snprintf(report.path, sizeof(report.path), "%s/%s",
1409 log_opts.basedir,
1410 "postfix_ops.txt");
1411
1412 upgrade_task_add_step(task, query, process_user_defined_postfix_ops,
1413 true, &report);
1414 upgrade_task_run(task, cluster);
1415 upgrade_task_free(task);
1416
1417 if (report.file)
1418 {
1419 fclose(report.file);
1420 pg_log(PG_REPORT, "fatal");
1421 pg_fatal("Your installation contains user-defined postfix operators, which are not\n"
1422 "supported anymore. Consider dropping the postfix operators and replacing\n"
1423 "them with prefix operators or function calls.\n"
1424 "A list of user-defined postfix operators is in the file:\n"
1425 " %s", report.path);
1426 }
1427 else
1428 check_ok();
1429 }
1430
1431 /*
1432 * Callback function for processing results of query for
1433 * check_for_incompatible_polymorphics()'s UpgradeTask. If the query returned
1434 * any rows (i.e., the check failed), write the details to the report file.
1435 */
1436 static void
1437 process_incompat_polymorphics(DbInfo *dbinfo, PGresult *res, void *arg)
1438 {
1439 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1440 int ntups = PQntuples(res);
1441 int i_objkind = PQfnumber(res, "objkind");
1442 int i_objname = PQfnumber(res, "objname");
1443
1444 AssertVariableIsOfType(&process_incompat_polymorphics,
1445 UpgradeTaskProcessCB);
1446
1447 if (ntups == 0)
1448 return;
1449
1450 if (report->file == NULL &&
1451 (report->file = fopen_priv(report->path, "w")) == NULL)
1452 pg_fatal("could not open file \"%s\": %m", report->path);
1453
1454 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1455
1456 for (int rowno = 0; rowno < ntups; rowno++)
1457 fprintf(report->file, " %s: %s\n",
1458 PQgetvalue(res, rowno, i_objkind),
1459 PQgetvalue(res, rowno, i_objname));
1460 }
1461
1462 /*
1463 * check_for_incompatible_polymorphics()
1464 *
1465 * Make sure nothing is using old polymorphic functions with
1466 * anyarray/anyelement rather than the new anycompatible variants.
1467 */
1468 static void
1469 check_for_incompatible_polymorphics(ClusterInfo *cluster)
1470 {
1471 PQExpBufferData old_polymorphics;
1472 UpgradeTask *task = upgrade_task_create();
1473 UpgradeTaskReport report;
1474 char *query;
1475
1476 prep_status("Checking for incompatible polymorphic functions");
1477
1478 report.file = NULL;
1479 snprintf(report.path, sizeof(report.path), "%s/%s",
1480 log_opts.basedir,
1481 "incompatible_polymorphics.txt");
1482
1483 /* The set of problematic functions varies a bit in different versions */
1484 initPQExpBuffer(&old_polymorphics);
1485
1486 appendPQExpBufferStr(&old_polymorphics,
1487 "'array_append(anyarray,anyelement)'"
1488 ", 'array_cat(anyarray,anyarray)'"
1489 ", 'array_prepend(anyelement,anyarray)'");
1490
1491 if (GET_MAJOR_VERSION(cluster->major_version) >= 903)
1492 appendPQExpBufferStr(&old_polymorphics,
1493 ", 'array_remove(anyarray,anyelement)'"
1494 ", 'array_replace(anyarray,anyelement,anyelement)'");
1495
1496 if (GET_MAJOR_VERSION(cluster->major_version) >= 905)
1497 appendPQExpBufferStr(&old_polymorphics,
1498 ", 'array_position(anyarray,anyelement)'"
1499 ", 'array_position(anyarray,anyelement,integer)'"
1500 ", 'array_positions(anyarray,anyelement)'"
1501 ", 'width_bucket(anyelement,anyarray)'");
1502
1503 /*
1504 * The query below hardcodes FirstNormalObjectId as 16384 rather than
1505 * interpolating that C #define into the query because, if that #define is
1506 * ever changed, the cutoff we want to use is the value used by
1507 * pre-version 14 servers, not that of some future version.
1508 */
1509
1510 /* Aggregate transition functions */
1511 query = psprintf("SELECT 'aggregate' AS objkind, p.oid::regprocedure::text AS objname "
1512 "FROM pg_proc AS p "
1513 "JOIN pg_aggregate AS a ON a.aggfnoid=p.oid "
1514 "JOIN pg_proc AS transfn ON transfn.oid=a.aggtransfn "
1515 "WHERE p.oid >= 16384 "
1516 "AND a.aggtransfn = ANY(ARRAY[%s]::regprocedure[]) "
1517 "AND a.aggtranstype = ANY(ARRAY['anyarray', 'anyelement']::regtype[]) "
1518
1519 /* Aggregate final functions */
1520 "UNION ALL "
1521 "SELECT 'aggregate' AS objkind, p.oid::regprocedure::text AS objname "
1522 "FROM pg_proc AS p "
1523 "JOIN pg_aggregate AS a ON a.aggfnoid=p.oid "
1524 "JOIN pg_proc AS finalfn ON finalfn.oid=a.aggfinalfn "
1525 "WHERE p.oid >= 16384 "
1526 "AND a.aggfinalfn = ANY(ARRAY[%s]::regprocedure[]) "
1527 "AND a.aggtranstype = ANY(ARRAY['anyarray', 'anyelement']::regtype[]) "
1528
1529 /* Operators */
1530 "UNION ALL "
1531 "SELECT 'operator' AS objkind, op.oid::regoperator::text AS objname "
1532 "FROM pg_operator AS op "
1533 "WHERE op.oid >= 16384 "
1534 "AND oprcode = ANY(ARRAY[%s]::regprocedure[]) "
1535 "AND oprleft = ANY(ARRAY['anyarray', 'anyelement']::regtype[])",
1536 old_polymorphics.data,
1537 old_polymorphics.data,
1538 old_polymorphics.data);
1539
1540 upgrade_task_add_step(task, query, process_incompat_polymorphics,
1541 true, &report);
1542 upgrade_task_run(task, cluster);
1543 upgrade_task_free(task);
1544
1545 if (report.file)
1546 {
1547 fclose(report.file);
1548 pg_log(PG_REPORT, "fatal");
1549 pg_fatal("Your installation contains user-defined objects that refer to internal\n"
1550 "polymorphic functions with arguments of type \"anyarray\" or \"anyelement\".\n"
1551 "These user-defined objects must be dropped before upgrading and restored\n"
1552 "afterwards, changing them to refer to the new corresponding functions with\n"
1553 "arguments of type \"anycompatiblearray\" and \"anycompatible\".\n"
1554 "A list of the problematic objects is in the file:\n"
1555 " %s", report.path);
1556 }
1557 else
1558 check_ok();
1559
1560 termPQExpBuffer(&old_polymorphics);
1561 pg_free(query);
1562 }
1563
1564 /*
1565 * Callback function for processing results of query for
1566 * check_for_tables_with_oids()'s UpgradeTask. If the query returned any rows
1567 * (i.e., the check failed), write the details to the report file.
1568 */
1569 static void
1570 process_with_oids_check(DbInfo *dbinfo, PGresult *res, void *arg)
1571 {
1572 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1573 int ntups = PQntuples(res);
1574 int i_nspname = PQfnumber(res, "nspname");
1575 int i_relname = PQfnumber(res, "relname");
1576
1577 AssertVariableIsOfType(&process_with_oids_check, UpgradeTaskProcessCB);
1578
1579 if (ntups == 0)
1580 return;
1581
1582 if (report->file == NULL &&
1583 (report->file = fopen_priv(report->path, "w")) == NULL)
1584 pg_fatal("could not open file \"%s\": %m", report->path);
1585
1586 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1587
1588 for (int rowno = 0; rowno < ntups; rowno++)
1589 fprintf(report->file, " %s.%s\n",
1590 PQgetvalue(res, rowno, i_nspname),
1591 PQgetvalue(res, rowno, i_relname));
1592 }
1593
1594 /*
1595 * Verify that no tables are declared WITH OIDS.
1596 */
1597 static void
1598 check_for_tables_with_oids(ClusterInfo *cluster)
1599 {
1600 UpgradeTaskReport report;
1601 UpgradeTask *task = upgrade_task_create();
1602 const char *query = "SELECT n.nspname, c.relname "
1603 "FROM pg_catalog.pg_class c, "
1604 " pg_catalog.pg_namespace n "
1605 "WHERE c.relnamespace = n.oid AND "
1606 " c.relhasoids AND"
1607 " n.nspname NOT IN ('pg_catalog')";
1608
1609 prep_status("Checking for tables WITH OIDS");
1610
1611 report.file = NULL;
1612 snprintf(report.path, sizeof(report.path), "%s/%s",
1613 log_opts.basedir,
1614 "tables_with_oids.txt");
1615
1616 upgrade_task_add_step(task, query, process_with_oids_check,
1617 true, &report);
1618 upgrade_task_run(task, cluster);
1619 upgrade_task_free(task);
1620
1621 if (report.file)
1622 {
1623 fclose(report.file);
1624 pg_log(PG_REPORT, "fatal");
1625 pg_fatal("Your installation contains tables declared WITH OIDS, which is not\n"
1626 "supported anymore. Consider removing the oid column using\n"
1627 " ALTER TABLE ... SET WITHOUT OIDS;\n"
1628 "A list of tables with the problem is in the file:\n"
1629 " %s", report.path);
1630 }
1631 else
1632 check_ok();
1633 }
1634
1635 /*
1636 * Callback function for processing results of query for
1637 * check_for_not_null_inheritance.
1638 */
1639 static void
1640 process_inconsistent_notnull(DbInfo *dbinfo, PGresult *res, void *arg)
1641 {
1642 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1643 int ntups = PQntuples(res);
1644 int i_nspname = PQfnumber(res, "nspname");
1645 int i_relname = PQfnumber(res, "relname");
1646 int i_attname = PQfnumber(res, "attname");
1647
1648 AssertVariableIsOfType(&process_inconsistent_notnull,
1649 UpgradeTaskProcessCB);
1650
1651 if (ntups == 0)
1652 return;
1653
1654 if (report->file == NULL &&
1655 (report->file = fopen_priv(report->path, "w")) == NULL)
1656 pg_fatal("could not open file \"%s\": %m", report->path);
1657
1658 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1659
1660 for (int rowno = 0; rowno < ntups; rowno++)
1661 {
1662 fprintf(report->file, " %s.%s.%s\n",
1663 PQgetvalue(res, rowno, i_nspname),
1664 PQgetvalue(res, rowno, i_relname),
1665 PQgetvalue(res, rowno, i_attname));
1666 }
1667 }
1668
1669 /*
1670 * check_for_not_null_inheritance()
1671 *
1672 * An attempt to create child tables lacking not-null constraints that are
1673 * present in their parents errors out. This can no longer occur since 18,
1674 * but previously there were various ways for that to happen. Check that
1675 * the cluster to be upgraded doesn't have any of those problems.
1676 */
1677 static void
1678 check_for_not_null_inheritance(ClusterInfo *cluster)
1679 {
1680 UpgradeTaskReport report;
1681 UpgradeTask *task;
1682 const char *query;
1683
1684 prep_status("Checking for not-null constraint inconsistencies");
1685
1686 report.file = NULL;
1687 snprintf(report.path, sizeof(report.path), "%s/%s",
1688 log_opts.basedir,
1689 "not_null_inconsistent_columns.txt");
1690
1691 query = "SELECT nspname, cc.relname, ac.attname "
1692 "FROM pg_catalog.pg_inherits i, pg_catalog.pg_attribute ac, "
1693 " pg_catalog.pg_attribute ap, pg_catalog.pg_class cc, "
1694 " pg_catalog.pg_namespace nc "
1695 "WHERE cc.oid = ac.attrelid AND i.inhrelid = ac.attrelid "
1696 " AND i.inhparent = ap.attrelid AND ac.attname = ap.attname "
1697 " AND cc.relnamespace = nc.oid "
1698 " AND ap.attnum > 0 and ap.attnotnull AND NOT ac.attnotnull";
1699
1700 task = upgrade_task_create();
1701 upgrade_task_add_step(task, query,
1702 process_inconsistent_notnull,
1703 true, &report);
1704 upgrade_task_run(task, cluster);
1705 upgrade_task_free(task);
1706
1707 if (report.file)
1708 {
1709 fclose(report.file);
1710 pg_log(PG_REPORT, "fatal");
1711 pg_fatal("Your installation contains inconsistent NOT NULL constraints.\n"
1712 "If the parent column(s) are NOT NULL, then the child column must\n"
1713 "also be marked NOT NULL, or the upgrade will fail.\n"
1714 "You can fix this by running\n"
1715 " ALTER TABLE tablename ALTER column SET NOT NULL;\n"
1716 "on each column listed in the file:\n"
1717 " %s", report.path);
1718 }
1719 else
1720 check_ok();
1721 }
1722
1723
1724 /*
1725 * check_for_pg_role_prefix()
1726 *
1727 * Versions older than 9.6 should not have any pg_* roles
1728 */
1729 static void
1730 check_for_pg_role_prefix(ClusterInfo *cluster)
1731 {
1732 PGresult *res;
1733 PGconn *conn = connectToServer(cluster, "template1");
1734 int ntups;
1735 int i_roloid;
1736 int i_rolname;
1737 FILE *script = NULL;
1738 char output_path[MAXPGPATH];
1739
1740 prep_status("Checking for roles starting with \"pg_\"");
1741
1742 snprintf(output_path, sizeof(output_path), "%s/%s",
1743 log_opts.basedir,
1744 "pg_role_prefix.txt");
1745
1746 res = executeQueryOrDie(conn,
1747 "SELECT oid AS roloid, rolname "
1748 "FROM pg_catalog.pg_roles "
1749 "WHERE rolname ~ '^pg_'");
1750
1751 ntups = PQntuples(res);
1752 i_roloid = PQfnumber(res, "roloid");
1753 i_rolname = PQfnumber(res, "rolname");
1754 for (int rowno = 0; rowno < ntups; rowno++)
1755 {
1756 if (script == NULL && (script = fopen_priv(output_path, "w")) == NULL)
1757 pg_fatal("could not open file \"%s\": %m", output_path);
1758 fprintf(script, "%s (oid=%s)\n",
1759 PQgetvalue(res, rowno, i_rolname),
1760 PQgetvalue(res, rowno, i_roloid));
1761 }
1762
1763 PQclear(res);
1764
1765 PQfinish(conn);
1766
1767 if (script)
1768 {
1769 fclose(script);
1770 pg_log(PG_REPORT, "fatal");
1771 pg_fatal("Your installation contains roles starting with \"pg_\".\n"
1772 "\"pg_\" is a reserved prefix for system roles. The cluster\n"
1773 "cannot be upgraded until these roles are renamed.\n"
1774 "A list of roles starting with \"pg_\" is in the file:\n"
1775 " %s", output_path);
1776 }
1777 else
1778 check_ok();
1779 }
1780
1781 /*
1782 * Callback function for processing results of query for
1783 * check_for_user_defined_encoding_conversions()'s UpgradeTask. If the query
1784 * returned any rows (i.e., the check failed), write the details to the report
1785 * file.
1786 */
1787 static void
1788 process_user_defined_encoding_conversions(DbInfo *dbinfo, PGresult *res, void *arg)
1789 {
1790 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1791 int ntups = PQntuples(res);
1792 int i_conoid = PQfnumber(res, "conoid");
1793 int i_conname = PQfnumber(res, "conname");
1794 int i_nspname = PQfnumber(res, "nspname");
1795
1796 AssertVariableIsOfType(&process_user_defined_encoding_conversions,
1797 UpgradeTaskProcessCB);
1798
1799 if (ntups == 0)
1800 return;
1801
1802 if (report->file == NULL &&
1803 (report->file = fopen_priv(report->path, "w")) == NULL)
1804 pg_fatal("could not open file \"%s\": %m", report->path);
1805
1806 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1807
1808 for (int rowno = 0; rowno < ntups; rowno++)
1809 fprintf(report->file, " (oid=%s) %s.%s\n",
1810 PQgetvalue(res, rowno, i_conoid),
1811 PQgetvalue(res, rowno, i_nspname),
1812 PQgetvalue(res, rowno, i_conname));
1813 }
1814
1815 /*
1816 * Verify that no user-defined encoding conversions exist.
1817 */
1818 static void
1819 check_for_user_defined_encoding_conversions(ClusterInfo *cluster)
1820 {
1821 UpgradeTaskReport report;
1822 UpgradeTask *task = upgrade_task_create();
1823 const char *query;
1824
1825 prep_status("Checking for user-defined encoding conversions");
1826
1827 report.file = NULL;
1828 snprintf(report.path, sizeof(report.path), "%s/%s",
1829 log_opts.basedir,
1830 "encoding_conversions.txt");
1831
1832 /*
1833 * The query below hardcodes FirstNormalObjectId as 16384 rather than
1834 * interpolating that C #define into the query because, if that #define is
1835 * ever changed, the cutoff we want to use is the value used by
1836 * pre-version 14 servers, not that of some future version.
1837 */
1838 query = "SELECT c.oid as conoid, c.conname, n.nspname "
1839 "FROM pg_catalog.pg_conversion c, "
1840 " pg_catalog.pg_namespace n "
1841 "WHERE c.connamespace = n.oid AND "
1842 " c.oid >= 16384";
1843
1844 upgrade_task_add_step(task, query,
1845 process_user_defined_encoding_conversions,
1846 true, &report);
1847 upgrade_task_run(task, cluster);
1848 upgrade_task_free(task);
1849
1850 if (report.file)
1851 {
1852 fclose(report.file);
1853 pg_log(PG_REPORT, "fatal");
1854 pg_fatal("Your installation contains user-defined encoding conversions.\n"
1855 "The conversion function parameters changed in PostgreSQL version 14\n"
1856 "so this cluster cannot currently be upgraded. You can remove the\n"
1857 "encoding conversions in the old cluster and restart the upgrade.\n"
1858 "A list of user-defined encoding conversions is in the file:\n"
1859 " %s", report.path);
1860 }
1861 else
1862 check_ok();
1863 }
1864
1865 /*
1866 * Callback function for processing results of query for
1867 * check_for_unicode_update()'s UpgradeTask. If the query returned any rows
1868 * (i.e., the check failed), write the details to the report file.
1869 */
1870 static void
1871 process_unicode_update(DbInfo *dbinfo, PGresult *res, void *arg)
1872 {
1873 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
1874 int ntups = PQntuples(res);
1875 int i_reloid = PQfnumber(res, "reloid");
1876 int i_nspname = PQfnumber(res, "nspname");
1877 int i_relname = PQfnumber(res, "relname");
1878
1879 if (ntups == 0)
1880 return;
1881
1882 if (report->file == NULL &&
1883 (report->file = fopen_priv(report->path, "w")) == NULL)
1884 pg_fatal("could not open file \"%s\": %m", report->path);
1885
1886 fprintf(report->file, "In database: %s\n", dbinfo->db_name);
1887
1888 for (int rowno = 0; rowno < ntups; rowno++)
1889 fprintf(report->file, " (oid=%s) %s.%s\n",
1890 PQgetvalue(res, rowno, i_reloid),
1891 PQgetvalue(res, rowno, i_nspname),
1892 PQgetvalue(res, rowno, i_relname));
1893 }
1894
1895 /*
1896 * Check if the Unicode version built into Postgres changed between the old
1897 * cluster and the new cluster.
1898 */
1899 static bool
1900 unicode_version_changed(ClusterInfo *cluster)
1901 {
1902 PGconn *conn_template1 = connectToServer(cluster, "template1");
1903 PGresult *res;
1904 char *old_unicode_version;
1905 bool unicode_updated;
1906
1907 res = executeQueryOrDie(conn_template1, "SELECT unicode_version()");
1908 old_unicode_version = PQgetvalue(res, 0, 0);
1909 unicode_updated = (strcmp(old_unicode_version, PG_UNICODE_VERSION) != 0);
1910
1911 PQclear(res);
1912 PQfinish(conn_template1);
1913
1914 return unicode_updated;
1915 }
1916
1917 /*
1918 * check_for_unicode_update()
1919 *
1920 * Check if the version of Unicode in the old server and the new server
1921 * differ. If so, check for indexes, partitioned tables, or constraints that
1922 * use expressions with functions dependent on Unicode behavior.
1923 */
1924 static void
1925 check_for_unicode_update(ClusterInfo *cluster)
1926 {
1927 UpgradeTaskReport report;
1928 UpgradeTask *task;
1929 const char *query;
1930
1931 /*
1932 * The builtin provider did not exist prior to version 17. While there are
1933 * still problems that could potentially be caught from earlier versions,
1934 * such as an index on NORMALIZE(), we don't check for that here.
1935 */
1936 if (GET_MAJOR_VERSION(cluster->major_version) < 1700)
1937 return;
1938
1939 prep_status("Checking for objects affected by Unicode update");
1940
1941 if (!unicode_version_changed(cluster))
1942 {
1943 check_ok();
1944 return;
1945 }
1946
1947 report.file = NULL;
1948 snprintf(report.path, sizeof(report.path), "%s/%s",
1949 log_opts.basedir,
1950 "unicode_dependent_rels.txt");
1951
1952 query =
1953 /* collations that use built-in Unicode for character semantics */
1954 "WITH collations(collid) AS ( "
1955 " SELECT oid FROM pg_collation "
1956 " WHERE collprovider='b' AND colllocale IN ('C.UTF-8','PG_UNICODE_FAST') "
1957 /* include default collation, if appropriate */
1958 " UNION "
1959 " SELECT 'pg_catalog.default'::regcollation FROM pg_database "
1960 " WHERE datname = current_database() AND "
1961 " datlocprovider='b' AND datlocale IN ('C.UTF-8','PG_UNICODE_FAST') "
1962 "), "
1963 /* functions that use built-in Unicode */
1964 "functions(procid) AS ( "
1965 " SELECT proc.oid FROM pg_proc proc "
1966 " WHERE proname IN ('normalize','unicode_assigned','unicode_version','is_normalized') AND "
1967 " pronamespace='pg_catalog'::regnamespace "
1968 "), "
1969 /* operators that use the input collation for character semantics */
1970 "coll_operators(operid, procid, collid) AS ( "
1971 " SELECT oper.oid, oper.oprcode, collid FROM pg_operator oper, collations "
1972 " WHERE oprname IN ('~', '~*', '!~', '!~*', '~~*', '!~~*') AND "
1973 " oprnamespace='pg_catalog'::regnamespace AND "
1974 " oprright='pg_catalog.text'::pg_catalog.regtype "
1975 "), "
1976 /* functions that use the input collation for character semantics */
1977 "coll_functions(procid, collid) AS ( "
1978 " SELECT proc.oid, collid FROM pg_proc proc, collations "
1979 " WHERE pronamespace='pg_catalog'::regnamespace AND "
1980 " ((proname IN ('lower','initcap','upper','casefold') AND "
1981 " pronargs = 1 AND "
1982 " proargtypes[0] = 'pg_catalog.text'::pg_catalog.regtype) OR "
1983 " (proname = 'substring' AND pronargs = 2 AND "
1984 " proargtypes[0] = 'pg_catalog.text'::pg_catalog.regtype AND "
1985 " proargtypes[1] = 'pg_catalog.text'::pg_catalog.regtype) OR "
1986 " proname LIKE 'regexp_%') "
1987 /* include functions behind the operators listed above */
1988 " UNION "
1989 " SELECT procid, collid FROM coll_operators "
1990 "), "
1991
1992 /*
1993 * Generate patterns to search a pg_node_tree for the above functions and
1994 * operators.
1995 */
1996 "patterns(p) AS ( "
1997 " SELECT '{FUNCEXPR :funcid ' || procid::text || '[ }]' FROM functions "
1998 " UNION "
1999 " SELECT '{OPEXPR :opno ' || operid::text || ' (:\\w+ \\w+ )*' || "
2000 " ':inputcollid ' || collid::text || '[ }]' FROM coll_operators "
2001 " UNION "
2002 " SELECT '{FUNCEXPR :funcid ' || procid::text || ' (:\\w+ \\w+ )*' || "
2003 " ':inputcollid ' || collid::text || '[ }]' FROM coll_functions "
2004 ") "
2005
2006 /*
2007 * Match the patterns against expressions used for relation contents.
2008 */
2009 "SELECT reloid, relkind, nspname, relname "
2010 " FROM ( "
2011 " SELECT conrelid "
2012 " FROM pg_constraint, patterns WHERE conbin::text ~ p "
2013 " UNION "
2014 " SELECT indexrelid "
2015 " FROM pg_index, patterns WHERE indexprs::text ~ p OR indpred::text ~ p "
2016 " UNION "
2017 " SELECT partrelid "
2018 " FROM pg_partitioned_table, patterns WHERE partexprs::text ~ p "
2019 " UNION "
2020 " SELECT ev_class "
2021 " FROM pg_rewrite, pg_class, patterns "
2022 " WHERE ev_class = pg_class.oid AND relkind = 'm' AND ev_action::text ~ p"
2023 " ) s(reloid), pg_class c, pg_namespace n, pg_database d "
2024 " WHERE s.reloid = c.oid AND c.relnamespace = n.oid AND "
2025 " d.datname = current_database() AND "
2026 " d.encoding = pg_char_to_encoding('UTF8');";
2027
2028 task = upgrade_task_create();
2029 upgrade_task_add_step(task, query,
2030 process_unicode_update,
2031 true, &report);
2032 upgrade_task_run(task, cluster);
2033 upgrade_task_free(task);
2034
2035 if (report.file)
2036 {
2037 fclose(report.file);
2038 report_status(PG_WARNING, "warning");
2039 pg_log(PG_WARNING, "Your installation contains relations that might be affected by a new version of Unicode.\n"
2040 "A list of potentially-affected relations is in the file:\n"
2041 " %s", report.path);
2042 }
2043 else
2044 check_ok();
2045 }
2046
2047 /*
2048 * check_new_cluster_logical_replication_slots()
2049 *
2050 * Verify that there are no logical replication slots on the new cluster and
2051 * that the parameter settings necessary for creating slots are sufficient.
2052 */
2053 static void
2054 check_new_cluster_logical_replication_slots(void)
2055 {
2056 PGresult *res;
2057 PGconn *conn;
2058 int nslots_on_old;
2059 int nslots_on_new;
2060 int max_replication_slots;
2061 char *output_plugin_libraries;
2062 char *wal_level;
2063
2064 /* Logical slots can be migrated since PG17. */
2065 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 1600)
2066 return;
2067
2068 nslots_on_old = count_old_cluster_logical_slots();
2069
2070 /* Quick return if there are no logical slots to be migrated. */
2071 if (nslots_on_old == 0)
2072 return;
2073
2074 conn = connectToServer(&new_cluster, "template1");
2075
2076 prep_status("Checking for new cluster logical replication slots");
2077
2078 res = executeQueryOrDie(conn, "SELECT count(*) "
2079 "FROM pg_catalog.pg_replication_slots "
2080 "WHERE slot_type = 'logical' AND "
2081 "temporary IS FALSE;");
2082
2083 if (PQntuples(res) != 1)
2084 pg_fatal("could not count the number of logical replication slots");
2085
2086 nslots_on_new = atoi(PQgetvalue(res, 0, 0));
2087
2088 if (nslots_on_new)
2089 pg_fatal("expected 0 logical replication slots but found %d",
2090 nslots_on_new);
2091
2092 PQclear(res);
2093
2094 res = executeQueryOrDie(conn, "SELECT setting FROM pg_settings "
2095 "WHERE name IN ('wal_level', 'output_plugin_libraries', 'max_replication_slots') "
2096 "ORDER BY name DESC;");
2097
2098 if (PQntuples(res) != 3)
2099 pg_fatal("could not determine parameter settings on new cluster");
2100
2101 wal_level = PQgetvalue(res, 0, 0);
2102
2103 if (strcmp(wal_level, "logical") != 0)
2104 pg_fatal("\"wal_level\" must be \"logical\" but is set to \"%s\"",
2105 wal_level);
2106
2107 output_plugin_libraries = PQgetvalue(res, 1, 0);
2108
2109 /*
2110 * Make sure the output_plugin_libraries setting covers all plugins needed
2111 * by any migrated slots.
2112 */
2113 if (nslots_on_old > 0)
2114 {
2115 char *guc_copy = pg_strdup(output_plugin_libraries);
2116 char **allowed_plugins;
2117 char output_path[MAXPGPATH];
2118 FILE *script = NULL;
2119
2120 if (!SplitGUCList(guc_copy, ',', &allowed_plugins))
2121 {
2122 /*
2123 * Should not happen. (Frontend and backend GUC_LIST_QUOTE parsing
2124 * have to remain compatible for pg_dump at minimum.)
2125 */
2126 pg_fatal("could not parse \"output_plugin_libraries\" setting '%s'",
2127 output_plugin_libraries);
2128 }
2129
2130 snprintf(output_path, sizeof(output_path), "%s/%s",
2131 log_opts.basedir,
2132 "disallowed_output_plugins.txt");
2133
2134 for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
2135 {
2136 LogicalSlotInfoArr *slot_arr = &old_cluster.dbarr.dbs[dbnum].slot_arr;
2137
2138 for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
2139 {
2140 LogicalSlotInfo *slot = &slot_arr->slots[slotnum];
2141 bool allowed = false;
2142
2143 /*
2144 * We expect the output_plugin_libraries length to be small in
2145 * practice; O(n*m) shouldn't be a problem here.
2146 */
2147 for (char **p = allowed_plugins; *p; p++)
2148 {
2149 if (strcmp(slot->plugin, *p) == 0)
2150 {
2151 allowed = true;
2152 break;
2153 }
2154 }
2155
2156 if (!allowed)
2157 {
2158 if (script == NULL &&
2159 (script = fopen_priv(output_path, "w")) == NULL)
2160 pg_fatal("could not open file \"%s\": %m", output_path);
2161
2162 fprintf(script, "The slot \"%s\" uses plugin \"%s\"\n",
2163 slot->slotname, slot->plugin);
2164 }
2165 }
2166 }
2167
2168 if (script)
2169 {
2170 fclose(script);
2171
2172 pg_log(PG_REPORT, "fatal");
2173 pg_fatal("Your installation contains logical replication slots with plugins\n"
2174 "that are not allowed by the new cluster's output_plugin_libraries\n"
2175 "setting. You can add trusted plugins to output_plugin_libraries\n"
2176 "and/or remove affected slots, and then restart the upgrade.\n"
2177 "A list of the problematic slots is in the file:\n"
2178 " %s", output_path);
2179 }
2180
2181 pg_free(allowed_plugins);
2182 pg_free(guc_copy);
2183 }
2184
2185 max_replication_slots = atoi(PQgetvalue(res, 2, 0));
2186
2187 if (nslots_on_old > max_replication_slots)
2188 pg_fatal("\"max_replication_slots\" (%d) must be greater than or equal to the number of "
2189 "logical replication slots (%d) on the old cluster",
2190 max_replication_slots, nslots_on_old);
2191
2192 PQclear(res);
2193 PQfinish(conn);
2194
2195 check_ok();
2196 }
2197
2198 /*
2199 * check_new_cluster_subscription_configuration()
2200 *
2201 * Verify that the max_active_replication_origins configuration specified is
2202 * enough for creating the subscriptions. This is required to create the
2203 * replication origin for each subscription.
2204 */
2205 static void
2206 check_new_cluster_subscription_configuration(void)
2207 {
2208 PGresult *res;
2209 PGconn *conn;
2210 int max_active_replication_origins;
2211
2212 /* Subscriptions and their dependencies can be migrated since PG17. */
2213 if (GET_MAJOR_VERSION(old_cluster.major_version) < 1700)
2214 return;
2215
2216 /* Quick return if there are no subscriptions to be migrated. */
2217 if (old_cluster.nsubs == 0)
2218 return;
2219
2220 prep_status("Checking for new cluster configuration for subscriptions");
2221
2222 conn = connectToServer(&new_cluster, "template1");
2223
2224 res = executeQueryOrDie(conn, "SELECT setting FROM pg_settings "
2225 "WHERE name = 'max_active_replication_origins';");
2226
2227 if (PQntuples(res) != 1)
2228 pg_fatal("could not determine parameter settings on new cluster");
2229
2230 max_active_replication_origins = atoi(PQgetvalue(res, 0, 0));
2231 if (old_cluster.nsubs > max_active_replication_origins)
2232 pg_fatal("\"max_active_replication_origins\" (%d) must be greater than or equal to the number of "
2233 "subscriptions (%d) on the old cluster",
2234 max_active_replication_origins, old_cluster.nsubs);
2235
2236 PQclear(res);
2237 PQfinish(conn);
2238
2239 check_ok();
2240 }
2241
2242 /*
2243 * check_old_cluster_for_valid_slots()
2244 *
2245 * Verify that all the logical slots are valid and have consumed all the WAL
2246 * before shutdown.
2247 */
2248 static void
2249 check_old_cluster_for_valid_slots(void)
2250 {
2251 char output_path[MAXPGPATH];
2252 FILE *script = NULL;
2253
2254 prep_status("Checking for valid logical replication slots");
2255
2256 snprintf(output_path, sizeof(output_path), "%s/%s",
2257 log_opts.basedir,
2258 "invalid_logical_slots.txt");
2259
2260 for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
2261 {
2262 LogicalSlotInfoArr *slot_arr = &old_cluster.dbarr.dbs[dbnum].slot_arr;
2263
2264 for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
2265 {
2266 LogicalSlotInfo *slot = &slot_arr->slots[slotnum];
2267
2268 /* Is the slot usable? */
2269 if (slot->invalid)
2270 {
2271 if (script == NULL &&
2272 (script = fopen_priv(output_path, "w")) == NULL)
2273 pg_fatal("could not open file \"%s\": %m", output_path);
2274
2275 fprintf(script, "The slot \"%s\" is invalid\n",
2276 slot->slotname);
2277
2278 continue;
2279 }
2280
2281 /*
2282 * Do additional check to ensure that all logical replication
2283 * slots have consumed all the WAL before shutdown.
2284 *
2285 * Note: This can be satisfied only when the old cluster has been
2286 * shut down, so we skip this for live checks.
2287 */
2288 if (!user_opts.live_check && !slot->caught_up)
2289 {
2290 if (script == NULL &&
2291 (script = fopen_priv(output_path, "w")) == NULL)
2292 pg_fatal("could not open file \"%s\": %m", output_path);
2293
2294 fprintf(script,
2295 "The slot \"%s\" has not consumed the WAL yet\n",
2296 slot->slotname);
2297 }
2298 }
2299 }
2300
2301 if (script)
2302 {
2303 fclose(script);
2304
2305 pg_log(PG_REPORT, "fatal");
2306 pg_fatal("Your installation contains logical replication slots that cannot be upgraded.\n"
2307 "You can remove invalid slots and/or consume the pending WAL for other slots,\n"
2308 "and then restart the upgrade.\n"
2309 "A list of the problematic slots is in the file:\n"
2310 " %s", output_path);
2311 }
2312
2313 check_ok();
2314 }
2315
2316 /*
2317 * Callback function for processing results of query for
2318 * check_old_cluster_subscription_state()'s UpgradeTask. If the query returned
2319 * any rows (i.e., the check failed), write the details to the report file.
2320 */
2321 static void
2322 process_old_sub_state_check(DbInfo *dbinfo, PGresult *res, void *arg)
2323 {
2324 UpgradeTaskReport *report = (UpgradeTaskReport *) arg;
2325 int ntups = PQntuples(res);
2326 int i_srsubstate = PQfnumber(res, "srsubstate");
2327 int i_subname = PQfnumber(res, "subname");
2328 int i_nspname = PQfnumber(res, "nspname");
2329 int i_relname = PQfnumber(res, "relname");
2330
2331 AssertVariableIsOfType(&process_old_sub_state_check, UpgradeTaskProcessCB);
2332
2333 if (ntups == 0)
2334 return;
2335
2336 if (report->file == NULL &&
2337 (report->file = fopen_priv(report->path, "w")) == NULL)
2338 pg_fatal("could not open file \"%s\": %m", report->path);
2339
2340 for (int i = 0; i < ntups; i++)
2341 fprintf(report->file, "The table sync state \"%s\" is not allowed for database:\"%s\" subscription:\"%s\" schema:\"%s\" relation:\"%s\"\n",
2342 PQgetvalue(res, i, i_srsubstate),
2343 dbinfo->db_name,
2344 PQgetvalue(res, i, i_subname),
2345 PQgetvalue(res, i, i_nspname),
2346 PQgetvalue(res, i, i_relname));
2347 }
2348
2349 /*
2350 * check_old_cluster_subscription_state()
2351 *
2352 * Verify that the replication origin corresponding to each of the
2353 * subscriptions are present and each of the subscribed tables is in
2354 * 'i' (initialize) or 'r' (ready) state.
2355 */
2356 static void
2357 check_old_cluster_subscription_state(void)
2358 {
2359 UpgradeTask *task = upgrade_task_create();
2360 UpgradeTaskReport report;
2361 const char *query;
2362 PGresult *res;
2363 PGconn *conn;
2364 int ntup;
2365
2366 prep_status("Checking for subscription state");
2367
2368 report.file = NULL;
2369 snprintf(report.path, sizeof(report.path), "%s/%s",
2370 log_opts.basedir,
2371 "subs_invalid.txt");
2372
2373 /*
2374 * Check that all the subscriptions have their respective replication
2375 * origin. This check only needs to run once.
2376 */
2377 conn = connectToServer(&old_cluster, old_cluster.dbarr.dbs[0].db_name);
2378 res = executeQueryOrDie(conn,
2379 "SELECT d.datname, s.subname "
2380 "FROM pg_catalog.pg_subscription s "
2381 "LEFT OUTER JOIN pg_catalog.pg_replication_origin o "
2382 " ON o.roname = 'pg_' || s.oid "
2383 "INNER JOIN pg_catalog.pg_database d "
2384 " ON d.oid = s.subdbid "
2385 "WHERE o.roname IS NULL;");
2386 ntup = PQntuples(res);
2387 for (int i = 0; i < ntup; i++)
2388 {
2389 if (report.file == NULL &&
2390 (report.file = fopen_priv(report.path, "w")) == NULL)
2391 pg_fatal("could not open file \"%s\": %m", report.path);
2392 fprintf(report.file, "The replication origin is missing for database:\"%s\" subscription:\"%s\"\n",
2393 PQgetvalue(res, i, 0),
2394 PQgetvalue(res, i, 1));
2395 }
2396 PQclear(res);
2397 PQfinish(conn);
2398
2399 /*
2400 * We don't allow upgrade if there is a risk of dangling slot or origin
2401 * corresponding to initial sync after upgrade.
2402 *
2403 * A slot/origin not created yet refers to the 'i' (initialize) state,
2404 * while 'r' (ready) state refers to a slot/origin created previously but
2405 * already dropped. These states are supported for pg_upgrade. The other
2406 * states listed below are not supported:
2407 *
2408 * a) SUBREL_STATE_DATASYNC: A relation upgraded while in this state would
2409 * retain a replication slot and origin. The sync worker spawned after the
2410 * upgrade cannot drop them because the subscription ID used for the slot
2411 * and origin name no longer matches.
2412 *
2413 * b) SUBREL_STATE_SYNCDONE: A relation upgraded while in this state would
2414 * retain the replication origin when there is a failure in tablesync
2415 * worker immediately after dropping the replication slot in the
2416 * publisher.
2417 *
2418 * c) SUBREL_STATE_FINISHEDCOPY: A tablesync worker spawned to work on a
2419 * relation upgraded while in this state would expect an origin ID with
2420 * the OID of the subscription used before the upgrade, causing it to
2421 * fail.
2422 *
2423 * d) SUBREL_STATE_SYNCWAIT, SUBREL_STATE_CATCHUP and
2424 * SUBREL_STATE_UNKNOWN: These states are not stored in the catalog, so we
2425 * need not allow these states.
2426 */
2427 query = "SELECT r.srsubstate, s.subname, n.nspname, c.relname "
2428 "FROM pg_catalog.pg_subscription_rel r "
2429 "LEFT JOIN pg_catalog.pg_subscription s"
2430 " ON r.srsubid = s.oid "
2431 "LEFT JOIN pg_catalog.pg_class c"
2432 " ON r.srrelid = c.oid "
2433 "LEFT JOIN pg_catalog.pg_namespace n"
2434 " ON c.relnamespace = n.oid "
2435 "WHERE r.srsubstate NOT IN ('i', 'r') "
2436 "ORDER BY s.subname";
2437
2438 upgrade_task_add_step(task, query, process_old_sub_state_check,
2439 true, &report);
2440
2441 upgrade_task_run(task, &old_cluster);
2442 upgrade_task_free(task);
2443
2444 if (report.file)
2445 {
2446 fclose(report.file);
2447 pg_log(PG_REPORT, "fatal");
2448 pg_fatal("Your installation contains subscriptions without origin or having relations not in i (initialize) or r (ready) state.\n"
2449 "You can allow the initial sync to finish for all relations and then restart the upgrade.\n"
2450 "A list of the problematic subscriptions is in the file:\n"
2451 " %s", report.path);
2452 }
2453 else
2454 check_ok();
2455 }