PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
pg_upgrade.c
Go to the documentation of this file.
1/*
2 * pg_upgrade.c
3 *
4 * main source file
5 *
6 * Copyright (c) 2010-2025, PostgreSQL Global Development Group
7 * src/bin/pg_upgrade/pg_upgrade.c
8 */
9
10/*
11 * To simplify the upgrade process, we force certain system values to be
12 * identical between old and new clusters:
13 *
14 * We control all assignments of pg_class.oid (and relfilenode) so toast
15 * oids are the same between old and new clusters. This is important
16 * because toast oids are stored as toast pointers in user tables.
17 *
18 * While pg_class.oid and pg_class.relfilenode are initially the same in a
19 * cluster, they can diverge due to CLUSTER, REINDEX, or VACUUM FULL. We
20 * control assignments of pg_class.relfilenode because we want the filenames
21 * to match between the old and new cluster.
22 *
23 * We control assignment of pg_tablespace.oid because we want the oid to match
24 * between the old and new cluster.
25 *
26 * We control all assignments of pg_type.oid because these oids are stored
27 * in user composite type values.
28 *
29 * We control all assignments of pg_enum.oid because these oids are stored
30 * in user tables as enum values.
31 *
32 * We control all assignments of pg_authid.oid for historical reasons (the
33 * oids used to be stored in pg_largeobject_metadata, which is now copied via
34 * SQL commands), that might change at some point in the future.
35 *
36 * We control all assignments of pg_database.oid because we want the directory
37 * names to match between the old and new cluster.
38 */
39
40
41
42#include "postgres_fe.h"
43
44#include <time.h>
45
46#include "catalog/pg_class_d.h"
47#include "common/file_perm.h"
48#include "common/logging.h"
51#include "pg_upgrade.h"
52
53/*
54 * Maximum number of pg_restore actions (TOC entries) to process within one
55 * transaction. At some point we might want to make this user-controllable,
56 * but for now a hard-wired setting will suffice.
57 */
58#define RESTORE_TRANSACTION_SIZE 1000
59
60static void set_new_cluster_char_signedness(void);
61static void set_locale_and_encoding(void);
62static void prepare_new_cluster(void);
63static void prepare_new_globals(void);
64static void create_new_objects(void);
65static void copy_xact_xlog_xid(void);
66static void set_frozenxids(bool minmxid_only);
67static void make_outputdirs(char *pgdata);
68static void setup(char *argv0);
69static void create_logical_replication_slots(void);
70
74
75char *output_files[] = {
77#ifdef WIN32
78 /* unique file for pg_ctl start */
80#endif
83 NULL
84};
85
86
87int
88main(int argc, char **argv)
89{
90 char *deletion_script_file_name = NULL;
91
92 /*
93 * pg_upgrade doesn't currently use common/logging.c, but initialize it
94 * anyway because we might call common code that does.
95 */
96 pg_logging_init(argv[0]);
97 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_upgrade"));
98
99 /* Set default restrictive mask until new cluster permissions are read */
100 umask(PG_MODE_MASK_OWNER);
101
102 parseCommandLine(argc, argv);
103
105
108
109 /*
110 * Set mask based on PGDATA permissions, needed for the creation of the
111 * output directories with correct permissions.
112 */
114 pg_fatal("could not read permissions of directory \"%s\": %m",
116
117 umask(pg_mode_mask);
118
119 /*
120 * This needs to happen after adjusting the data directory of the new
121 * cluster in adjust_data_dir().
122 */
124
125 setup(argv[0]);
126
128
130
133
135
137
138
139 /* -- NEW -- */
141
144
146 "\n"
147 "Performing Upgrade\n"
148 "------------------");
149
151
153
154 stop_postmaster(false);
155
156 /*
157 * Destructive Changes to New Cluster
158 */
159
162
163 /* New now using xids of the old system */
164
165 /* -- NEW -- */
167
169
171
172 stop_postmaster(false);
173
174 /*
175 * Most failures happen in create_new_objects(), which has completed at
176 * this point. We do this here because it is just before file transfer,
177 * which for --link will make it unsafe to start the old cluster once the
178 * new cluster is started, and for --swap will make it unsafe to start the
179 * old cluster at all.
180 */
184
187
188 /*
189 * Assuming OIDs are only used in system tables, there is no need to
190 * restore the OID counter because we have not transferred any OIDs from
191 * the old system, but we do it anyway just in case. We do it late here
192 * because there is no need to have the schema load use new oids.
193 */
194 prep_status("Setting next OID for new cluster");
195 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
196 "\"%s/pg_resetwal\" -o %u \"%s\"",
199 check_ok();
200
201 /*
202 * Migrate the logical slots to the new cluster. Note that we need to do
203 * this after resetting WAL because otherwise the required WAL would be
204 * removed and slots would become unusable. There is a possibility that
205 * background processes might generate some WAL before we could create the
206 * slots in the new cluster but we can ignore that WAL as that won't be
207 * required downstream.
208 */
210 {
213 stop_postmaster(false);
214 }
215
216 if (user_opts.do_sync)
217 {
218 prep_status("Sync data directory to disk");
219 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
220 "\"%s/initdb\" --sync-only %s \"%s\" --sync-method %s",
223 "--no-sync-data-files" : "",
226 check_ok();
227 }
228
229 create_script_for_old_cluster_deletion(&deletion_script_file_name);
230
232
234 "\n"
235 "Upgrade Complete\n"
236 "----------------");
237
238 output_completion_banner(deletion_script_file_name);
239
240 pg_free(deletion_script_file_name);
241
243
244 return 0;
245}
246
247/*
248 * Create and assign proper permissions to the set of output directories
249 * used to store any data generated internally, filling in log_opts in
250 * the process.
251 */
252static void
253make_outputdirs(char *pgdata)
254{
255 FILE *fp;
256 char **filename;
257 time_t run_time = time(NULL);
258 char filename_path[MAXPGPATH];
259 char timebuf[128];
260 struct timeval time;
261 time_t tt;
262 int len;
263
265 len = snprintf(log_opts.rootdir, MAXPGPATH, "%s/%s", pgdata, BASE_OUTPUTDIR);
266 if (len >= MAXPGPATH)
267 pg_fatal("directory path for new cluster is too long");
268
269 /* BASE_OUTPUTDIR/$timestamp/ */
270 gettimeofday(&time, NULL);
271 tt = (time_t) time.tv_sec;
272 strftime(timebuf, sizeof(timebuf), "%Y%m%dT%H%M%S", localtime(&tt));
273 /* append milliseconds */
274 snprintf(timebuf + strlen(timebuf), sizeof(timebuf) - strlen(timebuf),
275 ".%03d", (int) (time.tv_usec / 1000));
278 timebuf);
279 if (len >= MAXPGPATH)
280 pg_fatal("directory path for new cluster is too long");
281
282 /* BASE_OUTPUTDIR/$timestamp/dump/ */
285 timebuf, DUMP_OUTPUTDIR);
286 if (len >= MAXPGPATH)
287 pg_fatal("directory path for new cluster is too long");
288
289 /* BASE_OUTPUTDIR/$timestamp/log/ */
292 timebuf, LOG_OUTPUTDIR);
293 if (len >= MAXPGPATH)
294 pg_fatal("directory path for new cluster is too long");
295
296 /*
297 * Ignore the error case where the root path exists, as it is kept the
298 * same across runs.
299 */
300 if (mkdir(log_opts.rootdir, pg_dir_create_mode) < 0 && errno != EEXIST)
301 pg_fatal("could not create directory \"%s\": %m", log_opts.rootdir);
303 pg_fatal("could not create directory \"%s\": %m", log_opts.basedir);
305 pg_fatal("could not create directory \"%s\": %m", log_opts.dumpdir);
307 pg_fatal("could not create directory \"%s\": %m", log_opts.logdir);
308
309 len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
311 if (len >= sizeof(filename_path))
312 pg_fatal("directory path for new cluster is too long");
313
314 if ((log_opts.internal = fopen_priv(filename_path, "a")) == NULL)
315 pg_fatal("could not open log file \"%s\": %m", filename_path);
316
317 /* label start of upgrade in logfiles */
318 for (filename = output_files; *filename != NULL; filename++)
319 {
320 len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
322 if (len >= sizeof(filename_path))
323 pg_fatal("directory path for new cluster is too long");
324 if ((fp = fopen_priv(filename_path, "a")) == NULL)
325 pg_fatal("could not write to log file \"%s\": %m", filename_path);
326
327 fprintf(fp,
328 "-----------------------------------------------------------------\n"
329 " pg_upgrade run on %s"
330 "-----------------------------------------------------------------\n\n",
331 ctime(&run_time));
332 fclose(fp);
333 }
334}
335
336
337static void
339{
340 /*
341 * make sure the user has a clean environment, otherwise, we may confuse
342 * libpq when we connect to one (or both) of the servers.
343 */
345
346 /*
347 * In case the user hasn't specified the directory for the new binaries
348 * with -B, default to using the path of the currently executed pg_upgrade
349 * binary.
350 */
351 if (!new_cluster.bindir)
352 {
353 char exec_path[MAXPGPATH];
354
355 if (find_my_exec(argv0, exec_path) < 0)
356 pg_fatal("%s: could not find own program executable", argv0);
357 /* Trim off program name and keep just path */
361 }
362
364
365 /* no postmasters should be running, except for a live check */
367 {
368 /*
369 * If we have a postmaster.pid file, try to start the server. If it
370 * starts, the pid file was stale, so stop the server. If it doesn't
371 * start, assume the server is running. If the pid file is left over
372 * from a server crash, this also allows any committed transactions
373 * stored in the WAL to be replayed so they are not lost, because WAL
374 * files are not transferred from old to new servers. We later check
375 * for a clean shutdown.
376 */
377 if (start_postmaster(&old_cluster, false))
378 stop_postmaster(false);
379 else
380 {
381 if (!user_opts.check)
382 pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
383 "Please shutdown that postmaster and try again.");
384 else
385 user_opts.live_check = true;
386 }
387 }
388
389 /* same goes for the new postmaster */
391 {
392 if (start_postmaster(&new_cluster, false))
393 stop_postmaster(false);
394 else
395 pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
396 "Please shutdown that postmaster and try again.");
397 }
398}
399
400/*
401 * Set the new cluster's default char signedness using the old cluster's
402 * value.
403 */
404static void
406{
407 bool new_char_signedness;
408
409 /*
410 * Use the specified char signedness if specified. Otherwise we inherit
411 * the source database's signedness.
412 */
413 if (user_opts.char_signedness != -1)
414 new_char_signedness = (user_opts.char_signedness == 1);
415 else
416 new_char_signedness = old_cluster.controldata.default_char_signedness;
417
418 /* Change the char signedness of the new cluster, if necessary */
419 if (new_cluster.controldata.default_char_signedness != new_char_signedness)
420 {
421 prep_status("Setting the default char signedness for new cluster");
422
423 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
424 "\"%s/pg_resetwal\" --char-signedness %s \"%s\"",
426 new_char_signedness ? "signed" : "unsigned",
428
429 check_ok();
430 }
431}
432
433/*
434 * Copy locale and encoding information into the new cluster's template0.
435 *
436 * We need to copy the encoding, datlocprovider, datcollate, datctype, and
437 * datlocale. We don't need datcollversion because that's never set for
438 * template0.
439 */
440static void
442{
443 PGconn *conn_new_template1;
444 char *datcollate_literal;
445 char *datctype_literal;
446 char *datlocale_literal = NULL;
448
449 prep_status("Setting locale and encoding for new cluster");
450
451 /* escape literals with respect to new cluster */
452 conn_new_template1 = connectToServer(&new_cluster, "template1");
453
454 datcollate_literal = PQescapeLiteral(conn_new_template1,
455 locale->db_collate,
456 strlen(locale->db_collate));
457 datctype_literal = PQescapeLiteral(conn_new_template1,
458 locale->db_ctype,
459 strlen(locale->db_ctype));
460
461 if (locale->db_locale)
462 datlocale_literal = PQescapeLiteral(conn_new_template1,
463 locale->db_locale,
464 strlen(locale->db_locale));
465 else
466 datlocale_literal = "NULL";
467
468 /* update template0 in new cluster */
470 PQclear(executeQueryOrDie(conn_new_template1,
471 "UPDATE pg_catalog.pg_database "
472 " SET encoding = %d, "
473 " datlocprovider = '%c', "
474 " datcollate = %s, "
475 " datctype = %s, "
476 " datlocale = %s "
477 " WHERE datname = 'template0' ",
478 locale->db_encoding,
479 locale->db_collprovider,
480 datcollate_literal,
481 datctype_literal,
482 datlocale_literal));
484 PQclear(executeQueryOrDie(conn_new_template1,
485 "UPDATE pg_catalog.pg_database "
486 " SET encoding = %d, "
487 " datlocprovider = '%c', "
488 " datcollate = %s, "
489 " datctype = %s, "
490 " daticulocale = %s "
491 " WHERE datname = 'template0' ",
492 locale->db_encoding,
493 locale->db_collprovider,
494 datcollate_literal,
495 datctype_literal,
496 datlocale_literal));
497 else
498 PQclear(executeQueryOrDie(conn_new_template1,
499 "UPDATE pg_catalog.pg_database "
500 " SET encoding = %d, "
501 " datcollate = %s, "
502 " datctype = %s "
503 " WHERE datname = 'template0' ",
504 locale->db_encoding,
505 datcollate_literal,
506 datctype_literal));
507
508 PQfreemem(datcollate_literal);
509 PQfreemem(datctype_literal);
510 if (locale->db_locale)
511 PQfreemem(datlocale_literal);
512
513 PQfinish(conn_new_template1);
514
515 check_ok();
516}
517
518
519static void
521{
522 /*
523 * It would make more sense to freeze after loading the schema, but that
524 * would cause us to lose the frozenxids restored by the load. We use
525 * --analyze so autovacuum doesn't update statistics later
526 */
527 prep_status("Analyzing all rows in the new cluster");
528 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
529 "\"%s/vacuumdb\" %s --all --analyze %s",
531 log_opts.verbose ? "--verbose" : "");
532 check_ok();
533
534 /*
535 * We do freeze after analyze so pg_statistic is also frozen. template0 is
536 * not frozen here, but data rows were frozen by initdb, and we set its
537 * datfrozenxid, relfrozenxids, and relminmxid later to match the new xid
538 * counter later.
539 */
540 prep_status("Freezing all rows in the new cluster");
541 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
542 "\"%s/vacuumdb\" %s --all --freeze %s",
544 log_opts.verbose ? "--verbose" : "");
545 check_ok();
546}
547
548
549static void
551{
552 /*
553 * Before we restore anything, set frozenxids of initdb-created tables.
554 */
555 set_frozenxids(false);
556
557 /*
558 * Now restore global objects (roles and tablespaces).
559 */
560 prep_status("Restoring global objects in the new cluster");
561
562 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
563 "\"%s/psql\" " EXEC_PSQL_ARGS " %s -f \"%s/%s\"",
567 check_ok();
568}
569
570
571static void
573{
574 int dbnum;
575 PGconn *conn_new_template1;
576
577 prep_status_progress("Restoring database schemas in the new cluster");
578
579 /*
580 * Ensure that any changes to template0 are fully written out to disk
581 * prior to restoring the databases. This is necessary because we use the
582 * FILE_COPY strategy to create the databases (which testing has shown to
583 * be faster), and when the server is in binary upgrade mode, it skips the
584 * checkpoints this strategy ordinarily performs.
585 */
586 conn_new_template1 = connectToServer(&new_cluster, "template1");
587 PQclear(executeQueryOrDie(conn_new_template1, "CHECKPOINT"));
588 PQfinish(conn_new_template1);
589
590 /*
591 * We cannot process the template1 database concurrently with others,
592 * because when it's transiently dropped, connection attempts would fail.
593 * So handle it in a separate non-parallelized pass.
594 */
595 for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
596 {
597 char sql_file_name[MAXPGPATH],
598 log_file_name[MAXPGPATH];
599 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
600 const char *create_opts;
601
602 /* Process only template1 in this pass */
603 if (strcmp(old_db->db_name, "template1") != 0)
604 continue;
605
606 pg_log(PG_STATUS, "%s", old_db->db_name);
607 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
608 snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
609
610 /*
611 * template1 database will already exist in the target installation,
612 * so tell pg_restore to drop and recreate it; otherwise we would fail
613 * to propagate its database-level properties.
614 */
615 create_opts = "--clean --create";
616
617 exec_prog(log_file_name,
618 NULL,
619 true,
620 true,
621 "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
622 "--transaction-size=%d "
623 "--dbname postgres \"%s/%s\"",
626 create_opts,
629 sql_file_name);
630
631 break; /* done once we've processed template1 */
632 }
633
634 for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
635 {
636 char sql_file_name[MAXPGPATH],
637 log_file_name[MAXPGPATH];
638 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
639 const char *create_opts;
640 int txn_size;
641
642 /* Skip template1 in this pass */
643 if (strcmp(old_db->db_name, "template1") == 0)
644 continue;
645
646 pg_log(PG_STATUS, "%s", old_db->db_name);
647 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
648 snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
649
650 /*
651 * postgres database will already exist in the target installation, so
652 * tell pg_restore to drop and recreate it; otherwise we would fail to
653 * propagate its database-level properties.
654 */
655 if (strcmp(old_db->db_name, "postgres") == 0)
656 create_opts = "--clean --create";
657 else
658 create_opts = "--create";
659
660 /*
661 * In parallel mode, reduce the --transaction-size of each restore job
662 * so that the total number of locks that could be held across all the
663 * jobs stays in bounds.
664 */
665 txn_size = RESTORE_TRANSACTION_SIZE;
666 if (user_opts.jobs > 1)
667 {
668 txn_size /= user_opts.jobs;
669 /* Keep some sanity if -j is huge */
670 txn_size = Max(txn_size, 10);
671 }
672
673 parallel_exec_prog(log_file_name,
674 NULL,
675 "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
676 "--transaction-size=%d "
677 "--dbname template1 \"%s/%s\"",
680 create_opts,
681 txn_size,
683 sql_file_name);
684 }
685
686 /* reap all children */
687 while (reap_child(true) == true)
688 ;
689
691 check_ok();
692
693 /*
694 * We don't have minmxids for databases or relations in pre-9.3 clusters,
695 * so set those after we have restored the schema.
696 */
698 set_frozenxids(true);
699
700 /* update new_cluster info now that we have objects in the databases */
702}
703
704/*
705 * Delete the given subdirectory contents from the new cluster
706 */
707static void
708remove_new_subdir(const char *subdir, bool rmtopdir)
709{
710 char new_path[MAXPGPATH];
711
712 prep_status("Deleting files from new %s", subdir);
713
714 snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
715 if (!rmtree(new_path, rmtopdir))
716 pg_fatal("could not delete directory \"%s\"", new_path);
717
718 check_ok();
719}
720
721/*
722 * Copy the files from the old cluster into it
723 */
724static void
725copy_subdir_files(const char *old_subdir, const char *new_subdir)
726{
727 char old_path[MAXPGPATH];
728 char new_path[MAXPGPATH];
729
730 remove_new_subdir(new_subdir, true);
731
732 snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, old_subdir);
733 snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, new_subdir);
734
735 prep_status("Copying old %s to new server", old_subdir);
736
737 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
738#ifndef WIN32
739 "cp -Rf \"%s\" \"%s\"",
740#else
741 /* flags: everything, no confirm, quiet, overwrite read-only */
742 "xcopy /e /y /q /r \"%s\" \"%s\\\"",
743#endif
744 old_path, new_path);
745
746 check_ok();
747}
748
749static void
751{
752 /*
753 * Copy old commit logs to new data dir. pg_clog has been renamed to
754 * pg_xact in post-10 clusters.
755 */
757 "pg_clog" : "pg_xact",
759 "pg_clog" : "pg_xact");
760
761 prep_status("Setting oldest XID for new cluster");
762 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
763 "\"%s/pg_resetwal\" -f -u %u \"%s\"",
766 check_ok();
767
768 /* set the next transaction id and epoch of the new cluster */
769 prep_status("Setting next transaction ID and epoch for new cluster");
770 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
771 "\"%s/pg_resetwal\" -f -x %u \"%s\"",
774 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
775 "\"%s/pg_resetwal\" -f -e %u \"%s\"",
778 /* must reset commit timestamp limits also */
779 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
780 "\"%s/pg_resetwal\" -f -c %u,%u \"%s\"",
785 check_ok();
786
787 /*
788 * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
789 * (see pg_upgrade.h) and the new server is after, then we don't copy
790 * pg_multixact files, but we need to reset pg_control so that the new
791 * server doesn't attempt to read multis older than the cutoff value.
792 */
795 {
796 copy_subdir_files("pg_multixact/offsets", "pg_multixact/offsets");
797 copy_subdir_files("pg_multixact/members", "pg_multixact/members");
798
799 prep_status("Setting next multixact ID and offset for new cluster");
800
801 /*
802 * we preserve all files and contents, so we must preserve both "next"
803 * counters here and the oldest multi present on system.
804 */
805 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
806 "\"%s/pg_resetwal\" -O %u -m %u,%u \"%s\"",
812 check_ok();
813 }
815 {
816 /*
817 * Remove offsets/0000 file created by initdb that no longer matches
818 * the new multi-xid value. "members" starts at zero so no need to
819 * remove it.
820 */
821 remove_new_subdir("pg_multixact/offsets", false);
822
823 prep_status("Setting oldest multixact ID in new cluster");
824
825 /*
826 * We don't preserve files in this case, but it's important that the
827 * oldest multi is set to the latest value used by the old system, so
828 * that multixact.c returns the empty set for multis that might be
829 * present on disk. We set next multi to the value following that; it
830 * might end up wrapped around (i.e. 0) if the old cluster had
831 * next=MaxMultiXactId, but multixact.c can cope with that just fine.
832 */
833 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
834 "\"%s/pg_resetwal\" -m %u,%u \"%s\"",
839 check_ok();
840 }
841
842 /* now reset the wal archives in the new cluster */
843 prep_status("Resetting WAL archives");
844 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
845 /* use timeline 1 to match controldata and no WAL history file */
846 "\"%s/pg_resetwal\" -l 00000001%s \"%s\"", new_cluster.bindir,
849 check_ok();
850}
851
852
853/*
854 * set_frozenxids()
855 *
856 * This is called on the new cluster before we restore anything, with
857 * minmxid_only = false. Its purpose is to ensure that all initdb-created
858 * vacuumable tables have relfrozenxid/relminmxid matching the old cluster's
859 * xid/mxid counters. We also initialize the datfrozenxid/datminmxid of the
860 * built-in databases to match.
861 *
862 * As we create user tables later, their relfrozenxid/relminmxid fields will
863 * be restored properly by the binary-upgrade restore script. Likewise for
864 * user-database datfrozenxid/datminmxid. However, if we're upgrading from a
865 * pre-9.3 database, which does not store per-table or per-DB minmxid, then
866 * the relminmxid/datminmxid values filled in by the restore script will just
867 * be zeroes.
868 *
869 * Hence, with a pre-9.3 source database, a second call occurs after
870 * everything is restored, with minmxid_only = true. This pass will
871 * initialize all tables and databases, both those made by initdb and user
872 * objects, with the desired minmxid value. frozenxid values are left alone.
873 */
874static void
875set_frozenxids(bool minmxid_only)
876{
877 int dbnum;
878 PGconn *conn,
879 *conn_template1;
880 PGresult *dbres;
881 int ntups;
882 int i_datname;
883 int i_datallowconn;
884
885 if (!minmxid_only)
886 prep_status("Setting frozenxid and minmxid counters in new cluster");
887 else
888 prep_status("Setting minmxid counter in new cluster");
889
890 conn_template1 = connectToServer(&new_cluster, "template1");
891
892 if (!minmxid_only)
893 /* set pg_database.datfrozenxid */
894 PQclear(executeQueryOrDie(conn_template1,
895 "UPDATE pg_catalog.pg_database "
896 "SET datfrozenxid = '%u'",
898
899 /* set pg_database.datminmxid */
900 PQclear(executeQueryOrDie(conn_template1,
901 "UPDATE pg_catalog.pg_database "
902 "SET datminmxid = '%u'",
904
905 /* get database names */
906 dbres = executeQueryOrDie(conn_template1,
907 "SELECT datname, datallowconn "
908 "FROM pg_catalog.pg_database");
909
910 i_datname = PQfnumber(dbres, "datname");
911 i_datallowconn = PQfnumber(dbres, "datallowconn");
912
913 ntups = PQntuples(dbres);
914 for (dbnum = 0; dbnum < ntups; dbnum++)
915 {
916 char *datname = PQgetvalue(dbres, dbnum, i_datname);
917 char *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
918
919 /*
920 * We must update databases where datallowconn = false, e.g.
921 * template0, because autovacuum increments their datfrozenxids,
922 * relfrozenxids, and relminmxid even if autovacuum is turned off, and
923 * even though all the data rows are already frozen. To enable this,
924 * we temporarily change datallowconn.
925 */
926 if (strcmp(datallowconn, "f") == 0)
927 PQclear(executeQueryOrDie(conn_template1,
928 "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
930
932
933 if (!minmxid_only)
934 /* set pg_class.relfrozenxid */
936 "UPDATE pg_catalog.pg_class "
937 "SET relfrozenxid = '%u' "
938 /* only heap, materialized view, and TOAST are vacuumed */
939 "WHERE relkind IN ("
940 CppAsString2(RELKIND_RELATION) ", "
941 CppAsString2(RELKIND_MATVIEW) ", "
942 CppAsString2(RELKIND_TOASTVALUE) ")",
944
945 /* set pg_class.relminmxid */
947 "UPDATE pg_catalog.pg_class "
948 "SET relminmxid = '%u' "
949 /* only heap, materialized view, and TOAST are vacuumed */
950 "WHERE relkind IN ("
951 CppAsString2(RELKIND_RELATION) ", "
952 CppAsString2(RELKIND_MATVIEW) ", "
953 CppAsString2(RELKIND_TOASTVALUE) ")",
955 PQfinish(conn);
956
957 /* Reset datallowconn flag */
958 if (strcmp(datallowconn, "f") == 0)
959 PQclear(executeQueryOrDie(conn_template1,
960 "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
962 }
963
964 PQclear(dbres);
965
966 PQfinish(conn_template1);
967
968 check_ok();
969}
970
971/*
972 * create_logical_replication_slots()
973 *
974 * Similar to create_new_objects() but only restores logical replication slots.
975 */
976static void
978{
979 prep_status_progress("Restoring logical replication slots in the new cluster");
980
981 for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
982 {
983 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
984 LogicalSlotInfoArr *slot_arr = &old_db->slot_arr;
985 PGconn *conn;
986 PQExpBuffer query;
987
988 /* Skip this database if there are no slots */
989 if (slot_arr->nslots == 0)
990 continue;
991
993 query = createPQExpBuffer();
994
995 pg_log(PG_STATUS, "%s", old_db->db_name);
996
997 for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
998 {
999 LogicalSlotInfo *slot_info = &slot_arr->slots[slotnum];
1000
1001 /* Constructs a query for creating logical replication slots */
1003 "SELECT * FROM "
1004 "pg_catalog.pg_create_logical_replication_slot(");
1005 appendStringLiteralConn(query, slot_info->slotname, conn);
1006 appendPQExpBufferStr(query, ", ");
1007 appendStringLiteralConn(query, slot_info->plugin, conn);
1008
1009 appendPQExpBuffer(query, ", false, %s, %s);",
1010 slot_info->two_phase ? "true" : "false",
1011 slot_info->failover ? "true" : "false");
1012
1013 PQclear(executeQueryOrDie(conn, "%s", query->data));
1014
1015 resetPQExpBuffer(query);
1016 }
1017
1018 PQfinish(conn);
1019
1020 destroyPQExpBuffer(query);
1021 }
1022
1024 check_ok();
1025
1026 return;
1027}
bool exec_prog(const char *log_filename, const char *opt_log_file, bool report_error, bool exit_on_error, const char *fmt,...)
Definition: exec.c:85
bool pid_lock_file_exists(const char *datadir)
Definition: exec.c:233
void verify_directories(void)
Definition: exec.c:263
bool reap_child(bool wait_for_child)
Definition: parallel.c:278
void parallel_exec_prog(const char *log_file, const char *opt_log_file, const char *fmt,...)
Definition: parallel.c:62
#define Max(x, y)
Definition: c.h:969
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1185
#define CppAsString2(x)
Definition: c.h:363
void check_cluster_versions(void)
Definition: check.c:838
void issue_warnings_and_set_wal_level(void)
Definition: check.c:783
void check_cluster_compatibility(void)
Definition: check.c:893
void check_new_cluster(void)
Definition: check.c:701
void report_clusters_compatible(void)
Definition: check.c:764
void create_script_for_old_cluster_deletion(char **deletion_script_file_name)
Definition: check.c:968
void check_and_dump_old_cluster(void)
Definition: check.c:588
void output_completion_banner(char *deletion_script_file_name)
Definition: check.c:804
void output_check_banner(void)
Definition: check.c:570
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:429
void disable_old_cluster(transferMode transfer_mode)
Definition: controldata.c:755
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
void PQfinish(PGconn *conn)
Definition: fe-connect.c:5290
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
void PQclear(PGresult *res)
Definition: fe-exec.c:721
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3589
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4363
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
void pg_free(void *ptr)
Definition: fe_memutils.c:105
int pg_mode_mask
Definition: file_perm.c:25
int pg_dir_create_mode
Definition: file_perm.c:18
bool GetDataDirectoryCreatePerm(const char *dataDir)
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
int count_old_cluster_logical_slots(void)
Definition: info.c:744
void get_db_rel_and_slot_infos(ClusterInfo *cluster)
Definition: info.c:280
static char * locale
Definition: initdb.c:140
static void check_ok(void)
Definition: initdb.c:2117
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_fatal(...)
#define MAXPGPATH
const void size_t len
static void adjust_data_dir(void)
Definition: pg_ctl.c:2125
static char * argv0
Definition: pg_ctl.c:93
static pid_t start_postmaster(void)
Definition: pg_ctl.c:440
static char * exec_path
Definition: pg_ctl.c:88
NameData datname
Definition: pg_database.h:35
bool datallowconn
Definition: pg_database.h:50
static char * filename
Definition: pg_dumpall.c:123
char * output_files[]
Definition: pg_upgrade.c:75
static void create_logical_replication_slots(void)
Definition: pg_upgrade.c:977
static void set_frozenxids(bool minmxid_only)
Definition: pg_upgrade.c:875
static void make_outputdirs(char *pgdata)
Definition: pg_upgrade.c:253
static void prepare_new_cluster(void)
Definition: pg_upgrade.c:520
int main(int argc, char **argv)
Definition: pg_upgrade.c:88
static void copy_subdir_files(const char *old_subdir, const char *new_subdir)
Definition: pg_upgrade.c:725
static void set_new_cluster_char_signedness(void)
Definition: pg_upgrade.c:405
OSInfo os_info
Definition: pg_upgrade.c:73
ClusterInfo new_cluster
Definition: pg_upgrade.c:72
static void create_new_objects(void)
Definition: pg_upgrade.c:572
static void remove_new_subdir(const char *subdir, bool rmtopdir)
Definition: pg_upgrade.c:708
static void copy_xact_xlog_xid(void)
Definition: pg_upgrade.c:750
ClusterInfo old_cluster
Definition: pg_upgrade.c:71
static void set_locale_and_encoding(void)
Definition: pg_upgrade.c:441
static void setup(char *argv0)
Definition: pg_upgrade.c:338
#define RESTORE_TRANSACTION_SIZE
Definition: pg_upgrade.c:58
static void prepare_new_globals(void)
Definition: pg_upgrade.c:550
void transfer_all_new_tablespaces(DbInfoArr *old_db_arr, DbInfoArr *new_db_arr, char *old_pgdata, char *new_pgdata)
#define SERVER_START_LOG_FILE
Definition: pg_upgrade.h:67
void check_pghost_envvar(void)
Definition: server.c:376
#define MULTIXACT_FORMATCHANGE_CAT_VER
Definition: pg_upgrade.h:115
PGresult char * cluster_conn_opts(ClusterInfo *cluster)
Definition: server.c:92
PGconn * connectToServer(ClusterInfo *cluster, const char *db_name)
Definition: server.c:28
#define LOG_OUTPUTDIR
Definition: pg_upgrade.h:40
#define GLOBALS_DUMP_FILE
Definition: pg_upgrade.h:30
#define DB_DUMP_LOG_FILE_MASK
Definition: pg_upgrade.h:43
#define UTILITY_LOG_FILE
Definition: pg_upgrade.h:45
void cleanup_output_dirs(void)
Definition: util.c:63
void void pg_log(eLogType type, const char *fmt,...) pg_attribute_printf(2
@ TRANSFER_MODE_LINK
Definition: pg_upgrade.h:264
@ TRANSFER_MODE_SWAP
Definition: pg_upgrade.h:265
#define SERVER_LOG_FILE
Definition: pg_upgrade.h:44
PGresult * executeQueryOrDie(PGconn *conn, const char *fmt,...) pg_attribute_printf(2
#define EXEC_PSQL_ARGS
Definition: pg_upgrade.h:405
LogOpts log_opts
Definition: util.c:17
void void prep_status_progress(const char *fmt,...) pg_attribute_printf(1
void void pg_noreturn void void end_progress_output(void)
Definition: util.c:43
#define fopen_priv(path, mode)
Definition: pg_upgrade.h:430
#define DUMP_OUTPUTDIR
Definition: pg_upgrade.h:41
@ PG_STATUS
Definition: pg_upgrade.h:274
@ PG_REPORT
Definition: pg_upgrade.h:276
#define BASE_OUTPUTDIR
Definition: pg_upgrade.h:39
#define GET_MAJOR_VERSION(v)
Definition: pg_upgrade.h:27
void stop_postmaster(bool in_atexit)
Definition: server.c:349
void prep_status(const char *fmt,...) pg_attribute_printf(1
#define INTERNAL_LOG_FILE
Definition: pg_upgrade.h:46
#define DB_DUMP_FILE_MASK
Definition: pg_upgrade.h:31
char * last_dir_separator(const char *filename)
Definition: path.c:145
void canonicalize_path(char *path)
Definition: path.c:337
#define snprintf
Definition: port.h:239
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
void get_restricted_token(void)
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:13019
UserOpts user_opts
Definition: option.c:30
void parseCommandLine(int argc, char *argv[])
Definition: option.c:39
void get_sock_dir(ClusterInfo *cluster)
Definition: option.c:499
PGconn * conn
Definition: streamutil.c:52
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:446
char * pgdata
Definition: pg_upgrade.h:292
ControlData controldata
Definition: pg_upgrade.h:289
char * bindir
Definition: pg_upgrade.h:295
DbInfoArr dbarr
Definition: pg_upgrade.h:291
uint32 major_version
Definition: pg_upgrade.h:300
DbLocaleInfo * template0
Definition: pg_upgrade.h:290
uint32 chkpnt_nxtxid
Definition: pg_upgrade.h:234
uint32 chkpnt_nxtoid
Definition: pg_upgrade.h:236
char nextxlogfile[25]
Definition: pg_upgrade.h:233
uint32 chkpnt_nxtmxoff
Definition: pg_upgrade.h:238
bool default_char_signedness
Definition: pg_upgrade.h:253
uint32 cat_ver
Definition: pg_upgrade.h:232
uint32 chkpnt_nxtmulti
Definition: pg_upgrade.h:237
uint32 chkpnt_oldstxid
Definition: pg_upgrade.h:240
uint32 chkpnt_nxtepoch
Definition: pg_upgrade.h:235
uint32 chkpnt_oldstMulti
Definition: pg_upgrade.h:239
DbInfo * dbs
Definition: pg_upgrade.h:220
LogicalSlotInfoArr slot_arr
Definition: pg_upgrade.h:203
char * db_name
Definition: pg_upgrade.h:199
Oid db_oid
Definition: pg_upgrade.h:198
char * dumpdir
Definition: pg_upgrade.h:319
char * rootdir
Definition: pg_upgrade.h:317
FILE * internal
Definition: pg_upgrade.h:313
char * basedir
Definition: pg_upgrade.h:318
char * logdir
Definition: pg_upgrade.h:320
bool verbose
Definition: pg_upgrade.h:314
LogicalSlotInfo * slots
Definition: pg_upgrade.h:174
char * sync_method
Definition: pg_upgrade.h:336
bool do_sync
Definition: pg_upgrade.h:332
bool live_check
Definition: pg_upgrade.h:331
int char_signedness
Definition: pg_upgrade.h:338
transferMode transfer_mode
Definition: pg_upgrade.h:333
bool check
Definition: pg_upgrade.h:330
int jobs
Definition: pg_upgrade.h:334
#define mkdir(a, b)
Definition: win32_port.h:80
int gettimeofday(struct timeval *tp, void *tzp)