Sub topic 2
Upgrading PostgreSQL Major Versions with pg_upgrade
Preparing for the upgrade
This chapter assumes you know basic PostgreSQL administration, can use pg_ctl and initdb, and work comfortably at the Linux command line. A major upgrade, such as moving from PostgreSQL 16 to 17, changes the on-disk data format. The new server cannot start on the old data directory, so you need a separate new cluster and a tool to move the data. pg_upgrade is that tool.
Before you start, read the release notes for every major version you cross. Back up the old cluster with pg_dump or pg_basebackup. Install the new server binaries, and install or rebuild every extension for the new version. Keep the old binaries available, because pg_upgrade needs both bin directories.
Initializing the new cluster
Create an empty cluster with the new version's initdb. Match the encoding and locale of the old cluster, or the compatibility check will fail. Check the old values with SHOW server_encoding; and SHOW lc_collate;.
/opt/pg17/bin/initdb -D /data/pg17 --encoding=UTF8 --locale=en_US.UTF-8The paths and locale above are placeholders. Replace them with your own values.
Checking compatibility with --check
Stop both clusters. Then run pg_upgrade with --check. This mode reads both clusters and reports problems without changing any data.
/opt/pg17/bin/pg_upgrade \
--old-bindir=/opt/pg16/bin \
--new-bindir=/opt/pg17/bin \
--old-datadir=/data/pg16 \
--new-datadir=/data/pg17 \
--checkA clean run ends with "Clusters are compatible". Errors name the problem, such as a removed data type or an extension missing from the new binaries. Fix each one and rerun the check until it passes.
Running the upgrade
Choose a transfer mode. The default copies data files. This is the slowest option, but the old cluster stays usable for rollback. The --link option creates hard links instead of copies, which is much faster. However, the old cluster cannot be started after the new one runs.
/opt/pg17/bin/pg_upgrade \
--old-bindir=/opt/pg16/bin \
--new-bindir=/opt/pg17/bin \
--old-datadir=/data/pg16 \
--new-datadir=/data/pg17 \
--link \
--jobs=4> Note: the callout below is required format, so it is written as a fence.
Exercise
Why must both clusters be stopped before running pg_upgrade --check?
Show answer
pg_upgrade reads the control and catalog files of both clusters. A running server can change those files while the check reads them, so the results would be unreliable.