9.27. Функции для системного администрирования

Функции, описанные в этом разделе, предназначены для контроля и управления сервером Postgres Pro.

9.27.1. Функции для управления конфигурацией

В Таблице 9.83 показаны функции, позволяющие получить и изменить значения параметров конфигурации выполнения.

Таблица 9.83. Функции для управления конфигурацией

Функция

Описание

Пример(ы)

current_setting ( setting_name text [, missing_ok boolean] ) → text

Выдаёт текущее значение параметра setting_name. Если такого параметра нет, current_setting выдаёт ошибку, если только дополнительно не передан параметр missing_ok со значением true (в этом случае выдаётся NULL). Эта функция соответствует SQL-команде SHOW.

current_setting('datestyle')ISO, MDY

set_config ( setting_name text, new_value text, is_local boolean ) → text

Устанавливает для параметра setting_name значение new_value и возвращает это значение. Если параметр is_local равен true, новое значение будет действовать только в рамках текущей транзакции. Чтобы это значение действовало на протяжении текущего сеанса, присвойте этому параметру false. Эта функция соответствует SQL-команде SET.

set_config('log_statement_stats', 'off', false)off

pg_backend_set_config ( pid int, config text, wait int default 0 ) → boolean

Устанавливает в обслуживающем процессе с заданным идентификатором один или несколько параметров, указываемых в строке config. Все эти параметры должны записываться в соответствии с правилами postgresql.conf в отдельных строках, в формате имя=значение. Функция pg_backend_set_config воздействует только на параметры времени выполнения. При вызове она изменяет текущую конфигурацию до завершения сеанса или до следующего вызова pg_backend_set_config. Вносимые ей изменения вступают в силу с началом следующей транзакции.

Если дополнительный wait параметр не задан, функция возвращает true, не дожидаясь ответа от целевого обслуживающего процесса. Если этот параметр задан, функция ожидает, пока целевой процесс подтвердит получение команды, в течение указанного этим параметром интервала времени в секундах. Если подтверждение поступит за указанное время, результатом функции будет true, в противном случае — false. Заметьте, что возвращаемое значение не отражает действительный результат операции.

pg_backend_load_library ( pid int, name text, wait int default 0 ) → boolean

Загружает библиотеку с указанным именем в процесс с заданным идентификатором. За один вызов функции можно загрузить только одну библиотеку. При запуске без привилегий суперпользователя функция pg_backend_load_library позволяет загружать только те библиотеки, которые расположены в $libdir/plugins. Если вам нужно загрузить библиотеку из другого места, запустите эту функцию от имени суперпользователя.

Если дополнительный wait параметр не задан, функция возвращает true, не дожидаясь ответа от целевого обслуживающего процесса. Если этот параметр задан, функция ожидает, пока целевой процесс подтвердит получение команды, в течение указанного этим параметром интервала времени в секундах. Если подтверждение поступит за указанное время, результатом функции будет true, в противном случае — false. Заметьте, что возвращаемое значение не отражает действительный результат операции.


Функции pg_backend_set_config и pg_backend_load_library предназначены для изменения параметров конфигурации и загрузки общих библиотек в другие сеансы. Это может быть полезно для трассировки сеансов с необычным поведением. Во избежание угроз безопасности эти функции разрешено вызывать только суперпользователю.

Примечание

Эту функциональность нельзя использовать со встроенным пулом соединений, описанным в Главе 33.

В случаях сбоя при изменении конфигурации функцией pg_backend_set_config или при загрузке библиотеки функцией pg_backend_load_library в целевом процессе происходит ошибка, и текущая команда в этом процессе прерывается.

Рассмотрим следующие примеры:

SELECT pg_backend_set_config(pg_backend_pid(), 'statement_timeout=10000');
 pg_backend_set_config
-----------------------
 t
(1 row)

SELECT pg_backend_set_config(pg_backend_pid(),
       'statement_timeout=20000
        lock_timeout=10000');
 pg_backend_set_config
-----------------------
 t
(1 row)

SELECT pg_backend_set_config(pg_backend_pid(), 'fsync=on');
ERROR:  parameter "fsync" cannot be changed now

SELECT pg_backend_set_config(pg_backend_pid(), 'log_min_messages=INFO');
ERROR:  permission denied to set parameter "log_min_messages"

SELECT pg_backend_load_library(pg_backend_pid(), 'pgoutput');
 pg_backend_load_library
-------------------------
 t
(1 row)

Если параметр config, переданный функции pg_backend_set_config, содержит синтаксическую ошибку, функция возвращает соответствующее сообщение об ошибке.

Рассмотрим следующий пример:

SELECT pg_backend_set_config(pg_backend_pid(), 'test_param', 100000);
ERROR: syntax error in file "base/pgsql_tmp/pgsql_tmp87011.4" line 0, near end of line

9.27.2. Функции для передачи сигналов серверу

Функции, перечисленные в Таблице 9.84, позволяют передавать управляющие сигналы другим серверным процессам. Вызывать эти функции по умолчанию разрешено только суперпользователям, но доступ к ним можно дать и другим пользователям командой GRANT, кроме явно отмеченных исключений.

Каждая из этих функций возвращает true при успешном завершении и false в противном случае.

Таблица 9.84. Функции для передачи сигналов серверу

Функция

Описание

pg_cancel_backend ( pid integer ) → boolean

Отменяет текущий запрос в сеансе, который обслуживается процессом с заданным PID. Это действие разрешается и ролям, являющимся членами роли, запрос которой отменяется, и ролям, которым дано право pg_signal_backend; однако только суперпользователям разрешено отменять запросы других суперпользователей.

pg_reload_conf () → boolean

Даёт всем процессам сервера Postgres Pro команду перегрузить файлы конфигурации. (Для этого посылается сигнал SIGHUP главному процессу, который, в свой очередь, посылает SIGHUP всем своим дочерним процессам.)

pg_rotate_logfile () → boolean

Указывает менеджеру журнала сообщений немедленно переключиться на новый файл. Это имеет смысл, только когда работает встроенный сборщик сообщений, так как без него подпроцесс менеджера журнала не запускается.

pg_terminate_backend ( pid integer ) → boolean

Завершает сеанс, который обслуживается процессом с заданным PID. Это действие разрешается и ролям, являющимся членами роли, процесс которой прерывается, и ролям, которым дано право pg_signal_backend; однако только суперпользователям разрешено прерывать обслуживающие процессы других суперпользователей.


pg_cancel_backend и pg_terminate_backend передают сигналы (SIGINT и SIGTERM, соответственно) серверному процессу с заданным кодом PID. Код активного процесса можно получить из столбца pid представления pg_stat_activity или просмотрев на сервере процессы с именем postgres (используя ps в Unix или Диспетчер задач в Windows). Роль пользователя активного процесса можно узнать в столбце usename представления pg_stat_activity.

9.27.3. Функции управления резервным копированием

Функции, перечисленные в Таблице 9.85, предназначены для выполнения резервного копирования «на ходу». Эти функции нельзя выполнять во время восстановления (за исключением немонопольных вариантов pg_start_backup и pg_stop_backup, а также функций pg_is_in_backup, pg_backup_start_time и pg_wal_lsn_diff).

Подробнее практическое применение этих функций описывается в Разделе 25.3.

Таблица 9.85. Функции управления резервным копированием

Функция

Описание

pg_create_restore_point ( name text ) → pg_lsn

Создаёт в журнале предзаписи именованный маркер, который можно использовать как цель при восстановлении, и возвращает соответствующую ему позицию в журнале. Полученное имя затем можно указать в параметре recovery_target_name, определив тем самым точку, до которой будет выполняться восстановление. Учтите, что если будет создано несколько точек восстановления с одним именем, восстановление остановится на первой точке с этим именем.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_current_wal_flush_lsn () → pg_lsn

Выдаёт текущую позицию сброса данных в журнале предзаписи (см. примечания ниже).

pg_current_wal_insert_lsn () → pg_lsn

Выдаёт текущую позицию добавления в журнале предзаписи (см. примечания ниже).

pg_current_wal_lsn () → pg_lsn

Выдаёт текущую позицию записи в журнале предзаписи (см. примечания ниже).

pg_start_backup ( label text [, fast boolean [, exclusive boolean]] ) → pg_lsn

Подготавливает сервер к резервному копированию «на лету». Единственный обязательный параметр задаёт произвольную пользовательскую метку резервной копии. (Обычно это имя, которое получит файл резервной копии.) Если необязательный второй параметр задан и имеет значение true, функция pg_start_backup должна выполниться максимально быстро. Это означает, что принудительно будет выполнена контрольная точка, вследствие чего кратковременно увеличится нагрузка на ввод-вывод и параллельно выполняемые запросы могут замедлиться. Необязательный третий параметр указывает, будет ли резервное копирование выполняться в немонопольном или монопольном режиме (по умолчанию).

При копировании в монопольном режиме эта функция записывает файл метки (backup_label) и, если есть ссылки в каталоге pg_tblspc/, файл карты табличных пространств (tablespace_map) в каталог данных кластера БД, выполняет процедуру контрольной точки, а затем возвращает начальную позицию создаваемой копии в журнале предзаписи. (Результат этой функции может быть полезен, но если он не нужен, его можно просто игнорировать.) При копировании в немонопольном режиме содержимое этих файлов выдаётся функцией pg_stop_backup, и должно быть записано в архивную копию внешними средствами.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_stop_backup ( exclusive boolean [, wait_for_archive boolean] ) → setof record ( lsn pg_lsn, labelfile text, spcmapfile text )

Завершает процедуру немонопольного или монопольного копирования «на лету». Значение параметра exclusive должно соответствовать тому, что было передано в предшествующем вызове pg_start_backup. При монопольном копировании pg_stop_backup удаляет файл метки (и файл tablespace_map, если он существует), созданный функцией pg_start_backup. При немонопольном копировании ожидаемое содержимое этих файлов возвращается в результате этой функции и должно быть записано в файлы в архиве (не в каталоге данных).

У этой функции есть также необязательный второй параметр типа boolean. Если он равен false, pg_stop_backup завершится сразу после окончания резервного копирования, не дожидаясь архивации WAL. Это поведение полезно только для программ резервного копирования, которые осуществляют архивацию WAL независимо. Если же WAL не будет заархивирован вовсе, резервная копия может оказаться неполной, и, как следствие, непригодной для восстановления. Когда он равен true (по умолчанию), pg_stop_backup будет ждать выполнения архивации WAL, если архивирование включено. Для резервного сервера это означает, что ожидание возможно только при условии archive_mode = always. Если активность записи на ведущем сервере невысока, может иметь смысл выполнить на нём pg_switch_wal для немедленного переключения сегмента.

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

В результате эта функция выдаёт единственную запись. Столбец lsn в ней содержит позицию завершения копирования в журнале предзаписи (её также можно игнорировать). Второй и третий столбцы после окончания монопольного копирования содержат NULL, а после немонопольного — ожидаемое содержимое файлов метки и карты табличных пространств.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_stop_backup () → pg_lsn

Завершает процедуру монопольного копирования «на лету». Вызов этой упрощённой вариации равнозначен pg_stop_backup(true, true), за исключением того, что в результате выдаётся только pg_lsn.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_is_in_backup () → boolean

Возвращает true, если в данный момент выполняется исключительное резервное копирование.

pg_backup_start_time () → timestamp with time zone

Выдаёт время начала исключительного резервного копирования, если оно выполняется в данный момент, иначе — NULL.

pg_switch_wal () → pg_lsn

Производит принудительное переключение журнала предзаписи на новый файл, что позволяет архивировать текущий (в предположении, что выполняется непрерывная архивация). Результат функции — конечная позиция в только что законченном файле журнала предзаписи + 1. Если с момента последнего переключения файлов не было активности, отражающейся в журнале предзаписи, pg_switch_wal не делает ничего и возвращает начальную позицию в файле журнала предзаписи, используемом в данный момент.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_walfile_name ( lsn pg_lsn ) → text

Выдаёт для заданной позиции в журнале предзаписи имя соответствующего файла WAL.

pg_walfile_name_offset ( lsn pg_lsn ) → record ( file_name text, file_offset integer )

Выдаёт для заданной позиции в журнале предзаписи имя соответствующего файла и байтовое смещение в нём.

pg_wal_lsn_diff ( lsn1 pg_lsn, lsn2 pg_lsn ) → numeric

Вычисляет разницу в байтах (lsn1 - lsn2) между двумя позициями в журнале предзаписи. Полученный результат можно использовать с pg_stat_replication или с некоторыми функциями, перечисленными в Таблица 9.85, для определения задержки репликации.


pg_current_wal_lsn выводит текущую позицию записи в журнале предзаписи в том же формате, что и вышеописанные функции. pg_current_wal_insert_lsn подобным образом выводит текущую позицию добавления, а pg_current_wal_flush_lsn — позицию сброса данных журнала. Позицией добавления называется «логический» конец журнала предзаписи в любой момент времени, тогда как позиция записи указывает на конец данных, фактически вынесённых из внутренних буферов сервера, а позиция сброса показывает, до какого места данные считаются сохранёнными в надёжном хранилище. Позиция записи отмечает конец данных, которые может видеть снаружи внешний процесс, и именно она представляет интерес при копировании частично заполненных файлов журнала. Позиция добавления и позиция сброса выводятся в основном для отладки серверной части. Все эти функции выполняются в режиме «только чтение» и не требуют прав суперпользователя.

Используя функцию pg_walfile_name_offset, из значения pg_lsn можно получить имя соответствующего ему файла журнала предзаписи и байтовое смещение в этом файле. Например:

postgres=# SELECT * FROM pg_walfile_name_offset(pg_stop_backup());
        file_name         | file_offset
--------------------------+-------------
 00000001000000000000000D |     4039624
(1 row)

Родственная ей функция pg_walfile_name извлекает только имя файла журнала предзаписи. Когда заданная позиция в журнале предзаписи находится ровно на границе файлов, обе эти функции возвращают имя предыдущего файла. Обычно это поведение предпочтительно при архивировании журнала предзаписи, так как именно предыдущий файл является последним подлежащим архивации.

9.27.4. Функции управления восстановлением

Функции, показанные в Таблице 9.86, предоставляют сведения о текущем состоянии ведомого сервера. Эти функции могут выполняться как во время восстановления, так и в обычном режиме работы.

Таблица 9.86. Функции для получения информации о восстановлении

Функция

Описание

pg_is_in_recovery () → boolean

Возвращает true, если в данный момент выполняется процедура восстановления.

pg_last_wal_receive_lsn () → pg_lsn

Выдаёт позицию последней записи в журнале предзаписи, которая была получена и записана на диск в процессе потоковой репликации. Пока выполняется потоковая репликация, эта позиция постоянно увеличивается. По окончании восстановления она остаётся на записи WAL, полученной и записанной на диск последней. Если потоковая репликация отключена или ещё не запускалась, функция возвращает NULL.

pg_last_wal_replay_lsn () → pg_lsn

Выдаёт позицию последней записи в журнале предзаписи, которая была воспроизведёна при восстановлении. В процессе восстановления эта позиция постоянно увеличивается. По окончании этого процесса она остаётся на записи WAL, которая была восстановлена последней. Если сервер при запуске не выполнял процедуру восстановления, эта функция выдаёт NULL.

pg_last_xact_replay_timestamp () → timestamp with time zone

Выдаёт отметку времени последней транзакции, воспроизведённой при восстановлении. Это время, когда на главном сервере произошла фиксация или откат записи WAL для этой транзакции. Если в процессе восстановления не была воспроизведена ни одна транзакция, эта функция выдаёт NULL. В противном случае возвращаемое значение постоянно увеличивается в процессе восстановления. По окончании восстановления в нём остаётся время транзакции, которая была восстановлена последней. Если сервер при запуске не выполнял процедуру восстановления, эта функция выдаёт NULL.


Функции, перечисленные в Таблице 9.87 управляют процессом восстановления. Вызывать их в другое время нельзя.

Таблица 9.87. Функции управления восстановлением

Функция

Описание

pg_is_wal_replay_paused () → boolean

Возвращает true, если восстановление приостановлено.

pg_promote ( wait boolean DEFAULT true, wait_seconds integer DEFAULT 60 ) → boolean

Повышает статус ведомого сервера до ведущего. Если параметр wait равен true (по умолчанию), эта функция дожидается завершения операции повышения в течение wait_seconds секунд и возвращает true в случае успешного повышения или false в противном случае. Если параметр wait равен false, функция возвращает true сразу после передачи процессу postmaster сигнала SIGUSR1, инициирующего повышение.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_wal_replay_pause () → void

Приостанавливает восстановление. Когда восстановление приостановлено, запись изменений в базу не производится. В режиме «горячего резерва» все последующие запросы будут видеть один согласованный снимок базы данных, что исключает конфликты запросов до продолжения восстановления.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_wal_replay_resume () → void

Возобновляет восстановление, если оно было приостановлено.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.


Функции pg_wal_replay_pause и pg_wal_replay_resume нельзя выполнять в процессе повышения. Если повышение запрашивается, когда восстановление приостановлено, сервер выходит из состояния паузы и продолжает процедуру повышения.

Когда потоковая репликация отключена, пауза при восстановлении может длиться сколь угодно долго без каких-либо проблем. Если же потоковая репликация осуществляется, новые записи WAL продолжат поступать и заполнят весь диск рано или поздно, в зависимости от длительности паузы, интенсивности записи в WAL и объёма свободного пространства.

9.27.5. Функции синхронизации снимков

Postgres Pro позволяет синхронизировать снимки состояния между сеансами баз данных. Снимок состояния определяет, какие данные видны транзакции, работающей с этим снимком. Синхронизация снимков необходима, когда в двух или более сеансах нужно видеть одно и то же содержимое базы данных. Если в двух сеансах транзакции запускаются независимо, всегда есть вероятность, что некая третья транзакция будет зафиксирована между командами START TRANSACTION для первых двух, и в результате в одном сеансе будет виден результат третьей, а в другом — нет.

Для решения этой проблемы Postgres Pro позволяет транзакции экспортировать снимок состояния, с которым она работает. Пока экспортирующая этот снимок транзакция выполняется, другие транзакции могут импортировать его и, таким образом, увидеть абсолютно то же состояние базы данных, что видит первая транзакция. Но учтите, что любые изменения, произведённые этими транзакциями, будут не видны для других, как это и должно быть с изменениями в незафиксированных транзакциях. Таким образом, транзакции синхронизируют только начальное состояние данных, а последующие производимые в них изменения изолируются как обычно.

Снимки состояния экспортируются с помощью функции pg_export_snapshot, показанной в Таблице 9.88, и импортируются командой SET TRANSACTION.

Таблица 9.88. Функции синхронизации снимков

Функция

Описание

pg_export_snapshot () → text

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

Если необходимо, транзакция может экспортировать несколько снимков. Заметьте, что это имеет смысл только для транзакций уровня READ COMMITTED, так как транзакции уровня изоляции REPEATABLE READ и выше работают с одним снимком состояния на протяжении всего своего существования. После того как транзакция экспортировала снимок, её нельзя сделать подготовленной с помощью PREPARE TRANSACTION.


9.27.6. Функции управления репликацией

В Таблице 9.89 показаны функции, предназначенные для управления механизмом репликации и взаимодействия с ним. Чтобы изучить этот механизм детальнее, обратитесь к Подразделу 26.2.5, Подразделу 26.2.6 и Главе 52. Использовать эти функции для источников репликации разрешено только суперпользователям, а для слотов репликации — только суперпользователям и пользователям, имеющим право REPLICATION.

Многие из этих функций соответствуют командам в протоколе репликации; см. Раздел 55.4.

Функции, описанные в Подразделе 9.27.3, Подразделе 9.27.4 и Подразделе 9.27.5, также имеют отношение к репликации.

Таблица 9.89. Функции управления репликацией

Функция

Описание

pg_create_physical_replication_slot ( slot_name name [, immediately_reserve boolean, temporary boolean] ) → record ( slot_name name, lsn pg_lsn )

Создаёт новый физический слот репликации с именем slot_name. Необязательный второй параметр, когда он равен true, указывает, что LSN для этого слота репликации должен быть зарезервирован немедленно; в противном случае LSN резервируется при первом подключении клиента потоковой репликации. Передача изменений из физического слота возможна только по протоколу потоковой репликации — см. Раздел 55.4. Необязательный третий параметр, temporary, когда он равен true, указывает, что этот слот не должен постоянно храниться на диске, так как он предназначен только для текущего сеанса. Временные слоты также освобождаются при любой ошибке. Эта функция соответствует команде протокола репликации CREATE_REPLICATION_SLOT ... PHYSICAL.

pg_drop_replication_slot ( slot_name name ) → void

Удаляет физический или логический слот репликации с именем slot_name. Соответствует команде протокола репликации DROP_REPLICATION_SLOT.

pg_create_logical_replication_slot ( slot_name name, plugin name [, temporary boolean] ) → record ( slot_name name, lsn pg_lsn )

Создаёт новый логический (декодирующий) слот репликации с именем slot_name, используя модуль вывода plugin. Необязательный третий параметр, temporary, когда равен true, указывает, что этот слот не должен постоянно храниться на диске, так как предназначен только для текущего сеанса. Временные слоты также освобождаются при любой ошибке. Вызов этой функции равнозначен выполнению команды протокола репликации CREATE_REPLICATION_SLOT ... LOGICAL.

pg_copy_physical_replication_slot ( src_slot_name name, dst_slot_name name [, temporary boolean] ) → record ( slot_name name, lsn pg_lsn )

Копирует существующий слот физической репликации с именем src_slot_name в слот с именем dst_slot_name. Скопированный слот физической репликации начинает резервировать WAL с того же последовательного номера LSN, что и исходный слот. Параметр temporary является необязательным и позволяет указать, будет ли слот временным. Если параметр temporary опущен, сохраняется то же свойство, что имеет исходный слот.

pg_copy_logical_replication_slot ( src_slot_name name, dst_slot_name name [, temporary boolean [, plugin name]] ) → record ( slot_name name, lsn pg_lsn )

Копирует существующий слот логической репликации с именем src_slot_name в слот с именем dst_slot_name, с возможностью смены модуля вывода и свойства временности. Скопированный логический слот начинает передачу с того же последовательного номера LSN, что и исходный слот. Параметры temporary и plugin являются необязательными; если они опущены, сохраняются свойства исходного слота.

pg_logical_slot_get_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data text )

Возвращает изменения в слоте slot_name с позиции, до которой ранее были получены изменения. Если параметры upto_lsn и upto_nchanges равны NULL, логическое декодирование продолжится до конца журнала транзакций. Если upto_lsn не NULL, декодироваться будут только транзакции, зафиксированные до заданного LSN. Если upto_nchanges не NULL, декодирование остановится, когда число строк, полученных при декодировании, превысит заданное значение. Заметьте однако, что фактическое число возвращённых строк может быть больше, так как это ограничение проверяется только после добавления строк, декодированных для очередной транзакции.

pg_logical_slot_peek_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data text )

Работает так же, как функция pg_logical_slot_get_changes(), но не забирает изменения; то есть, они будут получены снова при следующих вызовах.

pg_logical_slot_get_binary_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data bytea )

Работает так же, как функция pg_logical_slot_get_changes(), но выдаёт изменения в типе bytea.

pg_logical_slot_peek_binary_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data bytea )

Работает аналогично функции pg_logical_slot_peek_changes(), но выдаёт изменения в значении bytea.

pg_replication_slot_advance ( slot_name name, upto_lsn pg_lsn ) → record ( slot_name name, end_lsn pg_lsn )

Продвигает текущую подтверждённую позицию слота репликации с именем slot_name. Слот нельзя переместить назад, а также вперёд за текущую позицию добавления. Возвращает имя слота и позицию, до которой он фактически продвинулся. Информация об изменившемся положении слота, если он продвинулся, сохраняется только при ближайшей контрольной точке. Поэтому в случае прерывания работы слот может оказаться в предыдущем положении.

pg_replication_origin_create ( node_name text ) → oid

Создаёт источник репликации с заданным внешним именем и возвращает назначенный ему внутренний идентификатор.

pg_replication_origin_drop ( node_name text ) → void

Удаляет ранее созданный источник репликации, в том числе связанную информацию о воспроизведении.

pg_replication_origin_oid ( node_name text ) → oid

Ищет источник репликации по имени и возвращает внутренний идентификатор. Если такой источник не находится, возвращает NULL.

pg_replication_origin_session_setup ( node_name text ) → void

Помечает текущий сеанс как воспроизводящий изменения из указанного источника, что позволяет отслеживать процесс воспроизведения. Может применяться, только если в текущий момент источник ещё не выбран. Для отмены этого действия вызовите pg_replication_origin_session_reset.

pg_replication_origin_session_reset () → void

Отменяет действие pg_replication_origin_session_setup().

pg_replication_origin_session_is_setup () → boolean

Возвращает true, если в текущем сеансе выбран источник репликации.

pg_replication_origin_session_progress ( flush boolean ) → pg_lsn

Возвращает позицию воспроизведения для источника репликации, выбранного в текущем сеансе. Параметр flush определяет, будет ли гарантироваться сохранение локальной транзакции на диске.

pg_replication_origin_xact_setup ( origin_lsn pg_lsn, origin_timestamp timestamp with time zone ) → void

Помечает текущую транзакцию как воспроизводящую транзакцию, зафиксированную с указанным LSN и временем. Может вызываться только после того, как источник репликации был выбран в результате вызова pg_replication_origin_session_setup().

pg_replication_origin_xact_reset () → void

Отменяет действие pg_replication_origin_xact_setup().

pg_replication_origin_advance ( node_name text, lsn pg_lsn ) → void

Устанавливает положение репликации для заданного узла в указанную позицию. Это в основном полезно для установки начальной позиции или новой позиции после изменения конфигурации и подобных действий. Но учтите, что неосторожное использование этой функции может привести к несогласованности реплицированных данных.

pg_replication_origin_progress ( node_name text, flush boolean ) → pg_lsn

Выдаёт позицию воспроизведения для заданного источника репликации. Параметр flush определяет, будет ли гарантироваться сохранение локальной транзакции на диске.

pg_logical_emit_message ( transactional boolean, prefix text, content text ) → pg_lsn

pg_logical_emit_message ( transactional boolean, prefix text, content bytea ) → pg_lsn

Генерирует сообщение логического декодирования. Её можно использовать для передачи через WAL произвольных сообщений модулям логического декодирования. Параметр transactional определяет, должно ли сообщение относиться к текущей транзакции или оно должно записываться немедленно и декодироваться сразу, как только эта запись будет прочитана при логическом декодировании. Параметр prefix задаёт текстовый префикс, по которому модуль логического декодирования может легко распознать интересующие именно его сообщения. В параметре content передаётся содержимое сообщения, в текстовом или двоичном виде.


9.27.7. Функции управления объектами баз данных

Функции, показанные в Таблице 9.90, вычисляют объём, который занимают на диске объекты базы данных, и помогают представить полученные результаты. Все эти функции выдают размеры в байтах. Если им передаётся OID, не соответствующий существующему объекту, они возвращают NULL.

Таблица 9.90. Функции получения размера объектов БД

Функция

Описание

pg_column_size ( "any" ) → integer

Показывает, сколько байт занимает при хранении отдельное значение. Если эта функция применяется непосредственно к значению в столбце таблицы, в результате отражается эффект возможного сжатия.

pg_database_size ( name ) → bigint

pg_database_size ( oid ) → bigint

Вычисляет общий объём, который занимает на диске база данных с указанным именем или OID. Для использования этой функции необходимо иметь право CONNECT для заданной базы (оно даётся по умолчанию) или быть членом роли pg_read_all_stats.

pg_indexes_size ( regclass ) → bigint

Вычисляет общий объём, который занимают на диске индексы, связанные с указанной таблицей.

pg_relation_size ( relation regclass [, fork text] ) → bigint

Вычисляет объём, который занимает на диске один «слой» заданного отношения. (Заметьте, что в большинстве случаев удобнее использовать более высокоуровневые функции pg_total_relation_size и pg_table_size, которые суммируют размер всех слоёв.) С одним аргументом она выдаёт размер основного слоя с данными отношения. Название другого интересующего слоя можно передать во втором аргументе:

  • main выдаёт размер основного слоя данных заданного отношения.

  • fsm выдаёт размер карты свободного места (см. Раздел 70.3), связанной с заданным отношением.

  • vm выдаёт размер карты видимости (см. Раздел 70.4), связанной с заданным отношением.

  • init выдаёт размер слоя инициализации для заданного отношения, если он имеется.

pg_temp_relation_size ( relation regclass ) → bigint

Принимает OID или имя временной таблицы и возвращает общий размер в байтах слоя main данного отношения. Физический файл временной таблицы расширяется только когда она перестаёт помещаться в кеш temp_buffers. Поэтому общий размер временной таблицы может отличаться от её размера на диске. Если отношение не является временной таблицей, эта функция не выдаёт ошибку, а просто возвращает NULL.

pg_size_bytes ( text ) → bigint

Преобразует размер в человеко-ориентированном формате (который выдаёт pg_size_pretty) в число байт.

pg_size_pretty ( bigint ) → text

pg_size_pretty ( numeric ) → text

Преобразует размер в байтах в более понятный человеку формат с единицами измерения размера (bytes, kB, MB, GB или TB, в зависимости от значения). Заметьте, что эти единицы определяются как степени 2, а не 10, так что 1kB — это 1024 байта, 1MB — 10242 = 1048576 байт и т. д.

pg_table_size ( regclass ) → bigint

Вычисляет объём, который занимает на диске данная таблица, за исключением индексов (но включая её TOAST-таблицу (если она есть), карту свободного места и карту видимости).

pg_tablespace_size ( name ) → bigint

pg_tablespace_size ( oid ) → bigint

Вычисляет общий объём, который занимает на диске табличное пространство с заданным именем или OID. Для использования этой функции требуется иметь право CREATE для указанного табличного пространства или быть членом роли pg_read_all_stats, если только это не табличное пространство по умолчанию для текущей базы данных.

pg_total_relation_size ( regclass ) → bigint

Вычисляет общий объём, который занимает на диске заданная таблица, включая все её индексы и данные TOAST. Результат этой функции равен значению pg_table_size + pg_indexes_size.


Вышеописанные функции, работающие с таблицами или индексами, принимают аргумент типа regclass, который представляет собой просто OID таблицы или индекса в системном каталоге pg_class. Однако вам не нужно вручную вычислять OID, так как процедура ввода значения regclass может сделать это за вас. Для этого достаточно записать имя таблицы в апострофах, как обычную текстовую константу. В соответствии с правилами обработки обычных имён SQL, если имя таблицы не заключено в кавычки, эта строка будет переведена в нижний регистр.

Функции, перечисленные в Таблице 9.91, помогают определить, в каких файлах на диске хранятся объекты базы данных.

Таблица 9.91. Функции определения расположения объектов

Функция

Описание

pg_relation_filenode ( relation regclass ) → oid

Выдаёт номер «файлового узла», связанного с заданным объектом. Файловым узлом называется основной компонент имени файла, используемого для хранения данных (подробнее это описано в Разделе 70.1). Для большинства отношений этот номер совпадает со значением pg_class.relfilenode, но для некоторых системных каталогов relfilenode равен 0, и нужно использовать эту функцию, чтобы узнать действительное значение. Если указанное отношение не хранится на диске, как, например представление, данная функция возвращает NULL.

pg_relation_filepath ( relation regclass ) → text

Выдаёт полный путь к файлу отношения (относительно каталога данных PGDATA).

pg_filenode_relation ( tablespace oid, filenode oid ) → regclass

Выдаёт OID отношения, которое хранится в табличном пространстве, заданном по OID, в указанном файловом узле. По сути эта функция является обратной к pg_relation_filepath. Для табличного пространства по умолчанию можно передать нулевое значение OID. Если эта функция не находит в базе данных отношение по заданным значениям или если отношение является временным, она выдаёт NULL.


В Таблица 9.92 перечислены функции, предназначенные для управления правилами сортировки.

Таблица 9.92. Функции управления правилами сортировки

Функция

Описание

pg_collation_actual_version ( oid ) → text

Возвращает действующую версию объекта правила сортировки, которая в настоящее время установлена в операционной системе. Если она отличается от значения в pg_collation.collversion, может потребоваться перестроить объекты, зависящие от данного правила сортировки. См. также ALTER COLLATION.

pg_import_system_collations ( schema regnamespace ) → integer

Добавляет правила сортировки в системный каталог pg_collation, анализируя все локали, которые она находит в операционной системе. Эту информацию использует initdb; за подробностями обратитесь к Подразделу 23.2.2. Если позднее в систему устанавливаются дополнительные локали, эту функцию можно запустить снова, чтобы добавились правила сортировки для новых локалей. Локали, для которых обнаруживаются существующие записи в pg_collation, будут пропущены. (Объекты правил сортировки для локалей, которые перестают существовать в операционной системе, никогда не удаляются этой функцией.) В параметре schema обычно передаётся pg_catalog, но это не обязательно; правила сортировки могут быть установлены и в другую схему. Эта функция возвращает число созданных ей объектов правил сортировки; вызывать её разрешено только суперпользователям.


В Таблице 9.93 перечислены функции, предоставляющие информацию о структуре секционированных таблиц.

Таблица 9.93. Функции получения информации о секционировании

Функция

Описание

pg_partition_tree ( regclass ) → setof record ( relid regclass, parentrelid regclass, isleaf boolean, level integer )

Выводит информацию о таблицах и индексах в дереве секционирования для заданной секционированной таблицы или секционированного индекса, отражая каждую секцию в отдельной строке. В этой информации представляется OID секции, OID её непосредственного родителя, логический признак того, что секция является конечной, и целое число, показывающее её уровень в иерархии. На уровне 0 будет находится указанная таблица или индекс, на уровне 1 непосредственные потомки-секции, на уровне 2 секции последних и т. д. Если заданное отношение не существует или не является секцией или секционированным отношением, эта функция выдаёт пустой результат.

pg_partition_ancestors ( regclass ) → setof regclass

Выводит список вышестоящих отношений для заданной секции, включая её саму. Если заданное отношение не существует или не является секцией или секционированным отношением, эта функция выдаёт пустой результат.

pg_partition_root ( regclass ) → regclass

Выдаёт самое верхнее отношение в дереве секционирования, к которому относится заданное отношение. Если заданное отношение не существует или не является секцией или секционированным отношением, эта функция выдаёт NULL.


Например, чтобы определить общий размер данных, содержащихся в секционированной таблице measurement, можно использовать следующий запрос:

SELECT pg_size_pretty(sum(pg_relation_size(relid))) AS total_size
  FROM pg_partition_tree('measurement');

9.27.8. Функции обслуживания индексов

В Таблице 9.94 перечислены функции, предназначенные для обслуживания индексов. (Заметьте, что задачи обслуживания обычно выполняются автоматически в ходе автоочистки; пользоваться данными функциями требуется только в особых случаях.) Выполнять эти функции во время восстановления нельзя. Использовать их разрешено только суперпользователям и владельцу определённого индекса.

Таблица 9.94. Функции обслуживания индексов

Функция

Описание

brin_summarize_new_values ( index regclass ) → integer

Сканирует указанный BRIN-индекс в поисках зон страниц в базовой таблице, ещё не обобщённых в индексе; для каждой такой зоны в результате сканирования этих страниц создаётся новый обобщающий кортеж в индексе. Возвращает эта функция число вставленных в индекс обобщающих записей о зонах страниц.

brin_summarize_range ( index regclass, blockNumber bigint ) → integer

Обобщает зону страниц, охватывающую данный блок, если она ещё не была обобщена. Эта функция подобна brin_summarize_new_values, но обрабатывает только одну выбранную зону страниц.

brin_desummarize_range ( index regclass, blockNumber bigint ) → void

Удаляет из BRIN-индекса кортеж, который обобщает зону страниц, охватывающую данный блок таблицы, если такой кортеж имеется.

gin_clean_pending_list ( index regclass ) → bigint

Очищает очередь указанного GIN-индекса, массово перемещая элементы из неё в основную структуру данных GIN, и возвращает число страниц, убранных из очереди. Если для обработки ей передаётся индекс GIN, построенный с отключённым параметром fastupdate, очистка не производится и возвращается 0, так как у такого индекса нет очереди записей. Подробнее об очереди записей и параметре fastupdate рассказывается в Подразделе 67.4.1 и Разделе 67.5.


9.27.9. Функции для работы с обычными файлами

Функции, перечисленные в Таблице 9.95, предоставляют прямой доступ к файлам, находящимся на сервере. Обычным пользователям, не включённым в роль pg_read_server_files, они позволяют обращаться только к файлам в каталоге кластера баз данных и в каталоге log_directory. Для файлов в каталоге кластера этим функциям передаётся относительный путь, а для файлов журнала — путь, соответствующий значению параметра log_directory.

Заметьте, что пользователи, обладающие правом EXECUTE для pg_read_file() или связанных функций, имеют возможность читать любой файл на сервере, который может прочитать серверный процесс; на эти функции не действуют никакие ограничения доступа внутри базы данных. В частности это означает, что пользователь с такими правами может прочитать содержимое таблицы pg_authid, в которой хранятся данные аутентификации, равно как и любой другой файл в базе данных. Таким образом, разрешать доступ к этим функциям следует с большой осторожностью.

Некоторые из этих функций принимают необязательный параметр missing_ok, который определяет их поведение в случае отсутствия файла или каталога. Если он равен true, функция возвращает NULL или пустой набор данных. Если же он равен false, в указанном случае выдаётся ошибка. Значение по умолчанию — false.

Таблица 9.95. Функции для работы с обычными файлами

Функция

Описание

pg_ls_dir ( dirname text [, missing_ok boolean, include_dot_dirs boolean] ) → setof text

Выдаёт имена всех файлов (а также каталогов и других специальных файлов) в заданном каталоге. Параметр include_dot_dirs определяет, будут ли в результирующий набор включаться каталоги «.» и «..». По умолчанию они не включаются, но их можно включить, чтобы с параметром missing_ok равным true, пустой каталог можно было отличить от несуществующего.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_ls_logdir () → setof record ( name text, size bigint, modification timestamp with time zone )

Выводит имя, размер и время последнего изменения (mtime) всех обычных файлов в каталоге журналов сервера. Файлы с именами, начинающимися с точки, каталоги и другие специальные файлы исключаются из рассмотрения.

По умолчанию доступ к этой функции имеют только суперпользователи и члены группы pg_monitor, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_ls_waldir () → setof record ( name text, size bigint, modification timestamp with time zone )

Выводит имя, размер и время последнего изменения (mtime) всех обычных файлов в каталоге журнала предзаписи (WAL) сервера. Файлы с именами, начинающимися с точки, каталоги и другие специальные файлы исключаются из рассмотрения.

По умолчанию доступ к этой функции имеют только суперпользователи и члены группы pg_monitor, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_ls_archive_statusdir () → setof record ( name text, size bigint, modification timestamp with time zone )

Выводит имя, размер и время последнего изменения (mtime) всех обычных файлов в каталоге состояния архива WAL (pg_wal/archive_status). Файлы с именами, начинающимися с точки, каталоги и другие специальные файлы исключаются из рассмотрения.

По умолчанию доступ к этой функции имеют только суперпользователи и члены группы pg_monitor, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_ls_tmpdir ( [tablespace oid] ) → setof record ( name text, size bigint, modification timestamp with time zone )

Выводит имя, размер и время последнего изменения (mtime) всех обычных файлов во временном каталоге для табличного пространства tablespace. Если параметр tablespace не задан, подразумевается табличное пространство pg_default. Файлы с именами, начинающимися с точки, каталоги и другие специальные файлы исключаются из рассмотрения.

По умолчанию доступ к этой функции имеют только суперпользователи и члены группы pg_monitor, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_read_file ( filename text [, offset bigint, length bigint [, missing_ok boolean]] ) → text

Читает из текстового файла всё содержимое или фрагмент с заданного смещения (offset), размером не больше length байт (размер может быть меньше, если файл кончится раньше). Если смещение offset отрицательно, оно отсчитывается от конца файла. Если параметры offset и length опущены, возвращается всё содержимое файла. Прочитанные из файла байты обрабатываются как символы в кодировке базы данных; если они оказываются недопустимыми для этой кодировки, возникает ошибка.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

pg_read_binary_file ( filename text [, offset bigint, length bigint [, missing_ok boolean]] ) → bytea

Читает из текстового файла всё содержимое или заданный фрагмент. Эта функция подобна pg_read_file, но может читать произвольные двоичные данные и возвращает результат в значении типа bytea, а не text; как следствие, никакие проверки кодировок не производятся.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.

В сочетании с convert_from эту функцию можно применять для чтения текста в указанной кодировке и преобразования в кодировку базы данных:

SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');

pg_stat_file ( filename text [, missing_ok boolean] ) → record ( size bigint, access timestamp with time zone, modification timestamp with time zone, change timestamp with time zone, creation timestamp with time zone, isdir boolean )

Выдаёт запись, содержащую размер файла, время последнего обращения и последнего изменения, а также время последнего изменения состояния (только в Unix-системах), время создания (только в Windows) и флаг, показывающий, что это каталог.

По умолчанию доступ к этой функции имеют только суперпользователи, но право на её выполнение (EXECUTE) можно дать и другим пользователям.


9.27.10. Функции управления рекомендательными блокировками

Функции, перечисленные в Таблице 9.96, предназначены для управления рекомендательными блокировками. Подробнее об их использовании можно узнать в Подразделе 13.3.5.

Все эти функции предназначены для оперирования блокировками ресурсов, определяемых приложением и задаваемых одним 64-битным или двумя 32-битными ключами (заметьте, что пространства этих ключей не пересекаются). Если конфликтующую блокировку с тем же идентификатором уже удерживает другой сеанс, эти функции либо дожидаются освобождения ресурса, либо выдают в результате false, в зависимости от вида функции. Блокировки могут быть как исключительными, так и разделяемыми — разделяемая блокировка не конфликтует с другими разделяемыми блокировками того же ресурса, но конфликтует с исключительными. Блокировки могут устанавливаться на сеансовом уровне (тогда они удерживаются до момента освобождения или до завершения сеанса) и на транзакционном (тогда они удерживаются до конца текущей транзакции, освободить их вручную нет возможности). Когда поступает несколько запросов на блокировку сеансового уровня, они накапливаются, так что если один идентификатор ресурса был заблокирован три раза, должны поступить три запроса на освобождение блокировки, чтобы ресурс был разблокирован до завершения сеанса.

Таблица 9.96. Функции управления рекомендательными блокировками

Функция

Описание

pg_advisory_lock ( key bigint ) → void

pg_advisory_lock ( key1 integer, key2 integer ) → void

Получает исключительную рекомендательную блокировку сеансового уровня, ожидая её, если это необходимо.

pg_advisory_lock_shared ( key bigint ) → void

pg_advisory_lock_shared ( key1 integer, key2 integer ) → void

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

pg_advisory_unlock ( key bigint ) → boolean

pg_advisory_unlock ( key1 integer, key2 integer ) → boolean

Освобождает ранее полученную исключительную рекомендательную блокировку сеансового уровня. Если блокировка освобождена успешно, эта функция возвращает true, а если сеанс не владел ей — false, при этом сервер выдаёт предупреждение SQL.

pg_advisory_unlock_all () → void

Освобождает все закреплённые за текущим сеансом рекомендательные блокировки сеансового уровня. (Эта функция неявно вызывается в конце любого сеанса, даже при нештатном отключении клиента.)

pg_advisory_unlock_shared ( key bigint ) → boolean

pg_advisory_unlock_shared ( key1 integer, key2 integer ) → boolean

Освобождает ранее полученную разделяемую рекомендательную блокировку сеансового уровня. Если она освобождена успешно, эта функция возвращает true, а если сеанс не владел этой блокировкой — false, при этом сервер выдаёт предупреждение SQL.

pg_advisory_xact_lock ( key bigint ) → void

pg_advisory_xact_lock ( key1 integer, key2 integer ) → void

Получает исключительную рекомендательную блокировку транзакционного уровня, ожидая её, если это необходимо.

pg_advisory_xact_lock_shared ( key bigint ) → void

pg_advisory_xact_lock_shared ( key1 integer, key2 integer ) → void

Получает разделяемую рекомендательную блокировку транзакционного уровня, ожидая её, если это необходимо.

pg_try_advisory_lock ( key bigint ) → boolean

pg_try_advisory_lock ( key1 integer, key2 integer ) → boolean

Получает исключительную рекомендательную блокировку сеансового уровня, если она доступна. То есть эта функция либо немедленно получает блокировку и возвращает true, либо сразу возвращает false, если получить её нельзя.

pg_try_advisory_lock_shared ( key bigint ) → boolean

pg_try_advisory_lock_shared ( key1 integer, key2 integer ) → boolean

Получает разделяемую рекомендательную блокировку сеансового уровня, если она доступна. То есть эта функция либо немедленно получает блокировку и возвращает true, либо сразу возвращает false, если получить её нельзя.

pg_try_advisory_xact_lock ( key bigint ) → boolean

pg_try_advisory_xact_lock ( key1 integer, key2 integer ) → boolean

Получает исключительную рекомендательную блокировку транзакционного уровня, если она доступна. То есть эта функция либо немедленно получает блокировку и возвращает true, либо сразу возвращает false, если получить её нельзя.

pg_try_advisory_xact_lock_shared ( key bigint ) → boolean

pg_try_advisory_xact_lock_shared ( key1 integer, key2 integer ) → boolean

Получает разделяемую рекомендательную блокировку транзакционного уровня, если она доступна. То есть эта функция либо немедленно получает блокировку и возвращает true, либо сразу возвращает false, если получить её нельзя.


9.27.11. Функции управления сжатием

Функции, приведённые в Таблице 9.97, выдают информацию о состоянии и активности CFS, а также управляют сборкой мусора CFS.

Таблица 9.97. Функции управления сжатием

ИмяТип результатаОписание
cfs_start_gc(n_workers integer)integerЗапускает сборку мусора с заданным числом рабочих процессов. Вы можете запустить её вручную с помощью этой функции, только если фоновая сборка мусора отключена.
cfs_enable_gc(enabled boolean)booleanВключает/отключает фоновый процесс сборки мусора. Для управления вы также можете использовать переменную конфигурации cfs_gc.
cfs_gc_relation(rel regclass)integerВыполняет сборку мусора для заданной таблицы. Эта функция возвращает число обработанных сегментов.
cfs_version()textВыводит версию CFS и используемый алгоритм сжатия.
cfs_estimate(rel regclass)float8Оценивает возможный эффект от сжатия таблицы. Возвращает средний коэффициент сжатия для первых десяти процентов блоков отношения (но не более 100 блоков).
cfs_compression_ratio(rel regclass)float8Возвращает фактический коэффициент сжатия для всех сегментов сжатого отношения.
cfs_fragmentation(rel regclass)float8Возвращает средний коэффициент фрагментации для файлов заданного отношения.
cfs_gc_activity_processed_bytes()int64Возвращает общий размер страниц, обработанных механизмом CFS в процессе сборки мусора.
cfs_gc_activity_processed_pages()int64Возвращает число страниц, обработанных механизмом CFS в процессе сборки мусора.
cfs_gc_activity_processed_files()int64Возвращает число файлов, сжатых механизмом CFS в процессе сборки мусора.
cfs_gc_activity_scanned_files()int64Возвращает число файлов, просканированных механизмом CFS в процессе сборки мусора.

9.27.12. Опорные функции журнала операций

В журнале операций хранится информация о критически важных системных событиях, таких как обновление, выполнение pg_resetwal и т. п. Эта информация не представляет особого интереса для обычного пользователя, но важна для осуществления технической поддержки со стороны поставщика. Запись в журнал операций производится только на системном уровне (без каких-либо действий со стороны пользователя), а для его чтения используются функции SQL. Функция, показанная в Таблица 9.98, читает журнал операций.

Таблица 9.98. Опорные функции журнала операций

Функция

Описание

pg_operation_log () → setof record ( event text, edition text, version text, lsn pg_lsn, last timestamptz, count int4 )

Здесь:

  • event — тип события (операции). Может быть bootstrap, startup, pg_resetwal, pg_rewind, pg_upgrade или promoted.

  • edition — редакция Postgres Pro. Может быть vanilla, 1c, std, ent или unknown.

  • version — версия Postgres Pro.

  • lsn — положение последней контрольной точки, возвращённое утилитой pg_controldata на момент возникновения события.

  • last — дата/время возникновения последнего события этого типа, если события накапливаются, или дата/время возникновения события в противном случае.

  • count — количество событий этого типа, если события накапливаются, или 1 в противном случае.

Эта системная функция создаётся автоматически для новых баз данных, а для существующих баз данных должна создаваться следующим образом:

CREATE OR REPLACE FUNCTION
  pg_operation_log(
    OUT event text,
    OUT edition text,
    OUT version text,
    OUT lsn pg_lsn,
    OUT last timestamptz,
    OUT count int4)
 RETURNS SETOF record
 LANGUAGE INTERNAL
 STABLE STRICT PARALLEL SAFE
AS 'pg_operation_log';         

Ниже представлен пример вывода для функции pg_operation_log:

select * from pg_operation_log();
   event    | edition | version |    lsn    |          last          | count
------------+---------+---------+-----------+------------------------+-------
 startup    | vanilla | 10.22.0 | 0/8000028 | 2022-10-27 23:06:27+03 |     1
 pg_upgrade | 1c      | 15.0.0  | 0/8000028 | 2022-10-27 23:06:27+03 |     1
 startup    | 1c      | 15.0.0  | 0/80001F8 | 2022-10-27 23:06:53+03 |     2
(3 rows)

Примечание

Если журнал операций пуст, то при обновлении перед записью pg_upgrade сначала записывается событие startup с предыдущим значением version, имеющим следующие особенности: вместо версии патча (третья цифра в номере версии) всегда устанавливается ноль, поскольку в pg_upgrade нет информации о версии патча ни для одной редакции (1c, std, ent). При обновлении с 1c или vanilla невозможно выяснить, к какой из этих редакций относится база данных до обновления, поэтому для записи startup используется редакция vanilla.

9.27.13. Отладочные функции

Функция, показанная в Таблице 9.99, может быть полезна для низкоуровневых операций, например в целях отладки или исследования испорченных баз данных Postgres Pro.

Таблица 9.99. Функции синхронизации снимков

ИмяТип результатаОписание
pg_snapshot_any()voidОтключает действие правил MVCC в рамках текущей транзакции, что позволяет видеть в ней все версии данных.

Применяйте pg_snapshot_any крайне осторожно. Выполнять её следует в транзакции с уровнем изоляции REPEATABLE READ или выше, в противном случае следующий же запрос заменит выбранный снимок новым. Выполнять её могут только суперпользователи.

Примечание

Если ваш кластер БД создавался сервером версии, в которой этой функции ещё не было, определите её следующей командой:

CREATE FUNCTION pg_snapshot_any() RETURNS void AS 'pg_snapshot_any' LANGUAGE internal;

9.27. System Administration Functions

The functions described in this section are used to control and monitor a Postgres Pro installation.

9.27.1. Configuration Settings Functions

Table 9.83 shows the functions available to query and alter run-time configuration parameters.

Table 9.83. Configuration Settings Functions

Function

Description

Example(s)

current_setting ( setting_name text [, missing_ok boolean ] ) → text

Returns the current value of the setting setting_name. If there is no such setting, current_setting throws an error unless missing_ok is supplied and is true (in which case NULL is returned). This function corresponds to the SQL command SHOW.

current_setting('datestyle')ISO, MDY

set_config ( setting_name text, new_value text, is_local boolean ) → text

Sets the parameter setting_name to new_value, and returns that value. If is_local is true, the new value will only apply during the current transaction. If you want the new value to apply for the rest of the current session, use false instead. This function corresponds to the SQL command SET.

set_config('log_statement_stats', 'off', false)off

pg_backend_set_config ( pid int, config text, wait int default 0 ) → boolean

Sets one or more parameters provided in the config string for the backend with the specified PID. Following the postgresql.conf convention, each configuration parameter in the config string must be written on a separate line, in the name=value format. The pg_backend_set_config function only affects run-time parameters. When called, it modifies the main configuration until the end of the session or the next pg_backend_set_config call. The changes take effect starting from the next transaction.

If the optional wait parameter is not specified, this function returns true, without waiting for response from the other backend. If it is specified, the function waits for wait seconds for the confirmation that the target backend has received the command. If the confirmation is received, the function returns true. Otherwise, false is returned. Note that the returned value does not reflect the actual result of the operation.

pg_backend_load_library ( pid int, name text, wait int default 0 ) → boolean

Loads the library with the provided name for the backend with the specified PID. You can load only one library at a time. When run without superuser privileges, pg_backend_load_library only allows to load libraries located in $libdir/plugins. If you need to load a library from a different location, run this function on behalf of a superuser.

If the optional wait parameter is not specified, this function returns true, without waiting for response from the other backend. If it is specified, the function waits for wait seconds for the confirmation that the target backend has received the command. If the confirmation is received, the function returns true. Otherwise, false is returned. Note that the returned value does not reflect the actual result of the operation.


Functions pg_backend_set_config and pg_backend_load_library are designed to set configuration parameters and load shared libraries in other sessions, which may be useful for tracing sessions with unexpected behavior. To avoid potential security issues, these functions can only be called by a superuser.

Note

This functionality cannot be used together with the built-in connection pooler described in Chapter 33.

If a configuration update by pg_backend_set_config or a library loading by pg_backend_load_library fails, an error occurs on the target backend, and the current command on this backend is aborted.

Consider the following examples:

SELECT pg_backend_set_config(pg_backend_pid(), 'statement_timeout=10000');
 pg_backend_set_config
-----------------------
 t
(1 row)

SELECT pg_backend_set_config(pg_backend_pid(),
       'statement_timeout=20000
        lock_timeout=10000');
 pg_backend_set_config
-----------------------
 t
(1 row)

SELECT pg_backend_set_config(pg_backend_pid(), 'fsync=on');
ERROR:  parameter "fsync" cannot be changed now

SELECT pg_backend_set_config(pg_backend_pid(), 'log_min_messages=INFO');
ERROR:  permission denied to set parameter "log_min_messages"

SELECT pg_backend_load_library(pg_backend_pid(), 'pgoutput');
 pg_backend_load_library
-------------------------
 t
(1 row)

If the config parameter passed to pg_backend_set_config contains a syntax error, the function returns a corresponding error message.

Consider the following example:

SELECT pg_backend_set_config(pg_backend_pid(), 'test_param', 100000);
ERROR: syntax error in file "base/pgsql_tmp/pgsql_tmp87011.4" line 0, near end of line

9.27.2. Server Signaling Functions

The functions shown in Table 9.84 send control signals to other server processes. Use of these functions is restricted to superusers by default but access may be granted to others using GRANT, with noted exceptions.

Each of these functions returns true if successful and false otherwise.

Table 9.84. Server Signaling Functions

Function

Description

pg_cancel_backend ( pid integer ) → boolean

Cancels the current query of the session whose backend process has the specified process ID. This is also allowed if the calling role is a member of the role whose backend is being canceled or the calling role has been granted pg_signal_backend, however only superusers can cancel superuser backends.

pg_reload_conf () → boolean

Causes all processes of the Postgres Pro server to reload their configuration files. (This is initiated by sending a SIGHUP signal to the postmaster process, which in turn sends SIGHUP to each of its children.)

pg_rotate_logfile () → boolean

Signals the log-file manager to switch to a new output file immediately. This works only when the built-in log collector is running, since otherwise there is no log-file manager subprocess.

pg_terminate_backend ( pid integer ) → boolean

Terminates the session whose backend process has the specified process ID. This is also allowed if the calling role is a member of the role whose backend is being terminated or the calling role has been granted pg_signal_backend, however only superusers can terminate superuser backends.


pg_cancel_backend and pg_terminate_backend send signals (SIGINT or SIGTERM respectively) to backend processes identified by process ID. The process ID of an active backend can be found from the pid column of the pg_stat_activity view, or by listing the postgres processes on the server (using ps on Unix or the Task Manager on Windows). The role of an active backend can be found from the usename column of the pg_stat_activity view.

9.27.3. Backup Control Functions

The functions shown in Table 9.85 assist in making on-line backups. These functions cannot be executed during recovery (except non-exclusive pg_start_backup, non-exclusive pg_stop_backup, pg_is_in_backup, pg_backup_start_time and pg_wal_lsn_diff).

For details about proper usage of these functions, see Section 25.3.

Table 9.85. Backup Control Functions

Function

Description

pg_create_restore_point ( name text ) → pg_lsn

Creates a named marker record in the write-ahead log that can later be used as a recovery target, and returns the corresponding write-ahead log location. The given name can then be used with recovery_target_name to specify the point up to which recovery will proceed. Avoid creating multiple restore points with the same name, since recovery will stop at the first one whose name matches the recovery target.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_current_wal_flush_lsn () → pg_lsn

Returns the current write-ahead log flush location (see notes below).

pg_current_wal_insert_lsn () → pg_lsn

Returns the current write-ahead log insert location (see notes below).

pg_current_wal_lsn () → pg_lsn

Returns the current write-ahead log write location (see notes below).

pg_start_backup ( label text [, fast boolean [, exclusive boolean ]] ) → pg_lsn

Prepares the server to begin an on-line backup. The only required parameter is an arbitrary user-defined label for the backup. (Typically this would be the name under which the backup dump file will be stored.) If the optional second parameter is given as true, it specifies executing pg_start_backup as quickly as possible. This forces an immediate checkpoint which will cause a spike in I/O operations, slowing any concurrently executing queries. The optional third parameter specifies whether to perform an exclusive or non-exclusive backup (default is exclusive).

When used in exclusive mode, this function writes a backup label file (backup_label) and, if there are any links in the pg_tblspc/ directory, a tablespace map file (tablespace_map) into the database cluster's data directory, then performs a checkpoint, and then returns the backup's starting write-ahead log location. (The user can ignore this result value, but it is provided in case it is useful.) When used in non-exclusive mode, the contents of these files are instead returned by the pg_stop_backup function, and should be copied to the backup area by the user.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_stop_backup ( exclusive boolean [, wait_for_archive boolean ] ) → setof record ( lsn pg_lsn, labelfile text, spcmapfile text )

Finishes performing an exclusive or non-exclusive on-line backup. The exclusive parameter must match the previous pg_start_backup call. In an exclusive backup, pg_stop_backup removes the backup label file and, if it exists, the tablespace map file created by pg_start_backup. In a non-exclusive backup, the desired contents of these files are returned as part of the result of the function, and should be written to files in the backup area (not in the data directory).

There is an optional second parameter of type boolean. If false, the function will return immediately after the backup is completed, without waiting for WAL to be archived. This behavior is only useful with backup software that independently monitors WAL archiving. Otherwise, WAL required to make the backup consistent might be missing and make the backup useless. By default or when this parameter is true, pg_stop_backup will wait for WAL to be archived when archiving is enabled. (On a standby, this means that it will wait only when archive_mode = always. If write activity on the primary is low, it may be useful to run pg_switch_wal on the primary in order to trigger an immediate segment switch.)

When executed on a primary, this function also creates a backup history file in the write-ahead log archive area. The history file includes the label given to pg_start_backup, the starting and ending write-ahead log locations for the backup, and the starting and ending times of the backup. After recording the ending location, the current write-ahead log insertion point is automatically advanced to the next write-ahead log file, so that the ending write-ahead log file can be archived immediately to complete the backup.

The result of the function is a single record. The lsn column holds the backup's ending write-ahead log location (which again can be ignored). The second and third columns are NULL when ending an exclusive backup; after a non-exclusive backup they hold the desired contents of the label and tablespace map files.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_stop_backup () → pg_lsn

Finishes performing an exclusive on-line backup. This simplified version is equivalent to pg_stop_backup(true, true), except that it only returns the pg_lsn result.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_is_in_backup () → boolean

Returns true if an on-line exclusive backup is in progress.

pg_backup_start_time () → timestamp with time zone

Returns the start time of the current on-line exclusive backup if one is in progress, otherwise NULL.

pg_switch_wal () → pg_lsn

Forces the server to switch to a new write-ahead log file, which allows the current file to be archived (assuming you are using continuous archiving). The result is the ending write-ahead log location plus 1 within the just-completed write-ahead log file. If there has been no write-ahead log activity since the last write-ahead log switch, pg_switch_wal does nothing and returns the start location of the write-ahead log file currently in use.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_walfile_name ( lsn pg_lsn ) → text

Converts a write-ahead log location to the name of the WAL file holding that location.

pg_walfile_name_offset ( lsn pg_lsn ) → record ( file_name text, file_offset integer )

Converts a write-ahead log location to a WAL file name and byte offset within that file.

pg_wal_lsn_diff ( lsn1 pg_lsn, lsn2 pg_lsn ) → numeric

Calculates the difference in bytes (lsn1 - lsn2) between two write-ahead log locations. This can be used with pg_stat_replication or some of the functions shown in Table 9.85 to get the replication lag.


pg_current_wal_lsn displays the current write-ahead log write location in the same format used by the above functions. Similarly, pg_current_wal_insert_lsn displays the current write-ahead log insertion location and pg_current_wal_flush_lsn displays the current write-ahead log flush location. The insertion location is the logical end of the write-ahead log at any instant, while the write location is the end of what has actually been written out from the server's internal buffers, and the flush location is the last location known to be written to durable storage. The write location is the end of what can be examined from outside the server, and is usually what you want if you are interested in archiving partially-complete write-ahead log files. The insertion and flush locations are made available primarily for server debugging purposes. These are all read-only operations and do not require superuser permissions.

You can use pg_walfile_name_offset to extract the corresponding write-ahead log file name and byte offset from a pg_lsn value. For example:

postgres=# SELECT * FROM pg_walfile_name_offset(pg_stop_backup());
        file_name         | file_offset
--------------------------+-------------
 00000001000000000000000D |     4039624
(1 row)

Similarly, pg_walfile_name extracts just the write-ahead log file name. When the given write-ahead log location is exactly at a write-ahead log file boundary, both these functions return the name of the preceding write-ahead log file. This is usually the desired behavior for managing write-ahead log archiving behavior, since the preceding file is the last one that currently needs to be archived.

9.27.4. Recovery Control Functions

The functions shown in Table 9.86 provide information about the current status of a standby server. These functions may be executed both during recovery and in normal running.

Table 9.86. Recovery Information Functions

Function

Description

pg_is_in_recovery () → boolean

Returns true if recovery is still in progress.

pg_last_wal_receive_lsn () → pg_lsn

Returns the last write-ahead log location that has been received and synced to disk by streaming replication. While streaming replication is in progress this will increase monotonically. If recovery has completed then this will remain static at the location of the last WAL record received and synced to disk during recovery. If streaming replication is disabled, or if it has not yet started, the function returns NULL.

pg_last_wal_replay_lsn () → pg_lsn

Returns the last write-ahead log location that has been replayed during recovery. If recovery is still in progress this will increase monotonically. If recovery has completed then this will remain static at the location of the last WAL record applied during recovery. When the server has been started normally without recovery, the function returns NULL.

pg_last_xact_replay_timestamp () → timestamp with time zone

Returns the time stamp of the last transaction replayed during recovery. This is the time at which the commit or abort WAL record for that transaction was generated on the primary. If no transactions have been replayed during recovery, the function returns NULL. Otherwise, if recovery is still in progress this will increase monotonically. If recovery has completed then this will remain static at the time of the last transaction applied during recovery. When the server has been started normally without recovery, the function returns NULL.


The functions shown in Table 9.87 control the progress of recovery. These functions may be executed only during recovery.

Table 9.87. Recovery Control Functions

Function

Description

pg_is_wal_replay_paused () → boolean

Returns true if recovery is paused.

pg_promote ( wait boolean DEFAULT true, wait_seconds integer DEFAULT 60 ) → boolean

Promotes a standby server to primary status. With wait set to true (the default), the function waits until promotion is completed or wait_seconds seconds have passed, and returns true if promotion is successful and false otherwise. If wait is set to false, the function returns true immediately after sending a SIGUSR1 signal to the postmaster to trigger promotion.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_wal_replay_pause () → void

Pauses recovery. While recovery is paused, no further database changes are applied. If hot standby is active, all new queries will see the same consistent snapshot of the database, and no further query conflicts will be generated until recovery is resumed.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_wal_replay_resume () → void

Restarts recovery if it was paused.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.


pg_wal_replay_pause and pg_wal_replay_resume cannot be executed while a promotion is ongoing. If a promotion is triggered while recovery is paused, the paused state ends and promotion continues.

If streaming replication is disabled, the paused state may continue indefinitely without a problem. If streaming replication is in progress then WAL records will continue to be received, which will eventually fill available disk space, depending upon the duration of the pause, the rate of WAL generation and available disk space.

9.27.5. Snapshot Synchronization Functions

Postgres Pro allows database sessions to synchronize their snapshots. A snapshot determines which data is visible to the transaction that is using the snapshot. Synchronized snapshots are necessary when two or more sessions need to see identical content in the database. If two sessions just start their transactions independently, there is always a possibility that some third transaction commits between the executions of the two START TRANSACTION commands, so that one session sees the effects of that transaction and the other does not.

To solve this problem, Postgres Pro allows a transaction to export the snapshot it is using. As long as the exporting transaction remains open, other transactions can import its snapshot, and thereby be guaranteed that they see exactly the same view of the database that the first transaction sees. But note that any database changes made by any one of these transactions remain invisible to the other transactions, as is usual for changes made by uncommitted transactions. So the transactions are synchronized with respect to pre-existing data, but act normally for changes they make themselves.

Snapshots are exported with the pg_export_snapshot function, shown in Table 9.88, and imported with the SET TRANSACTION command.

Table 9.88. Snapshot Synchronization Functions

Function

Description

pg_export_snapshot () → text

Saves the transaction's current snapshot and returns a text string identifying the snapshot. This string must be passed (outside the database) to clients that want to import the snapshot. The snapshot is available for import only until the end of the transaction that exported it.

A transaction can export more than one snapshot, if needed. Note that doing so is only useful in READ COMMITTED transactions, since in REPEATABLE READ and higher isolation levels, transactions use the same snapshot throughout their lifetime. Once a transaction has exported any snapshots, it cannot be prepared with PREPARE TRANSACTION.


9.27.6. Replication Management Functions

The functions shown in Table 9.89 are for controlling and interacting with replication features. See Section 26.2.5, Section 26.2.6, and Chapter 52 for information about the underlying features. Use of functions for replication origin is restricted to superusers. Use of functions for replication slots is restricted to superusers and users having REPLICATION privilege.

Many of these functions have equivalent commands in the replication protocol; see Section 55.4.

The functions described in Section 9.27.3, Section 9.27.4, and Section 9.27.5 are also relevant for replication.

Table 9.89. Replication Management Functions

Function

Description

pg_create_physical_replication_slot ( slot_name name [, immediately_reserve boolean, temporary boolean ] ) → record ( slot_name name, lsn pg_lsn )

Creates a new physical replication slot named slot_name. The optional second parameter, when true, specifies that the LSN for this replication slot be reserved immediately; otherwise the LSN is reserved on first connection from a streaming replication client. Streaming changes from a physical slot is only possible with the streaming-replication protocol — see Section 55.4. The optional third parameter, temporary, when set to true, specifies that the slot should not be permanently stored to disk and is only meant for use by the current session. Temporary slots are also released upon any error. This function corresponds to the replication protocol command CREATE_REPLICATION_SLOT ... PHYSICAL.

pg_drop_replication_slot ( slot_name name ) → void

Drops the physical or logical replication slot named slot_name. Same as replication protocol command DROP_REPLICATION_SLOT.

pg_create_logical_replication_slot ( slot_name name, plugin name [, temporary boolean ] ) → record ( slot_name name, lsn pg_lsn )

Creates a new logical (decoding) replication slot named slot_name using the output plugin plugin. The optional third parameter, temporary, when set to true, specifies that the slot should not be permanently stored to disk and is only meant for use by the current session. Temporary slots are also released upon any error. A call to this function has the same effect as the replication protocol command CREATE_REPLICATION_SLOT ... LOGICAL.

pg_copy_physical_replication_slot ( src_slot_name name, dst_slot_name name [, temporary boolean ] ) → record ( slot_name name, lsn pg_lsn )

Copies an existing physical replication slot named src_slot_name to a physical replication slot named dst_slot_name. The copied physical slot starts to reserve WAL from the same LSN as the source slot. temporary is optional. If temporary is omitted, the same value as the source slot is used.

pg_copy_logical_replication_slot ( src_slot_name name, dst_slot_name name [, temporary boolean [, plugin name ]] ) → record ( slot_name name, lsn pg_lsn )

Copies an existing logical replication slot named src_slot_name to a logical replication slot named dst_slot_name, optionally changing the output plugin and persistence. The copied logical slot starts from the same LSN as the source logical slot. Both temporary and plugin are optional; if they are omitted, the values of the source slot are used.

pg_logical_slot_get_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data text )

Returns changes in the slot slot_name, starting from the point from which changes have been consumed last. If upto_lsn and upto_nchanges are NULL, logical decoding will continue until end of WAL. If upto_lsn is non-NULL, decoding will include only those transactions which commit prior to the specified LSN. If upto_nchanges is non-NULL, decoding will stop when the number of rows produced by decoding exceeds the specified value. Note, however, that the actual number of rows returned may be larger, since this limit is only checked after adding the rows produced when decoding each new transaction commit.

pg_logical_slot_peek_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data text )

Behaves just like the pg_logical_slot_get_changes() function, except that changes are not consumed; that is, they will be returned again on future calls.

pg_logical_slot_get_binary_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data bytea )

Behaves just like the pg_logical_slot_get_changes() function, except that changes are returned as bytea.

pg_logical_slot_peek_binary_changes ( slot_name name, upto_lsn pg_lsn, upto_nchanges integer, VARIADIC options text[] ) → setof record ( lsn pg_lsn, xid xid, data bytea )

Behaves just like the pg_logical_slot_peek_changes() function, except that changes are returned as bytea.

pg_replication_slot_advance ( slot_name name, upto_lsn pg_lsn ) → record ( slot_name name, end_lsn pg_lsn )

Advances the current confirmed position of a replication slot named slot_name. The slot will not be moved backwards, and it will not be moved beyond the current insert location. Returns the name of the slot and the actual position that it was advanced to. The updated slot position information is written out at the next checkpoint if any advancing is done. So in the event of a crash, the slot may return to an earlier position.

pg_replication_origin_create ( node_name text ) → oid

Creates a replication origin with the given external name, and returns the internal ID assigned to it.

pg_replication_origin_drop ( node_name text ) → void

Deletes a previously-created replication origin, including any associated replay progress.

pg_replication_origin_oid ( node_name text ) → oid

Looks up a replication origin by name and returns the internal ID. If no such replication origin is found, NULL is returned.

pg_replication_origin_session_setup ( node_name text ) → void

Marks the current session as replaying from the given origin, allowing replay progress to be tracked. Can only be used if no origin is currently selected. Use pg_replication_origin_session_reset to undo.

pg_replication_origin_session_reset () → void

Cancels the effects of pg_replication_origin_session_setup().

pg_replication_origin_session_is_setup () → boolean

Returns true if a replication origin has been selected in the current session.

pg_replication_origin_session_progress ( flush boolean ) → pg_lsn

Returns the replay location for the replication origin selected in the current session. The parameter flush determines whether the corresponding local transaction will be guaranteed to have been flushed to disk or not.

pg_replication_origin_xact_setup ( origin_lsn pg_lsn, origin_timestamp timestamp with time zone ) → void

Marks the current transaction as replaying a transaction that has committed at the given LSN and timestamp. Can only be called when a replication origin has been selected using pg_replication_origin_session_setup.

pg_replication_origin_xact_reset () → void

Cancels the effects of pg_replication_origin_xact_setup().

pg_replication_origin_advance ( node_name text, lsn pg_lsn ) → void

Sets replication progress for the given node to the given location. This is primarily useful for setting up the initial location, or setting a new location after configuration changes and similar. Be aware that careless use of this function can lead to inconsistently replicated data.

pg_replication_origin_progress ( node_name text, flush boolean ) → pg_lsn

Returns the replay location for the given replication origin. The parameter flush determines whether the corresponding local transaction will be guaranteed to have been flushed to disk or not.

pg_logical_emit_message ( transactional boolean, prefix text, content text ) → pg_lsn

pg_logical_emit_message ( transactional boolean, prefix text, content bytea ) → pg_lsn

Emits a logical decoding message. This can be used to pass generic messages to logical decoding plugins through WAL. The transactional parameter specifies if the message should be part of the current transaction, or if it should be written immediately and decoded as soon as the logical decoder reads the record. The prefix parameter is a textual prefix that can be used by logical decoding plugins to easily recognize messages that are interesting for them. The content parameter is the content of the message, given either in text or binary form.


9.27.7. Database Object Management Functions

The functions shown in Table 9.90 calculate the disk space usage of database objects, or assist in presentation of usage results. All these functions return sizes measured in bytes. If an OID that does not represent an existing object is passed to one of these functions, NULL is returned.

Table 9.90. Database Object Size Functions

Function

Description

pg_column_size ( "any" ) → integer

Shows the number of bytes used to store any individual data value. If applied directly to a table column value, this reflects any compression that was done.

pg_database_size ( name ) → bigint

pg_database_size ( oid ) → bigint

Computes the total disk space used by the database with the specified name or OID. To use this function, you must have CONNECT privilege on the specified database (which is granted by default) or be a member of the pg_read_all_stats role.

pg_indexes_size ( regclass ) → bigint

Computes the total disk space used by indexes attached to the specified table.

pg_relation_size ( relation regclass [, fork text ] ) → bigint

Computes the disk space used by one fork of the specified relation. (Note that for most purposes it is more convenient to use the higher-level functions pg_total_relation_size or pg_table_size, which sum the sizes of all forks.) With one argument, this returns the size of the main data fork of the relation. The second argument can be provided to specify which fork to examine:

  • main returns the size of the main data fork of the relation.

  • fsm returns the size of the Free Space Map (see Section 70.3) associated with the relation.

  • vm returns the size of the Visibility Map (see Section 70.4) associated with the relation.

  • init returns the size of the initialization fork, if any, associated with the relation.

pg_temp_relation_size ( relation regclass ) → bigint

Accepts the OID or name of a temporary table and returns the total size in bytes of main fork of that relation. We extend physical file for temp table when table doesn't fit into temp_buffers cache anymore. So total and on-disk size of the temporary table can differ. For other kinds of relations it will not throw any error, just return NULL.

pg_size_bytes ( text ) → bigint

Converts a size in human-readable format (as returned by pg_size_pretty) into bytes.

pg_size_pretty ( bigint ) → text

pg_size_pretty ( numeric ) → text

Converts a size in bytes into a more easily human-readable format with size units (bytes, kB, MB, GB or TB as appropriate). Note that the units are powers of 2 rather than powers of 10, so 1kB is 1024 bytes, 1MB is 10242 = 1048576 bytes, and so on.

pg_table_size ( regclass ) → bigint

Computes the disk space used by the specified table, excluding indexes (but including its TOAST table if any, free space map, and visibility map).

pg_tablespace_size ( name ) → bigint

pg_tablespace_size ( oid ) → bigint

Computes the total disk space used in the tablespace with the specified name or OID. To use this function, you must have CREATE privilege on the specified tablespace or be a member of the pg_read_all_stats role, unless it is the default tablespace for the current database.

pg_total_relation_size ( regclass ) → bigint

Computes the total disk space used by the specified table, including all indexes and TOAST data. The result is equivalent to pg_table_size + pg_indexes_size.


The functions above that operate on tables or indexes accept a regclass argument, which is simply the OID of the table or index in the pg_class system catalog. You do not have to look up the OID by hand, however, since the regclass data type's input converter will do the work for you. Just write the table name enclosed in single quotes so that it looks like a literal constant. For compatibility with the handling of ordinary SQL names, the string will be converted to lower case unless it contains double quotes around the table name.

The functions shown in Table 9.91 assist in identifying the specific disk files associated with database objects.

Table 9.91. Database Object Location Functions

Function

Description

pg_relation_filenode ( relation regclass ) → oid

Returns the filenode number currently assigned to the specified relation. The filenode is the base component of the file name(s) used for the relation (see Section 70.1 for more information). For most relations the result is the same as pg_class.relfilenode, but for certain system catalogs relfilenode is zero and this function must be used to get the correct value. The function returns NULL if passed a relation that does not have storage, such as a view.

pg_relation_filepath ( relation regclass ) → text

Returns the entire file path name (relative to the database cluster's data directory, PGDATA) of the relation.

pg_filenode_relation ( tablespace oid, filenode oid ) → regclass

Returns a relation's OID given the tablespace OID and filenode it is stored under. This is essentially the inverse mapping of pg_relation_filepath. For a relation in the database's default tablespace, the tablespace can be specified as zero. Returns NULL if no relation in the current database is associated with the given values, or if dealing with a temporary relation.


Table 9.92 lists functions used to manage collations.

Table 9.92. Collation Management Functions

Function

Description

pg_collation_actual_version ( oid ) → text

Returns the actual version of the collation object as it is currently installed in the operating system. If this is different from the value in pg_collation.collversion, then objects depending on the collation might need to be rebuilt. See also ALTER COLLATION.

pg_import_system_collations ( schema regnamespace ) → integer

Adds collations to the system catalog pg_collation based on all the locales it finds in the operating system. This is what initdb uses; see Section 23.2.2 for more details. If additional locales are installed into the operating system later on, this function can be run again to add collations for the new locales. Locales that match existing entries in pg_collation will be skipped. (But collation objects based on locales that are no longer present in the operating system are not removed by this function.) The schema parameter would typically be pg_catalog, but that is not a requirement; the collations could be installed into some other schema as well. The function returns the number of new collation objects it created. Use of this function is restricted to superusers.


Table 9.93 lists functions that provide information about the structure of partitioned tables.

Table 9.93. Partitioning Information Functions

Function

Description

pg_partition_tree ( regclass ) → setof record ( relid regclass, parentrelid regclass, isleaf boolean, level integer )

Lists the tables or indexes in the partition tree of the given partitioned table or partitioned index, with one row for each partition. Information provided includes the OID of the partition, the OID of its immediate parent, a boolean value telling if the partition is a leaf, and an integer telling its level in the hierarchy. The level value is 0 for the input table or index, 1 for its immediate child partitions, 2 for their partitions, and so on. Returns no rows if the relation does not exist or is not a partition or partitioned table.

pg_partition_ancestors ( regclass ) → setof regclass

Lists the ancestor relations of the given partition, including the relation itself. Returns no rows if the relation does not exist or is not a partition or partitioned table.

pg_partition_root ( regclass ) → regclass

Returns the top-most parent of the partition tree to which the given relation belongs. Returns NULL if the relation does not exist or is not a partition or partitioned table.


For example, to check the total size of the data contained in a partitioned table measurement, one could use the following query:

SELECT pg_size_pretty(sum(pg_relation_size(relid))) AS total_size
  FROM pg_partition_tree('measurement');

9.27.8. Index Maintenance Functions

Table 9.94 shows the functions available for index maintenance tasks. (Note that these maintenance tasks are normally done automatically by autovacuum; use of these functions is only required in special cases.) These functions cannot be executed during recovery. Use of these functions is restricted to superusers and the owner of the given index.

Table 9.94. Index Maintenance Functions

Function

Description

brin_summarize_new_values ( index regclass ) → integer

Scans the specified BRIN index to find page ranges in the base table that are not currently summarized by the index; for any such range it creates a new summary index tuple by scanning those table pages. Returns the number of new page range summaries that were inserted into the index.

brin_summarize_range ( index regclass, blockNumber bigint ) → integer

Summarizes the page range covering the given block, if not already summarized. This is like brin_summarize_new_values except that it only processes the page range that covers the given table block number.

brin_desummarize_range ( index regclass, blockNumber bigint ) → void

Removes the BRIN index tuple that summarizes the page range covering the given table block, if there is one.

gin_clean_pending_list ( index regclass ) → bigint

Cleans up the pending list of the specified GIN index by moving entries in it, in bulk, to the main GIN data structure. Returns the number of pages removed from the pending list. If the argument is a GIN index built with the fastupdate option disabled, no cleanup happens and the result is zero, because the index doesn't have a pending list. See Section 67.4.1 and Section 67.5 for details about the pending list and fastupdate option.


9.27.9. Generic File Access Functions

The functions shown in Table 9.95 provide native access to files on the machine hosting the server. Only files within the database cluster directory and the log_directory can be accessed, unless the user is a superuser or is granted the role pg_read_server_files. Use a relative path for files in the cluster directory, and a path matching the log_directory configuration setting for log files.

Note that granting users the EXECUTE privilege on pg_read_file(), or related functions, allows them the ability to read any file on the server that the database server process can read; these functions bypass all in-database privilege checks. This means that, for example, a user with such access is able to read the contents of the pg_authid table where authentication information is stored, as well as read any table data in the database. Therefore, granting access to these functions should be carefully considered.

Some of these functions take an optional missing_ok parameter, which specifies the behavior when the file or directory does not exist. If true, the function returns NULL or an empty result set, as appropriate. If false, an error is raised. The default is false.

Table 9.95. Generic File Access Functions

Function

Description

pg_ls_dir ( dirname text [, missing_ok boolean, include_dot_dirs boolean ] ) → setof text

Returns the names of all files (and directories and other special files) in the specified directory. The include_dot_dirs parameter indicates whether . and .. are to be included in the result set; the default is to exclude them. Including them can be useful when missing_ok is true, to distinguish an empty directory from a non-existent directory.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_ls_logdir () → setof record ( name text, size bigint, modification timestamp with time zone )

Returns the name, size, and last modification time (mtime) of each ordinary file in the server's log directory. Filenames beginning with a dot, directories, and other special files are excluded.

This function is restricted to superusers and members of the pg_monitor role by default, but other users can be granted EXECUTE to run the function.

pg_ls_waldir () → setof record ( name text, size bigint, modification timestamp with time zone )

Returns the name, size, and last modification time (mtime) of each ordinary file in the server's write-ahead log (WAL) directory. Filenames beginning with a dot, directories, and other special files are excluded.

This function is restricted to superusers and members of the pg_monitor role by default, but other users can be granted EXECUTE to run the function.

pg_ls_archive_statusdir () → setof record ( name text, size bigint, modification timestamp with time zone )

Returns the name, size, and last modification time (mtime) of each ordinary file in the server's WAL archive status directory (pg_wal/archive_status). Filenames beginning with a dot, directories, and other special files are excluded.

This function is restricted to superusers and members of the pg_monitor role by default, but other users can be granted EXECUTE to run the function.

pg_ls_tmpdir ( [ tablespace oid ] ) → setof record ( name text, size bigint, modification timestamp with time zone )

Returns the name, size, and last modification time (mtime) of each ordinary file in the temporary file directory for the specified tablespace. If tablespace is not provided, the pg_default tablespace is examined. Filenames beginning with a dot, directories, and other special files are excluded.

This function is restricted to superusers and members of the pg_monitor role by default, but other users can be granted EXECUTE to run the function.

pg_read_file ( filename text [, offset bigint, length bigint [, missing_ok boolean ]] ) → text

Returns all or part of a text file, starting at the given byte offset, returning at most length bytes (less if the end of file is reached first). If offset is negative, it is relative to the end of the file. If offset and length are omitted, the entire file is returned. The bytes read from the file are interpreted as a string in the database's encoding; an error is thrown if they are not valid in that encoding.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

pg_read_binary_file ( filename text [, offset bigint, length bigint [, missing_ok boolean ]] ) → bytea

Returns all or part of a file. This function is identical to pg_read_file except that it can read arbitrary binary data, returning the result as bytea not text; accordingly, no encoding checks are performed.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.

In combination with the convert_from function, this function can be used to read a text file in a specified encoding and convert to the database's encoding:

SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');

pg_stat_file ( filename text [, missing_ok boolean ] ) → record ( size bigint, access timestamp with time zone, modification timestamp with time zone, change timestamp with time zone, creation timestamp with time zone, isdir boolean )

Returns a record containing the file's size, last access time stamp, last modification time stamp, last file status change time stamp (Unix platforms only), file creation time stamp (Windows only), and a flag indicating if it is a directory.

This function is restricted to superusers by default, but other users can be granted EXECUTE to run the function.


9.27.10. Advisory Lock Functions

The functions shown in Table 9.96 manage advisory locks. For details about proper use of these functions, see Section 13.3.5.

All these functions are intended to be used to lock application-defined resources, which can be identified either by a single 64-bit key value or two 32-bit key values (note that these two key spaces do not overlap). If another session already holds a conflicting lock on the same resource identifier, the functions will either wait until the resource becomes available, or return a false result, as appropriate for the function. Locks can be either shared or exclusive: a shared lock does not conflict with other shared locks on the same resource, only with exclusive locks. Locks can be taken at session level (so that they are held until released or the session ends) or at transaction level (so that they are held until the current transaction ends; there is no provision for manual release). Multiple session-level lock requests stack, so that if the same resource identifier is locked three times there must then be three unlock requests to release the resource in advance of session end.

Table 9.96. Advisory Lock Functions

Function

Description

pg_advisory_lock ( key bigint ) → void

pg_advisory_lock ( key1 integer, key2 integer ) → void

Obtains an exclusive session-level advisory lock, waiting if necessary.

pg_advisory_lock_shared ( key bigint ) → void

pg_advisory_lock_shared ( key1 integer, key2 integer ) → void

Obtains a shared session-level advisory lock, waiting if necessary.

pg_advisory_unlock ( key bigint ) → boolean

pg_advisory_unlock ( key1 integer, key2 integer ) → boolean

Releases a previously-acquired exclusive session-level advisory lock. Returns true if the lock is successfully released. If the lock was not held, false is returned, and in addition, an SQL warning will be reported by the server.

pg_advisory_unlock_all () → void

Releases all session-level advisory locks held by the current session. (This function is implicitly invoked at session end, even if the client disconnects ungracefully.)

pg_advisory_unlock_shared ( key bigint ) → boolean

pg_advisory_unlock_shared ( key1 integer, key2 integer ) → boolean

Releases a previously-acquired shared session-level advisory lock. Returns true if the lock is successfully released. If the lock was not held, false is returned, and in addition, an SQL warning will be reported by the server.

pg_advisory_xact_lock ( key bigint ) → void

pg_advisory_xact_lock ( key1 integer, key2 integer ) → void

Obtains an exclusive transaction-level advisory lock, waiting if necessary.

pg_advisory_xact_lock_shared ( key bigint ) → void

pg_advisory_xact_lock_shared ( key1 integer, key2 integer ) → void

Obtains a shared transaction-level advisory lock, waiting if necessary.

pg_try_advisory_lock ( key bigint ) → boolean

pg_try_advisory_lock ( key1 integer, key2 integer ) → boolean

Obtains an exclusive session-level advisory lock if available. This will either obtain the lock immediately and return true, or return false without waiting if the lock cannot be acquired immediately.

pg_try_advisory_lock_shared ( key bigint ) → boolean

pg_try_advisory_lock_shared ( key1 integer, key2 integer ) → boolean

Obtains a shared session-level advisory lock if available. This will either obtain the lock immediately and return true, or return false without waiting if the lock cannot be acquired immediately.

pg_try_advisory_xact_lock ( key bigint ) → boolean

pg_try_advisory_xact_lock ( key1 integer, key2 integer ) → boolean

Obtains an exclusive transaction-level advisory lock if available. This will either obtain the lock immediately and return true, or return false without waiting if the lock cannot be acquired immediately.

pg_try_advisory_xact_lock_shared ( key bigint ) → boolean

pg_try_advisory_xact_lock_shared ( key1 integer, key2 integer ) → boolean

Obtains a shared transaction-level advisory lock if available. This will either obtain the lock immediately and return true, or return false without waiting if the lock cannot be acquired immediately.


9.27.11. Compression Control Functions

The functions shown in Table 9.97 provide information about CFS state and activity and control CFS garbage collection.

Table 9.97. Compression Control Functions

NameReturn TypeDescription
cfs_start_gc(n_workers integer)integerStarts garbage collection using the specified number of workers. You can only run this function to start the garbage collection manually if background garbage collection is disabled.
cfs_enable_gc(enabled boolean)booleanEnables/disables background garbage collection. Alternatively, you can use the cfs_gc configuration variable.
cfs_gc_relation(rel regclass)integerPerforms garbage collection for a particular table. This function returns the number of processed segments.
cfs_version()textDisplays the CFS version and the specific compression algorithm used.
cfs_estimate(rel regclass)float8Estimates the effect of table compression. Returns the average compression ratio for the first ten percent of relation blocks (but no more than 100 blocks).
cfs_compression_ratio(rel regclass)float8Returns the actual compression ratio for all segments of the compressed relation.
cfs_fragmentation(rel regclass)float8Returns the average fragmentation ratio of the relation files.
cfs_gc_activity_processed_bytes()int64Returns the total size of pages processed by CFS during garbage collection.
cfs_gc_activity_processed_pages()int64Returns the number of pages processed by CFS during garbage collection.
cfs_gc_activity_processed_files()int64Returns the number of files compacted by CFS during garbage collection.
cfs_gc_activity_scanned_files()int64Returns the number of files scanned by CFS during garbage collection.

9.27.12. Operation Log Support Functions

An operation log stores information about system events of critical importance, such as an upgrade, execution of pg_resetwal and so on. This information is not interesting to regular users, but is highly useful for vendor's technical support. Recording to the operation log is only done at the system level (without any actions on the part of the user), and SQL functions are used to read the operation log. The function shown in Table 9.98 reads the operation log.

Table 9.98. Operation Log Support Functions

Function

Description

pg_operation_log () → setof record ( event text, edition text, version text, lsn pg_lsn, last timestamptz, count int4 )

Where:

  • event — event (operation) type. Can be bootstrap, startup, pg_resetwal, pg_rewind, pg_upgrade or promoted.

  • editionPostgres Pro edition. Can be vanilla, 1c, std, ent or unknown.

  • versionPostgres Pro version.

  • lsn — latest checkpoint location, returned by pg_controldata as of the moment when the event occurs.

  • last — date/time of the last occurrence of this event type if events are accumulated or date/time of the event occurrence otherwise.

  • count — number of events of this type if events are accumulated or 1 otherwise.

This system function is created automatically for new databases and needs to be created for existing databases, as follows:

CREATE OR REPLACE FUNCTION
  pg_operation_log(
    OUT event text,
    OUT edition text,
    OUT version text,
    OUT lsn pg_lsn,
    OUT last timestamptz,
    OUT count int4)
 RETURNS SETOF record
 LANGUAGE INTERNAL
 STABLE STRICT PARALLEL SAFE
AS 'pg_operation_log';         


This is an example of what the pg_operation_log function returns:

select * from pg_operation_log();
   event    | edition | version |    lsn    |          last          | count
------------+---------+---------+-----------+------------------------+-------
 startup    | vanilla | 10.22.0 | 0/8000028 | 2022-10-27 23:06:27+03 |     1
 pg_upgrade | 1c      | 15.0.0  | 0/8000028 | 2022-10-27 23:06:27+03 |     1
 startup    | 1c      | 15.0.0  | 0/80001F8 | 2022-10-27 23:06:53+03 |     2
(3 rows)

Note

If an operation log is empty, before a record for pg_upgrade, a record is added for startup with the previous version having the following specifics: as there is no information in pg_upgrade on the patch version number of the previous version for each edition (1c, std, ent), the patch version number (third number in the version number) is set to zero. For an upgrade from 1c or vanilla, it cannot be distinguished whether the edition of the database before upgrade is vanilla or 1c, and vanilla edition is used for the startup record.

9.27.13. Debugging Functions

The function shown in Table 9.99 can assist you in low-level activities, such as debugging or exploring corrupted Postgres Pro databases.

Table 9.99. Snapshot Synchronization Functions

NameReturn TypeDescription
pg_snapshot_any()voidSets the current transaction to ignore MVCC rules and see all versions of data.

Use pg_snapshot_any with care. Run it in a transaction with isolation level REPEATABLE READ or higher, otherwise the specific snapshot will be replaced by a new one by the next query. Only superusers can run this function.

Note

If you created the database cluster using the server version that did not provide this function, execute the command:

CREATE FUNCTION pg_snapshot_any() RETURNS void AS 'pg_snapshot_any' LANGUAGE internal;

FAQ