From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Bohyun Lee <bohyun.lee@databricks.com>
Date: Thu, 26 Nov 2026 17:18:10 +0000
Subject: [PATCH v1] pg_upgradecluster: use pg_upgrade initialization options

Use a supporting target pg_upgrade shell-only printer to preserve the
source WAL segment size and checksum setting. Keep Debian maintenance-
database selection, locale overrides, configuration copying, hooks,
and legacy discovery for older targets and dump migrations.

Preserve complete ICU rules and PG17+ locale-provider metadata. Keep
upstream client-encoding behavior, use bounded diagnostic-directory
names, and stop temporarily started sources on metadata failure.

Reuse existing upgrade tests and add a focused multiline-argument
regression checked before pg_upgrade can restore the metadata.
---
 PgCommon.pm               |  39 ++++++++++++------
 pg_createcluster          |   3 +-
 pg_upgradecluster         | 100 +++++++++++++++++++++++++++++++++++++++++-----
 t/040_upgrade.t           |  20 ++++++++--
 t/042_upgrade_rename.t    |  11 +++--
 t/051_icu_rules.t         |  50 +++++++++++++++++++++++
 t/052_upgrade_encodings.t |  23 ++++++++++-
 7 files changed, 213 insertions(+), 33 deletions(-)
 create mode 100644 t/051_icu_rules.t

diff --git a/PgCommon.pm b/PgCommon.pm
index 1b0ece757c1083684477e9e6f0fb1d0ee84ebca6..dac66a3e4b5eb194d8f4146aac66d5643b715af2 100644
--- a/PgCommon.pm
+++ b/PgCommon.pm
@@ -1350,9 +1350,10 @@ sub get_db_encoding {
  owner. (For versions >= 8.4; for older versions use get_cluster_locales()).
 
  Arguments: <version> <cluster> <database>
- Returns: (LC_CTYPE, LC_COLLATE, locprovider, iculocale, icurules) or undef if it cannot be determined.
+ Returns: (LC_CTYPE, LC_COLLATE, locprovider, locale, icurules) or undef if it cannot be determined.
  PG15 adds locale provider and icu locale to the returned values
  PG16 adds icu rules
+ PG17 stores ICU and builtin locale names in datlocale
 
 =cut
 
@@ -1362,7 +1363,6 @@ sub get_db_locales {
     my $socketdir = get_cluster_socketdir $version, $cluster;
     my $psql = get_program_path 'psql', $version;
     return undef unless ($port && $socketdir && $psql);
-    my ($ctype, $collate, $locale_provider, $icu_locale, $icu_rules);
 
     # try to switch to cluster owner
     prepare_exec 'LC_ALL';
@@ -1371,23 +1371,36 @@ sub get_db_locales {
     $> = (stat (cluster_data_directory $version, $cluster))[4];
 
     my $datlocprovider = $version >= 15 ? "CASE datlocprovider::text WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' WHEN 'b' THEN 'builtin' END" : "NULL";
-    my $daticulocale = ($version >= 15 and $version < 17) ? "daticulocale" : "NULL";
+    my $datlocale = $version >= 17 ? "datlocale" : $version >= 15 ? "daticulocale" : "NULL";
     my $daticurules = $version >= 16 ? "daticurules" : "NULL";
 
-    open PSQL, '-|', $psql, '-h', $socketdir, '-p', $port, '-AXtc',
-        "SELECT datctype, datcollate, $datlocprovider, $daticulocale, $daticurules FROM pg_database where datname = current_database()", $db or
+    # NUL separators preserve pipes and newlines in ICU rules. Keep the old
+    # output format for versions predating the supported pg_upgrade sources.
+    my @format = $version >= 10 ? ('-z', '-0') : ();
+    open PSQL, '-|', $psql, '-h', $socketdir, '-p', $port, @format, '-AXtc',
+        "SELECT datctype, datcollate, $datlocprovider, $datlocale, $daticurules FROM pg_database where datname = current_database()", $db or
         die "Internal error: could not call $psql to determine datctype and datcollate: $!";
-    my $out = <PSQL> // error 'could not determine datctype and datcollate';
+    my $out;
+    {
+        local $/ = $version >= 10 ? undef : $/;
+        $out = <PSQL>;
+    }
     close PSQL;
-    ($out) = $out =~ /^(.*)$/; # untaint
-    ($ctype, $collate, $locale_provider, $icu_locale, $icu_rules) = split /\|/, $out;
-
+    my $status = $?;
     $> = $orig_euid;
     restore_exec;
-    chomp $ctype;
-    chomp $collate;
-    return ($ctype, $collate, $locale_provider, $icu_locale, $icu_rules) unless $?;
-    return (undef, undef, undef, undef, undef);
+    return (undef, undef, undef, undef, undef) if $status || !defined $out;
+    ($out) = $out =~ /\A(.*)\z/s; # untaint without truncating multiline rules
+    my @values;
+    if ($version >= 10) {
+        @values = split /\0/, $out, -1;
+        return (undef, undef, undef, undef, undef) unless @values == 6 && pop(@values) eq '';
+    } else {
+        chomp $out;
+        @values = split /\|/, $out, -1;
+    }
+    return (undef, undef, undef, undef, undef) unless @values == 5;
+    return @values;
 }
 
 
diff --git a/pg_createcluster b/pg_createcluster
index 222e7544bd5228fed178ccacc79d99b960a3c79d..677e57bd028de6c8c1d20941515e1d6d9a14341a 100755
--- a/pg_createcluster
+++ b/pg_createcluster
@@ -296,7 +296,8 @@ foreach my $argv (@ARGV) {
     if ($argv =~ /^(-\w*A|--auth\b)/) { # -A --auth --auth-host --auth-local
 	$explicit_auth_config = 1;
     }
-    push @initdb_opts_from_cli, $argv =~ /(.*)/; # untaint
+    # Preserve embedded newlines, for example in --icu-rules.
+    push @initdb_opts_from_cli, $argv =~ /(.*)/s; # untaint
 }
 
 # pg_hba.conf authentication settings
diff --git a/pg_upgradecluster b/pg_upgradecluster
index fbeb27ce1b41af4fabedb23bc986bfbf915e8b9d..c2a35b9adf4219f54bc641d915d0fa9cbb78ddda 100755
--- a/pg_upgradecluster
+++ b/pg_upgradecluster
@@ -19,9 +19,10 @@
 use strict;
 use warnings;
 use PgCommon;
-use File::Temp qw(tempfile);
+use File::Temp qw(tempfile tempdir);
 use Getopt::Long;
 use POSIX qw(lchown);
+use Text::ParseWords qw(shellwords);
 
 # untaint environment
 $ENV{'PATH'} = '/bin:/usr/bin';
@@ -31,7 +32,7 @@ delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
 my ($version, $newversion, $cluster, $newcluster);
 my (%info, %newinfo);
 my ($encoding, $old_lc_ctype, $old_lc_collate); # old cluster encoding
-my ($old_locale_provider, $old_icu_locale, $old_icu_rules);
+my ($old_locale_provider, $old_db_locale, $old_icu_rules);
 my $maintenance_db = 'template1';
 my $keep_on_error = 0;
 
@@ -357,13 +358,75 @@ sub get_encoding {
     if ($version <= '8.3') {
 	($old_lc_ctype, $old_lc_collate) = get_cluster_locales $version, $cluster;
     } else {
-	($old_lc_ctype, $old_lc_collate, $old_locale_provider, $old_icu_locale, $old_icu_rules) = get_db_locales $version, $cluster, $maintenance_db;
+	($old_lc_ctype, $old_lc_collate, $old_locale_provider, $old_db_locale, $old_icu_rules) = get_db_locales $version, $cluster, $maintenance_db;
     }
     unless ($encoding && $old_lc_ctype && $old_lc_collate) {
 	error 'could not get cluster locales';
     }
 }
 
+# Let a supporting target pg_upgrade determine the control-data settings that
+# must match. Debian still selects encoding and locales from maintenance_db.
+# Run the printer as the source owner and give it a writable log directory.
+sub get_initdb_options {
+    my ($pg_upgrade, $old_bindir, $socketdir) = @_;
+    return unless $pg_upgrade;
+    my $workdir;
+
+    my $read_output = sub {
+        my @command = @_;
+        my ($errors) = tempfile('pg_upgradecluster.XXXXXX', TMPDIR => 1, UNLINK => 1);
+        my $pid = open(my $output, '-|');
+        defined $pid or error "Could not fork pg_upgrade: $!";
+        if (!$pid) {
+            open STDERR, '>&', $errors or error "Could not redirect pg_upgrade diagnostics: $!";
+            change_ugid $info{'owneruid'}, $info{'ownergid'};
+            chdir $workdir or error "Could not enter $workdir: $!" if defined $workdir;
+            exec @command or error "Could not execute $pg_upgrade: $!";
+        }
+        local $/;
+        my $result = <$output> // '';
+        unless (close $output) {
+            seek $errors, 0, 0;
+            my $diagnostics = <$errors> // '';
+            my $logs = defined $workdir ? "\nInitialization logs are in $workdir\n" : '';
+            error "Could not read initialization options from $pg_upgrade:\n$diagnostics$logs";
+        }
+        return $result;
+    };
+
+    my $help = $read_output->($pg_upgrade, '--help');
+    return unless $help =~ /--print-initdb-options/;
+
+    $workdir = tempdir("/var/log/postgresql/pg_upgradecluster-initdb-$version-$newversion.XXXX");
+    if ($> == 0) {
+        chown $info{'owneruid'}, $info{'ownergid'}, $workdir
+            or error "Could not set ownership of $workdir: $!";
+    }
+    my @command = ($pg_upgrade, '--print-initdb-options',
+        '-b', ($old_bindir || "$PgCommon::binroot$version/bin"),
+        '-d', ($version <= 9.1 ? $info{'pgdata'} : $info{'configdir'}),
+        '-p', $info{'port'}, '--socketdir', $socketdir);
+    push @command, '-o', "-D $info{configdir}" if $version <= 9.1;
+    my $output = $read_output->(@command);
+    error "Invalid initialization options from $pg_upgrade"
+        unless $output =~ /\A[^\0\r\n]+\r?\n\z/;
+    my @arguments = shellwords($output);
+    error "Invalid initialization options from $pg_upgrade"
+        unless @arguments && !grep { !/^--[a-z][a-z-]*(?:=|\z)/ } @arguments;
+
+    # Ignore printed locale defaults: maintenance_db and explicit overrides
+    # retain their existing meaning. Captures also untaint the two arguments.
+    my @wal = map { /^--wal-segsize=(\d+)\z/ ? $1 : () } @arguments;
+    error "Expected one WAL segment size from $pg_upgrade"
+        unless @wal == 1 && $wal[0] >= 1 && $wal[0] <= 1024
+            && ($wal[0] & ($wal[0] - 1)) == 0;
+    my @checksums = map { /\A(--(?:no-)?data-checksums)\z/ ? $1 : () } @arguments;
+    error "Expected one checksum setting from $pg_upgrade" unless @checksums == 1;
+    rmdir $workdir;
+    return ["--wal-segsize=$wal[0]", $checksums[0]];
+}
+
 # RedHat's run-parts doesn't support any options, supply a minimalistic implementation here
 # BUG: we don't care about validating the filenames yet
 # Arguments: <directory> <argv to pass to scripts>
@@ -518,9 +581,15 @@ if ($check_only) {
 
 print "Upgrading cluster $version/$cluster to $newversion/$newcluster ...\n";
 
-my $oldcontrol = get_cluster_controldata ($version, $cluster);
-
+# Keep dump-method policy and fall back for targets without the printer.
 my $oldsocket = get_cluster_socketdir $version, $cluster;
+my $source_initdb_options;
+if ($method eq 'upgrade') {
+    $source_initdb_options = get_initdb_options(
+        get_program_path('pg_upgrade', $newversion), $old_bindir, $oldsocket);
+}
+my $oldcontrol = get_cluster_controldata ($version, $cluster) unless $source_initdb_options;
+
 my $owner = getpwuid $info{'owneruid'};
 error 'could not get name of cluster owner' unless $owner;
 my $temp_hba_conf = temp_hba_conf $version, $cluster, $owner, $info{'owneruid'};
@@ -540,7 +609,12 @@ if ($method eq 'dump' or ($method eq 'upgrade' and not $info{'running'})) {
         $version, $cluster, 'start', '-o', "-c hba_file=$temp_hba_conf");
     error "Could not restart old cluster" if system @argv;
 
-    get_encoding $version, $cluster unless ($encoding); # if the cluster was not running before, get encoding now
+    # A metadata error must also stop a source started only for discovery.
+    eval { get_encoding $version, $cluster unless $encoding; 1 } or do {
+        my $error = $@;
+        system 'pg_ctlcluster', $version, $cluster, 'stop' unless $info{'running'};
+        die $error;
+    };
 
     if ($method eq 'upgrade') {
 	print "Stopping old cluster...\n";
@@ -572,9 +646,12 @@ push @argv, ('--lc-numeric', $lc_numeric) if $lc_numeric;
 push @argv, ('--lc-time', $lc_time) if $lc_time;
 push @argv, ('--');
 push @argv, ('--locale-provider', $old_locale_provider) if $old_locale_provider;
-push @argv, ('--icu-locale', $old_icu_locale) if $old_icu_locale;
+push @argv, ($old_locale_provider eq 'builtin' ? '--builtin-locale' : '--icu-locale', $old_db_locale)
+    if $old_db_locale;
 push @argv, ('--icu-rules', $old_icu_rules) if $old_icu_rules;
-if ($oldcontrol->{'Data page checksum version'} or (defined $data_checksums and $data_checksums == 1)) { # oldcontrol 0 = off
+if ($source_initdb_options) {
+    push @argv, @$source_initdb_options;
+} elsif ($oldcontrol->{'Data page checksum version'} or (defined $data_checksums and $data_checksums == 1)) { # oldcontrol 0 = off
     # enable data checksums if the old cluster had them
     push @argv, ('--data-checksums');
 } else {
@@ -645,8 +722,6 @@ if (!fork) {
     } else {
 	# pg_upgrade
 
-	use File::Temp qw(tempdir);
-
 	my $pg_upgrade = get_program_path 'pg_upgrade', $newversion;
         $pg_upgrade or error "pg_upgrade $newversion not found";
 	my @argv = ($pg_upgrade,
@@ -800,6 +875,11 @@ B<requiring index rebuilds after the upgrade>, or acknowledging that the
 ordering did not change using the B<ALTER COLLATION REFRESH VERSION> command.
 This step is not automated by B<pg_upgradecluster>.
 
+For pg_upgrade migrations, B<--print-initdb-options>, when supported by the
+target binary, supplies the matching WAL segment size and checksum setting.
+Encoding and locales still come from B<--maintenance-db> and explicit overrides.
+On failure, printer diagnostics remain under F</var/log/postgresql>.
+
 The cluster of the old version will be configured to use a previously unused
 port since the upgraded one will use the original port. The old cluster is not
 automatically removed. After upgrading, please verify that the new cluster
diff --git a/t/040_upgrade.t b/t/040_upgrade.t
index 692454df5470abb4ecaa92b741c738d0c4668ddb..97231cd59ee2ab890b72f37940d38d2f6b926fb1 100644
--- a/t/040_upgrade.t
+++ b/t/040_upgrade.t
@@ -15,7 +15,7 @@ use lib 't';
 use TestLib;
 use PgCommon;
 
-use Test::More tests => (@MAJORS == 1) ? 1 : 119 * 3;
+use Test::More tests => (@MAJORS == 1) ? 1 : 123 * 3;
 
 if (@MAJORS == 1) {
     pass 'only one major version installed, skipping upgrade tests';
@@ -24,13 +24,22 @@ if (@MAJORS == 1) {
 
 my $old_version = $MAJORS[0];
 my $new_version = $MAJORS[-1];
+my $pg_upgrade = get_program_path 'pg_upgrade', $new_version;
+my $has_printer = $pg_upgrade && `$pg_upgrade --help` =~ /--print-initdb-options/;
 
 foreach my $upgrade_options ('-m dump', '-m upgrade', '-m upgrade --link') {
 next if ($ENV{UPGRADE_METHOD} and $upgrade_options !~ /$ENV{UPGRADE_METHOD}$/); # hack to ease debugging individual methods
 note ("upgrade method \"$upgrade_options\", $MAJORS[0] -> $MAJORS[-1]");
 
+# Use nondefault WAL segments when the target can discover them, and exercise
+# enabled checksums in the link case as well as the usual disabled checksums.
+my $wal_size = $has_printer && $old_version >= 11 && $upgrade_options !~ /dump/ ? 2 : 16;
+my $old_has_checksums = $old_version >= 18 || ($old_version >= 9.3 && $upgrade_options =~ /--link/) ? 'on' : 'off';
+my @initdb_options = $wal_size == 2 ? ('--wal-segsize=2') : ();
+push @initdb_options, '--data-checksums' if $old_version >= 9.3 && $upgrade_options =~ /--link/;
+
 # create cluster
-ok ((system "pg_createcluster $MAJORS[0] upgr >/dev/null") == 0,
+ok ((system "pg_createcluster $MAJORS[0] upgr " . (@initdb_options ? "-- @initdb_options " : '') . ">/dev/null") == 0,
     "pg_createcluster $MAJORS[0] upgr");
 exec_as 'root', "sed -i '/^local.*postgres/ s/\$/\\nlocal all foo trust/' /etc/postgresql/$MAJORS[0]/upgr/pg_hba.conf";
 is ((system "pg_ctlcluster $MAJORS[0] upgr start"), 0, 'Starting upgr cluster');
@@ -129,10 +138,11 @@ like_program_out 'nobody', 'pg_lsclusters -h', 0,
     qr/^$MAJORS[0]\s+upgr\s+5432 online postgres/;
 SKIP: {
     skip "no data checksums before 9.3", 2 if ($old_version < 9.3);
-    my $old_has_checksums = $old_version >= 18 ? "on" : "off";
     is_program_out 'nobody', 'psql -Atc "show data_checksums" test', 0, "$old_has_checksums\n",
         "old cluster checksums are $old_has_checksums";
 }
+is_program_out 'nobody', 'psql -Atc "SHOW wal_segment_size" test', 0, "${wal_size}MB\n",
+    'source has the selected WAL segment size';
 
 # Check SELECT in original cluster
 my $select_old;
@@ -237,10 +247,12 @@ is_program_out 'postgres', "psql -Atc \"SELECT spcname FROM pg_class c LEFT JOIN
 # check cluster properties
 SKIP: {
     skip "no data checksums before 9.3", 2 if ($new_version < 9.3);
-    my $new_has_checksums = ($old_version >= 18 or ($old_version < 18 and $new_version >= 18 and $upgrade_options =~ /dump/)) ? "on" : "off";
+    my $new_has_checksums = ($old_has_checksums eq 'on' or ($new_version >= 18 and $upgrade_options =~ /dump/)) ? "on" : "off";
     is_program_out 'nobody', 'psql -Atc "show data_checksums" test', 0, "$new_has_checksums\n",
         "new cluster checksums are $new_has_checksums";
 }
+is_program_out 'nobody', 'psql -Atc "SHOW wal_segment_size" test', 0, "${wal_size}MB\n",
+    'upgrade preserves the WAL segment size';
 
 # stop servers, clean up
 is ((system "pg_dropcluster $MAJORS[0] upgr --stop"), 0, 'Dropping original cluster');
diff --git a/t/042_upgrade_rename.t b/t/042_upgrade_rename.t
index ef44f11dc0c66bf22188930ce2be742517485286..422086b7124e4311f6f42b0e898425157585a8de 100644
--- a/t/042_upgrade_rename.t
+++ b/t/042_upgrade_rename.t
@@ -8,16 +8,19 @@ use PgCommon;
 
 use Test::More tests => 15 * @MAJORS;
 
+# A valid long source name must not overflow temporary log directory names.
+my $cluster = 'a' x 225;
+
 foreach my $v (@MAJORS) {
   SKIP: {
     skip "pg_upgrade not supported on $v", 15 if ($v < 9.2);
     note "PostgreSQL $v";
 
-    program_ok 0, "pg_createcluster $v main --start", 0;
-    program_ok 0, "pg_upgradecluster -m upgrade --old-bindir=$PgCommon::binroot$v/bin -v $v --rename upgr $v main", 0;
-    like_program_out 0, "pg_lsclusters -h", 0, qr/$v main 5433 down.*\n$v upgr 5432 online/;
+    program_ok 0, "pg_createcluster $v $cluster --start", 0;
+    program_ok 0, "pg_upgradecluster -m upgrade --old-bindir=$PgCommon::binroot$v/bin -v $v --rename upgr $v $cluster", 0;
+    like_program_out 0, "pg_lsclusters -h", 0, qr/$v $cluster\s+5433 down.*\n$v upgr\s+5432 online/;
 
-    program_ok 0, "pg_dropcluster $v main --stop", 0;
+    program_ok 0, "pg_dropcluster $v $cluster --stop", 0;
     program_ok 0, "pg_dropcluster $v upgr --stop", 0;
     is ((system "rm -rf /var/log/postgresql/pg_upgradecluster-$v-$v-upgr.*"), 0, 'Cleaning pg_upgrade log files');
     check_clean;
diff --git a/t/051_icu_rules.t b/t/051_icu_rules.t
new file mode 100644
index 0000000000000000000000000000000000000000..1f506f576af8a53fdc2261d1ad49ead1fb5a4583
--- /dev/null
+++ b/t/051_icu_rules.t
@@ -0,0 +1,50 @@
+# Check that pg_createcluster forwards complete ICU rules to initdb.
+
+use strict;
+use warnings;
+
+use lib 't';
+use TestLib;
+use PgCommon;
+use IPC::Run qw(run);
+use Test::More;
+
+my @versions = grep { $_ >= 16 } @MAJORS;
+plan skip_all => 'initdb --icu-rules requires PostgreSQL 16 or later'
+    unless @versions;
+
+my $rules = "&a < '\$' < c < b\r\n&c < \xc3\xa9\n";
+my $hex = unpack 'H*', $rules;
+
+foreach my $v (@versions) {
+    foreach my $options (["--icu-rules=$rules"], ['--icu-rules', $rules]) {
+        my $form = @$options == 1 ? 'equals' : 'separate';
+        my $cluster = 'icurules';
+        BAIL_OUT "test cluster $v/$cluster already exists"
+            if cluster_exists $v, $cluster;
+        my ($stdout, $stderr);
+        my $created = run ['pg_createcluster', '--start', '--no-status',
+            '--locale=C', '--encoding=UTF8', $v, $cluster, '--',
+            '--locale-provider=icu', '--icu-locale=en-US', @$options],
+            \undef, \$stdout, \$stderr;
+        ok $created, "$v $form: create cluster";
+        diag $stdout . $stderr unless $created;
+
+        SKIP: {
+            skip 'cluster creation failed', 2 unless $created;
+            # Compare exact bytes in both templates before any upgrade:
+            # pg_upgrade's SQL restore could otherwise mask truncation.
+            is_program_out 'postgres', "psql --cluster $v/$cluster -XAt -c \"" .
+                "SELECT datname, convert_to(daticurules, 'UTF8') = decode('$hex', 'hex') " .
+                "FROM pg_database WHERE datname IN ('template0', 'template1') ORDER BY datname\"",
+                0, "template0|t\ntemplate1|t\n", "$v $form: preserve complete rules in both templates";
+        }
+
+        program_ok 0, "pg_dropcluster --stop $v $cluster", 0
+            if cluster_exists $v, $cluster;
+    }
+}
+
+done_testing();
+
+# vim: filetype=perl
diff --git a/t/052_upgrade_encodings.t b/t/052_upgrade_encodings.t
index e7a712500dd538cec72bb12b40237cc600860526..49814a8609b651acb4bb8b8c65a4631085804fc9 100644
--- a/t/052_upgrade_encodings.t
+++ b/t/052_upgrade_encodings.t
@@ -5,7 +5,7 @@ use strict;
 use lib 't';
 use TestLib;
 use PgCommon;
-use Test::More tests => (@MAJORS == 1) ? 1 : 46;
+use Test::More tests => (@MAJORS == 1) ? 1 : 51;
 
 if (@MAJORS == 1) {
         pass 'only one major version installed, skipping upgrade tests';
@@ -34,6 +34,27 @@ if ($oldv >= 15) {
     program_ok 'postgres', 'psql -c "create database icutest"', 0, "creating placeholder icutest database";
 }
 
+# Check the metadata reader before an upgrade can restore rules through SQL.
+# Pipes, newlines and non-ASCII text must survive in the client encoding
+# requested by the caller.
+SKIP: {
+    skip 'ICU rules require PostgreSQL 16 or later', 3 if $oldv < 16;
+    my $rules = "&a < '\$' < '|' < c < b\r\n&c < \xd0\xb0\n";
+    my $hex = unpack 'H*', $rules;
+    program_ok 'postgres', "psql -c \"UPDATE pg_database SET daticurules = convert_from(decode('$hex', 'hex'), 'UTF8') WHERE datname = 'icutest'\"", 0,
+        'set multiline ICU rules in database encoding';
+    local $ENV{'PGCLIENTENCODING'} = 'UTF8';
+    is_deeply [get_db_locales($oldv, 'main', 'icutest')], ['ru_RU', 'ru_RU', 'icu', 'de', $rules],
+        'locale reader preserves provider, locale and complete rules in the client encoding';
+    is $ENV{'PGCLIENTENCODING'}, 'UTF8', 'locale reader preserves client encoding';
+}
+SKIP: {
+    skip 'builtin locales require PostgreSQL 17 or later', 2 if $oldv < 17;
+    program_ok 'postgres', q{psql -c "CREATE DATABASE builtintest TEMPLATE template0 ENCODING 'UTF8' LOCALE_PROVIDER builtin BUILTIN_LOCALE 'C.UTF-8' LC_COLLATE 'C' LC_CTYPE 'C'"}, 0;
+    is_deeply [get_db_locales($oldv, 'main', 'builtintest')], ['C', 'C', 'builtin', 'C.UTF-8', ''],
+        'locale reader returns the builtin provider locale';
+}
+
 is ((exec_as 'postgres', "printf 'A\\324B' | psql -c \"create table t(x varchar); copy t from stdin\" latintest", $outref), 
     0, 'write LATIN database content to latintest');
 is ((exec_as 'postgres', "printf 'A\\324B' | psql -c \"create table t(x varchar); copy t from stdin\" asctest", $outref), 
