LCOV - code coverage report
Current view: top level - src/bin/pg_upgrade - pg_upgrade.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 83.6 % 323 270
Test Date: 2026-07-07 03:15:33 Functions: 100.0 % 14 14
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 60.3 % 116 70

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

Generated by: LCOV version 2.0-1