57.25. pg_settings #

Представление pg_settings открывает доступ к параметрам времени выполнения сервера. По сути оно представляет собой альтернативный интерфейс для команд SHOW и SET. Оно также позволяет получить некоторые свойства каждого параметра, которые нельзя получить непосредственно, используя команду SHOW, например минимальные и максимальные значения.

Таблица 57.25. Столбцы pg_settings

Тип столбца

Описание

name text

Имя параметра конфигурации времени выполнения

setting text

Текущее значение параметра

unit text

Неявно подразумеваемая единица измерения параметра

category text

Логическая группа параметра

short_desc text

Краткое описание параметра

extra_desc text

Дополнительное, более подробное, описание параметра

context text

Контекст, в котором может задаваться значение параметра (см. ниже)

vartype text

Тип параметра (bool, enum, integer, real или string)

source text

Источник текущего значения параметра

min_val text

Минимальное допустимое значение параметра (NULL для нечисловых значений)

max_val text

Максимально допустимое значение параметра (NULL для нечисловых значений)

enumvals text[]

Допустимые значения параметра-перечисления (NULL для значений не перечислений)

boot_val text

Значение параметра, устанавливаемое при запуске сервера, если параметр не устанавливается другим образом

reset_val text

Значение, к которому будет сбрасывать параметр команда RESET в текущем сеансе

sourcefile text

Файл конфигурации, в котором было задано текущее значение (NULL для значений, полученных не из файлов конфигурации, или при чтении этого поля не суперпользователем и не пользователем с правами роли pg_read_all_settings); полезно при использовании указаний include в файлах конфигурации

sourceline int4

Номер строки в файле конфигурации, в которой было задано текущее значение (NULL для значений, полученных не из файлов конфигурации, или при чтении этого поля не суперпользователем и не пользователем с правами роли pg_read_all_settings).

pending_restart bool

true, если значение изменено в файле конфигурации, но требуется перезапуск; в противном случае — false.


Поле context может содержать одно из следующих значений (они перечислены в порядке уменьшения сложности изменения параметров):

internal

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

postmaster

Эти параметры могут быть применены только при запуске сервера, так что любое изменение требует перезапуска сервера. Значения этих параметров обычно задаются в postgresql.conf, либо передаются в командной строке при запуске сервера. Разумеется, параметры более низкого уровня context также можно задать в момент запуска сервера.

sighup

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

superuser-backend

Внесённые в postgresql.conf изменения этих параметров можно применить без перезапуска сервера; их также можно задать для определённого сеанса в пакете запроса соединения (например, через переменную окружения PGOPTIONS, учитываемую библиотекой libpq), но сделать это может только суперпользователь или пользователь с соответствующими правами SET. Однако эти параметры никогда не меняются в сеансе, когда он уже начат. Если вы измените их в postgresql.conf, отправьте сигнал SIGHUP управляющему процессу, чтобы он перечитал postgresql.conf. Новые значения подействуют только на сеансы, запускаемые после этого.

backend

Внесённые в postgresql.conf изменения этих параметров можно применить без перезапуска сервера; их также можно задать для определённого сеанса в пакете запроса соединения (например, через переменную окружения PGOPTIONS, учитываемую библиотекой libpq); это может сделать любой пользователь в своём сеансе. Однако эти параметры никогда не меняются в сеансе, когда он уже начат. Если вы измените их в postgresql.conf, отправьте сигнал SIGHUP управляющему процессу, чтобы он перечитал postgresql.conf. Новые значения подействуют только на сеансы, запускаемые после этого.

superuser

Эти параметры можно изменить в postgresql.conf, либо в рамках сеанса, командой SET; но только суперпользователи и пользователи с соответствующими правами SET могут менять их, используя SET. Изменения postgresql.conf не повлияют на существующие сеансы, если в них командой SET были заданы локальные значения.

user

Эти параметры можно задать в postgresql.conf, либо в рамках сеанса, командой SET. В рамках сеанса изменять их разрешено всем пользователям. Изменения в postgresql.conf будут отражены в существующих сеансах, только если в них командой SET не были заданы локальные значения.

Чтобы узнать больше о различных способах изменения этих параметров, обратитесь к Разделу 19.1.

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

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

57.25. pg_settings #

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

Table 57.25. pg_settings Columns

Column Type

Description

name text

Run-time configuration parameter name

setting text

Current value of the parameter

unit text

Implicit unit of the parameter

category text

Logical group of the parameter

short_desc text

A brief description of the parameter

extra_desc text

Additional, more detailed, description of the parameter

context text

Context required to set the parameter's value (see below)

vartype text

Parameter type (bool, enum, integer, real, or string)

source text

Source of the current parameter value

min_val text

Minimum allowed value of the parameter (null for non-numeric values)

max_val text

Maximum allowed value of the parameter (null for non-numeric values)

enumvals text[]

Allowed values of an enum parameter (null for non-enum values)

boot_val text

Parameter value assumed at server startup if the parameter is not otherwise set

reset_val text

Value that RESET would reset the parameter to in the current session

sourcefile text

Configuration file the current value was set in (null for values set from sources other than configuration files, or when examined by a user who neither is a superuser nor has privileges of pg_read_all_settings); helpful when using include directives in configuration files

sourceline int4

Line number within the configuration file the current value was set at (null for values set from sources other than configuration files, or when examined by a user who neither is a superuser nor has privileges of pg_read_all_settings).

pending_restart bool

true if the value has been changed in the configuration file but needs a restart; or false otherwise.


There are several possible values of context. In order of decreasing difficulty of changing the setting, they are:

internal

These settings cannot be changed directly; they reflect internally determined values. Some of them may be adjustable by rebuilding the server with different configuration options, or by changing options supplied to initdb.

postmaster

These settings can only be applied when the server starts, so any change requires restarting the server. Values for these settings are typically stored in the postgresql.conf file, or passed on the command line when starting the server. Of course, settings with any of the lower context types can also be set at server start time.

sighup

Changes to these settings can be made in postgresql.conf without restarting the server. Send a SIGHUP signal to the postmaster to cause it to re-read postgresql.conf and apply the changes. The postmaster will also forward the SIGHUP signal to its child processes so that they all pick up the new value.

superuser-backend

Changes to these settings can be made in postgresql.conf without restarting the server. They can also be set for a particular session in the connection request packet (for example, via libpq's PGOPTIONS environment variable), but only if the connecting user is a superuser or has been granted the appropriate SET privilege. However, these settings never change in a session after it is started. If you change them in postgresql.conf, send a SIGHUP signal to the postmaster to cause it to re-read postgresql.conf. The new values will only affect subsequently-launched sessions.

backend

Changes to these settings can be made in postgresql.conf without restarting the server. They can also be set for a particular session in the connection request packet (for example, via libpq's PGOPTIONS environment variable); any user can make such a change for their session. However, these settings never change in a session after it is started. If you change them in postgresql.conf, send a SIGHUP signal to the postmaster to cause it to re-read postgresql.conf. The new values will only affect subsequently-launched sessions.

superuser

These settings can be set from postgresql.conf, or within a session via the SET command; but only superusers and users with the appropriate SET privilege can change them via SET. Changes in postgresql.conf will affect existing sessions only if no session-local value has been established with SET.

user

These settings can be set from postgresql.conf, or within a session via the SET command. Any user is allowed to change their session-local value. Changes in postgresql.conf will affect existing sessions only if no session-local value has been established with SET.

See Section 19.1 for more information about the various ways to change these parameters.

This view cannot be inserted into or deleted from, but it can be updated. An UPDATE applied to a row of pg_settings is equivalent to executing the SET command on that named parameter. The change only affects the value used by the current session. If an UPDATE is issued within a transaction that is later aborted, the effects of the UPDATE command disappear when the transaction is rolled back. Once the surrounding transaction is committed, the effects will persist until the end of the session, unless overridden by another UPDATE or SET.

This view does not display customized options unless the extension module that defines them has been loaded by the backend process executing the query (e.g., via a mention in shared_preload_libraries, a call to a C function in the extension, or the LOAD command). For example, since archive modules are normally loaded only by the archiver process not regular sessions, this view will not display any customized options defined by such modules unless special action is taken to load them into the backend process executing the query.

FAQ