From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Bohyun Lee Date: Thu, 26 Nov 2026 15:25:15 +0100 Subject: [PATCH v11] pg_upgrade: add --print-initdb-options Let callers obtain shell-quoted initdb arguments derived from the old cluster, then initialize and configure the new cluster before upgrading. Keep diagnostics on stderr and preserve the source's initial running state. Reuse the existing control-data reader, template0 query, and server lifecycle handling. Validate source binary/data versions before inspecting control data and reject combining printing with --check. Add TAP coverage for shell reuse, running and stopped sources, discovery failures, and upgrading a separately initialized target. --- doc/src/sgml/ref/pgupgrade.sgml | 57 ++++++++++++++-- src/bin/pg_upgrade/check.c | 29 ++++++-- src/bin/pg_upgrade/info.c | 3 +- src/bin/pg_upgrade/meson.build | 1 + src/bin/pg_upgrade/option.c | 19 ++++-- src/bin/pg_upgrade/pg_upgrade.c | 119 ++++++++++++++++++++++++++++++-- src/bin/pg_upgrade/pg_upgrade.h | 9 ++- src/bin/pg_upgrade/server.c | 4 +- src/bin/pg_upgrade/t/010_initdb.pl | 136 +++++++++++++++++++++++++++++++++++++ src/bin/pg_upgrade/util.c | 35 ++++++---- 10 files changed, 373 insertions(+), 39 deletions(-) create mode 100644 src/bin/pg_upgrade/t/010_initdb.pl diff --git a/doc/src/sgml/ref/pgupgrade.sgml b/doc/src/sgml/ref/pgupgrade.sgml index e4e8c02e6d67f3725f68a6e72d0f375f5d12fe8e..329fd86796162e52abb0d236cf1921783102e87c 100644 --- a/doc/src/sgml/ref/pgupgrade.sgml +++ b/doc/src/sgml/ref/pgupgrade.sgml @@ -31,6 +31,13 @@ PostgreSQL documentation newconfigdir option + + pg_upgrade + + oldbindir + oldconfigdir + option + @@ -262,6 +269,40 @@ PostgreSQL documentation + + + + + Print the old cluster's initialization options and exit. The output + contains its WAL segment size and checksum setting, and the encoding + and locale settings of its template0 database. + Standard output contains one line of shell-quoted arguments; + diagnostics are written to standard error. Target paths, the + superuser name, and authentication settings are left to the caller. + + + As with 's + output, preserve the shell quotation marks when reusing the arguments. + For example, in a POSIX shell script: + +initdb_options=$(/new/bin/pg_upgrade --print-initdb-options \ + --old-bindir=/old/bin --old-datadir=/old/data) || exit +eval /new/bin/initdb --pgdata=/new/data "$initdb_options" + + A wrapper can then configure the new cluster before running + pg_upgrade normally. + + + The old server is started temporarily if stopped, and is left running + otherwise. The current directory must be writable for diagnostic + logs in pg_upgrade_output.d. Logs are removed + on success unless is specified. + This mode does not perform upgrade compatibility checks and cannot + be combined with . + + + + @@ -457,10 +498,18 @@ make prefix=/usr/local/pgsql.new install Initialize the new cluster using initdb. - Again, use compatible initdb - flags that match the old cluster. Many - prebuilt installers do this step automatically. There is no need to - start the new cluster. + Two initdb settings must match the old cluster, or + pg_upgrade will fail with a control-data + mismatch: the WAL segment size () and the + data checksum setting ( or + ). You can read the old cluster's + values with + + pg_controldata. + (The encoding and locale need not match: + pg_upgrade copies them from the old cluster.) + Many prebuilt installers do this step automatically. There is no need + to start the new cluster. diff --git a/src/bin/pg_upgrade/check.c b/src/bin/pg_upgrade/check.c index 2da1962fa16d9ce1b3296197afc7f36102756328..ff2ec3139e061bcce928dceb9d925e129d1a9058 100644 --- a/src/bin/pg_upgrade/check.c +++ b/src/bin/pg_upgrade/check.c @@ -822,6 +822,27 @@ output_completion_banner(char *deletion_script_file_name) } +/* + * Require the binaries and data directory to have the same major version. + * Call this before inspecting control data with the cluster's binaries. + */ +void +check_cluster_binary_version(ClusterInfo *cluster) +{ + Assert(cluster->major_version != 0); + Assert(cluster->bin_version != 0); + + if (GET_MAJOR_VERSION(cluster->major_version) == + GET_MAJOR_VERSION(cluster->bin_version)) + return; + + if (cluster == &old_cluster) + pg_fatal("Old cluster data and binary directories are from different major versions."); + else + pg_fatal("New cluster data and binary directories are from different major versions."); +} + + void check_cluster_versions(void) { @@ -854,12 +875,8 @@ check_cluster_versions(void) pg_fatal("This utility cannot be used to downgrade to older major PostgreSQL versions."); /* Ensure binaries match the designated data directories */ - if (GET_MAJOR_VERSION(old_cluster.major_version) != - GET_MAJOR_VERSION(old_cluster.bin_version)) - pg_fatal("Old cluster data and binary directories are from different major versions."); - if (GET_MAJOR_VERSION(new_cluster.major_version) != - GET_MAJOR_VERSION(new_cluster.bin_version)) - pg_fatal("New cluster data and binary directories are from different major versions."); + check_cluster_binary_version(&old_cluster); + check_cluster_binary_version(&new_cluster); /* * Since from version 18, newly created database clusters always have diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c index 6d8f70c8c7d9416ebfc7a8572de2b07755c29771..d6535523295e7100819262e3c1e4327a93f45975 100644 --- a/src/bin/pg_upgrade/info.c +++ b/src/bin/pg_upgrade/info.c @@ -21,7 +21,6 @@ static void create_rel_filename_map(const char *old_data, const char *new_data, static void report_unmatched_relation(const RelInfo *rel, const DbInfo *db, bool is_new_db); static void free_db_and_rel_infos(DbInfoArr *db_arr); -static void get_template0_info(ClusterInfo *cluster); static void get_db_infos(ClusterInfo *cluster); static char *get_rel_infos_query(void); static void process_rel_infos(DbInfo *dbinfo, PGresult *res, void *arg); @@ -328,7 +327,7 @@ get_db_rel_and_slot_infos(ClusterInfo *cluster) * Get information about template0, which will be copied from the old cluster * to the new cluster. */ -static void +void get_template0_info(ClusterInfo *cluster) { PGconn *conn = connectToServer(cluster, "template1"); diff --git a/src/bin/pg_upgrade/meson.build b/src/bin/pg_upgrade/meson.build index 892be18780e27d78c7d17ec8822d014f40a1d3e8..b76459c1f0bd747ab43a28fc5d2ea78c2471d8b2 100644 --- a/src/bin/pg_upgrade/meson.build +++ b/src/bin/pg_upgrade/meson.build @@ -70,6 +70,7 @@ tests += { 't/007_multixact_conversion.pl', 't/008_extension_control_path.pl', 't/009_composite_types.pl', + 't/010_initdb.pl', ], 'deps': [test_ext], 'test_kwargs': {'priority': 40}, # pg_upgrade tests are slow diff --git a/src/bin/pg_upgrade/option.c b/src/bin/pg_upgrade/option.c index 179eaf0d5e62b0132860ff45c3d3b4e2702a5533..e18f9bf08e6a62a4b4760fcb839df2caa88fbebf 100644 --- a/src/bin/pg_upgrade/option.c +++ b/src/bin/pg_upgrade/option.c @@ -63,6 +63,7 @@ parseCommandLine(int argc, char *argv[]) {"no-statistics", no_argument, NULL, 5}, {"set-char-signedness", required_argument, NULL, 6}, {"swap", no_argument, NULL, 7}, + {"print-initdb-options", no_argument, NULL, 8}, {NULL, 0, NULL, 0} }; @@ -234,6 +235,10 @@ parseCommandLine(int argc, char *argv[]) user_opts.transfer_mode = TRANSFER_MODE_SWAP; break; + case 8: + user_opts.print_initdb_options = true; + break; + default: fprintf(stderr, _("Try \"%s --help\" for more information.\n"), os_info.progname); @@ -244,13 +249,16 @@ parseCommandLine(int argc, char *argv[]) if (optind < argc) pg_fatal("too many command-line arguments (first is \"%s\")", argv[optind]); + if (user_opts.print_initdb_options && user_opts.check) + pg_fatal("options --print-initdb-options and --check cannot be used together"); + if (!user_opts.sync_method) user_opts.sync_method = pg_strdup("fsync"); if (log_opts.verbose) pg_log(PG_REPORT, "Running in verbose mode"); - log_opts.isatty = isatty(fileno(stdout)); + log_opts.isatty = isatty(fileno(user_opts.print_initdb_options ? stderr : stdout)); /* Turn off read-only mode; add prefix to PGOPTIONS? */ if (getenv("PGOPTIONS")) @@ -272,7 +280,8 @@ parseCommandLine(int argc, char *argv[]) check_required_directory(&old_cluster.pgdata, "PGDATAOLD", false, "-d", _("old cluster data resides"), false); check_required_directory(&new_cluster.pgdata, "PGDATANEW", false, - "-D", _("new cluster data resides"), false); + "-D", _("new cluster data resides"), + user_opts.print_initdb_options); check_required_directory(&user_opts.socketdir, "PGSOCKETDIR", true, "-s", _("sockets will be created"), false); @@ -283,6 +292,7 @@ parseCommandLine(int argc, char *argv[]) * error on file pg_upgrade_utility.log if pg_upgrade is run inside the * new cluster directory, so we do a check here. */ + if (!user_opts.print_initdb_options) { char cwd[MAXPGPATH], new_cluster_pgdata[MAXPGPATH]; @@ -328,6 +338,7 @@ usage(void) printf(_(" --clone clone instead of copying files to new cluster\n")); printf(_(" --copy copy files to new cluster (default)\n")); printf(_(" --copy-file-range copy files to new cluster with copy_file_range\n")); + printf(_(" --print-initdb-options print old cluster initdb options, then exit\n")); printf(_(" --no-statistics do not import statistics from old cluster\n")); printf(_(" --set-char-signedness=OPTION set new cluster char signedness to \"signed\" or\n" " \"unsigned\"\n")); @@ -335,12 +346,12 @@ usage(void) printf(_(" --sync-method=METHOD set method for syncing files to disk\n")); printf(_(" -?, --help show this help, then exit\n")); printf(_("\n" - "Before running pg_upgrade you must:\n" + "Before performing an upgrade you must:\n" " create a new database cluster (using the new version of initdb)\n" " shutdown the postmaster servicing the old cluster\n" " shutdown the postmaster servicing the new cluster\n")); printf(_("\n" - "When you run pg_upgrade, you must provide the following information:\n" + "When performing an upgrade, you must provide the following information:\n" " the data directory for the old cluster (-d DATADIR)\n" " the data directory for the new cluster (-D DATADIR)\n" " the \"bin\" directory for the old version (-b BINDIR)\n" diff --git a/src/bin/pg_upgrade/pg_upgrade.c b/src/bin/pg_upgrade/pg_upgrade.c index 0c2f3122ad803b63f644e3d5c31df350fb8b6dd5..08dd4882a0454a0ed7a577265cccde312227f72c 100644 --- a/src/bin/pg_upgrade/pg_upgrade.c +++ b/src/bin/pg_upgrade/pg_upgrade.c @@ -45,10 +45,12 @@ #include "access/multixact.h" #include "catalog/pg_class_d.h" +#include "catalog/pg_collation_d.h" #include "common/file_perm.h" #include "common/logging.h" #include "common/restricted_token.h" #include "fe_utils/string_utils.h" +#include "mb/pg_wchar.h" #include "pg_upgrade.h" /* @@ -68,6 +70,9 @@ static void set_frozenxids(void); static void make_outputdirs(char *pgdata); static void check_bin_dirs(char *argv0); static void check_clusters_stopped(void); +static void print_initdb_options(void); +static void get_old_cluster_initdb_info(void); +static void append_source_initdb_options(PQExpBuffer options); static void create_logical_replication_slots(void); static void create_conflict_detection_slot(void); @@ -107,6 +112,15 @@ main(int argc, char **argv) get_restricted_token(); + if (user_opts.print_initdb_options) + { + check_pghost_envvar(); + check_bin_dir(&old_cluster, false); + adjust_data_dir(&old_cluster); + print_initdb_options(); + return 0; + } + /* * Resolve old and new binary dirs before adjust_data_dir(), because * adjust_data_dir() might need to call the binaries. @@ -402,7 +416,7 @@ check_clusters_stopped(void) */ check_pghost_envvar(); - /* no postmasters should be running, except for a live check */ + /* A running old server is allowed for live checks or printing. */ if (pid_lock_file_exists(old_cluster.pgdata)) { /* @@ -418,7 +432,7 @@ check_clusters_stopped(void) stop_postmaster(false); else { - if (!user_opts.check) + if (!user_opts.check && !user_opts.print_initdb_options) pg_fatal("There seems to be a postmaster servicing the old cluster.\n" "Please shutdown that postmaster and try again."); else @@ -426,8 +440,9 @@ check_clusters_stopped(void) } } - /* same goes for the new postmaster */ - if (pid_lock_file_exists(new_cluster.pgdata)) + /* Printing does not use the new cluster. */ + if (!user_opts.print_initdb_options && + pid_lock_file_exists(new_cluster.pgdata)) { if (start_postmaster(&new_cluster, false)) stop_postmaster(false); @@ -437,6 +452,102 @@ check_clusters_stopped(void) } } +/* + * Print one line of shell-quoted initdb arguments for callers that initialize + * and configure the new cluster themselves. Complete discovery and formatting + * before writing to stdout, so failures in those steps leave it empty. + */ +static void +print_initdb_options(void) +{ + PQExpBufferData options; + + check_current_dir_write_permissions(); + make_outputdirs("."); + get_old_cluster_initdb_info(); + + initPQExpBuffer(&options); + append_source_initdb_options(&options); + if (PQExpBufferBroken(&options)) + pg_fatal("out of memory"); + + if (printf("%s\n", options.data) < 0 || fflush(stdout) != 0) + pg_fatal("could not write initdb options: %m"); + termPQExpBuffer(&options); + + cleanup_output_dirs(); +} + + +/* + * Collect the source control data and template0 settings needed by initdb. + * Leave an already running source running, and stop any server started here. + * start_postmaster() registers an exit hook to stop it on discovery failure. + */ +static void +get_old_cluster_initdb_info(void) +{ + check_data_dir(&old_cluster); + check_cluster_binary_version(&old_cluster); + + if (!old_cluster.sockdir) + old_cluster.sockdir = user_opts.socketdir ? user_opts.socketdir : "."; + + check_clusters_stopped(); + + get_sock_dir(&old_cluster); + get_control_data(&old_cluster); + + prep_status("Examining old cluster settings"); + if (!user_opts.live_check) + start_postmaster(&old_cluster, true); + get_template0_info(&old_cluster); + if (!user_opts.live_check) + stop_postmaster(false); + check_ok(); +} + + +/* Append the source initialization settings as shell-quoted arguments. */ +static void +append_source_initdb_options(PQExpBuffer options) +{ + DbLocaleInfo *locale = old_cluster.template0; + + appendPQExpBuffer(options, "--wal-segsize=%u", + old_cluster.controldata.walseg / (1024 * 1024)); + + /* + * Pass --data-checksums or --no-data-checksums explicitly. Starting from + * PG18, initdb enables checksums by default, so we must mirror the old + * cluster's setting to avoid a mismatch that check_control_data() would + * reject. + */ + appendPQExpBufferStr(options, + old_cluster.controldata.data_checksum_version != 0 ? + " --data-checksums" : " --no-data-checksums"); + + appendPQExpBufferStr(options, " --encoding="); + appendShellString(options, pg_encoding_to_char(locale->db_encoding)); + appendPQExpBufferStr(options, " --locale-provider="); + appendShellString(options, collprovider_name(locale->db_collprovider)); + appendPQExpBufferStr(options, " --lc-collate="); + appendShellString(options, locale->db_collate); + appendPQExpBufferStr(options, " --lc-ctype="); + appendShellString(options, locale->db_ctype); + + if (locale->db_locale && + (locale->db_collprovider == COLLPROVIDER_ICU || + locale->db_collprovider == COLLPROVIDER_BUILTIN)) + { + appendPQExpBufferStr(options, + locale->db_collprovider == COLLPROVIDER_ICU ? + " --icu-locale=" : " --builtin-locale="); + appendShellString(options, locale->db_locale); + } +} + + /* * Set the new cluster's default char signedness using the old cluster's * value. diff --git a/src/bin/pg_upgrade/pg_upgrade.h b/src/bin/pg_upgrade/pg_upgrade.h index 427fb30238109f9c5f3b2a698b2359ce0259bb31..f9ed2d023a7a8b4b7fe8edae0c8600afd67ca204 100644 --- a/src/bin/pg_upgrade/pg_upgrade.h +++ b/src/bin/pg_upgrade/pg_upgrade.h @@ -32,7 +32,7 @@ /* * Base directories that include all the files generated internally, from the - * root path of the new cluster. The paths are dynamically built as of + * selected output root. The paths are dynamically built as of * BASE_OUTPUTDIR/$timestamp/{LOG_OUTPUTDIR,DUMP_OUTPUTDIR} to ensure their * uniqueness in each run. */ @@ -306,7 +306,7 @@ typedef struct char *basedir; /* Base output directory, with timestamp */ char *dumpdir; /* Dumps */ char *logdir; /* Log files */ - bool isatty; /* is stdout a tty */ + bool isatty; /* is progress output to a tty */ } LogOpts; @@ -316,7 +316,7 @@ typedef struct typedef struct { bool check; /* check clusters only, don't change any data */ - bool live_check; /* check clusters only, old server is running */ + bool live_check; /* inspect the already running old server */ bool do_sync; /* flush changes to disk */ transferMode transfer_mode; /* copy files or link them? */ int jobs; /* number of processes/threads to use */ @@ -326,6 +326,7 @@ typedef struct int char_signedness; /* default char signedness: -1 for initial * value, 1 for "signed" and 0 for * "unsigned" */ + bool print_initdb_options; /* print source-derived initdb options */ } UserOpts; typedef struct @@ -369,6 +370,7 @@ void check_new_cluster(void); void report_clusters_compatible(void); void issue_warnings_and_set_wal_level(void); void output_completion_banner(char *deletion_script_file_name); +void check_cluster_binary_version(ClusterInfo *cluster); void check_cluster_versions(void); void check_cluster_compatibility(void); void create_script_for_old_cluster_deletion(char **deletion_script_file_name); @@ -425,6 +427,7 @@ void check_loadable_libraries(void); FileNameMap *gen_db_file_maps(DbInfo *old_db, DbInfo *new_db, int *nmaps, const char *old_pgdata, const char *new_pgdata); +void get_template0_info(ClusterInfo *cluster); void get_db_rel_and_slot_infos(ClusterInfo *cluster); int count_old_cluster_logical_slots(void); void get_subscription_info(ClusterInfo *cluster); diff --git a/src/bin/pg_upgrade/server.c b/src/bin/pg_upgrade/server.c index a75daf09137a0671fc2cf36412be5d4dcf22cf1e..1c3a10dfaa486663716ae5c366dc975d2ba47f08 100644 --- a/src/bin/pg_upgrade/server.c +++ b/src/bin/pg_upgrade/server.c @@ -37,7 +37,7 @@ connectToServer(ClusterInfo *cluster, const char *db_name) if (conn) PQfinish(conn); - printf(_("Failure, exiting\n")); + pg_log(PG_REPORT, "Failure, exiting"); exit(1); } @@ -154,7 +154,7 @@ executeQueryOrDie(PGconn *conn, const char *fmt, ...) PQerrorMessage(conn)); PQclear(result); PQfinish(conn); - printf(_("Failure, exiting\n")); + pg_log(PG_REPORT, "Failure, exiting"); exit(1); } pg_free(query.data); diff --git a/src/bin/pg_upgrade/t/010_initdb.pl b/src/bin/pg_upgrade/t/010_initdb.pl new file mode 100644 index 0000000000000000000000000000000000000000..cd40195b94e37d22e21416608d810786e2e45d42 --- /dev/null +++ b/src/bin/pg_upgrade/t/010_initdb.pl @@ -0,0 +1,136 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Printed source settings must initialize a target that passes ordinary --check +# and upgrade, preserving source rows and configuration added by the caller. + +use strict; +use warnings FATAL => 'all'; + +use Cwd qw(getcwd); +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; +use Text::ParseWords qw(shellwords); + +my $oldnode = PostgreSQL::Test::Cluster->new('print_old_node'); +# A nondefault WAL size and disabled checksums must override initdb's defaults. +$oldnode->init( + extra => [ + '--wal-segsize=2', '--no-data-checksums', + '--encoding=UTF8', '--locale=C' + ]); +$oldnode->start; +$oldnode->safe_psql('postgres', + 'CREATE TABLE t (id int); INSERT INTO t VALUES (1), (2), (3)'); +my $newnode = PostgreSQL::Test::Cluster->new('print_new_node'); +my @print_command = ( + 'pg_upgrade', '--print-initdb-options', + '--old-datadir' => $oldnode->data_dir, + '--old-bindir' => $oldnode->config_data('--bindir'), + '--old-port' => $oldnode->port, + '--socketdir' => $oldnode->host,); +my $cwd = getcwd(); +chdir $oldnode->basedir; + +# A live source must remain running, with only reusable options on stdout. +my $start_time = + $oldnode->safe_psql('postgres', 'SELECT pg_postmaster_start_time()'); +my ($live_options, $stderr); +ok( run_log( + [ @print_command, '--verbose' ], + '>' => \$live_options, + '2>' => \$stderr), + 'print settings from a live source'); +like($live_options, qr/\A[^\r\n]+\r?\n\z/, 'stdout contains one line'); +like($stderr, qr/Running in verbose mode/, 'diagnostics go to stderr'); +ok(!-d $newnode->data_dir, 'printing does not create a target'); +is($oldnode->safe_psql('postgres', 'SELECT pg_postmaster_start_time()'), + $start_time, 'printing does not restart the source'); +my @options = shellwords($live_options); +is_deeply( + [ sort @options ], + [ + sort qw(--wal-segsize=2 --no-data-checksums --encoding=UTF8 + --locale-provider=libc --lc-collate=C --lc-ctype=C) + ], + 'output contains the source initialization settings'); + +# Inject a locale string to check shell quoting without requiring an OS locale. +SKIP: +{ + skip 'POSIX shell quoting test', 2 if $windows_os; + my $locale = q{C's locale $libdir; $(echo ignored)}; + $oldnode->safe_psql('postgres', + q{UPDATE pg_database SET datcollate = $locale$} + . $locale + . q{$locale$ WHERE datname = 'template0'}); + my $arguments; + ok( run_log( + [ + 'sh', + '-c', + q{options=$("$@") || exit; eval "set -- $options"; printf '%s\0' "$@"}, + 'sh', + @print_command, + ], + '>' => \$arguments), + 'reuse printed options in a shell'); + is_deeply( + [ split /\0/, $arguments ], + [ map { /^--lc-collate=/ ? "--lc-collate=$locale" : $_ } @options ], + 'shell reuse preserves argument boundaries and literal locale text'); + $oldnode->safe_psql('postgres', + "UPDATE pg_database SET datcollate = 'C' WHERE datname = 'template0'" + ); +} + +# A stopped source must produce the same settings and be stopped again. +$oldnode->stop; +my $stopped_options; +ok(run_log(\@print_command, '>' => \$stopped_options, '2>' => \$stderr), + 'print settings from a stopped source'); +is($stopped_options, $live_options, 'live and stopped settings agree'); +ok(!-f $oldnode->data_dir . '/postmaster.pid', 'temporary source is stopped'); +ok(!-d 'pg_upgrade_output.d', 'successful printing removes its logs'); + +# Failed discovery must leave stdout empty and stop its temporary source too. +command_checks_all( + [ @print_command, '--username' => 'missing_print_options_role' ], + 1, + [qr/\A\z/], + [qr/role .*missing_print_options_role.* does not exist/], + 'failed discovery does not print options'); +ok( !-f $oldnode->data_dir . '/postmaster.pid', + 'failed discovery stops its temporary source'); +command_checks_all( + [ 'pg_upgrade', '--print-initdb-options', '--check' ], + 1, + [qr/\A\z/], + [qr/options --print-initdb-options and --check cannot be used together/], + 'printing rejects --check'); + +# The caller can initialize and configure the target before a normal upgrade. +$newnode->init(extra => \@options); +$newnode->append_conf('postgresql.conf', + 'custom.before_upgrade = configured'); +my @upgrade_command = ( + 'pg_upgrade', '--no-sync', + '--old-datadir' => $oldnode->data_dir, + '--new-datadir' => $newnode->data_dir, + '--old-bindir' => $oldnode->config_data('--bindir'), + '--old-port' => $oldnode->port, + '--new-port' => $newnode->port, + '--socketdir' => $newnode->host,); +command_ok([ @upgrade_command, '--check' ], 'check the initialized target'); +command_ok(\@upgrade_command, 'upgrade the initialized target'); +$newnode->start; +is( $newnode->safe_psql( + 'postgres', 'SELECT array_agg(id ORDER BY id) FROM t'), + '{1,2,3}', + 'upgrade preserves source rows'); +is($newnode->safe_psql('postgres', 'SHOW custom.before_upgrade'), + 'configured', 'upgrade preserves caller configuration'); +$newnode->stop; +chdir $cwd; + +done_testing(); diff --git a/src/bin/pg_upgrade/util.c b/src/bin/pg_upgrade/util.c index abdb35764dee310bd21527cacb4f6c56bf0176f4..1a405e34e607e36ce92f2233fa6d935315332568 100644 --- a/src/bin/pg_upgrade/util.c +++ b/src/bin/pg_upgrade/util.c @@ -50,7 +50,7 @@ end_progress_output(void) */ if (log_opts.isatty) { - printf("\r"); + fputc('\r', user_opts.print_initdb_options ? stderr : stdout); pg_log(PG_REPORT_NONL, "%-*s", MESSAGE_WIDTH, ""); } else if (log_opts.verbose) @@ -58,12 +58,14 @@ end_progress_output(void) } /* - * Remove any logs generated internally. To be used once when exiting. + * Close the internal log and remove output directories unless --retain is set. + * Clear the log pointer so cleanup warnings cannot write to the closed stream. */ void cleanup_output_dirs(void) { fclose(log_opts.internal); + log_opts.internal = NULL; /* Remove dump and log files? */ if (log_opts.retain) @@ -173,10 +175,15 @@ prep_status_progress(const char *fmt, ...) pg_log(PG_REPORT_NONL, "%-*s", MESSAGE_WIDTH, message); } +/* + * Reserve stdout for the argument list consumed by wrappers in + * --print-initdb-options mode, and send diagnostics to stderr. + */ static void pg_log_v(eLogType type, const char *fmt, va_list ap) { int save_errno = errno; + FILE *output = user_opts.print_initdb_options ? stderr : stdout; StringInfoData buf; char *message; @@ -220,7 +227,7 @@ pg_log_v(eLogType type, const char *fmt, va_list ap) { case PG_VERBOSE: if (log_opts.verbose) - printf("%s\n", message); + fprintf(output, "%s\n", message); break; case PG_STATUS: @@ -240,37 +247,37 @@ pg_log_v(eLogType type, const char *fmt, va_list ap) bool itfits = (strlen(message) <= MESSAGE_WIDTH - 2); /* prefix with "..." if we do leading truncation */ - printf(" %s%-*.*s\r", - itfits ? "" : "...", - MESSAGE_WIDTH - 2, MESSAGE_WIDTH - 2, - itfits ? message : - message + strlen(message) - MESSAGE_WIDTH + 3 + 2); + fprintf(output, " %s%-*.*s\r", + itfits ? "" : "...", + MESSAGE_WIDTH - 2, MESSAGE_WIDTH - 2, + itfits ? message : + message + strlen(message) - MESSAGE_WIDTH + 3 + 2); } else if (log_opts.verbose) - printf(" %s\n", message); + fprintf(output, " %s\n", message); break; case PG_REPORT_NONL: /* This option is for use by prep_status and friends */ - printf("%s", message); + fprintf(output, "%s", message); break; case PG_REPORT: case PG_WARNING: - printf("%s\n", message); + fprintf(output, "%s\n", message); break; case PG_FATAL: /* Extra newline in case we're interrupting status output */ - printf("\n%s\n", message); - printf(_("Failure, exiting\n")); + fprintf(output, "\n%s\n", message); + fprintf(output, _("Failure, exiting\n")); exit(1); break; /* No default:, we want a warning for omitted cases */ } pg_free(message); - fflush(stdout); + fflush(output); }