PostgreSQL Source Code  git master
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-2024, 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 
37 
38 
39 #include "postgres_fe.h"
40 
41 #include <time.h>
42 
43 #ifdef HAVE_LANGINFO_H
44 #include <langinfo.h>
45 #endif
46 
47 #include "catalog/pg_class_d.h"
48 #include "common/file_perm.h"
49 #include "common/logging.h"
51 #include "fe_utils/string_utils.h"
52 #include "pg_upgrade.h"
53 
54 static void set_locale_and_encoding(void);
55 static void prepare_new_cluster(void);
56 static void prepare_new_globals(void);
57 static void create_new_objects(void);
58 static void copy_xact_xlog_xid(void);
59 static void set_frozenxids(bool minmxid_only);
60 static void make_outputdirs(char *pgdata);
61 static void setup(char *argv0, bool *live_check);
62 static void create_logical_replication_slots(void);
63 
67 
68 char *output_files[] = {
70 #ifdef WIN32
71  /* unique file for pg_ctl start */
73 #endif
76  NULL
77 };
78 
79 
80 int
81 main(int argc, char **argv)
82 {
83  char *deletion_script_file_name = NULL;
84  bool live_check = false;
85 
86  /*
87  * pg_upgrade doesn't currently use common/logging.c, but initialize it
88  * anyway because we might call common code that does.
89  */
90  pg_logging_init(argv[0]);
91  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_upgrade"));
92 
93  /* Set default restrictive mask until new cluster permissions are read */
94  umask(PG_MODE_MASK_OWNER);
95 
96  parseCommandLine(argc, argv);
97 
99 
102 
103  /*
104  * Set mask based on PGDATA permissions, needed for the creation of the
105  * output directories with correct permissions.
106  */
108  pg_fatal("could not read permissions of directory \"%s\": %s",
109  new_cluster.pgdata, strerror(errno));
110 
111  umask(pg_mode_mask);
112 
113  /*
114  * This needs to happen after adjusting the data directory of the new
115  * cluster in adjust_data_dir().
116  */
118 
119  setup(argv[0], &live_check);
120 
121  output_check_banner(live_check);
122 
124 
125  get_sock_dir(&old_cluster, live_check);
126  get_sock_dir(&new_cluster, false);
127 
128  check_cluster_compatibility(live_check);
129 
130  check_and_dump_old_cluster(live_check);
131 
132 
133  /* -- NEW -- */
135 
138 
140  "\n"
141  "Performing Upgrade\n"
142  "------------------");
143 
145 
147 
148  stop_postmaster(false);
149 
150  /*
151  * Destructive Changes to New Cluster
152  */
153 
155 
156  /* New now using xids of the old system */
157 
158  /* -- NEW -- */
160 
162 
164 
165  stop_postmaster(false);
166 
167  /*
168  * Most failures happen in create_new_objects(), which has completed at
169  * this point. We do this here because it is just before linking, which
170  * will link the old and new cluster data files, preventing the old
171  * cluster from being safely started once the new cluster is started.
172  */
175 
178 
179  /*
180  * Assuming OIDs are only used in system tables, there is no need to
181  * restore the OID counter because we have not transferred any OIDs from
182  * the old system, but we do it anyway just in case. We do it late here
183  * because there is no need to have the schema load use new oids.
184  */
185  prep_status("Setting next OID for new cluster");
186  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
187  "\"%s/pg_resetwal\" -o %u \"%s\"",
190  check_ok();
191 
192  /*
193  * Migrate the logical slots to the new cluster. Note that we need to do
194  * this after resetting WAL because otherwise the required WAL would be
195  * removed and slots would become unusable. There is a possibility that
196  * background processes might generate some WAL before we could create the
197  * slots in the new cluster but we can ignore that WAL as that won't be
198  * required downstream.
199  */
201  {
204  stop_postmaster(false);
205  }
206 
207  if (user_opts.do_sync)
208  {
209  prep_status("Sync data directory to disk");
210  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
211  "\"%s/initdb\" --sync-only \"%s\" --sync-method %s",
215  check_ok();
216  }
217 
218  create_script_for_old_cluster_deletion(&deletion_script_file_name);
219 
221 
223  "\n"
224  "Upgrade Complete\n"
225  "----------------");
226 
227  output_completion_banner(deletion_script_file_name);
228 
229  pg_free(deletion_script_file_name);
230 
232 
233  return 0;
234 }
235 
236 /*
237  * Create and assign proper permissions to the set of output directories
238  * used to store any data generated internally, filling in log_opts in
239  * the process.
240  */
241 static void
242 make_outputdirs(char *pgdata)
243 {
244  FILE *fp;
245  char **filename;
246  time_t run_time = time(NULL);
247  char filename_path[MAXPGPATH];
248  char timebuf[128];
249  struct timeval time;
250  time_t tt;
251  int len;
252 
253  log_opts.rootdir = (char *) pg_malloc0(MAXPGPATH);
254  len = snprintf(log_opts.rootdir, MAXPGPATH, "%s/%s", pgdata, BASE_OUTPUTDIR);
255  if (len >= MAXPGPATH)
256  pg_fatal("directory path for new cluster is too long");
257 
258  /* BASE_OUTPUTDIR/$timestamp/ */
259  gettimeofday(&time, NULL);
260  tt = (time_t) time.tv_sec;
261  strftime(timebuf, sizeof(timebuf), "%Y%m%dT%H%M%S", localtime(&tt));
262  /* append milliseconds */
263  snprintf(timebuf + strlen(timebuf), sizeof(timebuf) - strlen(timebuf),
264  ".%03d", (int) (time.tv_usec / 1000));
265  log_opts.basedir = (char *) pg_malloc0(MAXPGPATH);
267  timebuf);
268  if (len >= MAXPGPATH)
269  pg_fatal("directory path for new cluster is too long");
270 
271  /* BASE_OUTPUTDIR/$timestamp/dump/ */
272  log_opts.dumpdir = (char *) pg_malloc0(MAXPGPATH);
274  timebuf, DUMP_OUTPUTDIR);
275  if (len >= MAXPGPATH)
276  pg_fatal("directory path for new cluster is too long");
277 
278  /* BASE_OUTPUTDIR/$timestamp/log/ */
279  log_opts.logdir = (char *) pg_malloc0(MAXPGPATH);
281  timebuf, LOG_OUTPUTDIR);
282  if (len >= MAXPGPATH)
283  pg_fatal("directory path for new cluster is too long");
284 
285  /*
286  * Ignore the error case where the root path exists, as it is kept the
287  * same across runs.
288  */
289  if (mkdir(log_opts.rootdir, pg_dir_create_mode) < 0 && errno != EEXIST)
290  pg_fatal("could not create directory \"%s\": %m", log_opts.rootdir);
292  pg_fatal("could not create directory \"%s\": %m", log_opts.basedir);
294  pg_fatal("could not create directory \"%s\": %m", log_opts.dumpdir);
296  pg_fatal("could not create directory \"%s\": %m", log_opts.logdir);
297 
298  len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
300  if (len >= sizeof(filename_path))
301  pg_fatal("directory path for new cluster is too long");
302 
303  if ((log_opts.internal = fopen_priv(filename_path, "a")) == NULL)
304  pg_fatal("could not open log file \"%s\": %m", filename_path);
305 
306  /* label start of upgrade in logfiles */
307  for (filename = output_files; *filename != NULL; filename++)
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  if ((fp = fopen_priv(filename_path, "a")) == NULL)
314  pg_fatal("could not write to log file \"%s\": %m", filename_path);
315 
316  fprintf(fp,
317  "-----------------------------------------------------------------\n"
318  " pg_upgrade run on %s"
319  "-----------------------------------------------------------------\n\n",
320  ctime(&run_time));
321  fclose(fp);
322  }
323 }
324 
325 
326 static void
327 setup(char *argv0, bool *live_check)
328 {
329  /*
330  * make sure the user has a clean environment, otherwise, we may confuse
331  * libpq when we connect to one (or both) of the servers.
332  */
334 
335  /*
336  * In case the user hasn't specified the directory for the new binaries
337  * with -B, default to using the path of the currently executed pg_upgrade
338  * binary.
339  */
340  if (!new_cluster.bindir)
341  {
342  char exec_path[MAXPGPATH];
343 
344  if (find_my_exec(argv0, exec_path) < 0)
345  pg_fatal("%s: could not find own program executable", argv0);
346  /* Trim off program name and keep just path */
347  *last_dir_separator(exec_path) = '\0';
350  }
351 
353 
354  /* no postmasters should be running, except for a live check */
356  {
357  /*
358  * If we have a postmaster.pid file, try to start the server. If it
359  * starts, the pid file was stale, so stop the server. If it doesn't
360  * start, assume the server is running. If the pid file is left over
361  * from a server crash, this also allows any committed transactions
362  * stored in the WAL to be replayed so they are not lost, because WAL
363  * files are not transferred from old to new servers. We later check
364  * for a clean shutdown.
365  */
366  if (start_postmaster(&old_cluster, false))
367  stop_postmaster(false);
368  else
369  {
370  if (!user_opts.check)
371  pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
372  "Please shutdown that postmaster and try again.");
373  else
374  *live_check = true;
375  }
376  }
377 
378  /* same goes for the new postmaster */
380  {
381  if (start_postmaster(&new_cluster, false))
382  stop_postmaster(false);
383  else
384  pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
385  "Please shutdown that postmaster and try again.");
386  }
387 }
388 
389 
390 /*
391  * Copy locale and encoding information into the new cluster's template0.
392  *
393  * We need to copy the encoding, datlocprovider, datcollate, datctype, and
394  * daticulocale. We don't need datcollversion because that's never set for
395  * template0.
396  */
397 static void
399 {
400  PGconn *conn_new_template1;
401  char *datcollate_literal;
402  char *datctype_literal;
403  char *daticulocale_literal = NULL;
405 
406  prep_status("Setting locale and encoding for new cluster");
407 
408  /* escape literals with respect to new cluster */
409  conn_new_template1 = connectToServer(&new_cluster, "template1");
410 
411  datcollate_literal = PQescapeLiteral(conn_new_template1,
412  locale->db_collate,
413  strlen(locale->db_collate));
414  datctype_literal = PQescapeLiteral(conn_new_template1,
415  locale->db_ctype,
416  strlen(locale->db_ctype));
417  if (locale->db_iculocale)
418  daticulocale_literal = PQescapeLiteral(conn_new_template1,
419  locale->db_iculocale,
420  strlen(locale->db_iculocale));
421  else
422  daticulocale_literal = pg_strdup("NULL");
423 
424  /* update template0 in new cluster */
426  PQclear(executeQueryOrDie(conn_new_template1,
427  "UPDATE pg_catalog.pg_database "
428  " SET encoding = %d, "
429  " datlocprovider = '%c', "
430  " datcollate = %s, "
431  " datctype = %s, "
432  " daticulocale = %s "
433  " WHERE datname = 'template0' ",
434  locale->db_encoding,
435  locale->db_collprovider,
436  datcollate_literal,
437  datctype_literal,
438  daticulocale_literal));
439  else
440  PQclear(executeQueryOrDie(conn_new_template1,
441  "UPDATE pg_catalog.pg_database "
442  " SET encoding = %d, "
443  " datcollate = %s, "
444  " datctype = %s "
445  " WHERE datname = 'template0' ",
446  locale->db_encoding,
447  datcollate_literal,
448  datctype_literal));
449 
450  PQfreemem(datcollate_literal);
451  PQfreemem(datctype_literal);
452  PQfreemem(daticulocale_literal);
453 
454  PQfinish(conn_new_template1);
455 
456  check_ok();
457 }
458 
459 
460 static void
462 {
463  /*
464  * It would make more sense to freeze after loading the schema, but that
465  * would cause us to lose the frozenxids restored by the load. We use
466  * --analyze so autovacuum doesn't update statistics later
467  */
468  prep_status("Analyzing all rows in the new cluster");
469  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
470  "\"%s/vacuumdb\" %s --all --analyze %s",
472  log_opts.verbose ? "--verbose" : "");
473  check_ok();
474 
475  /*
476  * We do freeze after analyze so pg_statistic is also frozen. template0 is
477  * not frozen here, but data rows were frozen by initdb, and we set its
478  * datfrozenxid, relfrozenxids, and relminmxid later to match the new xid
479  * counter later.
480  */
481  prep_status("Freezing all rows in the new cluster");
482  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
483  "\"%s/vacuumdb\" %s --all --freeze %s",
485  log_opts.verbose ? "--verbose" : "");
486  check_ok();
487 }
488 
489 
490 static void
492 {
493  /*
494  * Before we restore anything, set frozenxids of initdb-created tables.
495  */
496  set_frozenxids(false);
497 
498  /*
499  * Now restore global objects (roles and tablespaces).
500  */
501  prep_status("Restoring global objects in the new cluster");
502 
503  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
504  "\"%s/psql\" " EXEC_PSQL_ARGS " %s -f \"%s/%s\"",
508  check_ok();
509 }
510 
511 
512 static void
514 {
515  int dbnum;
516 
517  prep_status_progress("Restoring database schemas in the new cluster");
518 
519  /*
520  * We cannot process the template1 database concurrently with others,
521  * because when it's transiently dropped, connection attempts would fail.
522  * So handle it in a separate non-parallelized pass.
523  */
524  for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
525  {
526  char sql_file_name[MAXPGPATH],
527  log_file_name[MAXPGPATH];
528  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
529  const char *create_opts;
530 
531  /* Process only template1 in this pass */
532  if (strcmp(old_db->db_name, "template1") != 0)
533  continue;
534 
535  pg_log(PG_STATUS, "%s", old_db->db_name);
536  snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
537  snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
538 
539  /*
540  * template1 database will already exist in the target installation,
541  * so tell pg_restore to drop and recreate it; otherwise we would fail
542  * to propagate its database-level properties.
543  */
544  create_opts = "--clean --create";
545 
546  exec_prog(log_file_name,
547  NULL,
548  true,
549  true,
550  "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
551  "--dbname postgres \"%s/%s\"",
554  create_opts,
556  sql_file_name);
557 
558  break; /* done once we've processed template1 */
559  }
560 
561  for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
562  {
563  char sql_file_name[MAXPGPATH],
564  log_file_name[MAXPGPATH];
565  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
566  const char *create_opts;
567 
568  /* Skip template1 in this pass */
569  if (strcmp(old_db->db_name, "template1") == 0)
570  continue;
571 
572  pg_log(PG_STATUS, "%s", old_db->db_name);
573  snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
574  snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
575 
576  /*
577  * postgres database will already exist in the target installation, so
578  * tell pg_restore to drop and recreate it; otherwise we would fail to
579  * propagate its database-level properties.
580  */
581  if (strcmp(old_db->db_name, "postgres") == 0)
582  create_opts = "--clean --create";
583  else
584  create_opts = "--create";
585 
586  parallel_exec_prog(log_file_name,
587  NULL,
588  "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
589  "--dbname template1 \"%s/%s\"",
592  create_opts,
594  sql_file_name);
595  }
596 
597  /* reap all children */
598  while (reap_child(true) == true)
599  ;
600 
602  check_ok();
603 
604  /*
605  * We don't have minmxids for databases or relations in pre-9.3 clusters,
606  * so set those after we have restored the schema.
607  */
609  set_frozenxids(true);
610 
611  /* update new_cluster info now that we have objects in the databases */
613 }
614 
615 /*
616  * Delete the given subdirectory contents from the new cluster
617  */
618 static void
619 remove_new_subdir(const char *subdir, bool rmtopdir)
620 {
621  char new_path[MAXPGPATH];
622 
623  prep_status("Deleting files from new %s", subdir);
624 
625  snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
626  if (!rmtree(new_path, rmtopdir))
627  pg_fatal("could not delete directory \"%s\"", new_path);
628 
629  check_ok();
630 }
631 
632 /*
633  * Copy the files from the old cluster into it
634  */
635 static void
636 copy_subdir_files(const char *old_subdir, const char *new_subdir)
637 {
638  char old_path[MAXPGPATH];
639  char new_path[MAXPGPATH];
640 
641  remove_new_subdir(new_subdir, true);
642 
643  snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, old_subdir);
644  snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, new_subdir);
645 
646  prep_status("Copying old %s to new server", old_subdir);
647 
648  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
649 #ifndef WIN32
650  "cp -Rf \"%s\" \"%s\"",
651 #else
652  /* flags: everything, no confirm, quiet, overwrite read-only */
653  "xcopy /e /y /q /r \"%s\" \"%s\\\"",
654 #endif
655  old_path, new_path);
656 
657  check_ok();
658 }
659 
660 static void
662 {
663  /*
664  * Copy old commit logs to new data dir. pg_clog has been renamed to
665  * pg_xact in post-10 clusters.
666  */
668  "pg_clog" : "pg_xact",
670  "pg_clog" : "pg_xact");
671 
672  prep_status("Setting oldest XID for new cluster");
673  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
674  "\"%s/pg_resetwal\" -f -u %u \"%s\"",
677  check_ok();
678 
679  /* set the next transaction id and epoch of the new cluster */
680  prep_status("Setting next transaction ID and epoch for new cluster");
681  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
682  "\"%s/pg_resetwal\" -f -x %u \"%s\"",
685  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
686  "\"%s/pg_resetwal\" -f -e %u \"%s\"",
689  /* must reset commit timestamp limits also */
690  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
691  "\"%s/pg_resetwal\" -f -c %u,%u \"%s\"",
696  check_ok();
697 
698  /*
699  * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
700  * (see pg_upgrade.h) and the new server is after, then we don't copy
701  * pg_multixact files, but we need to reset pg_control so that the new
702  * server doesn't attempt to read multis older than the cutoff value.
703  */
706  {
707  copy_subdir_files("pg_multixact/offsets", "pg_multixact/offsets");
708  copy_subdir_files("pg_multixact/members", "pg_multixact/members");
709 
710  prep_status("Setting next multixact ID and offset for new cluster");
711 
712  /*
713  * we preserve all files and contents, so we must preserve both "next"
714  * counters here and the oldest multi present on system.
715  */
716  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
717  "\"%s/pg_resetwal\" -O %u -m %u,%u \"%s\"",
723  check_ok();
724  }
726  {
727  /*
728  * Remove offsets/0000 file created by initdb that no longer matches
729  * the new multi-xid value. "members" starts at zero so no need to
730  * remove it.
731  */
732  remove_new_subdir("pg_multixact/offsets", false);
733 
734  prep_status("Setting oldest multixact ID in new cluster");
735 
736  /*
737  * We don't preserve files in this case, but it's important that the
738  * oldest multi is set to the latest value used by the old system, so
739  * that multixact.c returns the empty set for multis that might be
740  * present on disk. We set next multi to the value following that; it
741  * might end up wrapped around (i.e. 0) if the old cluster had
742  * next=MaxMultiXactId, but multixact.c can cope with that just fine.
743  */
744  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
745  "\"%s/pg_resetwal\" -m %u,%u \"%s\"",
750  check_ok();
751  }
752 
753  /* now reset the wal archives in the new cluster */
754  prep_status("Resetting WAL archives");
755  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
756  /* use timeline 1 to match controldata and no WAL history file */
757  "\"%s/pg_resetwal\" -l 00000001%s \"%s\"", new_cluster.bindir,
760  check_ok();
761 }
762 
763 
764 /*
765  * set_frozenxids()
766  *
767  * This is called on the new cluster before we restore anything, with
768  * minmxid_only = false. Its purpose is to ensure that all initdb-created
769  * vacuumable tables have relfrozenxid/relminmxid matching the old cluster's
770  * xid/mxid counters. We also initialize the datfrozenxid/datminmxid of the
771  * built-in databases to match.
772  *
773  * As we create user tables later, their relfrozenxid/relminmxid fields will
774  * be restored properly by the binary-upgrade restore script. Likewise for
775  * user-database datfrozenxid/datminmxid. However, if we're upgrading from a
776  * pre-9.3 database, which does not store per-table or per-DB minmxid, then
777  * the relminmxid/datminmxid values filled in by the restore script will just
778  * be zeroes.
779  *
780  * Hence, with a pre-9.3 source database, a second call occurs after
781  * everything is restored, with minmxid_only = true. This pass will
782  * initialize all tables and databases, both those made by initdb and user
783  * objects, with the desired minmxid value. frozenxid values are left alone.
784  */
785 static void
786 set_frozenxids(bool minmxid_only)
787 {
788  int dbnum;
789  PGconn *conn,
790  *conn_template1;
791  PGresult *dbres;
792  int ntups;
793  int i_datname;
794  int i_datallowconn;
795 
796  if (!minmxid_only)
797  prep_status("Setting frozenxid and minmxid counters in new cluster");
798  else
799  prep_status("Setting minmxid counter in new cluster");
800 
801  conn_template1 = connectToServer(&new_cluster, "template1");
802 
803  if (!minmxid_only)
804  /* set pg_database.datfrozenxid */
805  PQclear(executeQueryOrDie(conn_template1,
806  "UPDATE pg_catalog.pg_database "
807  "SET datfrozenxid = '%u'",
809 
810  /* set pg_database.datminmxid */
811  PQclear(executeQueryOrDie(conn_template1,
812  "UPDATE pg_catalog.pg_database "
813  "SET datminmxid = '%u'",
815 
816  /* get database names */
817  dbres = executeQueryOrDie(conn_template1,
818  "SELECT datname, datallowconn "
819  "FROM pg_catalog.pg_database");
820 
821  i_datname = PQfnumber(dbres, "datname");
822  i_datallowconn = PQfnumber(dbres, "datallowconn");
823 
824  ntups = PQntuples(dbres);
825  for (dbnum = 0; dbnum < ntups; dbnum++)
826  {
827  char *datname = PQgetvalue(dbres, dbnum, i_datname);
828  char *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
829 
830  /*
831  * We must update databases where datallowconn = false, e.g.
832  * template0, because autovacuum increments their datfrozenxids,
833  * relfrozenxids, and relminmxid even if autovacuum is turned off, and
834  * even though all the data rows are already frozen. To enable this,
835  * we temporarily change datallowconn.
836  */
837  if (strcmp(datallowconn, "f") == 0)
838  PQclear(executeQueryOrDie(conn_template1,
839  "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
841 
843 
844  if (!minmxid_only)
845  /* set pg_class.relfrozenxid */
847  "UPDATE pg_catalog.pg_class "
848  "SET relfrozenxid = '%u' "
849  /* only heap, materialized view, and TOAST are vacuumed */
850  "WHERE relkind IN ("
851  CppAsString2(RELKIND_RELATION) ", "
852  CppAsString2(RELKIND_MATVIEW) ", "
853  CppAsString2(RELKIND_TOASTVALUE) ")",
855 
856  /* set pg_class.relminmxid */
858  "UPDATE pg_catalog.pg_class "
859  "SET relminmxid = '%u' "
860  /* only heap, materialized view, and TOAST are vacuumed */
861  "WHERE relkind IN ("
862  CppAsString2(RELKIND_RELATION) ", "
863  CppAsString2(RELKIND_MATVIEW) ", "
864  CppAsString2(RELKIND_TOASTVALUE) ")",
866  PQfinish(conn);
867 
868  /* Reset datallowconn flag */
869  if (strcmp(datallowconn, "f") == 0)
870  PQclear(executeQueryOrDie(conn_template1,
871  "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
873  }
874 
875  PQclear(dbres);
876 
877  PQfinish(conn_template1);
878 
879  check_ok();
880 }
881 
882 /*
883  * create_logical_replication_slots()
884  *
885  * Similar to create_new_objects() but only restores logical replication slots.
886  */
887 static void
889 {
890  prep_status_progress("Restoring logical replication slots in the new cluster");
891 
892  for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
893  {
894  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
895  LogicalSlotInfoArr *slot_arr = &old_db->slot_arr;
896  PGconn *conn;
897  PQExpBuffer query;
898 
899  /* Skip this database if there are no slots */
900  if (slot_arr->nslots == 0)
901  continue;
902 
904  query = createPQExpBuffer();
905 
906  pg_log(PG_STATUS, "%s", old_db->db_name);
907 
908  for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
909  {
910  LogicalSlotInfo *slot_info = &slot_arr->slots[slotnum];
911 
912  /* Constructs a query for creating logical replication slots */
913  appendPQExpBuffer(query,
914  "SELECT * FROM "
915  "pg_catalog.pg_create_logical_replication_slot(");
916  appendStringLiteralConn(query, slot_info->slotname, conn);
917  appendPQExpBuffer(query, ", ");
918  appendStringLiteralConn(query, slot_info->plugin, conn);
919 
920  appendPQExpBuffer(query, ", false, %s, %s);",
921  slot_info->two_phase ? "true" : "false",
922  slot_info->failover ? "true" : "false");
923 
924  PQclear(executeQueryOrDie(conn, "%s", query->data));
925 
926  resetPQExpBuffer(query);
927  }
928 
929  PQfinish(conn);
930 
931  destroyPQExpBuffer(query);
932  }
933 
935  check_ok();
936 
937  return;
938 }
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:86
bool pid_lock_file_exists(const char *datadir)
Definition: exec.c:234
void verify_directories(void)
Definition: exec.c:265
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 PG_TEXTDOMAIN(domain)
Definition: c.h:1203
#define CppAsString2(x)
Definition: c.h:316
void output_check_banner(bool live_check)
Definition: check.c:71
void check_cluster_versions(void)
Definition: check.c:330
void check_cluster_compatibility(bool live_check)
Definition: check.c:373
void check_and_dump_old_cluster(bool live_check)
Definition: check.c:89
void issue_warnings_and_set_wal_level(void)
Definition: check.c:275
void check_new_cluster(void)
Definition: check.c:223
void report_clusters_compatible(void)
Definition: check.c:256
void create_script_for_old_cluster_deletion(char **deletion_script_file_name)
Definition: check.c:448
void output_completion_banner(char *deletion_script_file_name)
Definition: check.c:296
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:447
void disable_old_cluster(void)
Definition: controldata.c:713
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4562
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3441
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4264
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3836
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3549
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
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
void get_db_rel_and_slot_infos(ClusterInfo *cluster, bool live_check)
Definition: info.c:280
int count_old_cluster_logical_slots(void)
Definition: info.c:731
static char * locale
Definition: initdb.c:140
static void check_ok(void)
Definition: initdb.c:2029
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:2115
static char * argv0
Definition: pg_ctl.c:92
static pid_t start_postmaster(void)
Definition: pg_ctl.c:439
static char * exec_path
Definition: pg_ctl.c:87
NameData datname
Definition: pg_database.h:35
bool datallowconn
Definition: pg_database.h:50
static char * filename
Definition: pg_dumpall.c:121
char * output_files[]
Definition: pg_upgrade.c:68
static void create_logical_replication_slots(void)
Definition: pg_upgrade.c:888
static void set_frozenxids(bool minmxid_only)
Definition: pg_upgrade.c:786
static void make_outputdirs(char *pgdata)
Definition: pg_upgrade.c:242
static void prepare_new_cluster(void)
Definition: pg_upgrade.c:461
int main(int argc, char **argv)
Definition: pg_upgrade.c:81
static void copy_subdir_files(const char *old_subdir, const char *new_subdir)
Definition: pg_upgrade.c:636
OSInfo os_info
Definition: pg_upgrade.c:66
ClusterInfo new_cluster
Definition: pg_upgrade.c:65
static void create_new_objects(void)
Definition: pg_upgrade.c:513
static void remove_new_subdir(const char *subdir, bool rmtopdir)
Definition: pg_upgrade.c:619
static void copy_xact_xlog_xid(void)
Definition: pg_upgrade.c:661
ClusterInfo old_cluster
Definition: pg_upgrade.c:64
static void set_locale_and_encoding(void)
Definition: pg_upgrade.c:398
static void setup(char *argv0, bool *live_check)
Definition: pg_upgrade.c:327
static void prepare_new_globals(void)
Definition: pg_upgrade.c:491
void transfer_all_new_tablespaces(DbInfoArr *old_db_arr, DbInfoArr *new_db_arr, char *old_pgdata, char *new_pgdata)
Definition: relfilenumber.c:29
#define SERVER_START_LOG_FILE
Definition: pg_upgrade.h:67
void check_pghost_envvar(void)
Definition: server.c:369
#define MULTIXACT_FORMATCHANGE_CAT_VER
Definition: pg_upgrade.h:116
#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:259
#define SERVER_LOG_FILE
Definition: pg_upgrade.h:44
#define EXEC_PSQL_ARGS
Definition: pg_upgrade.h:391
LogOpts log_opts
Definition: util.c:17
void void prep_status_progress(const char *fmt,...) pg_attribute_printf(1
#define fopen_priv(path, mode)
Definition: pg_upgrade.h:413
#define DUMP_OUTPUTDIR
Definition: pg_upgrade.h:41
@ PG_STATUS
Definition: pg_upgrade.h:268
@ PG_REPORT
Definition: pg_upgrade.h:270
#define BASE_OUTPUTDIR
Definition: pg_upgrade.h:39
PGconn * connectToServer(ClusterInfo *cluster, const char *db_name)
Definition: server.c:28
#define GET_MAJOR_VERSION(v)
Definition: pg_upgrade.h:27
void stop_postmaster(bool in_atexit)
Definition: server.c:342
void prep_status(const char *fmt,...) pg_attribute_printf(1
#define INTERNAL_LOG_FILE
Definition: pg_upgrade.h:46
void end_progress_output(void)
Definition: util.c:43
PGresult char * cluster_conn_opts(ClusterInfo *cluster)
Definition: server.c:92
PGresult * executeQueryOrDie(PGconn *conn, const char *fmt,...) pg_attribute_printf(2
#define DB_DUMP_FILE_MASK
Definition: pg_upgrade.h:31
char * last_dir_separator(const char *filename)
Definition: path.c:139
void canonicalize_path(char *path)
Definition: path.c:264
#define strerror
Definition: port.h:251
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
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 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:11975
void get_sock_dir(ClusterInfo *cluster, bool live_check)
Definition: option.c:469
UserOpts user_opts
Definition: option.c:30
void parseCommandLine(int argc, char *argv[])
Definition: option.c:39
PGconn * conn
Definition: streamutil.c:54
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
char * pgdata
Definition: pg_upgrade.h:286
ControlData controldata
Definition: pg_upgrade.h:283
char * bindir
Definition: pg_upgrade.h:289
DbInfoArr dbarr
Definition: pg_upgrade.h:285
uint32 major_version
Definition: pg_upgrade.h:294
DbLocaleInfo * template0
Definition: pg_upgrade.h:284
uint32 chkpnt_nxtxid
Definition: pg_upgrade.h:231
uint32 chkpnt_nxtoid
Definition: pg_upgrade.h:233
char nextxlogfile[25]
Definition: pg_upgrade.h:230
uint32 chkpnt_nxtmxoff
Definition: pg_upgrade.h:235
uint32 cat_ver
Definition: pg_upgrade.h:229
uint32 chkpnt_nxtmulti
Definition: pg_upgrade.h:234
uint32 chkpnt_oldstxid
Definition: pg_upgrade.h:237
uint32 chkpnt_nxtepoch
Definition: pg_upgrade.h:232
uint32 chkpnt_oldstMulti
Definition: pg_upgrade.h:236
DbInfo * dbs
Definition: pg_upgrade.h:217
LogicalSlotInfoArr slot_arr
Definition: pg_upgrade.h:199
char * db_name
Definition: pg_upgrade.h:195
Oid db_oid
Definition: pg_upgrade.h:194
char * dumpdir
Definition: pg_upgrade.h:312
char * rootdir
Definition: pg_upgrade.h:310
FILE * internal
Definition: pg_upgrade.h:306
char * basedir
Definition: pg_upgrade.h:311
char * logdir
Definition: pg_upgrade.h:313
bool verbose
Definition: pg_upgrade.h:307
LogicalSlotInfo * slots
Definition: pg_upgrade.h:170
char * sync_method
Definition: pg_upgrade.h:329
bool do_sync
Definition: pg_upgrade.h:325
transferMode transfer_mode
Definition: pg_upgrade.h:326
bool check
Definition: pg_upgrade.h:323
#define mkdir(a, b)
Definition: win32_port.h:80
int gettimeofday(struct timeval *tp, void *tzp)