This section discusses how to upgrade your database data from one PostgreSQL release to a newer one.
Current PostgreSQL version numbers consist of a major and a minor version number. For example, in the version number 10.1, the 10 is the major version number and the 1 is the minor version number, meaning this would be the first minor release of the major release 10. For releases before PostgreSQL version 10.0, version numbers consist of three numbers, for example, 9.5.3. In those cases, the major version consists of the first two digit groups of the version number, e.g., 9.5, and the minor version is the third number, e.g., 3, meaning this would be the third minor release of the major release 9.5.
Minor releases never change the internal storage format and are always compatible with earlier and later minor releases of the same major version number. For example, version 10.1 is compatible with version 10.0 and version 10.6. Similarly, for example, 9.5.3 is compatible with 9.5.0, 9.5.1, and 9.5.6. To update between compatible versions, you simply replace the executables while the server is down and restart the server. The data directory remains unchanged — minor upgrades are that simple.
For major releases of PostgreSQL, the internal data storage format is subject to change, thus complicating upgrades. The traditional method for moving data to a new major version is to dump and restore the database, though this can be slow. A faster method is pg_upgrade. Replication methods are also available, as discussed below. (If you are using a pre-packaged version of PostgreSQL, it may provide scripts to assist with major version upgrades. Consult the package-level documentation for details.)
New major versions also typically introduce some user-visible incompatibilities, so application programming changes might be required. All user-visible changes are listed in the release notes (Appendix E); pay particular attention to the section labeled «Migration». Though you can upgrade from one major version to another without upgrading to intervening versions, you should read the major release notes of all intervening versions.
Cautious users will want to test their client applications on the new version before switching over fully; therefore, it’s often a good idea to set up concurrent installations of old and new versions. When testing a PostgreSQL major upgrade, consider the following categories of possible changes:
- Administration
-
The capabilities available for administrators to monitor and control the server often change and improve in each major release.
- SQL
-
Typically this includes new SQL command capabilities and not changes in behavior, unless specifically mentioned in the release notes.
- Library API
-
Typically libraries like libpq only add new functionality, again unless mentioned in the release notes.
- System Catalogs
-
System catalog changes usually only affect database management tools.
- Server C-language API
-
This involves changes in the backend function API, which is written in the C programming language. Such changes affect code that references backend functions deep inside the server.
19.6.1. Upgrading Data via pg_dumpall
One upgrade method is to dump data from one major version of PostgreSQL and restore it in another — to do this, you must use a logical backup tool like pg_dumpall; file system level backup methods will not work. (There are checks in place that prevent you from using a data directory with an incompatible version of PostgreSQL, so no great harm can be done by trying to start the wrong server version on a data directory.)
It is recommended that you use the pg_dump and pg_dumpall programs from the newer version of PostgreSQL, to take advantage of enhancements that might have been made in these programs. Current releases of the dump programs can read data from any server version back to 9.2.
These instructions assume that your existing installation is under the /usr/local/pgsql
directory, and that the data area is in /usr/local/pgsql/data
. Substitute your paths appropriately.
-
If making a backup, make sure that your database is not being updated. This does not affect the integrity of the backup, but the changed data would of course not be included. If necessary, edit the permissions in the file
/usr/local/pgsql/data/pg_hba.conf
(or equivalent) to disallow access from everyone except you. See Chapter 21 for additional information on access control.To back up your database installation, type:
pg_dumpall >
outputfile
To make the backup, you can use the pg_dumpall command from the version you are currently running; see Section 26.1.2 for more details. For best results, however, try to use the pg_dumpall command from PostgreSQL 15.2, since this version contains bug fixes and improvements over older versions. While this advice might seem idiosyncratic since you haven’t installed the new version yet, it is advisable to follow it if you plan to install the new version in parallel with the old version. In that case you can complete the installation normally and transfer the data later. This will also decrease the downtime.
-
Shut down the old server:
pg_ctl stop
On systems that have PostgreSQL started at boot time, there is probably a start-up file that will accomplish the same thing. For example, on a Red Hat Linux system one might find that this works:
/etc/rc.d/init.d/postgresql stop
See Chapter 19 for details about starting and stopping the server.
-
If restoring from backup, rename or delete the old installation directory if it is not version-specific. It is a good idea to rename the directory, rather than delete it, in case you have trouble and need to revert to it. Keep in mind the directory might consume significant disk space. To rename the directory, use a command like this:
mv /usr/local/pgsql /usr/local/pgsql.old
(Be sure to move the directory as a single unit so relative paths remain unchanged.)
-
Install the new version of PostgreSQL as outlined in Section 17.4.
-
Create a new database cluster if needed. Remember that you must execute these commands while logged in to the special database user account (which you already have if you are upgrading).
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
-
Restore your previous
pg_hba.conf
and anypostgresql.conf
modifications. -
Start the database server, again using the special database user account:
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
-
Finally, restore your data from backup with:
/usr/local/pgsql/bin/psql -d postgres -f
outputfile
using the new psql.
The least downtime can be achieved by installing the new server in a different directory and running both the old and the new servers in parallel, on different ports. Then you can use something like:
pg_dumpall -p 5432 | psql -d postgres -p 5433
to transfer your data.
19.6.2. Upgrading Data via pg_upgrade
The pg_upgrade module allows an installation to be migrated in-place from one major PostgreSQL version to another. Upgrades can be performed in minutes, particularly with --link
mode. It requires steps similar to pg_dumpall above, e.g., starting/stopping the server, running initdb. The pg_upgrade documentation outlines the necessary steps.
19.6.3. Upgrading Data via Replication
It is also possible to use logical replication methods to create a standby server with the updated version of PostgreSQL. This is possible because logical replication supports replication between different major versions of PostgreSQL. The standby can be on the same computer or a different computer. Once it has synced up with the primary server (running the older version of PostgreSQL), you can switch primaries and make the standby the primary and shut down the older database instance. Such a switch-over results in only several seconds of downtime for an upgrade.
This method of upgrading can be performed using the built-in logical replication facilities as well as using external logical replication systems such as pglogical, Slony, Londiste, and Bucardo.
-
Optionally move the old cluster
If you are using a version-specific installation directory, e.g.,
/opt/PostgreSQL/15
, you do not need to move the old cluster. The graphical installers all use version-specific installation directories.If your installation directory is not version-specific, e.g.,
/usr/local/pgsql
, it is necessary to move the current PostgreSQL install directory so it does not interfere with the new PostgreSQL installation. Once the current PostgreSQL server is shut down, it is safe to rename the PostgreSQL installation directory; assuming the old directory is/usr/local/pgsql
, you can do:mv /usr/local/pgsql /usr/local/pgsql.old
to rename the directory.
-
For source installs, build the new version
Build the new PostgreSQL source with
configure
flags that are compatible with the old cluster. pg_upgrade will checkpg_controldata
to make sure all settings are compatible before starting the upgrade. -
Install the new PostgreSQL binaries
Install the new server’s binaries and support files. pg_upgrade is included in a default installation.
For source installs, if you wish to install the new server in a custom location, use the
prefix
variable:make prefix=/usr/local/pgsql.new install
-
Initialize the new PostgreSQL cluster
Initialize the new cluster using
initdb
. Again, use compatibleinitdb
flags that match the old cluster. Many prebuilt installers do this step automatically. There is no need to start the new cluster. -
Install extension shared object files
Many extensions and custom modules, whether from
contrib
or another source, use shared object files (or DLLs), e.g.,pgcrypto.so
. If the old cluster used these, shared object files matching the new server binary must be installed in the new cluster, usually via operating system commands. Do not load the schema definitions, e.g.,CREATE EXTENSION pgcrypto
, because these will be duplicated from the old cluster. If extension updates are available, pg_upgrade will report this and create a script that can be run later to update them. -
Copy custom full-text search files
Copy any custom full text search files (dictionary, synonym, thesaurus, stop words) from the old to the new cluster.
-
Adjust authentication
pg_upgrade
will connect to the old and new servers several times, so you might want to set authentication topeer
inpg_hba.conf
or use a~/.pgpass
file (see Section 34.16). -
Stop both servers
Make sure both database servers are stopped using, on Unix, e.g.:
pg_ctl -D /opt/PostgreSQL/9.6 stop pg_ctl -D /opt/PostgreSQL/15 stop
or on Windows, using the proper service names:
NET STOP postgresql-9.6 NET STOP postgresql-15
Streaming replication and log-shipping standby servers can remain running until a later step.
-
Prepare for standby server upgrades
If you are upgrading standby servers using methods outlined in section Step 11, verify that the old standby servers are caught up by running pg_controldata against the old primary and standby clusters. Verify that the “Latest checkpoint location” values match in all clusters. (There will be a mismatch if old standby servers were shut down before the old primary or if the old standby servers are still running.) Also, make sure
wal_level
is not set tominimal
in thepostgresql.conf
file on the new primary cluster. -
Run pg_upgrade
Always run the pg_upgrade binary of the new server, not the old one. pg_upgrade requires the specification of the old and new cluster’s data and executable (
bin
) directories. You can also specify user and port values, and whether you want the data files linked or cloned instead of the default copy behavior.If you use link mode, the upgrade will be much faster (no file copying) and use less disk space, but you will not be able to access your old cluster once you start the new cluster after the upgrade. Link mode also requires that the old and new cluster data directories be in the same file system. (Tablespaces and
pg_wal
can be on different file systems.) Clone mode provides the same speed and disk space advantages but does not cause the old cluster to be unusable once the new cluster is started. Clone mode also requires that the old and new data directories be in the same file system. This mode is only available on certain operating systems and file systems.The
--jobs
option allows multiple CPU cores to be used for copying/linking of files and to dump and restore database schemas in parallel; a good place to start is the maximum of the number of CPU cores and tablespaces. This option can dramatically reduce the time to upgrade a multi-database server running on a multiprocessor machine.For Windows users, you must be logged into an administrative account, and then start a shell as the
postgres
user and set the proper path:RUNAS /USER:postgres "CMD.EXE" SET PATH=%PATH%;C:Program FilesPostgreSQL15bin;
and then run pg_upgrade with quoted directories, e.g.:
pg_upgrade.exe --old-datadir "C:/Program Files/PostgreSQL/9.6/data" --new-datadir "C:/Program Files/PostgreSQL/15/data" --old-bindir "C:/Program Files/PostgreSQL/9.6/bin" --new-bindir "C:/Program Files/PostgreSQL/15/bin"
Once started,
pg_upgrade
will verify the two clusters are compatible and then do the upgrade. You can usepg_upgrade --check
to perform only the checks, even if the old server is still running.pg_upgrade --check
will also outline any manual adjustments you will need to make after the upgrade. If you are going to be using link or clone mode, you should use the option--link
or--clone
with--check
to enable mode-specific checks.pg_upgrade
requires write permission in the current directory.Obviously, no one should be accessing the clusters during the upgrade. pg_upgrade defaults to running servers on port 50432 to avoid unintended client connections. You can use the same port number for both clusters when doing an upgrade because the old and new clusters will not be running at the same time. However, when checking an old running server, the old and new port numbers must be different.
If an error occurs while restoring the database schema,
pg_upgrade
will exit and you will have to revert to the old cluster as outlined in Step 17 below. To trypg_upgrade
again, you will need to modify the old cluster so the pg_upgrade schema restore succeeds. If the problem is acontrib
module, you might need to uninstall thecontrib
module from the old cluster and install it in the new cluster after the upgrade, assuming the module is not being used to store user data. -
Upgrade streaming replication and log-shipping standby servers
If you used link mode and have Streaming Replication (see Section 27.2.5) or Log-Shipping (see Section 27.2) standby servers, you can follow these steps to quickly upgrade them. You will not be running pg_upgrade on the standby servers, but rather rsync on the primary. Do not start any servers yet.
If you did not use link mode, do not have or do not want to use rsync, or want an easier solution, skip the instructions in this section and simply recreate the standby servers once pg_upgrade completes and the new primary is running.
-
Install the new PostgreSQL binaries on standby servers
Make sure the new binaries and support files are installed on all standby servers.
-
Make sure the new standby data directories do not exist
Make sure the new standby data directories do not exist or are empty. If initdb was run, delete the standby servers’ new data directories.
-
Install extension shared object files
Install the same extension shared object files on the new standbys that you installed in the new primary cluster.
-
Stop standby servers
If the standby servers are still running, stop them now using the above instructions.
-
Save configuration files
Save any configuration files from the old standbys’ configuration directories you need to keep, e.g.,
postgresql.conf
(and any files included by it),postgresql.auto.conf
,pg_hba.conf
, because these will be overwritten or removed in the next step. -
Run rsync
When using link mode, standby servers can be quickly upgraded using rsync. To accomplish this, from a directory on the primary server that is above the old and new database cluster directories, run this on the primary for each standby server:
rsync --archive --delete --hard-links --size-only --no-inc-recursive old_cluster new_cluster remote_dir
where
old_cluster
andnew_cluster
are relative to the current directory on the primary, andremote_dir
is above the old and new cluster directories on the standby. The directory structure under the specified directories on the primary and standbys must match. Consult the rsync manual page for details on specifying the remote directory, e.g.,rsync --archive --delete --hard-links --size-only --no-inc-recursive /opt/PostgreSQL/9.5 /opt/PostgreSQL/9.6 standby.example.com:/opt/PostgreSQL
You can verify what the command will do using rsync‘s
--dry-run
option. While rsync must be run on the primary for at least one standby, it is possible to run rsync on an upgraded standby to upgrade other standbys, as long as the upgraded standby has not been started.What this does is to record the links created by pg_upgrade‘s link mode that connect files in the old and new clusters on the primary server. It then finds matching files in the standby’s old cluster and creates links for them in the standby’s new cluster. Files that were not linked on the primary are copied from the primary to the standby. (They are usually small.) This provides rapid standby upgrades. Unfortunately, rsync needlessly copies files associated with temporary and unlogged tables because these files don’t normally exist on standby servers.
If you have tablespaces, you will need to run a similar rsync command for each tablespace directory, e.g.:
rsync --archive --delete --hard-links --size-only --no-inc-recursive /vol1/pg_tblsp/PG_9.5_201510051 /vol1/pg_tblsp/PG_9.6_201608131 standby.example.com:/vol1/pg_tblsp
If you have relocated
pg_wal
outside the data directories, rsync must be run on those directories too. -
Configure streaming replication and log-shipping standby servers
Configure the servers for log shipping. (You do not need to run
pg_backup_start()
andpg_backup_stop()
or take a file system backup as the standbys are still synchronized with the primary.) Replication slots are not copied and must be recreated.
-
-
Restore
pg_hba.conf
If you modified
pg_hba.conf
, restore its original settings. It might also be necessary to adjust other configuration files in the new cluster to match the old cluster, e.g.,postgresql.conf
(and any files included by it),postgresql.auto.conf
. -
Start the new server
The new server can now be safely started, and then any rsync‘ed standby servers.
-
Post-upgrade processing
If any post-upgrade processing is required, pg_upgrade will issue warnings as it completes. It will also generate script files that must be run by the administrator. The script files will connect to each database that needs post-upgrade processing. Each script should be run using:
psql --username=postgres --file=script.sql postgres
The scripts can be run in any order and can be deleted once they have been run.
Caution
In general it is unsafe to access tables referenced in rebuild scripts until the rebuild scripts have run to completion; doing so could yield incorrect results or poor performance. Tables not referenced in rebuild scripts can be accessed immediately.
-
Statistics
Because optimizer statistics are not transferred by
pg_upgrade
, you will be instructed to run a command to regenerate that information at the end of the upgrade. You might need to set connection parameters to match your new cluster. -
Delete old cluster
Once you are satisfied with the upgrade, you can delete the old cluster’s data directories by running the script mentioned when
pg_upgrade
completes. (Automatic deletion is not possible if you have user-defined tablespaces inside the old data directory.) You can also delete the old installation directories (e.g.,bin
,share
). -
Reverting to old cluster
If, after running
pg_upgrade
, you wish to revert to the old cluster, there are several options:-
If the
--check
option was used, the old cluster was unmodified; it can be restarted. -
If the
--link
option was not used, the old cluster was unmodified; it can be restarted. -
If the
--link
option was used, the data files might be shared between the old and new cluster:-
If
pg_upgrade
aborted before linking started, the old cluster was unmodified; it can be restarted. -
If you did not start the new cluster, the old cluster was unmodified except that, when linking started, a
.old
suffix was appended to$PGDATA/global/pg_control
. To reuse the old cluster, remove the.old
suffix from$PGDATA/global/pg_control
; you can then restart the old cluster. -
If you did start the new cluster, it has written to shared files and it is unsafe to use the old cluster. The old cluster will need to be restored from backup in this case.
-
-
Опубликовано: 28.09.2022
В нашей инструкции мы рассмотрим пример обновления СУБД PostgreSQL с версии 11 на версию 13. В качестве рабочей операционной системы будет использоваться CentOS, однако, с заменой путей до баз и конфигурационных файлов, можно будет выполнить обновление для других систем.
Процедура обновления состоит из нескольких шагов:
- Создание резервных копий.
- Установка и запуск PostgreSQL новой версии (она будет работать параллельно со старой).
- Запуск pg_upgrade для проверки возможности обновления.
- Запуск pg_upgrade для выполнения обновления.
- Проверка работоспособности СУБД.
- Настройка новой версии в качестве основного экземпляра сервера баз данных.
Предполагается, что у нас уже установлена одна СУБД, которую мы и будем обновлять.
Подготовка к обновлению
Установка новой СУБД
Тестирование системы перед обновлением
Обновление PostgreSQL
Проверка после обновления
Решение возможных проблем
Читайте также
Прежде чем начать
1. Операция по обновлению PostgreSQL, потенциально, опасна. Поэтому стоит позаботиться о создании резервной копии.
Подробнее процесс описан в инструкции Резервное копирование PostgreSQL.
Также, если мы работает на виртуальной машине, можно создать снапшот.
2. Заранее посмотрим список расширений, которые мы используем в текущем PostgreSQL (это делается из консоли psql):
su — postgres -c «psql»
=# dx
Мы можем увидеть что-то на подобие:
Name | Version | Schema | Description
—————+———+————+—————————————
btree_gin | 1.3 | public | support for indexing common datatypes
btree_gist | 1.5 | public | support for indexing common datatypes
В данной таблице представлен список установленных расширений postgresql. Вам нужно будет установить те же расширения для новой версии СУБД. Также обратите внимание, что некоторые расширения могут быть установлены для конкретной базы. Нужно по очереди подключиться к каждой базе:
=# c database_name
И запросить список расширений:
=> dx
После окончания работы, выходим из оболочки psql:
=> quit
Установка и запуск PostgreSQL 13
В нашей инструкции мы планируем обновление до версии 13. Установим нужный нам пакет.
Для этого необходимо установить репозиторий.
Так как в нашей системе уже установлен PostgreSQL, скорее всего, репозиторий уже настроен, но мы все же, рассмотрим его установку.
Вводим команду:
yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
* в данном примере мы установим репозиторий для CentOS 7 с архитектурой x86_64 (EL-7-x86_64). Полный список вариантов можно посмотреть по на странице репозитория PostgreSQL.
Если мы получим ошибку:
…
Error: Nothing to do… значит репозиторий уже настроен. Идем дальше.
Устанавливаем postgresql:
yum install postgresql13 postgresql13-server postgresql13-contrib
* где:
- postgresql13 — клиент.
- postgresql13-server — сервер.
- postgresql13-contrib — набор дополнительных утилит и расширений для postgresql.
Инициализируем базу для нового postgresql:
/usr/pgsql-13/bin/postgresql-13-setup initdb
Откроем конфигурационный файл для postgresql 13:
vi /var/lib/pgsql/13/data/postgresql.conf
Как минимум, нам нужно поменять порт, на котором должен запуститься наш сервер:
port = 5433
* порт по умолчанию 5432 и, скорее всего, на нем работает наш сервер версии 11, который мы будем обновлять. Поэтому мы поменяли порт, например, на 5433.
Стоит сравнить настройки для файлов postgresql.conf и pg_hba.conf. Некоторые настройки, которые явно менялись для текущей версии СУБД, стоит перенести в конфигурационные файлы нового postgresql.
Запускаем сервис для установленного PostgreSQL:
systemctl start postgresql-13
Стоит сразу проверить, запустилась ли служба и слушает ли сервис на нужном порту (мы настроили 5433):
systemctl status postgresql-13
ss -tunlp | grep :5433
Подключиться к новой версии СУБД можно командой:
su — postgres -c «PGPORT=5433 psql»
Сбор данных и запуск проверки на возможность обновления
И так, на текущий момент у нас запущены две версии postgresql (в нашем примере 11 и 13). Так как СУБД позволяет системному администратору тонко настроить расположение путей до рабочих данных и конфигов, выполним запросы, которые позволят однозначно определить их локацию.
Для текущей версии:
su — postgres -c «psql»
=# SELECT current_setting(‘data_directory’), current_setting(‘config_file’);
=# quit
Для новой:
su — postgres -c «PGPORT=5433 psql»
=# SELECT current_setting(‘data_directory’), current_setting(‘config_file’);
=# quit
Фиксируем полученные ответы. Они нам понадобятся для теста конфигурации.
Останавливаем службу postgresql для новой версии:
systemctl stop postgresql-13
Выполняем тест — в моем случае получилась такая команда:
su — postgres -c »
/usr/pgsql-13/bin/pg_upgrade
—old-datadir=/var/lib/pgsql/11/data
—new-datadir=/var/lib/pgsql/13/data
—old-bindir=/usr/pgsql-11/bin
—new-bindir=/usr/pgsql-13/bin
—old-options ‘-c config_file=/var/lib/pgsql/11/data/postgresql.conf’
—new-options ‘-c config_file=/var/lib/pgsql/13/data/postgresql.conf’
—check
«
* еще раз стоит отметить, что пути зависят от версий postgresql и индивидуальных настроек.
Если все хорошо, то мы увидим:
Performing Consistency Checks on Old Live Server
————————————————
Checking cluster versions ok
Checking database user is the install user ok
Checking database connection settings ok
Checking for prepared transactions ok
Checking for system-defined composite types in user tables ok
Checking for reg* data types in user tables ok
Checking for contrib/isn with bigint-passing mismatch ok
Checking for tables WITH OIDS ok
Checking for invalid «sql_identifier» user columns ok
Checking for presence of required libraries ok
Checking database user is the install user ok
Checking for prepared transactions ok
Checking for new cluster tablespace directories ok
*Clusters are compatible*
Мы готовы обновить СУБД.
Обновление PostgreSQL
Остается выполнить само обновление.
Сначала нужно остановить текущий экземпляр СУБД:
systemctl stop postgresql-11
Для обновления используем такую же команду, как при проверке, за исключением опции check:
su — postgres -c »
/usr/pgsql-13/bin/pg_upgrade
—old-datadir=/var/lib/pgsql/11/data
—new-datadir=/var/lib/pgsql/13/data
—old-bindir=/usr/pgsql-11/bin
—new-bindir=/usr/pgsql-13/bin
—old-options ‘-c config_file=/var/lib/pgsql/11/data/postgresql.conf’
—new-options ‘-c config_file=/var/lib/pgsql/13/data/postgresql.conf’
«
Если размер базы большой, и места на сервере не хватит для создания полной копии, мы можем добавить опцию —link. Она создает символьные ссылки вместо полноценных копий данных.
После ее работы мы должны увидеть:
Upgrade Complete
—————-
Optimizer statistics are not transferred by pg_upgrade so,
once you start the new server, consider running:
./analyze_new_cluster.sh
Running this script will delete the old cluster’s data files:
./delete_old_cluster.sh
В данном тексте предлагается перенести статистику оптимизатора на новый сервер. В двух словах, данная статистика позволяет делать большие запросы быстрее. Также, в сообщении предлагается удалить данные старого сервера.
Стартуем новый сервер:
systemctl start postgresql-13
Переносим статистику командой:
su — postgres -c «PGPORT=5433 /var/lib/pgsql/analyze_new_cluster.sh»
Тест сервера и завершение настройки
Напоследок, проверим, что наш сервер выполняет запросы и настроим ему порт по умолчанию.
Зайдем в командную оболочку нового сервера:
su — postgres -c «PGPORT=5433 psql»
На свое усмотрение, сделаем несколько запросов, чтобы убедиться в базовой работоспособности СУБД. Если запросы прошли, выходим из оболочки:
=# quit
Открываем конфигурационный файл:
vi /var/lib/pgsql/13/data/postgresql.conf
Меняем порт, на котором должен слушать сервер:
port = 5432
* ранее мы использовали порт 5433.
Перезапускаем сервер:
systemctl restart postgresql-13
Проверяем работу приложений, которые используют СУБД.
Если тесты прошли успешно и мы не использовали опцию —link при обновлении, то можно удалить данные старого кластера:
su — postgres -c «/var/lib/pgsql/delete_old_cluster.sh»
Обновление PostgreSQL можно считать, полностью, завершенным.
Возможные проблемы
В данном разделе рассмотрим проблемы, с которыми можно столкнуться при обновлении PostgreSQL.
Checking for presence of required libraries
Появляется при проверке на возможность сделать обновление. Ошибка также сопровождается текстом:
Your installation references loadable libraries that are missing from the
new installation. You can add these libraries to the new installation,
or remove the functions using them from the old installation. A list of
problem libraries is in the file:
loadable_libraries.txt
Причина: в новой версии PostgreSQL нет нужных библиотек для расширений, используемых в старой.
Решение: смотрим содержимое файла loadable_libraries.txt:
cat /var/lib/pgsql/loadable_libraries.txt
В нем перечислены библиотеки, которые нужно доустановить в новой версии. Установка расширений для postgresql, как правило, выполняется с помощью пакетного менеджера, например:
yum install pgtap_13
Однако, некоторые расширения нужно будет собирать, поэтому решение проблемы имеет индивидуальный характер.
Проблема подключения к СУБД после обновления
После завершения работы утилиты pg_upgrade и запуска службы, мы можем подключиться к СУБД от пользователя postgres, но не можем подключиться по сети или из приложения.
Причина: как правило, проблема в конфигурации pg_hba.
Решение: файл pg_hba.conf регламентирует условия подключения к СУБД — с каких узлов, для каких учетных записей, к каким базам и с помощью какого метода аутентификации. Необходимо привести в соответствие наши файлы. Данный файл находится в том же каталоге, что и основной файл конфигурации, в нашем примере это:
vi /var/lib/pgsql/11/data/pg_hba.conf
Файл для нового postgresql:
vi /var/lib/pgsql/13/data/pg_hba.conf
Также необходимо обратить внимание на методы шифрования паролей. Например, в 11 версии по умолчанию используется md5, например:
host all all 127.0.0.1/32 md5
В то время, как в 13 версии уже используется scram-sha-256:
host all all 127.0.0.1/32 scram-sha-256
Таким образом, при миграции данных в новую базу были перенесены и пароли с алгоритмом шифрования md5, а при подключении система пытается использовать scram-sha-256. Полученная таким образом последовательность не соответствует записанной, что приводит к ошибкам аутентификации. Для решения проблемы можно поменять scram-sha-256 на md5 в файле pg_hba.conf.
Читайте также
Возможно, это тоже будет интересным:
1. Установка и запуск PostgreSQL на CentOS.
2. Как работать с пользователями в PostgreSQL.
3. Как настроить удаленное подключение к PostgreSQL.
-
Optionally move the old cluster
If you are using a version-specific installation directory, e.g.,
/opt/PostgreSQL/11
, you do not need to move the old cluster. The graphical installers all use version-specific installation directories.If your installation directory is not version-specific, e.g.,
/usr/local/pgsql
, it is necessary to move the current PostgreSQL install directory so it does not interfere with the new PostgreSQL installation. Once the current PostgreSQL server is shut down, it is safe to rename the PostgreSQL installation directory; assuming the old directory is/usr/local/pgsql
, you can do:mv /usr/local/pgsql /usr/local/pgsql.old
to rename the directory.
-
For source installs, build the new version
Build the new PostgreSQL source with
configure
flags that are compatible with the old cluster. pg_upgrade will checkpg_controldata
to make sure all settings are compatible before starting the upgrade. -
Install the new PostgreSQL binaries
Install the new server’s binaries and support files. pg_upgrade is included in a default installation.
For source installs, if you wish to install the new server in a custom location, use the
prefix
variable:make prefix=/usr/local/pgsql.new install
-
Initialize the new PostgreSQL cluster
Initialize the new cluster using
initdb
. Again, use compatibleinitdb
flags that match the old cluster. Many prebuilt installers do this step automatically. There is no need to start the new cluster. -
Install extension shared object files
Many extensions and custom modules, whether from
contrib
or another source, use shared object files (or DLLs), e.g.,pgcrypto.so
. If the old cluster used these, shared object files matching the new server binary must be installed in the new cluster, usually via operating system commands. Do not load the schema definitions, e.g.,CREATE EXTENSION pgcrypto
, because these will be duplicated from the old cluster. If extension updates are available, pg_upgrade will report this and create a script that can be run later to update them. -
Copy custom full-text search files
Copy any custom full text search files (dictionary, synonym, thesaurus, stop words) from the old to the new cluster.
-
Adjust authentication
pg_upgrade
will connect to the old and new servers several times, so you might want to set authentication topeer
inpg_hba.conf
or use a~/.pgpass
file (see Section 34.15). -
Stop both servers
Make sure both database servers are stopped using, on Unix, e.g.:
pg_ctl -D /opt/PostgreSQL/9.6 stop pg_ctl -D /opt/PostgreSQL/11 stop
or on Windows, using the proper service names:
NET STOP postgresql-9.6 NET STOP postgresql-11
Streaming replication and log-shipping standby servers can remain running until a later step.
-
Prepare for standby server upgrades
If you are upgrading standby servers using methods outlined in section Step 11, verify that the old standby servers are caught up by running pg_controldata against the old primary and standby clusters. Verify that the “Latest checkpoint location” values match in all clusters. (There will be a mismatch if old standby servers were shut down before the old primary or if the old standby servers are still running.) Also, make sure
wal_level
is not set tominimal
in thepostgresql.conf
file on the new primary cluster. -
Run pg_upgrade
Always run the pg_upgrade binary of the new server, not the old one. pg_upgrade requires the specification of the old and new cluster’s data and executable (
bin
) directories. You can also specify user and port values, and whether you want the data files linked instead of the default copy behavior.If you use link mode, the upgrade will be much faster (no file copying) and use less disk space, but you will not be able to access your old cluster once you start the new cluster after the upgrade. Link mode also requires that the old and new cluster data directories be in the same file system. (Tablespaces and
pg_wal
can be on different file systems.) Seepg_upgrade --help
for a full list of options.The
--jobs
option allows multiple CPU cores to be used for copying/linking of files and to dump and restore database schemas in parallel; a good place to start is the maximum of the number of CPU cores and tablespaces. This option can dramatically reduce the time to upgrade a multi-database server running on a multiprocessor machine.For Windows users, you must be logged into an administrative account, and then start a shell as the
postgres
user and set the proper path:RUNAS /USER:postgres "CMD.EXE" SET PATH=%PATH%;C:Program FilesPostgreSQL11bin;
and then run pg_upgrade with quoted directories, e.g.:
pg_upgrade.exe --old-datadir "C:/Program Files/PostgreSQL/9.6/data" --new-datadir "C:/Program Files/PostgreSQL/11/data" --old-bindir "C:/Program Files/PostgreSQL/9.6/bin" --new-bindir "C:/Program Files/PostgreSQL/11/bin"
Once started,
pg_upgrade
will verify the two clusters are compatible and then do the upgrade. You can usepg_upgrade --check
to perform only the checks, even if the old server is still running.pg_upgrade --check
will also outline any manual adjustments you will need to make after the upgrade. If you are going to be using link mode, you should use the--link
option with--check
to enable link-mode-specific checks.pg_upgrade
requires write permission in the current directory.Obviously, no one should be accessing the clusters during the upgrade. pg_upgrade defaults to running servers on port 50432 to avoid unintended client connections. You can use the same port number for both clusters when doing an upgrade because the old and new clusters will not be running at the same time. However, when checking an old running server, the old and new port numbers must be different.
If an error occurs while restoring the database schema,
pg_upgrade
will exit and you will have to revert to the old cluster as outlined in Step 17 below. To trypg_upgrade
again, you will need to modify the old cluster so the pg_upgrade schema restore succeeds. If the problem is acontrib
module, you might need to uninstall thecontrib
module from the old cluster and install it in the new cluster after the upgrade, assuming the module is not being used to store user data. -
Upgrade Streaming Replication and Log-Shipping standby servers
If you used link mode and have Streaming Replication (see Section 26.2.5) or Log-Shipping (see Section 26.2) standby servers, you can follow these steps to quickly upgrade them. You will not be running pg_upgrade on the standby servers, but rather rsync on the primary. Do not start any servers yet.
If you did not use link mode, do not have or do not want to use rsync, or want an easier solution, skip the instructions in this section and simply recreate the standby servers once pg_upgrade completes and the new primary is running.
-
Install the new PostgreSQL binaries on standby servers
Make sure the new binaries and support files are installed on all standby servers.
-
Make sure the new standby data directories do not exist
Make sure the new standby data directories do not exist or are empty. If initdb was run, delete the standby servers’ new data directories.
-
Install extension shared object files
Install the same extension shared object files on the new standbys that you installed in the new primary cluster.
-
Stop standby servers
If the standby servers are still running, stop them now using the above instructions.
-
Save configuration files
Save any configuration files from the old standbys’ configuration directories you need to keep, e.g.,
postgresql.conf
(and any files included by it),postgresql.auto.conf
,recovery.conf
,pg_hba.conf
, because these will be overwritten or removed in the next step. -
Run rsync
When using link mode, standby servers can be quickly upgraded using rsync. To accomplish this, from a directory on the primary server that is above the old and new database cluster directories, run this on the primary for each standby server:
rsync --archive --delete --hard-links --size-only --no-inc-recursive old_cluster new_cluster remote_dir
where
old_cluster
andnew_cluster
are relative to the current directory on the primary, andremote_dir
is above the old and new cluster directories on the standby. The directory structure under the specified directories on the primary and standbys must match. Consult the rsync manual page for details on specifying the remote directory, e.g.,rsync --archive --delete --hard-links --size-only --no-inc-recursive /opt/PostgreSQL/9.5 /opt/PostgreSQL/9.6 standby.example.com:/opt/PostgreSQL
You can verify what the command will do using rsync‘s
--dry-run
option. While rsync must be run on the primary for at least one standby, it is possible to run rsync on an upgraded standby to upgrade other standbys, as long as the upgraded standby has not been started.What this does is to record the links created by pg_upgrade‘s link mode that connect files in the old and new clusters on the primary server. It then finds matching files in the standby’s old cluster and creates links for them in the standby’s new cluster. Files that were not linked on the primary are copied from the primary to the standby. (They are usually small.) This provides rapid standby upgrades. Unfortunately, rsync needlessly copies files associated with temporary and unlogged tables because these files don’t normally exist on standby servers.
If you have tablespaces, you will need to run a similar rsync command for each tablespace directory, e.g.:
rsync --archive --delete --hard-links --size-only --no-inc-recursive /vol1/pg_tblsp/PG_9.5_201510051 /vol1/pg_tblsp/PG_9.6_201608131 standby.example.com:/vol1/pg_tblsp
If you have relocated
pg_wal
outside the data directories, rsync must be run on those directories too. -
Configure streaming replication and log-shipping standby servers
Configure the servers for log shipping. (You do not need to run
pg_start_backup()
andpg_stop_backup()
or take a file system backup as the standbys are still synchronized with the primary.) Replication slots are not copied and must be recreated.
-
-
Restore
pg_hba.conf
If you modified
pg_hba.conf
, restore its original settings. It might also be necessary to adjust other configuration files in the new cluster to match the old cluster, e.g.,postgresql.conf
(and any files included by it),postgresql.auto.conf
. -
Start the new server
The new server can now be safely started, and then any rsync‘ed standby servers.
-
Post-Upgrade processing
If any post-upgrade processing is required, pg_upgrade will issue warnings as it completes. It will also generate script files that must be run by the administrator. The script files will connect to each database that needs post-upgrade processing. Each script should be run using:
psql --username=postgres --file=script.sql postgres
The scripts can be run in any order and can be deleted once they have been run.
Caution
In general it is unsafe to access tables referenced in rebuild scripts until the rebuild scripts have run to completion; doing so could yield incorrect results or poor performance. Tables not referenced in rebuild scripts can be accessed immediately.
-
Statistics
Because optimizer statistics are not transferred by
pg_upgrade
, you will be instructed to run a command to regenerate that information at the end of the upgrade. You might need to set connection parameters to match your new cluster. -
Delete old cluster
Once you are satisfied with the upgrade, you can delete the old cluster’s data directories by running the script mentioned when
pg_upgrade
completes. (Automatic deletion is not possible if you have user-defined tablespaces inside the old data directory.) You can also delete the old installation directories (e.g.,bin
,share
). -
Reverting to old cluster
If, after running
pg_upgrade
, you wish to revert to the old cluster, there are several options:-
If the
--check
option was used, the old cluster was unmodified; it can be restarted. -
If the
--link
option was not used, the old cluster was unmodified; it can be restarted. -
If the
--link
option was used, the data files might be shared between the old and new cluster:-
If
pg_upgrade
aborted before linking started, the old cluster was unmodified; it can be restarted. -
If you did not start the new cluster, the old cluster was unmodified except that, when linking started, a
.old
suffix was appended to$PGDATA/global/pg_control
. To reuse the old cluster, remove the.old
suffix from$PGDATA/global/pg_control
; you can then restart the old cluster. -
If you did start the new cluster, it has written to shared files and it is unsafe to use the old cluster. The old cluster will need to be restored from backup in this case.
-
-
-
Optionally move the old cluster
If you are using a version-specific installation directory, e.g.,
/opt/PostgreSQL/11
, you do not need to move the old cluster. The graphical installers all use version-specific installation directories.If your installation directory is not version-specific, e.g.,
/usr/local/pgsql
, it is necessary to move the current PostgreSQL install directory so it does not interfere with the new PostgreSQL installation. Once the current PostgreSQL server is shut down, it is safe to rename the PostgreSQL installation directory; assuming the old directory is/usr/local/pgsql
, you can do:mv /usr/local/pgsql /usr/local/pgsql.old
to rename the directory.
-
For source installs, build the new version
Build the new PostgreSQL source with
configure
flags that are compatible with the old cluster. pg_upgrade will checkpg_controldata
to make sure all settings are compatible before starting the upgrade. -
Install the new PostgreSQL binaries
Install the new server’s binaries and support files. pg_upgrade is included in a default installation.
For source installs, if you wish to install the new server in a custom location, use the
prefix
variable:make prefix=/usr/local/pgsql.new install
-
Initialize the new PostgreSQL cluster
Initialize the new cluster using
initdb
. Again, use compatibleinitdb
flags that match the old cluster. Many prebuilt installers do this step automatically. There is no need to start the new cluster. -
Install extension shared object files
Many extensions and custom modules, whether from
contrib
or another source, use shared object files (or DLLs), e.g.,pgcrypto.so
. If the old cluster used these, shared object files matching the new server binary must be installed in the new cluster, usually via operating system commands. Do not load the schema definitions, e.g.,CREATE EXTENSION pgcrypto
, because these will be duplicated from the old cluster. If extension updates are available, pg_upgrade will report this and create a script that can be run later to update them. -
Copy custom full-text search files
Copy any custom full text search files (dictionary, synonym, thesaurus, stop words) from the old to the new cluster.
-
Adjust authentication
pg_upgrade
will connect to the old and new servers several times, so you might want to set authentication topeer
inpg_hba.conf
or use a~/.pgpass
file (see Section 34.15). -
Stop both servers
Make sure both database servers are stopped using, on Unix, e.g.:
pg_ctl -D /opt/PostgreSQL/9.6 stop pg_ctl -D /opt/PostgreSQL/11 stop
or on Windows, using the proper service names:
NET STOP postgresql-9.6 NET STOP postgresql-11
Streaming replication and log-shipping standby servers can remain running until a later step.
-
Prepare for standby server upgrades
If you are upgrading standby servers using methods outlined in section Step 11, verify that the old standby servers are caught up by running pg_controldata against the old primary and standby clusters. Verify that the “Latest checkpoint location” values match in all clusters. (There will be a mismatch if old standby servers were shut down before the old primary or if the old standby servers are still running.) Also, make sure
wal_level
is not set tominimal
in thepostgresql.conf
file on the new primary cluster. -
Run pg_upgrade
Always run the pg_upgrade binary of the new server, not the old one. pg_upgrade requires the specification of the old and new cluster’s data and executable (
bin
) directories. You can also specify user and port values, and whether you want the data files linked instead of the default copy behavior.If you use link mode, the upgrade will be much faster (no file copying) and use less disk space, but you will not be able to access your old cluster once you start the new cluster after the upgrade. Link mode also requires that the old and new cluster data directories be in the same file system. (Tablespaces and
pg_wal
can be on different file systems.) Seepg_upgrade --help
for a full list of options.The
--jobs
option allows multiple CPU cores to be used for copying/linking of files and to dump and restore database schemas in parallel; a good place to start is the maximum of the number of CPU cores and tablespaces. This option can dramatically reduce the time to upgrade a multi-database server running on a multiprocessor machine.For Windows users, you must be logged into an administrative account, and then start a shell as the
postgres
user and set the proper path:RUNAS /USER:postgres "CMD.EXE" SET PATH=%PATH%;C:Program FilesPostgreSQL11bin;
and then run pg_upgrade with quoted directories, e.g.:
pg_upgrade.exe --old-datadir "C:/Program Files/PostgreSQL/9.6/data" --new-datadir "C:/Program Files/PostgreSQL/11/data" --old-bindir "C:/Program Files/PostgreSQL/9.6/bin" --new-bindir "C:/Program Files/PostgreSQL/11/bin"
Once started,
pg_upgrade
will verify the two clusters are compatible and then do the upgrade. You can usepg_upgrade --check
to perform only the checks, even if the old server is still running.pg_upgrade --check
will also outline any manual adjustments you will need to make after the upgrade. If you are going to be using link mode, you should use the--link
option with--check
to enable link-mode-specific checks.pg_upgrade
requires write permission in the current directory.Obviously, no one should be accessing the clusters during the upgrade. pg_upgrade defaults to running servers on port 50432 to avoid unintended client connections. You can use the same port number for both clusters when doing an upgrade because the old and new clusters will not be running at the same time. However, when checking an old running server, the old and new port numbers must be different.
If an error occurs while restoring the database schema,
pg_upgrade
will exit and you will have to revert to the old cluster as outlined in Step 17 below. To trypg_upgrade
again, you will need to modify the old cluster so the pg_upgrade schema restore succeeds. If the problem is acontrib
module, you might need to uninstall thecontrib
module from the old cluster and install it in the new cluster after the upgrade, assuming the module is not being used to store user data. -
Upgrade Streaming Replication and Log-Shipping standby servers
If you used link mode and have Streaming Replication (see Section 26.2.5) or Log-Shipping (see Section 26.2) standby servers, you can follow these steps to quickly upgrade them. You will not be running pg_upgrade on the standby servers, but rather rsync on the primary. Do not start any servers yet.
If you did not use link mode, do not have or do not want to use rsync, or want an easier solution, skip the instructions in this section and simply recreate the standby servers once pg_upgrade completes and the new primary is running.
-
Install the new PostgreSQL binaries on standby servers
Make sure the new binaries and support files are installed on all standby servers.
-
Make sure the new standby data directories do not exist
Make sure the new standby data directories do not exist or are empty. If initdb was run, delete the standby servers’ new data directories.
-
Install extension shared object files
Install the same extension shared object files on the new standbys that you installed in the new primary cluster.
-
Stop standby servers
If the standby servers are still running, stop them now using the above instructions.
-
Save configuration files
Save any configuration files from the old standbys’ configuration directories you need to keep, e.g.,
postgresql.conf
(and any files included by it),postgresql.auto.conf
,recovery.conf
,pg_hba.conf
, because these will be overwritten or removed in the next step. -
Run rsync
When using link mode, standby servers can be quickly upgraded using rsync. To accomplish this, from a directory on the primary server that is above the old and new database cluster directories, run this on the primary for each standby server:
rsync --archive --delete --hard-links --size-only --no-inc-recursive old_cluster new_cluster remote_dir
where
old_cluster
andnew_cluster
are relative to the current directory on the primary, andremote_dir
is above the old and new cluster directories on the standby. The directory structure under the specified directories on the primary and standbys must match. Consult the rsync manual page for details on specifying the remote directory, e.g.,rsync --archive --delete --hard-links --size-only --no-inc-recursive /opt/PostgreSQL/9.5 /opt/PostgreSQL/9.6 standby.example.com:/opt/PostgreSQL
You can verify what the command will do using rsync‘s
--dry-run
option. While rsync must be run on the primary for at least one standby, it is possible to run rsync on an upgraded standby to upgrade other standbys, as long as the upgraded standby has not been started.What this does is to record the links created by pg_upgrade‘s link mode that connect files in the old and new clusters on the primary server. It then finds matching files in the standby’s old cluster and creates links for them in the standby’s new cluster. Files that were not linked on the primary are copied from the primary to the standby. (They are usually small.) This provides rapid standby upgrades. Unfortunately, rsync needlessly copies files associated with temporary and unlogged tables because these files don’t normally exist on standby servers.
If you have tablespaces, you will need to run a similar rsync command for each tablespace directory, e.g.:
rsync --archive --delete --hard-links --size-only --no-inc-recursive /vol1/pg_tblsp/PG_9.5_201510051 /vol1/pg_tblsp/PG_9.6_201608131 standby.example.com:/vol1/pg_tblsp
If you have relocated
pg_wal
outside the data directories, rsync must be run on those directories too. -
Configure streaming replication and log-shipping standby servers
Configure the servers for log shipping. (You do not need to run
pg_start_backup()
andpg_stop_backup()
or take a file system backup as the standbys are still synchronized with the primary.) Replication slots are not copied and must be recreated.
-
-
Restore
pg_hba.conf
If you modified
pg_hba.conf
, restore its original settings. It might also be necessary to adjust other configuration files in the new cluster to match the old cluster, e.g.,postgresql.conf
(and any files included by it),postgresql.auto.conf
. -
Start the new server
The new server can now be safely started, and then any rsync‘ed standby servers.
-
Post-Upgrade processing
If any post-upgrade processing is required, pg_upgrade will issue warnings as it completes. It will also generate script files that must be run by the administrator. The script files will connect to each database that needs post-upgrade processing. Each script should be run using:
psql --username=postgres --file=script.sql postgres
The scripts can be run in any order and can be deleted once they have been run.
Caution
In general it is unsafe to access tables referenced in rebuild scripts until the rebuild scripts have run to completion; doing so could yield incorrect results or poor performance. Tables not referenced in rebuild scripts can be accessed immediately.
-
Statistics
Because optimizer statistics are not transferred by
pg_upgrade
, you will be instructed to run a command to regenerate that information at the end of the upgrade. You might need to set connection parameters to match your new cluster. -
Delete old cluster
Once you are satisfied with the upgrade, you can delete the old cluster’s data directories by running the script mentioned when
pg_upgrade
completes. (Automatic deletion is not possible if you have user-defined tablespaces inside the old data directory.) You can also delete the old installation directories (e.g.,bin
,share
). -
Reverting to old cluster
If, after running
pg_upgrade
, you wish to revert to the old cluster, there are several options:-
If the
--check
option was used, the old cluster was unmodified; it can be restarted. -
If the
--link
option was not used, the old cluster was unmodified; it can be restarted. -
If the
--link
option was used, the data files might be shared between the old and new cluster:-
If
pg_upgrade
aborted before linking started, the old cluster was unmodified; it can be restarted. -
If you did not start the new cluster, the old cluster was unmodified except that, when linking started, a
.old
suffix was appended to$PGDATA/global/pg_control
. To reuse the old cluster, remove the.old
suffix from$PGDATA/global/pg_control
; you can then restart the old cluster. -
If you did start the new cluster, it has written to shared files and it is unsafe to use the old cluster. The old cluster will need to be restored from backup in this case.
-
-