9.26. Системные информационные функции и операторы #

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

9.26.1. Функции получения информации о сеансе #

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

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

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

Функция

Описание

current_catalogname

current_database () → name

Выдаёт имя текущей базы данных. (В стандарте SQL базы данных называются «каталогами», поэтому стандарту соответствует написание current_catalog.)

current_query () → text

Выдаёт текст запроса, выполняемого в данный момент, в том виде, в каком его передал клиент (может состоять из нескольких операторов).

current_rolename

Аналог current_user.

current_schemaname

current_schema () → name

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

current_schemas ( include_implicit boolean ) → name[]

Выдаёт массив имён всех схем, в настоящее время представленных в действующем пути поиска, по порядку их приоритета. (Элементы текущего значения search_path, которым не соответствуют существующие схемы, опускаются). Если логический аргумент равен true, в результат включаются системные схемы, неявно просматриваемые при поиске, например, pg_catalog.

current_username

Выдаёт имя пользователя в текущем контексте выполнения.

inet_client_addr () → inet

Выдаёт IP-адрес текущего клиента либо NULL, если текущее соединение установлено через Unix-сокет.

inet_client_port () → integer

Выдаёт номер TCP-порта текущего клиента либо NULL, если текущее подключение установлено через Unix-сокет.

inet_server_addr () → inet

Выдаёт IP-адрес, через который сервер принял текущее подключение, либо NULL, если текущее подключение установлено через Unix-сокет.

inet_server_port () → integer

Выдаёт номер TCP-порта, через который сервер принял текущее подключение, либо NULL, если текущее подключение установлено через Unix-сокет.

pg_backend_pid () → integer

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

pg_blocking_pids ( integer ) → integer[]

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

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

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

pg_conf_load_time () → timestamp with time zone

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

pg_current_logfile ( [text] ) → text

Выдаёт путь к файлу журнала, в настоящее время используемому сборщиком сообщений. Этот путь состоит из пути каталога log_directory и имени конкретного файла. Если сборщик сообщений отключён, выдаётся значение NULL. Если ведутся несколько журналов в разных форматах, при вызове функции pg_current_logfile без аргументов возвращается путь первого существующего файла следующего формата (в порядке приоритета): stderr, csvlog, jsonlog. Если файл журнала в этих форматах отсутствует, выдаётся NULL. Чтобы запросить информацию о файле в определённом формате, передайте csvlog, jsonlog или stderr в качестве значения необязательного параметра типа text. Если запрошенный формат не включён в log_destination, результатом будет NULL. Результат функции отражает содержимое файла current_logfiles.

pg_my_temp_schema () → oid

Выдаёт OID временной схемы текущего сеанса или 0, если такой схемы нет (в рамках сеанса не создавались временные таблицы).

pg_is_other_temp_schema ( oid ) → boolean

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

pg_jit_available () → boolean

Выдаёт true, если в данном сеансе доступна JIT-компиляция (см. Главу 30) и параметр конфигурации jit включён.

pg_listening_channels () → setof text

Выдаёт список имён каналов асинхронных уведомлений, по которым текущий сеанс принимает сигналы.

pg_notification_queue_usage () → double precision

Выдаёт долю (0–1) максимального размера очереди асинхронных уведомлений, в настоящее время занятую уведомлениями, ожидающими обработки. За дополнительными сведениями обратитесь к LISTEN и NOTIFY.

pg_postmaster_start_time () → timestamp with time zone

Выдаёт время, когда был запущен сервер.

pg_safe_snapshot_blocking_pids ( integer ) → integer[]

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

Сеанс, выполняющий транзакцию уровня SERIALIZABLE, блокирует транзакцию SERIALIZABLE READ ONLY DEFERRABLE, не давая ей получить снимок, пока она не определит, что можно безопасно избежать установления предикатных блокировок. За дополнительными сведениями о сериализуемых и откладываемых транзакциях обратитесь к Подразделу 13.2.3.

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

pg_trigger_depth () → integer

Выдаёт текущий уровень вложенности в триггерах Postgres Pro (0, если эта функция вызывается не из тела триггера, непосредственно или косвенно).

session_username

Выдаёт имя пользователя сеанса.

system_usertext

Возвращает метод аутентификации и идентификационную информацию (если есть), которые пользователь представил во время цикла аутентификации до того, как ему была назначена роль базы данных. Он представлен как auth_method:identity или NULL, если пользователь не прошел аутентификацию (например, если была использована аутентификация trust).

username

Аналог current_user.

version () → text

Выдаёт текстовую строку, описывающую версию сервера PostgreSQL. Эту информацию также можно получить из переменной server_version или, в более машинно-ориентированном формате, из переменной server_version_num. При разработке программ следует использовать функцию server_version_num (появившуюся в версии 8.2) или PQserverVersion, а не разбирать текстовую версию.

pgpro_version () → text

Выдаёт текстовую строку, описывающую версию сервера Postgres Pro.

pgpro_edition () → text

Выдаёт текстовую строку, описывающую редакцию Postgres Pro, например standard или enterprise.

pgpro_build () → text

Выдаёт идентификатор состояния исходного кода, из которого скомпилирован Postgres Pro.


Примечание

Функции current_catalog, current_role, current_schema, current_user, session_user и user имеют особый синтаксический статус в SQL: они должны вызываться без скобок после имени. Postgres Pro позволяет добавить скобки в вызове current_schema, но не других функций.

Функция session_user обычно возвращает имя пользователя, установившего текущее соединение с базой данных, но суперпользователи могут изменить это имя, выполнив команду SET SESSION AUTHORIZATION. Функция current_user возвращает идентификатор пользователя, по которому будут проверяться его права. Обычно это тот же пользователь, что и пользователь сеанса, но его можно сменить с помощью SET ROLE. Этот идентификатор также меняется при выполнении функций с атрибутом SECURITY DEFINER. На языке Unix пользователь сеанса называется «реальным», а текущий — «эффективным». Имена current_role и user являются синонимами current_user. (В стандарте SQL current_role и current_user имеют разное значение, но в Postgres Pro они не различаются, так как пользователи и роли объединены в единую сущность.)

9.26.2. Функции для проверки прав доступа #

В Таблице 9.69 показаны функции, позволяющие программно проверить права доступа к объектам. (Подробнее о правах рассказывается в Разделе 5.7.) Этим функциям в качестве идентификатора пользователя, для которого запрашиваются права, можно передать его имя или OID (pg_authid.oid), а также можно передать public (это будет указывать на псевдороль PUBLIC). Кроме того, аргумент user можно полностью опустить, тогда будет подразумеваться current_user. Объект, права для доступа к которому запрашиваются, также можно задать по имени или по OID. Когда указывается имя объекта, его можно дополнить именем схемы, если это уместно. Запрашиваемое право записывается текстовой строкой, которая должна задавать одно из прав доступа, соответствующих типу объекта (например, SELECT). Дополнительно к названию права можно добавить WITH GRANT OPTION и проверить, разрешено ли пользователю передавать это право другим. Кроме того, в одном параметре можно перечислить несколько прав через запятую, и тогда функция возвратит true, если пользователь имеет какие-либо из них. (Регистр в названии прав не имеет значения, а между ними (но не внутри) разрешены пробельные символы.) Пара примеров:

SELECT has_table_privilege('myschema.mytable', 'select');
SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');

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

Функция

Описание

has_any_column_privilege ( [user name или oid, ] table text или oid, privilege text ) → boolean

Имеет ли пользователь указанное право для какого-либо столбца таблицы? Ответ положительный, когда он имеет это право для всей таблицы или ему дано соответствующее право на уровне столбцов хотя бы для одного столбца. Возможные права: SELECT, INSERT, UPDATE и REFERENCES.

has_column_privilege ( [user name или oid, ] table text или oid, column text или smallint, privilege text ) → boolean

Имеет ли пользователь указанное право для заданного столбца таблицы? Ответ положительный, когда он имеет это право для всей таблицы или ему дано соответствующее право на уровне столбца. Столбец можно задать по имени или номеру атрибута (pg_attribute.attnum). Возможные права: SELECT, INSERT, UPDATE и REFERENCES.

has_database_privilege ( [user name или oid, ] database text или oid, privilege text ) → boolean

Имеет ли пользователь указанное право в базе данных? Возможные права: CREATE, CONNECT, TEMPORARY и TEMP (синоним TEMPORARY).

has_foreign_data_wrapper_privilege ( [user name или oid, ] fdw text или oid, privilege text ) → boolean

Имеет ли пользователь право для обёртки сторонних данных? На данный момент возможно только одно право: USAGE.

has_function_privilege ( [user name или oid, ] function text или oid, privilege text ) → boolean

Имеет ли пользователь право для функции? Возможно единственное право: EXECUTE.

При указании функции по имени, а не по OID, допускаются те же входные значения, что и для типа regprocedure (см. Раздел 8.19). Например:

SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');

has_language_privilege ( [user name или oid, ] language text или oid, privilege text ) → boolean

Имеет ли пользователь право для языка? Возможно единственное право: USAGE.

has_parameter_privilege ( [user name или oid, ] parameter text, privilege text ) → boolean

Имеет ли пользователь право для параметра конфигурации? Регистр в имени параметра игнорируется. Возможные права: SET и ALTER SYSTEM.

has_schema_privilege ( [user name или oid, ] schema text или oid, privilege text ) → boolean

Имеет ли пользователь право для схемы? Возможные права: CREATE и USAGE.

has_sequence_privilege ( [user name или oid, ] sequence text или oid, privilege text ) → boolean

Имеет ли пользователь право для последовательности? Возможные права: USAGE, SELECT и UPDATE.

has_server_privilege ( [user name или oid, ] server text или oid, privilege text ) → boolean

Имеет ли пользователь право для стороннего сервера? На данный момент возможно только одно право: USAGE.

has_table_privilege ( [user name или oid, ] table text или oid, privilege text ) → boolean

Имеет ли пользователь право для таблицы? Возможные права: SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES и TRIGGER.

has_tablespace_privilege ( [user name или oid, ] tablespace text или oid, privilege text ) → boolean

Имеет ли пользователь право для табличного пространства? Возможно единственное право: CREATE.

has_type_privilege ( [user name или oid, ] type text или oid, privilege text ) → boolean

Имеет ли пользователь право для типа данных? Возможно единственное право: USAGE. При указании типа по имени, а не по OID, допускаются те же входные значения, что и для типа данных regtype (см. Раздел 8.19).

pg_has_role ( [user name или oid, ] role text или oid, privilege text ) → boolean

Имеет ли пользователь право для роли? Возможные права: MEMBER, USAGE и SET. Под MEMBER подразумевается непосредственное или косвенное членство в роли независимо от того, какие особые права могут быть предоставлены. USAGE означает, что пользователь получает права этой роли автоматически, не выполняя SET ROLE, а SET — можно ли изменить роль командой SET ROLE. К любому из этих типов прав можно добавить WITH ADMIN OPTION или WITH GRANT OPTION, чтобы проверить, имеется ли право ADMIN (все шесть вариантов написания проверяют одно и то же). Эта функция не поддерживает особый случай установки значения public для user, так как псевдороль PUBLIC не может быть членом обычных ролей.

row_security_active ( table text или oid ) → boolean

Действует ли защита на уровне строк для заданной таблицы в контексте текущего пользователя в текущем окружении?


В Таблице 9.70 показаны операторы, предназначенные для работы с типом aclitem, который представляет в системном каталоге права доступа. О содержании значений этого типа рассказывается в Разделе 5.7.

Таблица 9.70. Операторы для типа aclitem

Оператор

Описание

Пример(ы)

aclitem = aclitemboolean

Значения aclitem равны? (Заметьте, что для типа aclitem не определён обычный набор операторов сравнения, поддерживается только проверка равенства. Массивы aclitem, в свою очередь, также могут сравниваться только на равенство.)

'calvin=r*w/hobbes'::aclitem = 'calvin=r*w*/hobbes'::aclitemf

aclitem[] @> aclitemboolean

Содержит ли массив заданное право? (Ответ положительный, если в массиве есть запись, соответствующая правообладателю и праводателю из aclitem и содержащая как минимум указанный набор прав.)

'{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] @> 'calvin=r*/hobbes'::aclitemt

aclitem[] ~ aclitemboolean

Это устаревший синоним для @>.

'{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] ~ 'calvin=r*/hobbes'::aclitemt


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

Таблица 9.71. Функции для типа aclitem

Функция

Описание

acldefault ( type "char", ownerId oid ) → aclitem[]

Выдаёт массив с элементами aclitem, содержащий действующий по умолчанию набор прав доступа для объектов типа type, принадлежащих роли ownerId. Результат показывает, какие права доступа подразумеваются, когда список ACL определённого объекта пуст. (Права доступа, действующие по умолчанию, описываются в Разделе 5.7.) Параметр type может принимать одно из следующих значений: 'c' —столбец (COLUMN), 'r' — таблица или подобный таблице объект (TABLE), 's' — последовательность (SEQUENCE), 'd' — база данных (DATABASE), 'f' — функция (FUNCTION) или процедура (PROCEDURE), 'l' — язык (LANGUAGE), 'L' — большой объект (LARGE OBJECT), 'n' — схема (SCHEMA), 'p' — параметр (PARAMETER), 't' — табличное пространство (TABLESPACE), 'F' — обёртка сторонних данных (FOREIGN DATA WRAPPER), 'S' — сторонний сервер (FOREIGN SERVER) и 'T' — тип (TYPE) или домен (DOMAIN).

aclexplode ( aclitem[] ) → setof record ( grantor oid, grantee oid, privilege_type text, is_grantable boolean )

Возвращает массив aclitem в виде набора табличных строк. Если праводателем является псевдороль PUBLIC, она представляется нулём в столбце grantee. Назначенные права представляются ключевыми словами SELECT, INSERT и т. д. (полный список находится в Таблице 5.1). Заметьте, что каждое право выводится в отдельной строке, так что в столбце privilege_type содержится только одно ключевое слово.

makeaclitem ( grantee oid, grantor oid, privileges text, is_grantable boolean ) → aclitem

Конструирует значение aclitem с заданными свойствами. В аргументе privileges передаётся список имён прав, разделённых запятыми, таких как SELECT, INSERT и т. д., которые устанавливаются в результате. (Регистр строки права не имеет значения, дополнительные пробелы допускаются между именами прав, но не внутри них.)


9.26.3. Функции для определения видимости #

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

SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);

Объект, представляющий функцию и оператор, считаются видимым в пути поиска, если при просмотре пути не находится предшествующий ему другой объект с тем же именем и типами аргументов. Для семейств и классов операторов помимо имени объекта во внимание принимается также связанный метод доступа к индексу.

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

Функция

Описание

pg_collation_is_visible ( collation oid ) → boolean

Видимо ли правило сортировки в пути поиска?

pg_conversion_is_visible ( conversion oid ) → boolean

Видимо ли преобразование в пути поиска?

pg_function_is_visible ( function oid ) → boolean

Видима ли функция в пути поиска? (Также работает для процедур и агрегатных функций.)

pg_opclass_is_visible ( opclass oid ) → boolean

Виден ли класс операторов в пути поиска?

pg_operator_is_visible ( operator oid ) → boolean

Видим ли оператор в пути поиска?

pg_opfamily_is_visible ( opclass oid ) → boolean

Видимо ли семейство операторов в пути поиска?

pg_statistics_obj_is_visible ( stat oid ) → boolean

Видим ли объект статистики в пути поиска?

pg_table_is_visible ( table oid ) → boolean

Видима ли таблица в пути поиска? (Эта проверка работает со всеми типами отношений, включая представления, матпредставления, индексы, последовательности и сторонние таблицы.)

pg_ts_config_is_visible ( config oid ) → boolean

Видима ли конфигурация текстового поиска?

pg_ts_dict_is_visible ( dict oid ) → boolean

Видим ли словарь текстового поиска?

pg_ts_parser_is_visible ( parser oid ) → boolean

Видим ли анализатор текстового поиска?

pg_ts_template_is_visible ( template oid ) → boolean

Видим ли шаблон текстового поиска?

pg_type_is_visible ( type oid ) → boolean

Видим ли тип (или домен) в пути поиска?


Всем этим функциям должен передаваться OID проверяемого объекта. Если вы хотите проверить объект по имени, удобнее использовать типы-псевдонимы OID (regclass, regtype, regprocedure, regoperator, regconfig или regdictionary), например:

SELECT pg_type_is_visible('myschema.widget'::regtype);

Заметьте, что проверять таким способом имена без указания схемы не имеет большого смысла — если имя удастся распознать, значит и объект будет видимым.

9.26.4. Функции для обращения к системным каталогам #

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

Таблица 9.73. Функции для обращения к системным каталогам

Функция

Описание

format_type ( type oid, typemod integer ) → text

Выдаёт в формате SQL имя типа данных, определяемого по OID и, возможно, модификатору типа. Если модификатор неизвестен, вместо него можно передать NULL.

pg_char_to_encoding ( encoding name ) → integer

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

pg_encoding_to_char ( encoding integer ) → name

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

pg_get_catalog_foreign_keys () → setof record ( fktable regclass, fkcols text[], pktable regclass, pkcols text[], is_array boolean, is_opt boolean )

Возвращает набор записей, описывающих отношения внешних ключей, существующие в системных каталогах Postgres Pro. Столбец fktable содержит имя ссылающегося каталога, а столбец fkcols содержит имена ссылающихся столбцов. Точно так же столбец pktable содержит имя целевого каталога, а столбец pkcols содержит имена целевых столбцов. Если столбец is_array содержит значение true, последний ссылающийся столбец является массивом, каждый из элементов которого должен соответствовать некоторой записи в целевом каталоге. Если столбец is_opt содержит значение true, ссылающиеся столбцы могут содержать нули вместо действительной ссылки.

pg_get_constraintdef ( constraint oid [, pretty boolean] ) → text

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

pg_get_expr ( expr pg_node_tree, relation oid [, pretty boolean] ) → text

Декомпилирует внутреннюю форму выражений, находящихся в системных каталогах, например, выражений, задающих значения по умолчанию. Если выражение может содержать Vars (переменные), передайте во втором параметре OID отношения, к которому обращается данное выражение; в противном случае достаточно передать 0.

pg_get_functiondef ( func oid ) → text

Восстанавливает команду, создающую функцию или процедуру. (Текст команды не является изначальным, он восстанавливается путём декомпиляции.) В результате выдаётся полноценный оператор CREATE OR REPLACE FUNCTION или CREATE OR REPLACE PROCEDURE.

pg_get_function_arguments ( func oid ) → text

Восстанавливает список аргументов для функции или процедуры в том виде, в каком он должен задаваться в команде CREATE FUNCTION (включая значения по умолчанию).

pg_get_function_identity_arguments ( func oid ) → text

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

pg_get_function_result ( func oid ) → text

Восстанавливает для функции предложение RETURNS в том виде, в котором оно должно указываться в команде CREATE FUNCTION. Для процедуры возвращается NULL.

pg_get_indexdef ( index oid [, column integer, pretty boolean] ) → text

Восстанавливает команду, создающую индекс. (Текст команды не является изначальным, он восстанавливается путём декомпиляции.) Если передаётся значение column и оно отлично от нуля, восстанавливается только определение этого столбца.

pg_get_keywords () → setof record ( word text, catcode "char", barelabel boolean, catdesc text, baredesc text )

Выдаёт набор записей, описывающих ключевые слова, которые воспринимает сервер. Столбец word содержит слово, а столбец catcode — код категории: U — не зарезервировано, C — слово, которое может быть именем столбца, T — слово, которое может быть именем типа или функции, R — полностью зарезервированное слово. Столбец barelabel содержит true, если ключевое слово можно использовать в качестве «открытой» метки столбца в списках SELECT, или false, если его можно использовать только после AS. Столбец catdesc содержит описание категории слова, возможно локализованное. Столбец baredesc содержит возможно локализованную строку, описывающую статус метки столбца, содержащего слово.

pg_get_partition_constraintdef ( table oid ) → text

Восстанавливает определение ограничения секции. (Текст команды не является изначальным, он восстанавливается путём декомпиляции.)

pg_get_partkeydef ( table oid ) → text

Восстанавливает определение ключа секционирования секционированной таблицы в той форме, которую он имел бы в предложении PARTITION BY команды CREATE TABLE. (Текст команды не является изначальным, он восстанавливается путём декомпиляции.)

pg_get_ruledef ( rule oid [, pretty boolean] ) → text

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

pg_get_serial_sequence ( table text, column text ) → text

Выдаёт имя последовательности, связанной со столбцом, либо NULL, если такой последовательности нет. Для столбца идентификации это будет последовательность, созданная для него неявно внутри. Для столбцов, имеющих один из последовательных типов (serial, smallserial, bigserial), это последовательность, созданная объявлением данного столбца. В последнем случае эту связь можно изменить или разорвать, воспользовавшись командой ALTER SEQUENCE OWNED BY. (Возможно, эту функцию стоило назвать pg_get_owned_sequence; её существующее имя отражает тот факт, что изначально она использовалась со столбцами последовательных типов.) В первом параметре функции указывается имя таблицы (возможно, дополненное схемой), а во втором — имя столбца. Так как первый параметр может содержать имя схемы и таблицы, он воспринимается не как идентификатор в кавычках и поэтому по умолчанию приводится к нижнему регистру, тогда как имя столбца во втором параметре воспринимается как заключённое в кавычки и в нём регистр символов сохраняется. Эта функция возвращает имя в виде, пригодном для передачи функциям, работающим с последовательностями (см. Раздел 9.17).

Обычно эта функция применяется для получения текущего значения последовательности для столбца идентификации или последовательного столбца, например так:

SELECT currval(pg_get_serial_sequence('sometable', 'id'));

pg_get_statisticsobjdef ( statobj oid ) → text

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

pg_get_triggerdef ( trigger oid [, pretty boolean] ) → text

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

pg_get_userbyid ( role oid ) → name

Выдаёт имя роли по заданному OID.

pg_get_viewdef ( view oid [, pretty boolean] ) → text

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

pg_get_viewdef ( view oid, wrap_column integer ) → text

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

pg_get_viewdef ( view text [, pretty boolean] ) → text

Восстанавливает команду SELECT, определяющую представление или матпредставление, заданное по имени, а не по OID. (Это устаревшая вариация, используйте вместо неё вариацию с OID).

pg_index_column_has_property ( index regclass, column integer, property text ) → boolean

Проверяет, имеет ли столбец индекса заданное свойство. Типичные свойства столбцов описаны в Таблице 9.74. (Заметьте, что расширенные методы доступа могут определять для своих индексов дополнительные свойства.) Если заданное имя свойства не известно или не применимо к конкретному объекту, либо если OID или номер столбца не указывают на существующий объект, эта функция возвращает NULL.

pg_index_has_property ( index regclass, property text ) → boolean

Проверяет, имеет ли индекс заданное свойство. Типичные свойства индексов описаны в Таблице 9.74. (Заметьте, что расширенные методы доступа могут определять для своих индексов дополнительные свойства.) Если заданное имя свойства не известно или не применимо к конкретному объекту, либо если OID не указывает на существующий объект, эта функция возвращает NULL.

pg_indexam_has_property ( am oid, property text ) → boolean

Проверяет, имеет ли метод доступа индекса заданное свойство. Свойства методов доступа описаны в Таблице 9.76. Если заданное имя свойства неизвестно или не применимо к конкретному объекту, либо если OID не указывает на существующий объект, эта функция возвращает NULL.

pg_options_to_table ( options_array text[] ) → setof record ( option_name text, option_value text )

Выдаёт набор параметров хранилища, представленных значением из pg_class.reloptions или pg_attribute.attoptions.

pg_settings_get_flags ( guc text ) → text[]

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

pg_tablespace_databases ( tablespace oid ) → setof oid

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

pg_tablespace_location ( tablespace oid ) → text

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

pg_typeof ( "any" ) → regtype

Выдаёт OID типа данных для переданного значения. Это может быть полезно для разрешения проблем или динамического создания SQL-запросов. Эта функция объявлена как возвращающая тип regtype, который является псевдонимом типа OID (см. Раздел 8.19); это означает, что значение этого типа можно сравнивать как OID, но выводится оно как название типа.

Пример:

SELECT pg_typeof(33);
 pg_typeof
-----------
 integer

SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
 typlen
--------
      4

COLLATION FOR ( "any" ) → text

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

Пример:

SELECT collation for (description) FROM pg_description LIMIT 1;
 pg_collation_for
------------------
 "default"

SELECT collation for ('foo' COLLATE "de_DE");
 pg_collation_for
------------------
 "de_DE"

to_regclass ( text ) → regclass

Переводит в OID текстовое имя отношения. Подобный результат можно получить, приведя строку с именем к типу regclass (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regcollation ( text ) → regcollation

Переводит в OID текстовое имя правила сортировки. Подобный результат можно получить, приведя строку с именем к типу regcollation (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regnamespace ( text ) → regnamespace

Переводит в OID текстовое имя схемы. Подобный результат можно получить, приведя строку с именем к типу regnamespace (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regoper ( text ) → regoper

Переводит в OID текстовое имя оператора. Подобный результат можно получить, приведя строку с именем к типу regoper (см. Раздел 8.19); однако если имя не будет распознано или окажется неоднозначным, эта функция возвратит NULL, а не выдаст ошибку.

to_regoperator ( text ) → regoperator

Переводит в OID текстовое имя оператора с указанием типов параметров. Подобный результат можно получить, приведя строку с именем к типу regoperator (см Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regproc ( text ) → regproc

Переводит в OID текстовое имя функции или процедуры. Подобный результат можно получить, приведя строку с именем к типу regoperator (см. Раздел 8.19); однако если имя не будет распознано или окажется неоднозначным, эта функция возвратит NULL, а не выдаст ошибку.

to_regprocedure ( text ) → regprocedure

Переводит в OID текстовое имя функции или процедуры с указанием типов аргументов. Подобный результат можно получить, приведя строку с именем к типу regprocedure (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regprofile ( text ) → regprofile

Переводит в OID текстовое имя профиля. Подобный результат можно получить, приведя строку с именем к типу regprofile (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regrole ( text ) → regrole

Переводит в OID текстовое имя роли. Подобный результат можно получить, приведя строку с именем к типу regrole (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.

to_regtype ( text ) → regtype

Переводит в OID текстовое имя типа. Подобный результат можно получить, приведя строку с именем к типу regtype (см. Раздел 8.19); однако если имя не будет распознано, эта функция возвратит NULL, а не выдаст ошибку.


Многие из функций, восстанавливающих (декомпилирующих) объекты БД, принимают дополнительный флаг pretty, в котором можно передать true для визуального улучшения вывода. При этом будут убраны лишние скобки и добавлены пробельные символы, чтобы текст был более разборчивым. Преобразованный вывод легче читается, но формат по умолчанию с большей вероятностью будет успешно восприниматься будущими версиями Postgres Pro, поэтому для выгрузки содержимого БД рекомендуется избегать использования визуально улучшенного формата. Если параметр pretty равен false, это равнозначно его отсутствию.

Таблица 9.74. Свойства столбца индекса

ИмяОписание
ascСортируется ли столбец по возрастанию при сканировании вперёд?
descСортируется ли столбец по убыванию при сканировании вперёд?
nulls_firstВыдаются ли NULL в начале при сканирования вперёд?
nulls_lastВыдаются ли NULL в конце при сканировании вперёд?
orderableСвязан ли со столбцом некоторый порядок сортировки?
distance_orderableМожет ли столбец сканироваться по порядку оператором «расстояния», например, ORDER BY столбец <-> константа ?
returnableМожет ли значение столбца быть получено при сканировании только индекса?
search_arrayПоддерживает ли столбец внутренними средствами поиск столбец = ANY(массив)?
search_nullsПоддерживает ли столбец поиск IS NULL и IS NOT NULL?

Таблица 9.75. Свойства индекса

ИмяОписание
clusterableМожет ли индекс использоваться в команде CLUSTER?
index_scanПоддерживает ли индекс простое сканирование (не по битовой карте)?
bitmap_scanПоддерживает ли индекс сканирование по битовой карте?
backward_scanМожет ли в процессе сканирования меняться направление (для поддержки перемещения курсора FETCH BACKWARD без необходимости материализации)?

Таблица 9.76. Свойства метода доступа индекса

ИмяОписание
can_orderПоддерживает ли метод доступа ASC, DESC и связанные ключевые слова в CREATE INDEX?
can_uniqueПоддерживает ли метод доступа уникальные индексы?
can_multi_colПоддерживает ли метод доступа индексы по нескольким столбцам?
can_excludeПоддерживает ли метод доступа ограничения-исключения?
can_includeПоддерживает ли метод доступа предложение INCLUDE команды CREATE INDEX?

Таблица 9.77. Флаги параметров GUC

ФлагОписание
EXPLAINПараметры с этим флагом включаются в команды EXPLAIN (SETTINGS).
NO_SHOW_ALLПараметры с этим флагом исключаются из команд SHOW ALL.
NO_RESETПараметры с этим флагом не поддерживают команды RESET.
NO_RESET_ALLПараметры с этим флагом исключаются из команд RESET ALL.
NOT_IN_SAMPLEПараметры с этим флагом не включаются в postgresql.conf по умолчанию.
RUNTIME_COMPUTEDПараметры с этим флагом вычисляются во время выполнения.

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

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

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

Функция

Описание

pg_describe_object ( classid oid, objid oid, objsubid integer ) → text

Выдаёт текстовое описание объекта БД, идентифицируемого по OID каталога, OID объекта и ID подобъекта (например, номер столбца в таблице; ID подобъекта равен нулю для объекта в целом). Это описание предназначено для человека и может переводиться, в зависимости от конфигурации сервера. Данная функция в особенности полезна, когда требуется узнать, что за объект хранится в каталоге pg_depend. Эта функция возвращает значение NULL для неопределённых объектов.

pg_identify_object ( classid oid, objid oid, objsubid integer ) → record ( type text, schema text, name text, identity text )

Выдаёт запись, содержащую достаточно информации для однозначной идентификации объекта БД по OID каталога, OID объекта и ID подобъекта. Эта информация предназначена для машины и поэтому никогда не переводится. Столбец type содержит тип объекта БД; schema — имя схемы, к которой относится объект (либо NULL для объектов, не относящихся к схемам); name — имя объекта, при необходимости в кавычках, которое присутствует, только если оно (возможно, вместе со схемой) однозначно идентифицирует объект (в противном случае NULL); identity — полный идентификатор объекта, точный формат которого зависит от типа объекта, а каждая его часть дополняется схемой и заключается в кавычки, если требуется. Для неопределённых объектов эти столбцы содержат значение NULL.

pg_identify_object_as_address ( classid oid, objid oid, objsubid integer ) → record ( type text, object_names text[], object_args text[] )

Выдаёт запись, содержащую достаточно информации для однозначной идентификации объекта БД по OID каталога, OID объекта и ID подобъекта. Выдаваемая информация не зависит от текущего сервера, то есть по ней можно идентифицировать одноимённый объект на другом сервере. Поле type содержит тип объекта БД, а object_names и object_args — текстовые массивы, в совокупности формирующие ссылку на объект. Эти три значения можно передать функции pg_get_object_address, чтобы получить внутренний адрес объекта.

pg_get_object_address ( type text, object_names text[], object_args text[] ) → record ( classid oid, objid oid, objsubid integer )

Выдаёт запись, содержащую достаточно информации для уникальной идентификации объекта БД по коду типа и массивам имён и аргументов. В ней возвращаются значения, которые используются в системных каталогах, например pg_depend, и могут передаваться в другие системные функции, например pg_describe_object или pg_identify_object. Поле classid содержит OID системного каталога, к которому относится объект; objid — OID самого объекта, а objsubid — идентификатор подобъекта или 0 в случае его отсутствия. Эта функция является обратной к pg_identify_object_as_address. Для неопределённых объектов эти поля содержат значение NULL.


9.26.6. Функции получения комментариев #

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

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

Функция

Описание

col_description ( table oid, column integer ) → text

Выдаёт комментарий для столбца с заданным номером в таблице с указанным OID. (obj_description нельзя использовать для столбцов таблицы, так столбцы не имеют собственных OID.)

obj_description ( object oid, catalog name ) → text

Выдаёт комментарий для объекта, имеющего заданный OID и находящегося в указанном системном каталоге. Например, в результате вызова obj_description(123456,'pg_class') будет получен комментарий для таблицы с OID 123456.

obj_description ( object oid ) → text

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

shobj_description ( object oid, catalog name ) → text

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


9.26.7. Функции проверки допустимости данных #

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

Таблица 9.80. Функции проверки допустимости данных

Функция

Описание

Пример(ы)

pg_input_is_valid ( string text, type text ) → boolean

Проверяет, является ли заданный аргумент string допустимым входным значением для указанного типа данных, и возвращает true или false.

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

pg_input_is_valid('42', 'integer')t

pg_input_is_valid('42000000000', 'integer')f

pg_input_is_valid('1234.567', 'numeric(7,4)')f

pg_input_error_info ( string text, type text ) → record ( message text, detail text, hint text, sql_error_code text )

Проверяет, является ли заданный аргумент string допустимым входным значением для указанного типа данных; если нет, возвращает подробную информацию о ошибке, которая возникла бы в таком случае. Если ввод допустим, выдаётся NULL. Принимаются те же входные значения, что и для pg_input_is_valid.

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

select * from pg_input_error_info('42000000000', 'integer')

                       message                        | detail | hint | sql_error_code
------------------------------------------------------+--------+------+----------------
 value "42000000000" is out of range for type integer |        |      | 22003

select message, detail from pg_input_error_info('1234.567', 'numeric(7,4)')

        message         |                                      detail
------------------------+----------------------------------​-------------------------------------------------
 numeric field overflow | A field with precision 7, scale 4 must round to an absolute value less than 10^3.


9.26.8. Функции получения информации об идентификаторах транзакций и снимках состояния #

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

Таблица 9.81. Функции получения информации об идентификаторах транзакций и снимках состояния

Функция

Описание

age ( xid ) → integer

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

mxid_age ( xid ) → integer

Возвращает количество идентификаторов мультитранзакций между указанным идентификатором мультитранзакций и текущим значением счётчика мультитранзакций.

pg_current_xact_id () → xid8

Выдаёт идентификатор текущей транзакции. Если у текущей транзакции ещё нет идентификатора (она не успела выполнить какие-либо изменения в базе), он будет ей назначен; подробнее см. Раздел 71.1. Если выполняется в подтранзакции, выдаёт идентификатор транзакции верхнего уровня; подробнее см. Раздел 71.3.

pg_current_xact_id_if_assigned () → xid8

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

pg_xact_status ( xid8 ) → text

Выдаёт состояние фиксации транзакции. Результатом будет одно из значений: in progress (выполняется), committed (зафиксирована) и aborted (прервана), если только транзакция не настолько давняя, чтобы система удалила информацию о её состоянии. Если же упоминаний о транзакции в системе не осталось и информация о её фиксации потеряна, эта функция возвращает NULL. Приложения могут использовать эту функцию, например, чтобы определить, была ли транзакция зафиксирована или прервана, после потери подключения к серверу в процессе выполнения COMMIT. Заметьте, что для подготовленных транзакций возвращается состояние in progress; приложения должны проверять pg_prepared_xacts, если им нужно определить, является ли транзакция с заданным ID подготовленной.

pg_current_snapshot () → pg_snapshot

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

pg_snapshot_xip ( pg_snapshot ) → setof xid8

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

pg_snapshot_xmax ( pg_snapshot ) → xid8

Выдаёт значение xmax для заданного снимка.

pg_snapshot_xmin ( pg_snapshot ) → xid8

Выдаёт xmin для заданного снимка.

pg_visible_in_snapshot ( xid8, pg_snapshot ) → boolean

Видна ли транзакция с указанным идентификатором в данном снимке (то есть, была ли она завершена до момента получения снимка)? Обратите внимание, что эта функция не выдаст правильный ответ, если ей передать идентификатор подтранзакции (subxid); за подробностями обратитесь к Разделу 71.3.

pg_get_multixact_members ( multixid xid ) → setof record ( xid xid, mode text )

Выдаёт идентификатор транзакции и режима блокировки для каждого члена с заданным идентификатором мультитранзакции. Режимы блокировок forupd, fornokeyupd, sh и keysh соответствуют блокировкам уровня строк FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE и FOR KEY SHARE соответственно, более подробная информация предоставлена в Подразделе 13.3.2. Ещё два режима относятся только к мультитранзакциям: nokeyupd, используется для обновлений, не меняющий ключевые столбцы, и upd, используется для обновлений и удалений, которые затрагивают ключевые столбцы.


Внутренний тип идентификаторов транзакций, xid, имеет размер 32 бита и значения в нём повторяются через каждые 4 миллиарда транзакций. Однако функции, показанные в Таблице 9.81, за исключением age, mxid_age и pg_get_multixact_members, используют 64-битный тип xid8, значения которого не повторяются на протяжении всей жизни сервера и могут быть приведены к типу xid, если требуется (подробное описание находится в Разделе 71.1). Тип данных pg_snapshot содержит информацию о видимости транзакций в определённый момент времени. Его компоненты описаны в Таблице 9.82. В текстовом виде pg_snapshot представляется как xmin:xmax:список_xip. Например, запись 10:20:10,14,15 обозначает xmin=10, xmax=20, xip_list=10, 14, 15.

Таблица 9.82. Состав информации о снимке

ИмяОписание
xminМинимальный идентификатор транзакции среди всех активных. Все транзакции, идентификаторы которых меньше xmin, уже либо зафиксированы и видимы, либо отменены и «мертвы».
xmaxИдентификатор на один больше идентификатора последней завершённой транзакции. Все транзакции, идентификаторы которых больше или равны xmax, на момент получения снимка ещё не завершены и не являются видимыми.
xip_listТранзакции, выполняющиеся в момент получения снимка. Транзакции с такими идентификаторами, для которых xmin <= ид < xmax, не попавшие в этот список, были уже завершены на момент получения снимка, и поэтому либо видимы, либо «мертвы», в зависимости от варианта завершения. Идентификаторы подтранзакций (subxid) в этот список не включаются.

До версии 13 в Postgres Pro отсутствовал тип xid8, поэтому предлагались вариации этих функций, в которых 64-битные XID представлялись в типе bigint, а для информации о снимке использовался отдельный тип txid_snapshot. В названиях этих старых функций фигурирует txid. Они по-прежнему поддерживаются для обратной совместимости, но могут быть удалены в будущем. См. Таблицу 9.83.

Таблица 9.83. Устаревшие функции получения информации об идентификаторах транзакций и снимках состояния

Функция

Описание

txid_current () → bigint

См. pg_current_xact_id().

txid_current_if_assigned () → bigint

См. pg_current_xact_id_if_assigned().

txid_current_snapshot () → txid_snapshot

См. pg_current_snapshot().

txid_snapshot_xip ( txid_snapshot ) → setof bigint

См. pg_snapshot_xip().

txid_snapshot_xmax ( txid_snapshot ) → bigint

См. pg_snapshot_xmax().

txid_snapshot_xmin ( txid_snapshot ) → bigint

См. pg_snapshot_xmin().

txid_visible_in_snapshot ( bigint, txid_snapshot ) → boolean

См. pg_visible_in_snapshot().

txid_status ( bigint ) → text

См. pg_xact_status().


9.26.9. Функции получения информации о фиксации транзакций #

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

Таблица 9.84. Функции получения информации о фиксации транзакций

Функция

Описание

pg_xact_commit_timestamp ( xid ) → timestamp with time zone

Выдаёт время фиксации транзакции.

pg_xact_commit_timestamp_origin ( xid ) → record ( timestamp timestamp with time zone, roident oid)

Выдаёт время фиксации и источник репликации транзакции.

pg_last_committed_xact () → record ( xid xid, timestamp timestamp with time zone, roident oid )

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


9.26.10. Функции управления данными #

Функции, показанные в Таблице 9.85, выдают информацию, записываемую во время initdb, например, версию каталога. Они также выводят сведения о журнале предзаписи и контрольных точках. Эта информация относится ко всему кластеру, а не к отдельной базе. Данные функции выдают практически ту же информацию, и из того же источника, что и pg_controldata.

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

Функция

Описание

pg_control_checkpoint () → record

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

pg_control_system () → record

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

pg_control_init () → record

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

pg_control_recovery () → record

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


Таблица 9.86. Столбцы результата pg_control_checkpoint

Имя столбцаТип данных
checkpoint_lsnpg_lsn
redo_lsnpg_lsn
redo_wal_filetext
timeline_idinteger
prev_timeline_idinteger
full_page_writesboolean
next_xidtext
next_oidoid
next_multixact_idxid
next_multi_offsetxid
oldest_xidxid
oldest_xid_dbidoid
oldest_active_xidxid
oldest_multi_xidxid
oldest_multi_dbidoid
oldest_commit_ts_xidxid
newest_commit_ts_xidxid
checkpoint_timetimestamp with time zone

Таблица 9.87. Столбцы результата pg_control_system

Имя столбцаТип данных
pg_control_versioninteger
catalog_version_nointeger
system_identifierbigint
pg_control_last_modifiedtimestamp with time zone
pg_control_editiontext

Таблица 9.88. Столбцы результата pg_control_init

Имя столбцаТип данных
max_data_alignmentinteger
database_block_sizeinteger
blocks_per_segmentinteger
wal_block_sizeinteger
bytes_per_wal_segmentinteger
max_identifier_lengthinteger
max_index_columnsinteger
max_toast_chunk_sizeinteger
large_object_chunk_sizeinteger
float8_pass_by_valueboolean
data_page_checksum_versioninteger

Таблица 9.89. Столбцы результата pg_control_recovery

Имя столбцаТип данных
min_recovery_end_lsnpg_lsn
min_recovery_end_timelineinteger
backup_start_lsnpg_lsn
backup_end_lsnpg_lsn
end_of_backup_record_requiredboolean

9.26. System Information Functions and Operators #

The functions described in this section are used to obtain various information about a PostgreSQL installation.

9.26.1. Session Information Functions #

Table 9.68 shows several functions that extract session and system information.

In addition to the functions listed in this section, there are a number of functions related to the statistics system that also provide system information. See Section 26.2.25 for more information.

Table 9.68. Session Information Functions

Function

Description

current_catalogname

current_database () → name

Returns the name of the current database. (Databases are called catalogs in the SQL standard, so current_catalog is the standard's spelling.)

current_query () → text

Returns the text of the currently executing query, as submitted by the client (which might contain more than one statement).

current_rolename

This is equivalent to current_user.

current_schemaname

current_schema () → name

Returns the name of the schema that is first in the search path (or a null value if the search path is empty). This is the schema that will be used for any tables or other named objects that are created without specifying a target schema.

current_schemas ( include_implicit boolean ) → name[]

Returns an array of the names of all schemas presently in the effective search path, in their priority order. (Items in the current search_path setting that do not correspond to existing, searchable schemas are omitted.) If the Boolean argument is true, then implicitly-searched system schemas such as pg_catalog are included in the result.

current_username

Returns the user name of the current execution context.

inet_client_addr () → inet

Returns the IP address of the current client, or NULL if the current connection is via a Unix-domain socket.

inet_client_port () → integer

Returns the IP port number of the current client, or NULL if the current connection is via a Unix-domain socket.

inet_server_addr () → inet

Returns the IP address on which the server accepted the current connection, or NULL if the current connection is via a Unix-domain socket.

inet_server_port () → integer

Returns the IP port number on which the server accepted the current connection, or NULL if the current connection is via a Unix-domain socket.

pg_backend_pid () → integer

Returns the process ID of the server process attached to the current session.

pg_blocking_pids ( integer ) → integer[]

Returns an array of the process ID(s) of the sessions that are blocking the server process with the specified process ID from acquiring a lock, or an empty array if there is no such server process or it is not blocked.

One server process blocks another if it either holds a lock that conflicts with the blocked process's lock request (hard block), or is waiting for a lock that would conflict with the blocked process's lock request and is ahead of it in the wait queue (soft block). When using parallel queries the result always lists client-visible process IDs (that is, pg_backend_pid results) even if the actual lock is held or awaited by a child worker process. As a result of that, there may be duplicated PIDs in the result. Also note that when a prepared transaction holds a conflicting lock, it will be represented by a zero process ID.

Frequent calls to this function could have some impact on database performance, because it needs exclusive access to the lock manager's shared state for a short time.

pg_conf_load_time () → timestamp with time zone

Returns the time when the server configuration files were last loaded. If the current session was alive at the time, this will be the time when the session itself re-read the configuration files (so the reading will vary a little in different sessions). Otherwise it is the time when the postmaster process re-read the configuration files.

pg_current_logfile ( [ text ] ) → text

Returns the path name of the log file currently in use by the logging collector. The path includes the log_directory directory and the individual log file name. The result is NULL if the logging collector is disabled. When multiple log files exist, each in a different format, pg_current_logfile without an argument returns the path of the file having the first format found in the ordered list: stderr, csvlog, jsonlog. NULL is returned if no log file has any of these formats. To request information about a specific log file format, supply either csvlog, jsonlog or stderr as the value of the optional parameter. The result is NULL if the log format requested is not configured in log_destination. The result reflects the contents of the current_logfiles file.

pg_my_temp_schema () → oid

Returns the OID of the current session's temporary schema, or zero if it has none (because it has not created any temporary tables).

pg_is_other_temp_schema ( oid ) → boolean

Returns true if the given OID is the OID of another session's temporary schema. (This can be useful, for example, to exclude other sessions' temporary tables from a catalog display.)

pg_jit_available () → boolean

Returns true if a JIT compiler extension is available (see Chapter 30) and the jit configuration parameter is set to on.

pg_listening_channels () → setof text

Returns the set of names of asynchronous notification channels that the current session is listening to.

pg_notification_queue_usage () → double precision

Returns the fraction (0–1) of the asynchronous notification queue's maximum size that is currently occupied by notifications that are waiting to be processed. See LISTEN and NOTIFY for more information.

pg_postmaster_start_time () → timestamp with time zone

Returns the time when the server started.

pg_safe_snapshot_blocking_pids ( integer ) → integer[]

Returns an array of the process ID(s) of the sessions that are blocking the server process with the specified process ID from acquiring a safe snapshot, or an empty array if there is no such server process or it is not blocked.

A session running a SERIALIZABLE transaction blocks a SERIALIZABLE READ ONLY DEFERRABLE transaction from acquiring a snapshot until the latter determines that it is safe to avoid taking any predicate locks. See Section 13.2.3 for more information about serializable and deferrable transactions.

Frequent calls to this function could have some impact on database performance, because it needs access to the predicate lock manager's shared state for a short time.

pg_trigger_depth () → integer

Returns the current nesting level of Postgres Pro triggers (0 if not called, directly or indirectly, from inside a trigger).

session_username

Returns the session user's name.

system_usertext

Returns the authentication method and the identity (if any) that the user presented during the authentication cycle before they were assigned a database role. It is represented as auth_method:identity or NULL if the user has not been authenticated (for example if Trust authentication has been used).

username

This is equivalent to current_user.

version () → text

Returns a string describing the PostgreSQL server's version. You can also get this information from server_version, or for a machine-readable version use server_version_num. Software developers should use server_version_num (available since 8.2) or PQserverVersion instead of parsing the text version.

pgpro_version () → text

Returns a string describing the Postgres Pro server's version.

pgpro_edition () → text

Returns a string describing Postgres Pro edition, i.e. standard or enterprise.

pgpro_build () → text

Returns the commit ID of Postgres Pro source files.


Note

current_catalog, current_role, current_schema, current_user, session_user, and user have special syntactic status in SQL: they must be called without trailing parentheses. In Postgres Pro, parentheses can optionally be used with current_schema, but not with the others.

The session_user is normally the user who initiated the current database connection; but superusers can change this setting with SET SESSION AUTHORIZATION. The current_user is the user identifier that is applicable for permission checking. Normally it is equal to the session user, but it can be changed with SET ROLE. It also changes during the execution of functions with the attribute SECURITY DEFINER. In Unix parlance, the session user is the real user and the current user is the effective user. current_role and user are synonyms for current_user. (The SQL standard draws a distinction between current_role and current_user, but Postgres Pro does not, since it unifies users and roles into a single kind of entity.)

9.26.2. Access Privilege Inquiry Functions #

Table 9.69 lists functions that allow querying object access privileges programmatically. (See Section 5.7 for more information about privileges.) In these functions, the user whose privileges are being inquired about can be specified by name or by OID (pg_authid.oid), or if the name is given as public then the privileges of the PUBLIC pseudo-role are checked. Also, the user argument can be omitted entirely, in which case the current_user is assumed. The object that is being inquired about can be specified either by name or by OID, too. When specifying by name, a schema name can be included if relevant. The access privilege of interest is specified by a text string, which must evaluate to one of the appropriate privilege keywords for the object's type (e.g., SELECT). Optionally, WITH GRANT OPTION can be added to a privilege type to test whether the privilege is held with grant option. Also, multiple privilege types can be listed separated by commas, in which case the result will be true if any of the listed privileges is held. (Case of the privilege string is not significant, and extra whitespace is allowed between but not within privilege names.) Some examples:

SELECT has_table_privilege('myschema.mytable', 'select');
SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');

Table 9.69. Access Privilege Inquiry Functions

Function

Description

has_any_column_privilege ( [ user name or oid, ] table text or oid, privilege text ) → boolean

Does user have privilege for any column of table? This succeeds either if the privilege is held for the whole table, or if there is a column-level grant of the privilege for at least one column. Allowable privilege types are SELECT, INSERT, UPDATE, and REFERENCES.

has_column_privilege ( [ user name or oid, ] table text or oid, column text or smallint, privilege text ) → boolean

Does user have privilege for the specified table column? This succeeds either if the privilege is held for the whole table, or if there is a column-level grant of the privilege for the column. The column can be specified by name or by attribute number (pg_attribute.attnum). Allowable privilege types are SELECT, INSERT, UPDATE, and REFERENCES.

has_database_privilege ( [ user name or oid, ] database text or oid, privilege text ) → boolean

Does user have privilege for database? Allowable privilege types are CREATE, CONNECT, TEMPORARY, and TEMP (which is equivalent to TEMPORARY).

has_foreign_data_wrapper_privilege ( [ user name or oid, ] fdw text or oid, privilege text ) → boolean

Does user have privilege for foreign-data wrapper? The only allowable privilege type is USAGE.

has_function_privilege ( [ user name or oid, ] function text or oid, privilege text ) → boolean

Does user have privilege for function? The only allowable privilege type is EXECUTE.

When specifying a function by name rather than by OID, the allowed input is the same as for the regprocedure data type (see Section 8.19). An example is:

SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');

has_language_privilege ( [ user name or oid, ] language text or oid, privilege text ) → boolean

Does user have privilege for language? The only allowable privilege type is USAGE.

has_parameter_privilege ( [ user name or oid, ] parameter text, privilege text ) → boolean

Does user have privilege for configuration parameter? The parameter name is case-insensitive. Allowable privilege types are SET and ALTER SYSTEM.

has_schema_privilege ( [ user name or oid, ] schema text or oid, privilege text ) → boolean

Does user have privilege for schema? Allowable privilege types are CREATE and USAGE.

has_sequence_privilege ( [ user name or oid, ] sequence text or oid, privilege text ) → boolean

Does user have privilege for sequence? Allowable privilege types are USAGE, SELECT, and UPDATE.

has_server_privilege ( [ user name or oid, ] server text or oid, privilege text ) → boolean

Does user have privilege for foreign server? The only allowable privilege type is USAGE.

has_table_privilege ( [ user name or oid, ] table text or oid, privilege text ) → boolean

Does user have privilege for table? Allowable privilege types are SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, and TRIGGER.

has_tablespace_privilege ( [ user name or oid, ] tablespace text or oid, privilege text ) → boolean

Does user have privilege for tablespace? The only allowable privilege type is CREATE.

has_type_privilege ( [ user name or oid, ] type text or oid, privilege text ) → boolean

Does user have privilege for data type? The only allowable privilege type is USAGE. When specifying a type by name rather than by OID, the allowed input is the same as for the regtype data type (see Section 8.19).

pg_has_role ( [ user name or oid, ] role text or oid, privilege text ) → boolean

Does user have privilege for role? Allowable privilege types are MEMBER, USAGE, and SET. MEMBER denotes direct or indirect membership in the role without regard to what specific privileges may be conferred. USAGE denotes whether the privileges of the role are immediately available without doing SET ROLE, while SET denotes whether it is possible to change to the role using the SET ROLE command. WITH ADMIN OPTION or WITH GRANT OPTION can be added to any of these privilege types to test whether the ADMIN privilege is held (all six spellings test the same thing). This function does not allow the special case of setting user to public, because the PUBLIC pseudo-role can never be a member of real roles.

row_security_active ( table text or oid ) → boolean

Is row-level security active for the specified table in the context of the current user and current environment?


Table 9.70 shows the operators available for the aclitem type, which is the catalog representation of access privileges. See Section 5.7 for information about how to read access privilege values.

Table 9.70. aclitem Operators

Operator

Description

Example(s)

aclitem = aclitemboolean

Are aclitems equal? (Notice that type aclitem lacks the usual set of comparison operators; it has only equality. In turn, aclitem arrays can only be compared for equality.)

'calvin=r*w/hobbes'::aclitem = 'calvin=r*w*/hobbes'::aclitemf

aclitem[] @> aclitemboolean

Does array contain the specified privileges? (This is true if there is an array entry that matches the aclitem's grantee and grantor, and has at least the specified set of privileges.)

'{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] @> 'calvin=r*/hobbes'::aclitemt

aclitem[] ~ aclitemboolean

This is a deprecated alias for @>.

'{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] ~ 'calvin=r*/hobbes'::aclitemt


Table 9.71 shows some additional functions to manage the aclitem type.

Table 9.71. aclitem Functions

Function

Description

acldefault ( type "char", ownerId oid ) → aclitem[]

Constructs an aclitem array holding the default access privileges for an object of type type belonging to the role with OID ownerId. This represents the access privileges that will be assumed when an object's ACL entry is null. (The default access privileges are described in Section 5.7.) The type parameter must be one of 'c' for COLUMN, 'r' for TABLE and table-like objects, 's' for SEQUENCE, 'd' for DATABASE, 'f' for FUNCTION or PROCEDURE, 'l' for LANGUAGE, 'L' for LARGE OBJECT, 'n' for SCHEMA, 'p' for PARAMETER, 't' for TABLESPACE, 'F' for FOREIGN DATA WRAPPER, 'S' for FOREIGN SERVER, or 'T' for TYPE or DOMAIN.

aclexplode ( aclitem[] ) → setof record ( grantor oid, grantee oid, privilege_type text, is_grantable boolean )

Returns the aclitem array as a set of rows. If the grantee is the pseudo-role PUBLIC, it is represented by zero in the grantee column. Each granted privilege is represented as SELECT, INSERT, etc (see Table 5.1 for a full list). Note that each privilege is broken out as a separate row, so only one keyword appears in the privilege_type column.

makeaclitem ( grantee oid, grantor oid, privileges text, is_grantable boolean ) → aclitem

Constructs an aclitem with the given properties. privileges is a comma-separated list of privilege names such as SELECT, INSERT, etc, all of which are set in the result. (Case of the privilege string is not significant, and extra whitespace is allowed between but not within privilege names.)


9.26.3. Schema Visibility Inquiry Functions #

Table 9.72 shows functions that determine whether a certain object is visible in the current schema search path. For example, a table is said to be visible if its containing schema is in the search path and no table of the same name appears earlier in the search path. This is equivalent to the statement that the table can be referenced by name without explicit schema qualification. Thus, to list the names of all visible tables:

SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);

For functions and operators, an object in the search path is said to be visible if there is no object of the same name and argument data type(s) earlier in the path. For operator classes and families, both the name and the associated index access method are considered.

Table 9.72. Schema Visibility Inquiry Functions

Function

Description

pg_collation_is_visible ( collation oid ) → boolean

Is collation visible in search path?

pg_conversion_is_visible ( conversion oid ) → boolean

Is conversion visible in search path?

pg_function_is_visible ( function oid ) → boolean

Is function visible in search path? (This also works for procedures and aggregates.)

pg_opclass_is_visible ( opclass oid ) → boolean

Is operator class visible in search path?

pg_operator_is_visible ( operator oid ) → boolean

Is operator visible in search path?

pg_opfamily_is_visible ( opclass oid ) → boolean

Is operator family visible in search path?

pg_statistics_obj_is_visible ( stat oid ) → boolean

Is statistics object visible in search path?

pg_table_is_visible ( table oid ) → boolean

Is table visible in search path? (This works for all types of relations, including views, materialized views, indexes, sequences and foreign tables.)

pg_ts_config_is_visible ( config oid ) → boolean

Is text search configuration visible in search path?

pg_ts_dict_is_visible ( dict oid ) → boolean

Is text search dictionary visible in search path?

pg_ts_parser_is_visible ( parser oid ) → boolean

Is text search parser visible in search path?

pg_ts_template_is_visible ( template oid ) → boolean

Is text search template visible in search path?

pg_type_is_visible ( type oid ) → boolean

Is type (or domain) visible in search path?


All these functions require object OIDs to identify the object to be checked. If you want to test an object by name, it is convenient to use the OID alias types (regclass, regtype, regprocedure, regoperator, regconfig, or regdictionary), for example:

SELECT pg_type_is_visible('myschema.widget'::regtype);

Note that it would not make much sense to test a non-schema-qualified type name in this way — if the name can be recognized at all, it must be visible.

9.26.4. System Catalog Information Functions #

Table 9.73 lists functions that extract information from the system catalogs.

Table 9.73. System Catalog Information Functions

Function

Description

format_type ( type oid, typemod integer ) → text

Returns the SQL name for a data type that is identified by its type OID and possibly a type modifier. Pass NULL for the type modifier if no specific modifier is known.

pg_char_to_encoding ( encoding name ) → integer

Converts the supplied encoding name into an integer representing the internal identifier used in some system catalog tables. Returns -1 if an unknown encoding name is provided.

pg_encoding_to_char ( encoding integer ) → name

Converts the integer used as the internal identifier of an encoding in some system catalog tables into a human-readable string. Returns an empty string if an invalid encoding number is provided.

pg_get_catalog_foreign_keys () → setof record ( fktable regclass, fkcols text[], pktable regclass, pkcols text[], is_array boolean, is_opt boolean )

Returns a set of records describing the foreign key relationships that exist within the Postgres Pro system catalogs. The fktable column contains the name of the referencing catalog, and the fkcols column contains the name(s) of the referencing column(s). Similarly, the pktable column contains the name of the referenced catalog, and the pkcols column contains the name(s) of the referenced column(s). If is_array is true, the last referencing column is an array, each of whose elements should match some entry in the referenced catalog. If is_opt is true, the referencing column(s) are allowed to contain zeroes instead of a valid reference.

pg_get_constraintdef ( constraint oid [, pretty boolean ] ) → text

Reconstructs the creating command for a constraint. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_expr ( expr pg_node_tree, relation oid [, pretty boolean ] ) → text

Decompiles the internal form of an expression stored in the system catalogs, such as the default value for a column. If the expression might contain Vars, specify the OID of the relation they refer to as the second parameter; if no Vars are expected, passing zero is sufficient.

pg_get_functiondef ( func oid ) → text

Reconstructs the creating command for a function or procedure. (This is a decompiled reconstruction, not the original text of the command.) The result is a complete CREATE OR REPLACE FUNCTION or CREATE OR REPLACE PROCEDURE statement.

pg_get_function_arguments ( func oid ) → text

Reconstructs the argument list of a function or procedure, in the form it would need to appear in within CREATE FUNCTION (including default values).

pg_get_function_identity_arguments ( func oid ) → text

Reconstructs the argument list necessary to identify a function or procedure, in the form it would need to appear in within commands such as ALTER FUNCTION. This form omits default values.

pg_get_function_result ( func oid ) → text

Reconstructs the RETURNS clause of a function, in the form it would need to appear in within CREATE FUNCTION. Returns NULL for a procedure.

pg_get_indexdef ( index oid [, column integer, pretty boolean ] ) → text

Reconstructs the creating command for an index. (This is a decompiled reconstruction, not the original text of the command.) If column is supplied and is not zero, only the definition of that column is reconstructed.

pg_get_keywords () → setof record ( word text, catcode "char", barelabel boolean, catdesc text, baredesc text )

Returns a set of records describing the SQL keywords recognized by the server. The word column contains the keyword. The catcode column contains a category code: U for an unreserved keyword, C for a keyword that can be a column name, T for a keyword that can be a type or function name, or R for a fully reserved keyword. The barelabel column contains true if the keyword can be used as a bare column label in SELECT lists, or false if it can only be used after AS. The catdesc column contains a possibly-localized string describing the keyword's category. The baredesc column contains a possibly-localized string describing the keyword's column label status.

pg_get_partition_constraintdef ( table oid ) → text

Reconstructs the definition of a partition constraint. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_partkeydef ( table oid ) → text

Reconstructs the definition of a partitioned table's partition key, in the form it would have in the PARTITION BY clause of CREATE TABLE. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_ruledef ( rule oid [, pretty boolean ] ) → text

Reconstructs the creating command for a rule. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_serial_sequence ( table text, column text ) → text

Returns the name of the sequence associated with a column, or NULL if no sequence is associated with the column. If the column is an identity column, the associated sequence is the sequence internally created for that column. For columns created using one of the serial types (serial, smallserial, bigserial), it is the sequence created for that serial column definition. In the latter case, the association can be modified or removed with ALTER SEQUENCE OWNED BY. (This function probably should have been called pg_get_owned_sequence; its current name reflects the fact that it has historically been used with serial-type columns.) The first parameter is a table name with optional schema, and the second parameter is a column name. Because the first parameter potentially contains both schema and table names, it is parsed per usual SQL rules, meaning it is lower-cased by default. The second parameter, being just a column name, is treated literally and so has its case preserved. The result is suitably formatted for passing to the sequence functions (see Section 9.17).

A typical use is in reading the current value of the sequence for an identity or serial column, for example:

SELECT currval(pg_get_serial_sequence('sometable', 'id'));

pg_get_statisticsobjdef ( statobj oid ) → text

Reconstructs the creating command for an extended statistics object. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_triggerdef ( trigger oid [, pretty boolean ] ) → text

Reconstructs the creating command for a trigger. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_userbyid ( role oid ) → name

Returns a role's name given its OID.

pg_get_viewdef ( view oid [, pretty boolean ] ) → text

Reconstructs the underlying SELECT command for a view or materialized view. (This is a decompiled reconstruction, not the original text of the command.)

pg_get_viewdef ( view oid, wrap_column integer ) → text

Reconstructs the underlying SELECT command for a view or materialized view. (This is a decompiled reconstruction, not the original text of the command.) In this form of the function, pretty-printing is always enabled, and long lines are wrapped to try to keep them shorter than the specified number of columns.

pg_get_viewdef ( view text [, pretty boolean ] ) → text

Reconstructs the underlying SELECT command for a view or materialized view, working from a textual name for the view rather than its OID. (This is deprecated; use the OID variant instead.)

pg_index_column_has_property ( index regclass, column integer, property text ) → boolean

Tests whether an index column has the named property. Common index column properties are listed in Table 9.74. (Note that extension access methods can define additional property names for their indexes.) NULL is returned if the property name is not known or does not apply to the particular object, or if the OID or column number does not identify a valid object.

pg_index_has_property ( index regclass, property text ) → boolean

Tests whether an index has the named property. Common index properties are listed in Table 9.75. (Note that extension access methods can define additional property names for their indexes.) NULL is returned if the property name is not known or does not apply to the particular object, or if the OID does not identify a valid object.

pg_indexam_has_property ( am oid, property text ) → boolean

Tests whether an index access method has the named property. Access method properties are listed in Table 9.76. NULL is returned if the property name is not known or does not apply to the particular object, or if the OID does not identify a valid object.

pg_options_to_table ( options_array text[] ) → setof record ( option_name text, option_value text )

Returns the set of storage options represented by a value from pg_class.reloptions or pg_attribute.attoptions.

pg_settings_get_flags ( guc text ) → text[]

Returns an array of the flags associated with the given GUC, or NULL if it does not exist. The result is an empty array if the GUC exists but there are no flags to show. Only the most useful flags listed in Table 9.77 are exposed.

pg_tablespace_databases ( tablespace oid ) → setof oid

Returns the set of OIDs of databases that have objects stored in the specified tablespace. If this function returns any rows, the tablespace is not empty and cannot be dropped. To identify the specific objects populating the tablespace, you will need to connect to the database(s) identified by pg_tablespace_databases and query their pg_class catalogs.

pg_tablespace_location ( tablespace oid ) → text

Returns the file system path that this tablespace is located in.

pg_typeof ( "any" ) → regtype

Returns the OID of the data type of the value that is passed to it. This can be helpful for troubleshooting or dynamically constructing SQL queries. The function is declared as returning regtype, which is an OID alias type (see Section 8.19); this means that it is the same as an OID for comparison purposes but displays as a type name.

For example:

SELECT pg_typeof(33);
 pg_typeof
-----------
 integer

SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
 typlen
--------
      4

COLLATION FOR ( "any" ) → text

Returns the name of the collation of the value that is passed to it. The value is quoted and schema-qualified if necessary. If no collation was derived for the argument expression, then NULL is returned. If the argument is not of a collatable data type, then an error is raised.

For example:

SELECT collation for (description) FROM pg_description LIMIT 1;
 pg_collation_for
------------------
 "default"

SELECT collation for ('foo' COLLATE "de_DE");
 pg_collation_for
------------------
 "de_DE"

to_regclass ( text ) → regclass

Translates a textual relation name to its OID. A similar result is obtained by casting the string to type regclass (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regcollation ( text ) → regcollation

Translates a textual collation name to its OID. A similar result is obtained by casting the string to type regcollation (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regnamespace ( text ) → regnamespace

Translates a textual schema name to its OID. A similar result is obtained by casting the string to type regnamespace (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regoper ( text ) → regoper

Translates a textual operator name to its OID. A similar result is obtained by casting the string to type regoper (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found or is ambiguous.

to_regoperator ( text ) → regoperator

Translates a textual operator name (with parameter types) to its OID. A similar result is obtained by casting the string to type regoperator (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regproc ( text ) → regproc

Translates a textual function or procedure name to its OID. A similar result is obtained by casting the string to type regproc (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found or is ambiguous.

to_regprocedure ( text ) → regprocedure

Translates a textual function or procedure name (with argument types) to its OID. A similar result is obtained by casting the string to type regprocedure (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regprofile ( text ) → regprofile

Translates a textual profile name to its OID. A similar result is obtained by casting the string to type regprofile (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regrole ( text ) → regrole

Translates a textual role name to its OID. A similar result is obtained by casting the string to type regrole (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.

to_regtype ( text ) → regtype

Translates a textual type name to its OID. A similar result is obtained by casting the string to type regtype (see Section 8.19); however, this function will return NULL rather than throwing an error if the name is not found.


Most of the functions that reconstruct (decompile) database objects have an optional pretty flag, which if true causes the result to be pretty-printed. Pretty-printing suppresses unnecessary parentheses and adds whitespace for legibility. The pretty-printed format is more readable, but the default format is more likely to be interpreted the same way by future versions of Postgres Pro; so avoid using pretty-printed output for dump purposes. Passing false for the pretty parameter yields the same result as omitting the parameter.

Table 9.74. Index Column Properties

NameDescription
ascDoes the column sort in ascending order on a forward scan?
descDoes the column sort in descending order on a forward scan?
nulls_firstDoes the column sort with nulls first on a forward scan?
nulls_lastDoes the column sort with nulls last on a forward scan?
orderableDoes the column possess any defined sort ordering?
distance_orderableCan the column be scanned in order by a distance operator, for example ORDER BY col <-> constant ?
returnableCan the column value be returned by an index-only scan?
search_arrayDoes the column natively support col = ANY(array) searches?
search_nullsDoes the column support IS NULL and IS NOT NULL searches?

Table 9.75. Index Properties

NameDescription
clusterableCan the index be used in a CLUSTER command?
index_scanDoes the index support plain (non-bitmap) scans?
bitmap_scanDoes the index support bitmap scans?
backward_scanCan the scan direction be changed in mid-scan (to support FETCH BACKWARD on a cursor without needing materialization)?

Table 9.76. Index Access Method Properties

NameDescription
can_orderDoes the access method support ASC, DESC and related keywords in CREATE INDEX?
can_uniqueDoes the access method support unique indexes?
can_multi_colDoes the access method support indexes with multiple columns?
can_excludeDoes the access method support exclusion constraints?
can_includeDoes the access method support the INCLUDE clause of CREATE INDEX?

Table 9.77. GUC Flags

FlagDescription
EXPLAINParameters with this flag are included in EXPLAIN (SETTINGS) commands.
NO_SHOW_ALLParameters with this flag are excluded from SHOW ALL commands.
NO_RESETParameters with this flag do not support RESET commands.
NO_RESET_ALLParameters with this flag are excluded from RESET ALL commands.
NOT_IN_SAMPLEParameters with this flag are not included in postgresql.conf by default.
RUNTIME_COMPUTEDParameters with this flag are runtime-computed ones.

9.26.5. Object Information and Addressing Functions #

Table 9.78 lists functions related to database object identification and addressing.

Table 9.78. Object Information and Addressing Functions

Function

Description

pg_describe_object ( classid oid, objid oid, objsubid integer ) → text

Returns a textual description of a database object identified by catalog OID, object OID, and sub-object ID (such as a column number within a table; the sub-object ID is zero when referring to a whole object). This description is intended to be human-readable, and might be translated, depending on server configuration. This is especially useful to determine the identity of an object referenced in the pg_depend catalog. This function returns NULL values for undefined objects.

pg_identify_object ( classid oid, objid oid, objsubid integer ) → record ( type text, schema text, name text, identity text )

Returns a row containing enough information to uniquely identify the database object specified by catalog OID, object OID and sub-object ID. This information is intended to be machine-readable, and is never translated. type identifies the type of database object; schema is the schema name that the object belongs in, or NULL for object types that do not belong to schemas; name is the name of the object, quoted if necessary, if the name (along with schema name, if pertinent) is sufficient to uniquely identify the object, otherwise NULL; identity is the complete object identity, with the precise format depending on object type, and each name within the format being schema-qualified and quoted as necessary. Undefined objects are identified with NULL values.

pg_identify_object_as_address ( classid oid, objid oid, objsubid integer ) → record ( type text, object_names text[], object_args text[] )

Returns a row containing enough information to uniquely identify the database object specified by catalog OID, object OID and sub-object ID. The returned information is independent of the current server, that is, it could be used to identify an identically named object in another server. type identifies the type of database object; object_names and object_args are text arrays that together form a reference to the object. These three values can be passed to pg_get_object_address to obtain the internal address of the object.

pg_get_object_address ( type text, object_names text[], object_args text[] ) → record ( classid oid, objid oid, objsubid integer )

Returns a row containing enough information to uniquely identify the database object specified by a type code and object name and argument arrays. The returned values are the ones that would be used in system catalogs such as pg_depend; they can be passed to other system functions such as pg_describe_object or pg_identify_object. classid is the OID of the system catalog containing the object; objid is the OID of the object itself, and objsubid is the sub-object ID, or zero if none. This function is the inverse of pg_identify_object_as_address. Undefined objects are identified with NULL values.


9.26.6. Comment Information Functions #

The functions shown in Table 9.79 extract comments previously stored with the COMMENT command. A null value is returned if no comment could be found for the specified parameters.

Table 9.79. Comment Information Functions

Function

Description

col_description ( table oid, column integer ) → text

Returns the comment for a table column, which is specified by the OID of its table and its column number. (obj_description cannot be used for table columns, since columns do not have OIDs of their own.)

obj_description ( object oid, catalog name ) → text

Returns the comment for a database object specified by its OID and the name of the containing system catalog. For example, obj_description(123456, 'pg_class') would retrieve the comment for the table with OID 123456.

obj_description ( object oid ) → text

Returns the comment for a database object specified by its OID alone. This is deprecated since there is no guarantee that OIDs are unique across different system catalogs; therefore, the wrong comment might be returned.

shobj_description ( object oid, catalog name ) → text

Returns the comment for a shared database object specified by its OID and the name of the containing system catalog. This is just like obj_description except that it is used for retrieving comments on shared objects (that is, databases, roles, and tablespaces). Some system catalogs are global to all databases within each cluster, and the descriptions for objects in them are stored globally as well.


9.26.7. Data Validity Checking Functions #

The functions shown in Table 9.80 can be helpful for checking validity of proposed input data.

Table 9.80. Data Validity Checking Functions

Function

Description

Example(s)

pg_input_is_valid ( string text, type text ) → boolean

Tests whether the given string is valid input for the specified data type, returning true or false.

This function will only work as desired if the data type's input function has been updated to report invalid input as a soft error. Otherwise, invalid input will abort the transaction, just as if the string had been cast to the type directly.

pg_input_is_valid('42', 'integer')t

pg_input_is_valid('42000000000', 'integer')f

pg_input_is_valid('1234.567', 'numeric(7,4)')f

pg_input_error_info ( string text, type text ) → record ( message text, detail text, hint text, sql_error_code text )

Tests whether the given string is valid input for the specified data type; if not, return the details of the error that would have been thrown. If the input is valid, the results are NULL. The inputs are the same as for pg_input_is_valid.

This function will only work as desired if the data type's input function has been updated to report invalid input as a soft error. Otherwise, invalid input will abort the transaction, just as if the string had been cast to the type directly.

select * from pg_input_error_info('42000000000', 'integer')

                       message                        | detail | hint | sql_error_code
------------------------------------------------------+--------+------+----------------
 value "42000000000" is out of range for type integer |        |      | 22003

select message, detail from pg_input_error_info('1234.567', 'numeric(7,4)')

        message         |                                      detail
------------------------+----------------------------------​-------------------------------------------------
 numeric field overflow | A field with precision 7, scale 4 must round to an absolute value less than 10^3.


9.26.8. Transaction ID and Snapshot Information Functions #

The functions shown in Table 9.81 provide server transaction information in an exportable form. The main use of these functions is to determine which transactions were committed between two snapshots.

Table 9.81. Transaction ID and Snapshot Information Functions

Function

Description

age ( xid ) → integer

Returns the number of transactions between the supplied transaction id and the current transaction counter.

mxid_age ( xid ) → integer

Returns the number of multixacts IDs between the supplied multixact ID and the current multixacts counter.

pg_current_xact_id () → xid8

Returns the current transaction's ID. It will assign a new one if the current transaction does not have one already (because it has not performed any database updates); see Section 71.1 for details. If executed in a subtransaction, this will return the top-level transaction ID; see Section 71.3 for details.

pg_current_xact_id_if_assigned () → xid8

Returns the current transaction's ID, or NULL if no ID is assigned yet. (It's best to use this variant if the transaction might otherwise be read-only, to avoid unnecessary consumption of an XID.) If executed in a subtransaction, this will return the top-level transaction ID.

pg_xact_status ( xid8 ) → text

Reports the commit status of a recent transaction. The result is one of in progress, committed, or aborted, provided that the transaction is recent enough that the system retains the commit status of that transaction. If it is old enough that no references to the transaction survive in the system and the commit status information has been discarded, the result is NULL. Applications might use this function, for example, to determine whether their transaction committed or aborted after the application and database server become disconnected while a COMMIT is in progress. Note that prepared transactions are reported as in progress; applications must check pg_prepared_xacts if they need to determine whether a transaction ID belongs to a prepared transaction.

pg_current_snapshot () → pg_snapshot

Returns a current snapshot, a data structure showing which transaction IDs are now in-progress. Only top-level transaction IDs are included in the snapshot; subtransaction IDs are not shown; see Section 71.3 for details.

pg_snapshot_xip ( pg_snapshot ) → setof xid8

Returns the set of in-progress transaction IDs contained in a snapshot.

pg_snapshot_xmax ( pg_snapshot ) → xid8

Returns the xmax of a snapshot.

pg_snapshot_xmin ( pg_snapshot ) → xid8

Returns the xmin of a snapshot.

pg_visible_in_snapshot ( xid8, pg_snapshot ) → boolean

Is the given transaction ID visible according to this snapshot (that is, was it completed before the snapshot was taken)? Note that this function will not give the correct answer for a subtransaction ID (subxid); see Section 71.3 for details.

pg_get_multixact_members ( multixid xid ) → setof record ( xid xid, mode text )

Returns the transaction ID and lock mode for each member of the specified multixact ID. The lock modes forupd, fornokeyupd, sh, and keysh correspond to the row-level locks FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, and FOR KEY SHARE, respectively, as described in Section 13.3.2. Two additional modes are specific to multixacts: nokeyupd, used by updates that do not modify key columns, and upd, used by updates or deletes that modify key columns.


The internal transaction ID type xid is 32 bits wide and wraps around every 4 billion transactions. However, the functions shown in Table 9.81, except age, mxid_age, and pg_get_multixact_members, use a 64-bit type xid8 that does not wrap around during the life of an installation and can be converted to xid by casting if required; see Section 71.1 for details. The data type pg_snapshot stores information about transaction ID visibility at a particular moment in time. Its components are described in Table 9.82. pg_snapshot's textual representation is xmin:xmax:xip_list. For example 10:20:10,14,15 means xmin=10, xmax=20, xip_list=10, 14, 15.

Table 9.82. Snapshot Components

NameDescription
xmin Lowest transaction ID that was still active. All transaction IDs less than xmin are either committed and visible, or rolled back and dead.
xmax One past the highest completed transaction ID. All transaction IDs greater than or equal to xmax had not yet completed as of the time of the snapshot, and thus are invisible.
xip_list Transactions in progress at the time of the snapshot. A transaction ID that is xmin <= X < xmax and not in this list was already completed at the time of the snapshot, and thus is either visible or dead according to its commit status. This list does not include the transaction IDs of subtransactions (subxids).

In releases of Postgres Pro before 13 there was no xid8 type, so variants of these functions were provided that used bigint to represent a 64-bit XID, with a correspondingly distinct snapshot data type txid_snapshot. These older functions have txid in their names. They are still supported for backward compatibility, but may be removed from a future release. See Table 9.83.

Table 9.83. Deprecated Transaction ID and Snapshot Information Functions

Function

Description

txid_current () → bigint

See pg_current_xact_id().

txid_current_if_assigned () → bigint

See pg_current_xact_id_if_assigned().

txid_current_snapshot () → txid_snapshot

See pg_current_snapshot().

txid_snapshot_xip ( txid_snapshot ) → setof bigint

See pg_snapshot_xip().

txid_snapshot_xmax ( txid_snapshot ) → bigint

See pg_snapshot_xmax().

txid_snapshot_xmin ( txid_snapshot ) → bigint

See pg_snapshot_xmin().

txid_visible_in_snapshot ( bigint, txid_snapshot ) → boolean

See pg_visible_in_snapshot().

txid_status ( bigint ) → text

See pg_xact_status().


9.26.9. Committed Transaction Information Functions #

The functions shown in Table 9.84 provide information about when past transactions were committed. They only provide useful data when the track_commit_timestamp configuration option is enabled, and only for transactions that were committed after it was enabled. Commit timestamp information is routinely removed during vacuum.

Table 9.84. Committed Transaction Information Functions

Function

Description

pg_xact_commit_timestamp ( xid ) → timestamp with time zone

Returns the commit timestamp of a transaction.

pg_xact_commit_timestamp_origin ( xid ) → record ( timestamp timestamp with time zone, roident oid)

Returns the commit timestamp and replication origin of a transaction.

pg_last_committed_xact () → record ( xid xid, timestamp timestamp with time zone, roident oid )

Returns the transaction ID, commit timestamp and replication origin of the latest committed transaction.


9.26.10. Control Data Functions #

The functions shown in Table 9.85 print information initialized during initdb, such as the catalog version. They also show information about write-ahead logging and checkpoint processing. This information is cluster-wide, not specific to any one database. These functions provide most of the same information, from the same source, as the pg_controldata application.

Table 9.85. Control Data Functions

Function

Description

pg_control_checkpoint () → record

Returns information about current checkpoint state, as shown in Table 9.86.

pg_control_system () → record

Returns information about current control file state, as shown in Table 9.87.

pg_control_init () → record

Returns information about cluster initialization state, as shown in Table 9.88.

pg_control_recovery () → record

Returns information about recovery state, as shown in Table 9.89.


Table 9.86. pg_control_checkpoint Output Columns

Column NameData Type
checkpoint_lsnpg_lsn
redo_lsnpg_lsn
redo_wal_filetext
timeline_idinteger
prev_timeline_idinteger
full_page_writesboolean
next_xidtext
next_oidoid
next_multixact_idxid
next_multi_offsetxid
oldest_xidxid
oldest_xid_dbidoid
oldest_active_xidxid
oldest_multi_xidxid
oldest_multi_dbidoid
oldest_commit_ts_xidxid
newest_commit_ts_xidxid
checkpoint_timetimestamp with time zone

Table 9.87. pg_control_system Output Columns

Column NameData Type
pg_control_versioninteger
catalog_version_nointeger
system_identifierbigint
pg_control_last_modifiedtimestamp with time zone
pg_control_editiontext

Table 9.88. pg_control_init Output Columns

Column NameData Type
max_data_alignmentinteger
database_block_sizeinteger
blocks_per_segmentinteger
wal_block_sizeinteger
bytes_per_wal_segmentinteger
max_identifier_lengthinteger
max_index_columnsinteger
max_toast_chunk_sizeinteger
large_object_chunk_sizeinteger
float8_pass_by_valueboolean
data_page_checksum_versioninteger

Table 9.89. pg_control_recovery Output Columns

Column NameData Type
min_recovery_end_lsnpg_lsn
min_recovery_end_timelineinteger
backup_start_lsnpg_lsn
backup_end_lsnpg_lsn
end_of_backup_record_requiredboolean

FAQ