Debian Codegraph @

src/bin/pg_upgrade/t/002_pg_upgrade.pl

raw
1 # Copyright (c) 2022-2025, PostgreSQL Global Development Group
2
3 # Set of tests for pg_upgrade, including cross-version checks.
4 use strict;
5 use warnings FATAL => 'all';
6
7 use Cwd qw(abs_path);
8 use File::Basename qw(dirname);
9 use File::Find qw(find);
10 use File::Path qw(rmtree);
11
12 use PostgreSQL::Test::Cluster;
13 use PostgreSQL::Test::Utils;
14 use PostgreSQL::Test::AdjustDump;
15 use PostgreSQL::Test::AdjustUpgrade;
16 use Test::More;
17
18 # Can be changed to test the other modes.
19 my $mode = $ENV{PG_TEST_PG_UPGRADE_MODE} || '--copy';
20
21 my $tempdir = PostgreSQL::Test::Utils::tempdir;
22
23 # Generate a database with a name made of a range of ASCII characters.
24 sub generate_db
25 {
26 my ($node, $prefix, $from_char, $to_char, $suffix) = @_;
27
28 my $dbname = $prefix;
29 for my $i ($from_char .. $to_char)
30 {
31 next if $i == 7 || $i == 10 || $i == 13; # skip BEL, LF, and CR
32 $dbname = $dbname . sprintf('%c', $i);
33 }
34
35 $dbname .= $suffix;
36 $node->command_ok(
37 [ 'createdb', $dbname ],
38 "created database with ASCII characters from $from_char to $to_char");
39 }
40
41 # Filter the contents of a dump before its use in a content comparison for
42 # upgrade testing. This returns the path to the filtered dump.
43 sub filter_dump
44 {
45 my ($is_old, $old_version, $dump_file) = @_;
46 my $dump_contents = slurp_file($dump_file);
47
48 if ($is_old)
49 {
50 $dump_contents = adjust_old_dumpfile($old_version, $dump_contents);
51 }
52 else
53 {
54 $dump_contents = adjust_new_dumpfile($old_version, $dump_contents);
55 }
56
57 my $dump_file_filtered = "${dump_file}_filtered";
58 open(my $dh, '>', $dump_file_filtered)
59 || die "opening $dump_file_filtered";
60 print $dh $dump_contents;
61 close($dh);
62
63 return $dump_file_filtered;
64 }
65
66 # Dump database db from the given node in plain format and adjust it for
67 # comparing dumps from the original and the restored database.
68 #
69 # file_prefix is used to create unique names for all dump files so that they
70 # remain available for debugging in case the test fails.
71 #
72 # adjust_child_columns is passed to adjust_regress_dumpfile() which actually
73 # adjusts the dump output.
74 #
75 # The name of the file containing adjusted dump is returned.
76 sub get_dump_for_comparison
77 {
78 my ($node, $db, $file_prefix, $adjust_child_columns) = @_;
79
80 my $dumpfile = $tempdir . '/' . $file_prefix . '.sql';
81 my $dump_adjusted = "${dumpfile}_adjusted";
82
83 open(my $dh, '>', $dump_adjusted)
84 || die "could not open $dump_adjusted for writing $!";
85
86 $node->run_log(
87 [
88 'pg_dump', '--no-sync',
89 '--restrict-key=test',
90 '-d' => $node->connstr($db),
91 '-f' => $dumpfile
92 ]);
93
94 print $dh adjust_regress_dumpfile(slurp_file($dumpfile),
95 $adjust_child_columns);
96 close($dh);
97
98 return $dump_adjusted;
99 }
100
101 # The test of pg_upgrade requires two clusters, an old one and a new one
102 # that gets upgraded. Before running the upgrade, a logical dump of the
103 # old cluster is taken, and a second logical dump of the new one is taken
104 # after the upgrade. The upgrade test passes if there are no differences
105 # (after filtering) in these two dumps.
106
107 # Testing upgrades with an older version of PostgreSQL requires setting up
108 # two environment variables, as of:
109 # - "olddump", to point to a dump file that will be used to set up the old
110 # instance to upgrade from.
111 # - "oldinstall", to point to the installation path of the old cluster.
112 if ( (defined($ENV{olddump}) && !defined($ENV{oldinstall}))
113 || (!defined($ENV{olddump}) && defined($ENV{oldinstall})))
114 {
115 # Not all variables are defined, so leave and die if test is
116 # done with an older installation.
117 die "olddump or oldinstall is undefined";
118 }
119
120 # Paths to the dumps taken during the tests.
121 my $dump1_file = "$tempdir/dump1.sql";
122 my $dump2_file = "$tempdir/dump2.sql";
123
124 note "testing using transfer mode $mode";
125
126 # Initialize node to upgrade
127 my $oldnode =
128 PostgreSQL::Test::Cluster->new('old_node',
129 install_path => $ENV{oldinstall});
130
131 my %old_node_params = ();
132
133 # To increase coverage of non-standard segment size and group access without
134 # increasing test runtime, run these tests with a custom setting.
135 # --allow-group-access and --wal-segsize have been added in v11.
136 my @custom_opts = ();
137 if ($oldnode->pg_version >= 11)
138 {
139 push @custom_opts, ('--wal-segsize', '1');
140 push @custom_opts, '--allow-group-access';
141 }
142
143 my $old_provider_field;
144 my $old_datlocale_field;
145
146 # account for field additions and changes
147 if ($oldnode->pg_version >= 15)
148 {
149 $old_provider_field = "datlocprovider";
150 if ($oldnode->pg_version >= '17devel')
151 {
152 $old_datlocale_field = "datlocale";
153 }
154 else
155 {
156 $old_datlocale_field = "daticulocale AS datlocale";
157 }
158 }
159 else
160 {
161 $old_provider_field = "'c' AS datlocprovider";
162 $old_datlocale_field = "NULL AS datlocale";
163 }
164
165 # Set up the locale settings for the original cluster, so that we
166 # can test that pg_upgrade copies the locale settings of template0
167 # from the old to the new cluster.
168
169 my $original_enc_name;
170 my $original_provider;
171 my $original_datcollate = "C";
172 my $original_datctype = "C";
173 my $original_datlocale;
174
175 if ($oldnode->pg_version >= '17devel')
176 {
177 $original_enc_name = "UTF-8";
178 $original_provider = "b";
179 $original_datlocale = "C.UTF-8";
180 }
181 elsif ($oldnode->pg_version >= 15 && $ENV{with_icu} eq 'yes')
182 {
183 $original_enc_name = "UTF-8";
184 $original_provider = "i";
185 $original_datlocale = "fr-CA";
186 }
187 else
188 {
189 $original_enc_name = "SQL_ASCII";
190 $original_provider = "c";
191 $original_datlocale = "";
192 }
193
194 my %encodings = ('UTF-8' => 6, 'SQL_ASCII' => 0);
195 my $original_encoding = $encodings{$original_enc_name};
196
197 my @old_initdb_params = @custom_opts;
198
199 push @old_initdb_params, ('--encoding', $original_enc_name);
200 push @old_initdb_params, ('--lc-collate', $original_datcollate);
201 push @old_initdb_params, ('--lc-ctype', $original_datctype);
202
203 # add --locale-provider, if supported
204 my %provider_name = ('b' => 'builtin', 'i' => 'icu', 'c' => 'libc');
205 if ($oldnode->pg_version >= 15)
206 {
207 push @old_initdb_params,
208 ('--locale-provider', $provider_name{$original_provider});
209 if ($original_provider eq 'b')
210 {
211 push @old_initdb_params, ('--builtin-locale', $original_datlocale);
212 }
213 elsif ($original_provider eq 'i')
214 {
215 push @old_initdb_params, ('--icu-locale', $original_datlocale);
216 }
217 }
218
219 # Since checksums are now enabled by default, and weren't before 18,
220 # pass '-k' to initdb on old versions so that upgrades work.
221 push @old_initdb_params, '-k' if $oldnode->pg_version < 18;
222
223 $old_node_params{extra} = \@old_initdb_params;
224 $oldnode->init(%old_node_params);
225 # Override log_statement=all set by Cluster.pm. This avoids large amounts
226 # of log traffic that slow this test down even more when run under valgrind.
227 $oldnode->append_conf('postgresql.conf', 'log_statement = none');
228 $oldnode->start;
229
230 my $result;
231 $result = $oldnode->safe_psql(
232 'postgres',
233 "SELECT encoding, $old_provider_field, datcollate, datctype, $old_datlocale_field
234 FROM pg_database WHERE datname='template0'");
235 is( $result,
236 "$original_encoding|$original_provider|$original_datcollate|$original_datctype|$original_datlocale",
237 "check locales in original cluster");
238
239 # The default location of the source code is the root of this directory.
240 my $srcdir = abs_path("../../..");
241
242 # Set up the data of the old instance with a dump or pg_regress.
243 if (defined($ENV{olddump}))
244 {
245 # Use the dump specified.
246 my $olddumpfile = $ENV{olddump};
247 die "no dump file found!" unless -e $olddumpfile;
248
249 # Load the dump using the "postgres" database as "regression" does
250 # not exist yet, and we are done here.
251 $oldnode->command_ok(
252 [ 'psql', '--no-psqlrc', '--file' => $olddumpfile, 'postgres' ],
253 'loaded old dump file');
254 }
255 else
256 {
257 # Default is to use pg_regress to set up the old instance.
258
259 # Create databases with names covering most ASCII bytes. The
260 # first name exercises backslashes adjacent to double quotes, a
261 # Windows special case.
262 generate_db($oldnode, 'regression\\"\\', 1, 45, '\\\\"\\\\\\');
263 generate_db($oldnode, 'regression', 46, 90, '');
264 generate_db($oldnode, 'regression', 91, 127, '');
265
266 # Grab any regression options that may be passed down by caller.
267 my $extra_opts = $ENV{EXTRA_REGRESS_OPTS} || "";
268
269 # --dlpath is needed to be able to find the location of regress.so
270 # and any libraries the regression tests require.
271 my $dlpath = dirname($ENV{REGRESS_SHLIB});
272
273 # --outputdir points to the path where to place the output files.
274 my $outputdir = $PostgreSQL::Test::Utils::tmp_check;
275
276 # --inputdir points to the path of the input files.
277 my $inputdir = "$srcdir/src/test/regress";
278
279 note 'running regression tests in old instance';
280 my $rc =
281 system($ENV{PG_REGRESS}
282 . " $extra_opts "
283 . "--dlpath=\"$dlpath\" "
284 . "--bindir= "
285 . "--host="
286 . $oldnode->host . " "
287 . "--port="
288 . $oldnode->port . " "
289 . "--schedule=$srcdir/src/test/regress/parallel_schedule "
290 . "--max-concurrent-tests=20 "
291 . "--inputdir=\"$inputdir\" "
292 . "--outputdir=\"$outputdir\"");
293 if ($rc != 0)
294 {
295 # Dump out the regression diffs file, if there is one
296 my $diffs = "$outputdir/regression.diffs";
297 if (-e $diffs)
298 {
299 print "=== dumping $diffs ===\n";
300 print slurp_file($diffs);
301 print "=== EOF ===\n";
302 }
303 }
304 is($rc, 0, 'regression tests pass');
305 }
306
307 # Initialize a new node for the upgrade.
308 my $newnode = PostgreSQL::Test::Cluster->new('new_node');
309
310 # The new cluster will be initialized with different locale settings,
311 # but these settings will be overwritten with those of the original
312 # cluster.
313 my %new_node_params = %old_node_params;
314 my @new_initdb_params = @custom_opts;
315 push @new_initdb_params, ('--encoding', 'SQL_ASCII');
316 push @new_initdb_params, ('--locale-provider', 'libc');
317 $new_node_params{extra} = \@new_initdb_params;
318 $newnode->init(%new_node_params);
319 # Avoid unnecessary log noise
320 $newnode->append_conf('postgresql.conf', 'log_statement = none');
321
322 # Stabilize stats for comparison.
323 $newnode->append_conf('postgresql.conf', 'autovacuum = off');
324
325 my $newbindir = $newnode->config_data('--bindir');
326 my $oldbindir = $oldnode->config_data('--bindir');
327
328 # Before dumping, get rid of objects not existing or not supported in later
329 # versions. This depends on the version of the old server used, and matters
330 # only if different major versions are used for the dump.
331 if (defined($ENV{oldinstall}))
332 {
333 # Consult AdjustUpgrade to find out what we need to do.
334 my $dbnames =
335 $oldnode->safe_psql('postgres', qq(SELECT datname FROM pg_database));
336 my %dbnames;
337 do { $dbnames{$_} = 1; }
338 foreach split /\s+/s, $dbnames;
339 my $adjust_cmds =
340 adjust_database_contents($oldnode->pg_version, %dbnames);
341
342 foreach my $updb (keys %$adjust_cmds)
343 {
344 my @command_args = ();
345 for my $upcmd (@{ $adjust_cmds->{$updb} })
346 {
347 push @command_args, '--command' => $upcmd;
348 }
349
350 # For simplicity, use the newer version's psql to issue the commands.
351 $newnode->command_ok(
352 [
353 'psql', '--no-psqlrc',
354 '--set' => 'ON_ERROR_STOP=1',
355 '--dbname' => $oldnode->connstr($updb),
356 @command_args,
357 ],
358 "ran version adaptation commands for database $updb");
359 }
360 }
361
362 # Stabilize stats before pg_dump / pg_dumpall. Doing it after initializing
363 # the new node gives enough time for autovacuum to update statistics on the
364 # old node.
365 $oldnode->append_conf('postgresql.conf', 'autovacuum = off');
366 $oldnode->restart;
367
368 # Test that dump/restore of the regression database roundtrips cleanly. This
369 # doesn't work well when the nodes are different versions, so skip it in that
370 # case. Note that this isn't a pg_upgrade test, but it's convenient to do it
371 # here because we've gone to the trouble of creating the regression database.
372 #
373 # Do this while the old cluster is running before it is shut down by the
374 # upgrade test but after turning its autovacuum off for stable statistics.
375 SKIP:
376 {
377 my $dstnode = PostgreSQL::Test::Cluster->new('dst_node');
378
379 skip "regress_dump_restore not enabled in PG_TEST_EXTRA"
380 if (!$ENV{PG_TEST_EXTRA}
381 || $ENV{PG_TEST_EXTRA} !~ /\bregress_dump_restore\b/);
382 skip "different Postgres versions"
383 if ($oldnode->pg_version != $dstnode->pg_version);
384 skip "source node not using default install"
385 if (defined $oldnode->install_path);
386
387 # Setup destination database cluster with the same configuration as the
388 # source cluster to avoid any differences between dumps taken from both the
389 # clusters caused by differences in their configurations.
390 $dstnode->init(%old_node_params);
391 # Avoid unnecessary log noise
392 $dstnode->append_conf('postgresql.conf', 'log_statement = none');
393 # Stabilize stats for comparison.
394 $dstnode->append_conf('postgresql.conf', 'autovacuum = off');
395 $dstnode->start;
396
397 # Use --create in dump and restore commands so that the restored
398 # database has the same configurable variable settings as the original
399 # database so that the dumps taken from both databases taken do not
400 # differ because of locale changes. Additionally this provides test
401 # coverage for --create option.
402 #
403 # Use directory format so that we can use parallel dump/restore.
404 my $dump_file = "$tempdir/regression.dump";
405 $oldnode->command_ok(
406 [
407 'pg_dump', '-Fd', '-j2', '--no-sync',
408 '-d' => $oldnode->connstr('regression'),
409 '--create', '-f' => $dump_file
410 ],
411 'pg_dump on source instance');
412
413 $dstnode->command_ok(
414 [ 'pg_restore', '--create', '-j2', '-d' => 'postgres', $dump_file ],
415 'pg_restore to destination instance');
416
417 # Dump original and restored database for comparison.
418 my $src_dump =
419 get_dump_for_comparison($oldnode, 'regression', 'src_dump', 1);
420 my $dst_dump =
421 get_dump_for_comparison($dstnode, 'regression', 'dest_dump', 0);
422
423 compare_files($src_dump, $dst_dump,
424 'dump outputs from original and restored regression databases match');
425 }
426
427 # Take a dump before performing the upgrade as a base comparison. Note
428 # that we need to use pg_dumpall from the new node here.
429 my @dump_command = (
430 'pg_dumpall', '--no-sync',
431 '--restrict-key=test',
432 '--dbname' => $oldnode->connstr('postgres'),
433 '--file' => $dump1_file);
434 # --extra-float-digits is needed when upgrading from a version older than 11.
435 push(@dump_command, '--extra-float-digits', '0')
436 if ($oldnode->pg_version < 12);
437 $newnode->command_ok(\@dump_command, 'dump before running pg_upgrade');
438
439 # After dumping, update references to the old source tree's regress.so
440 # to point to the new tree.
441 if (defined($ENV{oldinstall}))
442 {
443 # First, fetch all the references to libraries that are not part
444 # of the default path $libdir.
445 my $output = $oldnode->safe_psql('regression',
446 "SELECT DISTINCT probin::text FROM pg_proc WHERE probin NOT LIKE '\$libdir%';"
447 );
448 chomp($output);
449 my @libpaths = split("\n", $output);
450
451 my $dump_data = slurp_file($dump1_file);
452
453 my $newregresssrc = dirname($ENV{REGRESS_SHLIB});
454 foreach (@libpaths)
455 {
456 my $libpath = $_;
457 $libpath = dirname($libpath);
458 $dump_data =~ s/$libpath/$newregresssrc/g;
459 }
460
461 open my $fh, ">", $dump1_file or die "could not open dump file";
462 print $fh $dump_data;
463 close $fh;
464
465 # This replaces any references to the old tree's regress.so
466 # the new tree's regress.so. Any references that do *not*
467 # match $libdir are switched so as this request does not
468 # depend on the path of the old source tree. This is useful
469 # when using an old dump. Do the operation on all the databases
470 # that allow connections so as this includes the regression
471 # database and anything the user has set up.
472 $output = $oldnode->safe_psql('postgres',
473 "SELECT datname FROM pg_database WHERE datallowconn;");
474 chomp($output);
475 my @datnames = split("\n", $output);
476 foreach (@datnames)
477 {
478 my $datname = $_;
479 $oldnode->safe_psql(
480 $datname, "UPDATE pg_proc SET probin =
481 regexp_replace(probin, '.*/', '$newregresssrc/')
482 WHERE probin NOT LIKE '\$libdir/%'");
483 }
484 }
485
486 # Create an invalid database, will be deleted below
487 $oldnode->safe_psql(
488 'postgres', qq(
489 CREATE DATABASE regression_invalid;
490 UPDATE pg_database SET datconnlimit = -2 WHERE datname = 'regression_invalid';
491 ));
492
493 # In a VPATH build, we'll be started in the source directory, but we want
494 # to run pg_upgrade in the build directory so that any files generated finish
495 # in it, like delete_old_cluster.{sh,bat}.
496 chdir ${PostgreSQL::Test::Utils::tmp_check};
497
498 # Upgrade the instance.
499 $oldnode->stop;
500
501 # Cause a failure at the start of pg_upgrade, this should create the logging
502 # directory pg_upgrade_output.d but leave it around. Keep --check for an
503 # early exit.
504 command_checks_all(
505 [
506 'pg_upgrade', '--no-sync',
507 '--old-datadir' => $oldnode->data_dir,
508 '--new-datadir' => $newnode->data_dir,
509 '--old-bindir' => $oldbindir . '/does/not/exist/',
510 '--new-bindir' => $newbindir,
511 '--socketdir' => $newnode->host,
512 '--old-port' => $oldnode->port,
513 '--new-port' => $newnode->port,
514 $mode, '--check',
515 ],
516 1,
517 [qr{check for ".*?does/not/exist" failed}],
518 [],
519 'run of pg_upgrade --check for new instance with incorrect binary path');
520 ok(-d $newnode->data_dir . "/pg_upgrade_output.d",
521 "pg_upgrade_output.d/ not removed after pg_upgrade failure");
522 rmtree($newnode->data_dir . "/pg_upgrade_output.d");
523
524 # Check that pg_upgrade aborts when encountering an invalid database
525 # (However, versions that were out of support by commit c66a7d75e652 don't
526 # know how to do this, so skip this test there.)
527 SKIP:
528 {
529 skip "database invalidation not implemented", 1
530 if $oldnode->pg_version < 11;
531
532 command_checks_all(
533 [
534 'pg_upgrade', '--no-sync',
535 '--old-datadir' => $oldnode->data_dir,
536 '--new-datadir' => $newnode->data_dir,
537 '--old-bindir' => $oldbindir,
538 '--new-bindir' => $newbindir,
539 '--socketdir' => $newnode->host,
540 '--old-port' => $oldnode->port,
541 '--new-port' => $newnode->port,
542 $mode, '--check',
543 ],
544 1,
545 [qr/datconnlimit/],
546 [qr/^$/],
547 'invalid database causes failure');
548 rmtree($newnode->data_dir . "/pg_upgrade_output.d");
549 }
550
551 # And drop it, so we can continue
552 $oldnode->start;
553 $oldnode->safe_psql('postgres', 'DROP DATABASE regression_invalid');
554 $oldnode->stop;
555
556 # --check command works here, cleans up pg_upgrade_output.d.
557 command_ok(
558 [
559 'pg_upgrade', '--no-sync',
560 '--old-datadir' => $oldnode->data_dir,
561 '--new-datadir' => $newnode->data_dir,
562 '--old-bindir' => $oldbindir,
563 '--new-bindir' => $newbindir,
564 '--socketdir' => $newnode->host,
565 '--old-port' => $oldnode->port,
566 '--new-port' => $newnode->port,
567 $mode, '--check',
568 ],
569 'run of pg_upgrade --check for new instance');
570 ok(!-d $newnode->data_dir . "/pg_upgrade_output.d",
571 "pg_upgrade_output.d/ removed after pg_upgrade --check success");
572
573 # Actual run, pg_upgrade_output.d is removed at the end.
574 command_ok(
575 [
576 'pg_upgrade', '--no-sync',
577 '--old-datadir' => $oldnode->data_dir,
578 '--new-datadir' => $newnode->data_dir,
579 '--old-bindir' => $oldbindir,
580 '--new-bindir' => $newbindir,
581 '--socketdir' => $newnode->host,
582 '--old-port' => $oldnode->port,
583 '--new-port' => $newnode->port,
584 $mode,
585 ],
586 'run of pg_upgrade for new instance');
587 ok( !-d $newnode->data_dir . "/pg_upgrade_output.d",
588 "pg_upgrade_output.d/ removed after pg_upgrade success");
589
590 $newnode->start;
591
592 # Check if there are any logs coming from pg_upgrade, that would only be
593 # retained on failure.
594 my $log_path = $newnode->data_dir . "/pg_upgrade_output.d";
595 if (-d $log_path)
596 {
597 my @log_files;
598 find(
599 sub {
600 push @log_files, $File::Find::name
601 if $File::Find::name =~ m/.*\.log/;
602 },
603 $newnode->data_dir . "/pg_upgrade_output.d");
604
605 my $test_logfile = $PostgreSQL::Test::Utils::test_logfile;
606
607 note "=== pg_upgrade logs found - appending to $test_logfile ===\n";
608 foreach my $log (@log_files)
609 {
610 note "=== appending $log ===\n";
611 print "=== contents of $log ===\n";
612 print slurp_file($log);
613 print "=== EOF ===\n";
614 }
615 }
616
617 # Test that upgraded cluster has original locale settings.
618 $result = $newnode->safe_psql(
619 'postgres',
620 "SELECT encoding, datlocprovider, datcollate, datctype, datlocale
621 FROM pg_database WHERE datname='template0'");
622 is( $result,
623 "$original_encoding|$original_provider|$original_datcollate|$original_datctype|$original_datlocale",
624 "check that locales in new cluster match original cluster");
625
626 # Second dump from the upgraded instance.
627 @dump_command = (
628 'pg_dumpall', '--no-sync',
629 '--restrict-key=test',
630 '--dbname' => $newnode->connstr('postgres'),
631 '--file' => $dump2_file);
632 # --extra-float-digits is needed when upgrading from a version older than 11.
633 push(@dump_command, '--extra-float-digits' => '0')
634 if ($oldnode->pg_version < 12);
635 $newnode->command_ok(\@dump_command, 'dump after running pg_upgrade');
636
637 # Filter the contents of the dumps.
638 my $dump1_filtered = filter_dump(1, $oldnode->pg_version, $dump1_file);
639 my $dump2_filtered = filter_dump(0, $oldnode->pg_version, $dump2_file);
640
641 # Compare the two dumps, there should be no differences.
642 compare_files($dump1_filtered, $dump2_filtered,
643 'old and new dumps match after pg_upgrade');
644
645 done_testing();