E.27. Postgres Pro Standard 12.1.1

Дата выпуска: 2019-12-23

E.27.1. Обзор

Этот выпуск основан на PostgreSQL 12.1 и включает все новые возможности, появившиеся в PostgreSQL 12, а также исправления ошибок, вошедшие в PostgreSQL 12.1. Подробное их описание вы можете найти в Замечаниях к выпуску PostgreSQL 12 и в Замечаниях к выпуску PostgreSQL 12.1, соответственно.

Также были перенесены все усовершенствования, разработанные для Postgres Pro Standard 11.6.1 и предыдущих версий, включая доработки ядра и модулей расширений, кроме следующих:

  • Представление pg_recovery_settings стало ненужным, так как содержимое recovery.conf было включено в postgresql.conf и теперь его можно просмотреть через системное представление pg_settings; параметры primary_conninfo, restore_command и primary_slot_name можно изменять, не перезапуская сервер.

  • Модификация, сокращающая объём записей в WAL, генерируемых при создании индексов GiST, GIN и SP-GiST, вошла в PostgreSQL 12, поэтому продукты Postgres Pro теперь включают её в несколько изменённом виде. Формат индексов не поменялся, поэтому все индексы должны остаться в рабочем состоянии.

  • Механизм PTRACK был основательно переработан и получил новый внешний API. Если ранее вы создавали резервные копии с использованием PTRACK в pg_probackup, вам нужно будет обновить pg_probackup до версии 2.2.6 или выше и настроить копирование PTRACK заново.

Список расширений и дополнительных утилит Postgres Pro Standard, а также основных видимых пользователю отличий от ванильной версии PostgreSQL приведён в Разделе 2.

Важно

Начиная с Postgres Pro 12, использовать pg_pathman не рекомендуется. Применяйте вместо него реализованное в ванильной версии декларативное секционирование, описанное в Разделе 5.11.

E.27.2. Миграция на версию 12

Вы можете перейти на Postgres Pro Standard 12 с той же или предыдущей версии PostgreSQL (которая поддерживается выбранным способом обновления) и с предыдущей версии Postgres Pro Standard. Способы обновления кластера базы данных описаны в Разделе 17.6. Если у вас возникнут проблемы при переходе на новую версию, обратитесь в службу поддержки Postgres Pro Standard. Обратный переход не поддерживается.

Для перехода с PostgreSQL или выпуска Postgres Pro Standard, базирующегося на предыдущей основной версии PostgreSQL, сначала установите его последний корректирующий выпуск, а затем выполните выгрузку/восстановление данных, применив pg_dumpall, или воспользуйтесь pg_upgrade:

  • Если вы решите использовать pg_upgrade, важно инициализировать новый кластер баз данных с совместимыми параметрами. В частности, обратите внимание на характеристику контрольных сумм и выбор провайдера основного правила сортировки в кластере, который вы будете обновлять. Если pg_upgrade создаст какие-либо скрипты SQL в текущем каталоге, выполните их для завершения обновления.

  • Если вы выбираете вариант с выгрузкой/восстановлением данных, не забудьте при выгрузке добавить ключ --add-collprovider, чтобы для обновляемой базы данных был установлен правильный провайдер основного правила сортировки.

Понять, какое правило сортировки является основным в старом кластере и какой провайдер оно использует, можно по значению datcollate для базы данных template0 в каталоге pg_database. Если вы производите обновление с версии, в которой провайдер основного правила сортировки не задан, опустите указание провайдера при переходе с предыдущих версий Postgres Pro или выберите провайдер libc при переходе с ванильного PostgreSQL.

Помимо этого, учтите описанные ниже особенности обновления, связанные с изменениями в использовании правил сортировки.

В Windows инсталляции Postgres Pro Standard могли содержать базы данных с правилами сортировки по умолчанию, использующими ICU, в которых имя правила имело синтаксически правильный формат языка BCP 47, но неправильный код языка или другие параметры, в результате чего это правило сортировки оказывалось недействительным для ICU.

Если эта проблема затрагивает вашу базу данных template0, при попытке инициализировать новый кластер с тем же правилом сортировки вы получите следующее сообщение об ошибке: failed to get the canonical name for collation locale (не удалось получить каноническое имя для локали правила сортировки). В этом случае выполнить обновление можно только путём выгрузки/восстановления данных, задав для нового кластера подходящую локаль для выбранного провайдера правил сортировки.

Если эта проблема затрагивает другие базы данных, вы получите то же сообщение об ошибке, что и при попытке создания в Postgres Pro нового кластера с некорректным правилом сортировки. Вы можете попытаться решить эту проблему следующим образом:

  1. Выгрузите базу данных, используя pg_dump; при этом необходимо указать параметры --create и --format=plain.

  2. Смените в выгруженном файле провайдер основного правила сортировки с '@icu' на '@libc'.

  3. Восстановите изменённое содержимое базы в psql для завершения обновления. Эта операция может прерваться ошибкой, если окажутся нарушенными какие-либо ограничения, зависящие от правил сортировки в базе данных. В этом случае вы можете попытаться разрешить эти проблемы вручную.

В некоторых особых случаях при выгрузке/восстановлении данных вы можете столкнуться с нарушением ограничений в восстанавливаемых базах данных, так что вместо этого метода лучше использовать pg_upgrade. В частности:

  • Если в инсталляции Postgres Pro Standard версии 9.6 или ниже содержались индексы или ограничения, зависящие от правил сортировки, отличных от правила сортировки, установленного для БД по умолчанию, а также от C или POSIX в базах данных с многобайтными кодировками, индексы и ограничения в таких базах могли оказаться несогласованными при обновлении до Postgres Pro версии 10 или выше. В Windows эта ситуация также могла иметь место, если база данных с многобайтной кодировкой содержала индексы или ограничения, зависящие от правила сортировки по умолчанию, имевшего полное имя "Russian_Russia[.кодировка]" или "English_United States[.кодировка]".

  • При обновлении с Postgres Pro Standard версии 10 кластеров, в которых нет информации о версии библиотеки ICU, состояние актуальности индексов и ограничений определяется по версиям правил сортировки. Однако для кластеров, в которых содержатся базы данных с системными правилами сортировки ICU, но отсутствует информация о версии библиотеки ICU и/или версиях правил сортировки, нет никакой возможности удостовериться в том, что в текущей версии Postgres Pro используется та же версия библиотеки ICU.

  • В Windows у кластеров Postgres Pro Standard 10 с правилами сортировки по умолчанию, использующими ICU, локаль правила сортировки может не совпадать с локалью соответствующего правила сортировки libc.

Когда вы используете программу pg_upgrade, она объявляет такие индексы и ограничения нерабочими и создаёт для их исправления файлы reindex_text_indexes.sql и validate_text_constraints.sql, соответственно. Для завершения обновления вам надо будет выполнить эти скрипты.

Примечание

Во избежание конфликтов в системах Linux не используйте пакет postgrespro-std-12 для установки исполняемых файлов Postgres Pro, а установите вместо него отдельные пакеты компонентов продукта. В этом случае режим автозапуска сервера, если он требуется, нужно будет включить вручную. Подробнее о предоставляемых пакетах вы можете узнать в Главе 16.

Другие особенности обновления, присущие и ванильной версии PostgreSQL, описаны в Разделе E.50.

E.27. Postgres Pro Standard 12.1.1

Release Date: 2019-12-23

E.27.1. Overview

This release is based on PostgreSQL 12.1 and includes all the new features introduced in PostgreSQL 12, as well as bug fixes implemented in PostgreSQL 12.1. For their detailed description, see PostgreSQL 12 Release Notes and PostgreSQL 12.1 Release Notes, respectively.

All the features developed for Postgres Pro Standard 11.6.1 or lower have been ported, including core patches and extension modules, except for the following:

  • The pg_recovery_settings view is no longer required because the recovery.conf settings have been integrated into postgresql.conf and can now be viewed via the pg_settings system view; primary_conninfo, restore_command, and primary_slot_name parameters can still be changed without restarting the server.

  • Reduction of WAL overhead for creation of GiST, GIN, and SP-GiST indexes has been committed to PostgreSQL 12, so Postgres Pro now inherits its modified implementation. The index format has not changed, so all these indexes should remain valid.

  • PTRACK has been thoroughly reworked and now has a new API. If you have been taking PTRACK backups using pg_probackup, you will have to upgrade it to version 2.2.6 or higher.

For the list of extension modules and utilities specific to Postgres Pro Standard, as well as the main user-visible core changes as compared to vanilla PostgreSQL, see Section 2.

Important

Starting from Postgres Pro 12, using pg_pathman is not recommended. Use vanilla declarative partitioning instead, as described in Section 5.11.

E.27.2. Migration to Version 12

You can migrate to Postgres Pro Standard 12 from the same or a previous version of PostgreSQL (that is supported by the upgrade method chosen) and from a previous version of Postgres Pro Standard. See Section 17.6 for the methods to upgrade your database cluster. Consult the Postgres Pro Standard support team if you experience issues during migration. Backward migration is not supported.

To migrate from PostgreSQL or a Postgres Pro Standard release based on a previous PostgreSQL major version, make sure to install its latest available minor version and then perform a dump/restore using pg_dumpall or use the pg_upgrade utility:

  • If you choose to run pg_upgrade, make sure to initialize the new database cluster with compatible parameters. In particular, pay attention to the provider of the default collation and the checksum settings in the cluster you are migrating from. If pg_upgrade creates any SQL files in its current directory, run these files to complete the upgrade.

  • If you are opting for a dump/restore, do not forget to use the --add-collprovider option to correctly choose the provider for the default collation of the migrated database.

To find out the default collation and its provider in the original cluster, see the datcollate value for the template0 database in the pg_database catalog. If you are upgrading from a version where provider of the default collation is not specified, use libc provider if upgrading from vanilla PostgreSQL, and omit the provider if upgrading from earlier versions of Postgres Pro.

Besides, note the following collation-related upgrade specifics described below.

On Windows, Postgres Pro Standard installations could contain databases with default collations provided by ICU, where the name of the database default collation used a syntactically correct BCP 47 language tag format, but had a wrong language code or other parameters, which invalidated the database default collation name for ICU.

If this issue affects the template0 database, you will get the following error message when trying to initialize the cluster with the same collation: failed to get the canonical name for collation locale. In this case, you can only use dump/restore for upgrade, specifying a valid locale for the selected collation provider.

If this issue affects other databases, you will get the same error message when Postgres Pro tries to create these databases with invalid collation in the new cluster. In this case, you can try the following:

  1. Make a dump of the database using pg_dump; it is required to use --create and --format=plain options.

  2. Change the provider for the default collation of the database in the dump file from '@icu' to '@libc'.

  3. In psql, restore the modified dump to complete the upgrade. This operation may fail if any constraints depending on the database collations are violated. In this case, you can try resolving the issues manually.

In some corner cases, using dump/restore could lead to invalid constraints in the restored databases, so you should use pg_upgrade. For example:

  • If the installation of Postgres Pro Standard 9.6 or lower contained any indexes or constraints depending on collations other than the default collation of the database, C, or POSIX in databases with multibyte encodings, indexes and constraints in such databases could become inconsistent when these databases are migrated to Postgres Pro 10 or higher. On Windows, this situation can also happen if the database with a multibyte encoding contained any indexes or constraints depending on the default collation with a verbose name, such as "Russian_Russia[.encoding]" or "English_United States[.encoding]".

  • For upgrades from Postgres Pro Standard 10, if the cluster has no information about the ICU library version, the ICU collation versions are checked to ensure that indexes and constraints remain valid after the upgrade. However, for clusters that contain databases with default ICU collations but have no information about the ICU library version and/or its collation versions, it is impossible to check that the current version of Postgres Pro uses the same version of the ICU library.

  • On Windows, in Postgres Pro Standard 10 clusters with default collations provided by ICU, the ICU collation locale may not match the corresponding libc collation locale.

If you use pg_upgrade, it declares such indexes and constraints invalid and creates reindex_text_indexes.sql and validate_text_constraints.sql, respectively. You have to run these files to complete the upgrade.

Note

To avoid conflicts on Linux systems, do not use the postgrespro-std-12 package to install the new Postgres Pro binaries. Use the individual packages instead. In this case, server autostart needs to be enabled manually, if required. For details on the available packages, see Chapter 16.

For other upgrade requirements imposed by vanilla PostgreSQL, see Section E.50.

FAQ