9.25. Системные информационные функции
В Таблице 9.60 перечислен ряд функций, предназначенных для получения информации о текущем сеансе и системе.
В дополнение к перечисленным здесь функциям существуют также функции, связанные с подсистемой статистики, которые тоже предоставляют системную информацию. Подробнее они рассматриваются в Подразделе 28.2.2.
Таблица 9.60. Функции получения информации о сеансе
| Имя | Тип результата | Описание |
|---|---|---|
| name | имя текущей базы данных (в стандарте SQL она называется «каталогом») |
| name | имя текущей базы данных |
| text | текст запроса, выполняемого в данный момент, в том виде, в каком его передал клиент (может состоять из нескольких операторов) |
| name | синоним current_user |
| name | имя текущей схемы |
| name[] | имена схем в пути поиска, возможно включая схемы, добавляемые в него неявно |
| name | имя пользователя в текущем контексте выполнения |
| inet | адрес удалённой стороны соединения |
| int | порт удалённой стороны соединения |
| inet | адрес локальной стороны соединения |
| int | порт локальной стороны соединения |
| int | код серверного процесса, обслуживающего текущий сеанс |
| int[] | идентификаторы процессов, не дающих серверному процессу с определённым ID получить блокировку |
| timestamp with time zone | время загрузки конфигурации |
| text | имя файла главного журнала или журнала в заданном формате, который в настоящее время используется сборщиком сообщений |
| oid | OID временной схемы этого сеанса или 0, если её нет |
| boolean | является ли заданная схема временной в другом сеансе? |
| setof text | имена каналов, по которым текущий сеанс принимает сигналы |
| double | занятая доля очереди асинхронных уведомлений (0-1) |
| timestamp with time zone | время запуска сервера |
| int[] | Идентификаторы процессов, не дающих серверному процессу с определённым ID получить безопасный снимок |
| int | текущий уровень вложенности в триггерах Postgres Pro (0, если эта функция вызывается (прямо или косвенно) не из тела триггера) |
| name | имя пользователя сеанса |
| name | синоним current_user |
| text | информация о версии PostgreSQL. Также можно прочитать версию в машинно-ориентированном виде, обратившись к переменной server_version_num. |
| text | информация о версии Postgres Pro |
| text | название редакции Postgres Pro |
| 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 они не различаются, так как пользователи и роли объединены в единую сущность.)
Функция current_schema возвращает имя схемы, которая стоит первой в пути поиска (или NULL, если путь поиска пуст). Эта схема будет задействована при создании таблиц или других именованных объектов, если целевая схема не указана явно. Функция current_schemas(boolean) возвращает массив имён всех схем, находящихся в пути поиска. Её логический параметр определяет, будут ли включаться в результат неявно добавляемые в путь поиска системные схемы, такие как pg_catalog.
Примечание
Путь поиска можно изменить во время выполнения следующей командой:
SET search_path TOсхема[,схема, ...]
Функция inet_client_addr возвращает IP-адрес текущего клиента, inet_client_port — номер его порта, inet_server_addr — IP-адрес сервера, по которому он принял подключение клиента, а inet_server_port — соответствующий номер порта. Все эти функции возвращают NULL, если текущее соединение устанавливается через Unix-сокет.
Функция pg_blocking_pids возвращает массив идентификаторов процессов сеансов, которые блокирует серверный процесс с указанным идентификатором, либо пустой массив, если такой серверный процесс не найден или не заблокирован. Один серверный процесс блокирует другой, если он либо удерживает блокировку, конфликтующую с блокировкой, запрашиваемой серверным процессом (жёсткая блокировка), либо ждёт блокировки, которая вызвала бы конфликт с запросом блокировки заблокированного процесса и находится перед ней в очереди ожидания (мягкая блокировка). При распараллеливании запросов эта функция всегда выдаёт видимые клиентом идентификаторы процессов (то есть, результаты pg_backend_pid), даже если фактическая блокировка удерживается или ожидается дочерним рабочим процессом. Вследствие этого, в результатах могут оказаться дублирующиеся PID. Также заметьте, что когда конфликтующую блокировку удерживает подготовленная транзакция, в выводе этой функции она будет представлена нулевым ID процесса. Частые вызовы этой функции могут отразиться на производительности базы данных, так как ей нужен монопольный доступ к общему состоянию менеджера блокировок, хоть и на короткое время.
Функция pg_conf_load_time возвращает время (timestamp with time zone), когда в последний раз сервер загружал файлы конфигурации. (Если текущий сеанс начался раньше, она возвращает время, когда эти файлы были перезагружены для данного сеанса, так что в разных сеансах это значение может немного различаться. В противном случае это будет время, когда файлы конфигурации считал главный процесс.)
Функция pg_current_logfile возвращает в значении text путь к файлам журналов, в настоящее время используемым сборщиком сообщений. Этот путь состоит из каталога log_directory и имени файла журнала. Если сборщик сообщений отключён, возвращается значение NULL. Если ведутся несколько журналов в разных форматах, при вызове функции pg_current_logfile без аргументов возвращается путь файла, имеющего первый формат по порядку из следующего списка: stderr, csvlog. Если файл журнала имеет какой-то иной формат, возвращается NULL. Чтобы запросить файл в определённом формате, передайте либо csvlog, либо stderr в качестве значения необязательного параметра типа text. Если запрошенный формат не включён в log_destination, будет возвращено значение NULL. Функция pg_current_logfile отражает содержимое файла current_logfiles.
pg_my_temp_schema возвращает OID временной схемы текущего сеанса или 0, если такой нет (в рамках сеанса не создавались временные таблицы). pg_is_other_temp_schema возвращает true, если заданный OID относится к временной схеме другого сеанса. (Это может быть полезно, например для исключения временных таблиц других сеансов из общего списка при просмотре таблиц базы данных.)
Функция pg_listening_channels возвращает набор имён каналов асинхронных уведомлений, на которые подписан текущий сеанс. Функция pg_notification_queue_usage возвращает долю от всего свободного пространства для уведомлений, в настоящее время занятую уведомлениями, ожидающими обработки, в виде значения double в диапазоне 0..1. За дополнительными сведениями обратитесь к LISTEN и NOTIFY.
pg_postmaster_start_time возвращает время (timestamp with time zone), когда был запущен сервер.
Функция pg_safe_snapshot_blocking_pids возвращает массив идентификаторов процессов сеансов, которые блокируют серверный процесс с указанным идентификатором (не дают получить ему безопасный снимок), либо пустой массив, если такой серверный процесс не найден или не заблокирован. Сеанс, выполняющий транзакцию уровня SERIALIZABLE, блокирует транзакцию SERIALIZABLE READ ONLY DEFERRABLE, не давая ей получить снимок, пока она не определит, что можно безопасно избежать установления предикатных блокировок. За дополнительными сведениями о сериализуемых и откладываемых транзакциях обратитесь к Подразделу 13.2.3. Частые вызовы этой функции могут отразиться на производительности базы данных, так как ей нужен доступ к общему состоянию менеджера предикатных блокировок, хоть и на короткое время.
Функция version возвращает строку, описывающую версию сервера Postgres Pro. Эту информацию также можно получить из переменной server_version или, в более машинно-ориентированном формате, из переменной server_version_num. При разработке программ следует использовать server_version_num (она появилась в версии 8.2) либо PQserverVersion , а не разбирать текстовую версию.
возвращает текстовую строку, описывающую редакцию Postgres Pro, например pgpro_edition()standard или enterprise.
возвращает текстовую строку, описывающую версию сервера Postgres Pro.pgpro_version()
В Таблице 9.61 перечислены функции, позволяющую пользователю программно проверить свои права доступа к объектам. Подробнее о правах можно узнать в Разделе 5.6.
Таблица 9.61. Функции для проверки прав доступа
| Имя | Тип результата | Описание |
|---|---|---|
| boolean | имеет ли пользователь указанное право для какого-либо столбца таблицы |
| boolean | имеет ли текущий пользователь указанное право для какого-либо столбца таблицы |
| boolean | имеет ли пользователь указанное право для столбца |
| boolean | имеет ли текущий пользователь указанное право для столбца |
| boolean | имеет ли пользователь указанное право для базы данных |
| boolean | имеет ли текущий пользователь указанное право для базы данных |
| boolean | имеет ли пользователь указанное право для обёртки сторонних данных |
| boolean | имеет ли текущий пользователь указанное право для обёртки сторонних данных |
| boolean | имеет ли пользователь указанное право для функции |
| boolean | имеет ли текущий пользователь указанное право для функции |
| boolean | имеет ли пользователь указанное право для языка |
| boolean | имеет ли текущий пользователь указанное право для языка |
| boolean | имеет ли пользователь указанное право для схемы |
| boolean | имеет ли текущий пользователь указанное право для схемы |
| boolean | имеет ли пользователь указанное право для последовательности |
| boolean | имеет ли текущий пользователь указанное право для последовательности |
| boolean | имеет ли пользователь указанное право для стороннего сервера |
| boolean | имеет ли текущий пользователь указанное право для стороннего сервера |
| boolean | имеет ли пользователь указанное право для таблицы |
| boolean | имеет ли текущий пользователь указанное право для таблицы |
| boolean | имеет ли пользователь указанное право для табличного пространства |
| boolean | имеет ли текущий пользователь указанное право для табличного пространства |
| boolean | имеет ли пользователь указанное право для типа |
| boolean | имеет ли текущий пользователь указанное право для типа |
| boolean | имеет ли пользователь указанное право для роли |
| boolean | имеет ли текущий пользователь указанное право для роли |
| boolean | включена ли для текущего пользователя защита на уровне строк для таблицы |
has_table_privilege проверяет, может ли пользователь выполнять с таблицей заданные действия. В качестве идентификатора пользователя можно задать его имя, OID (pg_authid.oid) или public (это будет указывать на псевдороль PUBLIC). Если этот аргумент опущен, подразумевается текущий пользователь (current_user). Таблицу можно указать по имени или по OID. (Таким образом, фактически есть шесть вариантов функции has_table_privilege, различающихся по числу и типу аргументов.) Когда указывается имя объекта, его можно дополнить именем схемы, если это необходимо. Интересующее право доступа записывается в виде текста и может быть одним из следующих: SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES и TRIGGER. Дополнительно к названию права можно добавить WITH GRANT OPTION и проверить, разрешено ли пользователю передавать это право другим. Кроме того, в одном параметре можно перечислить несколько названий прав через запятую, и тогда функция возвратит true, если пользователь имеет одно из этих прав. (Регистр в названии прав не имеет значения, а между ними (но не внутри) разрешены пробельные символы.) Пара примеров:
SELECT has_table_privilege('myschema.mytable', 'select');
SELECT has_table_privilege('joe', 'mytable',
'INSERT, SELECT WITH GRANT OPTION');has_sequence_privilege проверяет, может ли пользователь выполнять заданные действия с последовательностью. В определении аргументов эта функция аналогична has_table_privilege. Допустимые для неё права складываются из USAGE, SELECT и UPDATE.
has_any_column_privilege проверяет, может ли пользователь выполнять заданные действия с каким-либо столбцом таблицы. В определении аргументов эта функция аналогична has_table_privilege, а допустимые права складываются из SELECT, INSERT, UPDATE и REFERENCES. Заметьте, что любое из этих прав, назначенное на уровне таблицы, автоматически распространяется на все её столбцы, так что has_any_column_privilege всегда возвращает true, если has_table_privilege даёт положительный ответ для тех же аргументов. Но has_any_column_privilege возвращает true ещё и тогда, когда право назначено только для некоторых столбцов.
has_column_privilege проверяет, может ли пользователь выполнять заданные действия со столбцом таблицы. В определении аргументов эта функция аналогична has_table_privilege, с небольшим дополнением: столбец можно задать по имени или номеру атрибута. Для неё допустимые права складываются из SELECT, INSERT, UPDATE и REFERENCES. Заметьте, что любое из этих прав, назначенное на уровне таблицы, автоматически распространяется на все столбцы таблицы.
has_database_privilege проверяет, может ли пользователь выполнять заданные действия с базой данных. В определении аргументов эта функция аналогична has_table_privilege. Для неё допустимые права складываются из CREATE, CONNECT и TEMPORARY (или TEMP, что равносильно TEMPORARY).
has_function_privilege проверяет, может ли пользователь обратиться к заданной функции. В определении аргументов эта функция аналогична has_table_privilege. Когда функция определяется не своим OID, а текстовой строкой, эта строка должна быть допустимой для вводимого значения типа regprocedure (см. Раздел 8.18). Для этой функции допустимо только право EXECUTE. Например:
SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');has_foreign_data_wrapper_privilege проверяет, может ли пользователь обращаться к обёртке сторонних данных. В определении аргументов она аналогична has_table_privilege. Для неё допустимо только право USAGE.
has_language_privilege проверяет, может ли пользователь обращаться к процедурному языку. В определении аргументов эта функция аналогична has_table_privilege. Для неё допустимо только право USAGE.
has_schema_privilege проверяет, может ли пользователь выполнять заданные действия со схемой. В определении аргументов эта функция аналогична has_table_privilege. Для неё допустимые права складываются из CREATE и USAGE.
has_server_privilege проверяет, может ли пользователь обращаться к стороннему серверу. В определении аргументов она аналогична has_table_privilege. Для неё допустимо только право USAGE.
has_tablespace_privilege проверяет, может ли пользователь выполнять заданное действие в табличном пространстве. В определении аргументов эта функция аналогична has_table_privilege. Для неё допустимо только право CREATE.
has_type_privilege проверяет, может ли пользователь обратиться к типу определённым образом. Возможные аргументы аналогичны has_table_privilege. При указании типа текстовой строкой, а не по OID, допускаются те же входные значения, что и для типа данных regtype (см. Раздел 8.18). Для неё допустимо только право USAGE.
pg_has_role проверяет, может ли пользователь выполнять заданные действия с ролью. В определении аргументов эта функция аналогична has_table_privilege, за исключением того, что именем пользователя не может быть public. Для неё допустимые права складываются из MEMBER и USAGE. MEMBER обозначает прямое или косвенное членство в данной роли (то есть наличие права выполнить команду SET ROLE), тогда как USAGE показывает, что пользователь получает все права роли сразу, без SET ROLE.
row_security_active проверяет, включена ли защита на уровне строк для указанной таблицы в контексте и окружении текущего пользователя (current_user). Таблицу можно задать по имени или OID.
В Таблице 9.62 перечислены функции, определяющие видимость объекта с текущим путём поиска схем. К примеру, таблица считается видимой, если содержащая её схема включена в путь поиска и нет другой таблицы с тем же именем, которая была бы найдена по пути поиска раньше. Другими словами, к этой таблице можно будет обратиться просто по её имени, без явного указания схемы. Просмотреть список всех видимых таблиц можно так:
SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
Таблица 9.62. Функции для определения видимости
| Имя | Тип результата | Описание |
|---|---|---|
| boolean | видимо ли правило сортировки |
| boolean | видимо ли преобразование |
| boolean | видима ли функция |
| boolean | видим ли класс операторов |
| boolean | видим ли оператор |
| boolean | видимо ли семейство операторов |
| boolean | видим ли объект статистики в пути поиска |
| boolean | видима ли таблица |
| boolean | видима ли конфигурация текстового поиска |
| boolean | видим ли словарь текстового поиска |
| boolean | видим ли анализатор текстового поиска |
| boolean | видим ли шаблон текстового поиска |
| boolean | видим ли тип (или домен) |
Каждая из этих функций проверяет видимость объектов определённого типа. Заметьте, что pg_table_is_visible можно также использовать для представлений, материализованных представлений, индексов, последовательностей и сторонних таблиц; pg_type_is_visible можно также использовать и для доменов. Для функций и операторов объект считается видимым в пути поиска, если при просмотре пути не находится предшествующий ему другой объект с тем же именем и типами аргументов. Для классов операторов во внимание принимается и имя оператора, и связанный с ним метод доступа к индексу.
Всем этим функциям должен передаваться OID проверяемого объекта. Если вы хотите проверить объект по имени, удобнее использовать типы-псевдонимы OID (regclass, regtype, regprocedure, regoperator, regconfig или regdictionary), например:
SELECT pg_type_is_visible('myschema.widget'::regtype);Заметьте, что проверять таким способом имена без указания схемы не имеет большого смысла — если имя удастся распознать, значит и объект будет видимым.
В Таблице 9.63 перечислены функции, извлекающие информацию из системных каталогов.
Таблица 9.63. Функции для обращения к системным каталогам
| Имя | Тип результата | Описание |
|---|---|---|
| text | получает имя типа данных в формате SQL |
| text | получает определение ограничения |
| text | получает определение ограничения |
| text | декомпилирует внутреннюю форму выражения, в предположении, что все переменные в нём ссылаются на таблицу или отношение, указанное вторым параметром |
| text | декомпилирует внутреннюю форму выражения, в предположении, что все переменные в нём ссылаются на таблицу или отношение, указанное вторым параметром |
| text | получает определение функции |
| text | получает список аргументов из определения функции (со значениями по умолчанию) |
| text | получает список аргументов, идентифицирующий функцию (без значений по умолчанию) |
| text | получает предложение RETURNS для функции |
| text | получает команду CREATE INDEX для индекса |
| text | получает команду CREATE INDEX для индекса или определение одного индексированного столбца, когда column_no не равен 0 |
| setof record | получает список ключевых слов SQL по категориям |
| text | получает команду CREATE RULE для правила |
| text | получает команду CREATE RULE для правила |
| text | получает имя последовательности, используемой столбцом идентификации или столбцом serial |
| text | получает команду CREATE STATISTICS для объекта расширенной статистики |
pg_get_triggerdef(trigger_oid) | text | получает команду CREATE [ CONSTRAINT ] TRIGGER для триггера |
pg_get_triggerdef(trigger_oid, pretty_bool) | text | получает команду CREATE [ CONSTRAINT ] TRIGGER для триггера |
| name | получает имя роли по заданному OID |
| text | получает команду SELECT, определяющую представление или материализованное представление (устаревшая функция) |
| text | получает команду SELECT, определяющую представление или материализованное представление (устаревшая функция) |
| text | получает команду SELECT, определяющую представление или материализованное представление |
| text | получает команду SELECT, определяющую представление или материализованное представление |
| text | получает команду SELECT, определяющую представление или материализованное представление; при необходимости разбивает строки с полями, выходящие за wrap_int символов, подразумевая форматированный вывод |
| boolean | проверяет, имеет ли столбец индекса заданное свойство |
| boolean | проверяет, имеет ли индекс заданное свойство |
| boolean | проверяет, имеет ли метод доступа индекса заданное свойство |
| setof record | получает набор параметров хранилища в виде имя/значение |
| setof oid | получает или устанавливает OID баз данных, объекты которых содержатся в заданном табличном пространстве |
| text | получает путь в файловой системе к местоположению заданного табличного пространства |
| regtype | получает тип данных любого значения |
| text | получает правило сортировки для аргумента |
| regclass | получает OID указанного отношения |
| regproc | получает OID указанной функции |
| regprocedure | получает OID указанной функции |
| regoper | получает OID указанного оператора |
| regoperator | получает OID указанного оператора |
| regtype | получает OID указанного типа |
| regnamespace | получает OID указанной схемы |
| regrole | получает OID указанной роли |
format_type возвращает в формате SQL имя типа данных, определяемого по OID и, возможно, модификатору типа. Если модификатор неизвестен, вместо него можно передать NULL.
pg_get_keywords возвращает таблицу с ключевыми словами SQL, которые воспринимает сервер. Столбец word содержит ключевое слово, а catcode — код категории: U — не зарезервировано, C — имя столбца, T — имя типа или функции, R — зарезервировано. Столбец catdesc содержит возможно локализованное описание категории.
pg_get_constraintdef, pg_get_indexdef, pg_get_ruledef, pg_get_statisticsobjdef и pg_get_triggerdef восстанавливают команду, создававшую заданное ограничение, индекс, правило, объект статистики или триггер, соответственно. (Учтите, что они возвращают не изначальный текст команды, а результат декомпиляции.) pg_get_expr декомпилирует внутреннюю форму отдельного выражения, например значения по умолчанию для столбца. Это может быть полезно для изучения содержимого системных каталогов. Если выражение может содержать переменные, укажите во втором параметре OID отношения, на который они ссылаются; если таких переменных нет, вместо OID можно передать 0. pg_get_viewdef восстанавливает запрос SELECT, определяющий представление. Многие из этих функций имеют две версии, одна из которых позволяет получить форматированный вывод (с параметром pretty_bool). Форматированный текст легче читается, но нет гарантии, что он будет всегда восприниматься одинаково будущими версиями Postgres Pro; поэтому не следует применять форматирование при выгрузке метаданных. Если в параметре pretty_bool передаётся false, эта версия функции выдаёт тот же результат, что и версия без параметров.
pg_get_functiondef возвращает полный оператор CREATE OR REPLACE FUNCTION для заданной функции. pg_get_function_arguments возвращает список аргументов функции, в виде достаточном для включения в команду CREATE FUNCTION. pg_get_function_result в дополнение возвращает готовое предложение RETURNS для функции. pg_get_function_identity_arguments возвращает список аргументов, достаточный для однозначной идентификации функции, в форме, допустимой, например для команды ALTER FUNCTION. Значения по умолчанию в этой форме опускаются.
pg_get_serial_sequence возвращает имя последовательности, связанной со столбцом, либо NULL, если такой последовательности нет. Для столбца идентификации это будет последовательность, связанная с ним внутренним образом. Для столбцов, имеющих один из последовательных типов (serial, smallserial, bigserial), это последовательность, созданная объявлением данного столбца. В последнем случае эту связь можно изменить или разорвать, воспользовавшись командой ALTER SEQUENCE OWNED BY. (Возможно, эту функцию стоило назвать pg_get_owned_sequence; её существующее имя отражает тот факт, что она обычно используется со столбцами serial или bigserial.) В первом параметре функции указывается имя таблицы (возможно, дополненное схемой), а во втором имя столбца. Так как первый параметр может содержать имя схемы и таблицы, он воспринимается не как идентификатор в кавычках и поэтому по умолчанию приводится к нижнему регистру, тогда как имя столбца во втором параметре воспринимается как заключённое в кавычки и в нём регистр символов сохраняется. Эта функция возвращает имя в виде, пригодном для передачи функциям, работающим с последовательностями (см. Раздел 9.16). Обычно она применяется для получения текущего значения последовательности для столбца идентификации или последовательного столбца, например:
SELECT currval(pg_get_serial_sequence('sometable', 'id'));pg_get_userbyid получает имя роли по её OID.
Функции pg_index_column_has_property, pg_index_has_property и pg_indexam_has_property показывают, обладает ли указанный столбец индекса, индекс или метод доступа индекса заданным свойством. Они возвращают NULL, если имя свойства неизвестно или неприменимо к конкретному объекту, либо если OID или номер столбца не указывают на действительный объект. Описание свойств столбцов вы можете найти в Таблице 9.64, свойства индексов описаны в Таблице 9.65, а свойства методов доступа — в Таблица 9.66. (Заметьте, что методы доступа, реализуемые расширениями, могут определять для своих индексов дополнительные имена свойств.)
Таблица 9.64. Свойства столбца индекса
| Имя | Описание |
|---|---|
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.65. Свойства индекса
| Имя | Описание |
|---|---|
clusterable | Может ли индекс использоваться в команде CLUSTER? |
index_scan | Поддерживает ли индекс простое сканирование (не по битовой карте)? |
bitmap_scan | Поддерживает ли индекс сканирование по битовой карте? |
backward_scan | Может ли в процессе сканирования меняться направление (для поддержки перемещения курсора FETCH BACKWARD без необходимости материализации)? |
Таблица 9.66. Свойства метода доступа индекса
| Имя | Описание |
|---|---|
can_order | Поддерживает ли метод доступа ASC, DESC и связанные ключевые слова в CREATE INDEX? |
can_unique | Поддерживает ли метод доступа уникальные индексы? |
can_multi_col | Поддерживает ли метод доступа индексы по нескольким столбцам? |
can_exclude | Поддерживает ли метод доступа ограничения-исключения? |
pg_options_to_table возвращает набор параметров хранилища в виде пар (имя_параметра/значение_параметра), когда ей передаётся pg_class.reloptions или pg_attribute.attoptions.
pg_tablespace_databases позволяет изучить содержимое табличного пространства. Она возвращает набор OID баз данных, объекты которых размещены в этом табличном пространстве. Если эта функция возвращает строки, это означает, что табличное пространство не пустое и удалить его нельзя. Какие именно объекты находятся в табличном пространстве, можно узнать, подключаясь к базам данных, OID которых сообщила pg_tablespace_databases, и анализируя их каталоги pg_class.
pg_typeof возвращает OID типа данных для переданного значения. Это может быть полезно для разрешения проблем или динамического создания SQL-запросов. Эта функция объявлена как возвращающая тип regtype, который является псевдонимом типа OID (см. Раздел 8.18); это означает, что значение этого типа можно сравнивать как OID, но выводится оно как название типа. Например:
SELECT pg_typeof(33);
pg_typeof
-----------
integer
(1 row)
SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
typlen
--------
4
(1 row)Выражение collation for возвращает правило сортировки для переданного значения. Например:
SELECT collation for (description) FROM pg_description LIMIT 1;
pg_collation_for
------------------
"default"
(1 row)
SELECT collation for ('foo' COLLATE "de_DE");
pg_collation_for
------------------
"de_DE"
(1 row)Это значение может быть заключено в кавычки и дополнено схемой. Если для выражения аргумента нет правила сортировки, возвращается значение NULL. Если же правила сортировки не применимы для типа аргумента, происходит ошибка.
Функции to_regclass, to_regproc, to_regprocedure, to_regoper, to_regoperator, to_regtype, to_regnamespace и to_regrole преобразуют имена отношений, функций, операторов, типов, схем и ролей (заданных значением text) в объекты типа regclass, regproc, regprocedure, regoper, regoperator, regtype, regnamespace и regrole, соответственно. Перечисленные функции отличаются от явных приведений к этим типам тем, что они не принимают числовые OID и возвращают NULL вместо ошибки, если имя не найдено (или, в случае с to_regproc и to_regoper, если данному имени соответствуют несколько объектов).
В Таблице 9.67 перечислены функции, связанные с идентификацией и адресацией объектов баз данных.
Таблица 9.67. Функции получения информации и адресации объектов
| Имя | Тип результата | Описание |
|---|---|---|
| text | получает описание объекта базы данных |
| type text, schema text, name text, identity text | получает идентификатор объекта базы данных |
| type text, object_names text[], object_args text[] | получает внешнее представление адреса объекта базы данных |
| classid oid, objid oid, objsubid integer | получает адрес объекта базы данных из его внешнего представления |
pg_describe_object возвращает текстовое описание объекта БД, идентифицируемого по OID каталога, OID объекта и ID подобъекта (например, номер столбца в таблице; ID подобъекта равен нулю для объекта в целом). Это описание предназначено для человека и может переводиться, в зависимости от конфигурации сервера. С помощью этой функции, например, можно узнать, что за объект хранится в каталоге pg_depend.
pg_identify_object возвращает запись, содержащую достаточно информации для однозначной идентификации объекта БД по OID каталога, OID объекта и ID подобъекта. Эта информация предназначена для машины и поэтому никогда не переводится. Столбец type содержит тип объекта БД; schema — имя схемы, к которой относится объект (либо NULL для объектов, не относящихся к схемам); name — имя объекта, при необходимости в кавычках, которое присутствует, только если оно (возможно, вместе со схемой) однозначно идентифицирует объект (в противном случае NULL); identity — полный идентификатор объекта, точный формат которого зависит от типа объекта, а каждая его часть дополняется схемой и заключается в кавычки, если требуется.
pg_identify_object_as_address возвращает запись, содержащую достаточно информации для однозначной идентификации объекта БД по OID каталога, OID объекта и ID подобъекта. Выдаваемая информация не зависит от текущего сервера, то есть по ней можно идентифицировать одноимённый объект на другом сервере. Поле type содержит тип объекта БД, а object_names и object_args — текстовые массивы, в совокупности формирующие ссылку на объект. Эти три значения можно передать функции pg_get_object_address, чтобы получить внутренний адрес объекта. Данная функция является обратной к pg_get_object_address.
pg_get_object_address возвращает запись, содержащую достаточно информации для уникальной идентификации объекта БД по его типу и массивам имён и аргументов. В ней возвращаются значения, которые используются в системных каталогах, например pg_depend, и могут передаваться в другие системные функции, например pg_identify_object или pg_describe_object. Поле classid содержит OID системного каталога, к которому относится объект; objid — OID самого объекта, а objsubid — идентификатор подобъекта или 0 в случае его отсутствия. Эта функция является обратной к pg_identify_object_as_address.
Функции, перечисленные в Таблице 9.68, извлекают комментарии, заданные для объектов с помощью команды COMMENT. Если найти комментарий для заданных параметров не удаётся, они возвращают NULL.
Таблица 9.68. Функции получения комментариев
| Имя | Тип результата | Описание |
|---|---|---|
| text | получает комментарий для столбца таблицы |
| text | получает комментарий для объекта базы данных |
| text | получает комментарий для объекта базы данных (устаревшая форма) |
| text | получает комментарий для разделяемого объекта баз данных |
col_description возвращает комментарий для столбца с заданным номером в таблице с указанным OID. (obj_description нельзя использовать для столбцов таблицы, так столбцы не имеют собственных OID.)
Функция obj_description с двумя параметрами возвращает комментарий для объекта, имеющего заданный OID и находящегося в указанном системном каталоге. Например, obj_description(123456,'pg_class') вернёт комментарий для таблицы с OID 123456. Форма obj_description с одним параметром принимает только OID. Она является устаревшей, так как значения OID могут повторяться в разных системных каталогах, и поэтому она может возвращать комментарий для другого объекта.
shobj_description работает подобно obj_description, но она получает комментарии для разделяемых объектов. Некоторые системные каталоги являются глобальными для всех баз данных в кластере и описания объектов в них также хранятся глобально.
Функции, перечисленные в Таблице 9.69, выдают информацию о транзакциях сервера в форме во внешнем представлении. В основном эти функции используются, чтобы определить, какие транзакции были зафиксированы между двумя снимками состояния.
Таблица 9.69. Идентификаторы транзакций и снимков состояния
| Имя | Тип результата | Описание |
|---|---|---|
| bigint | получает идентификатор текущей транзакции и присваивает новый, если текущая транзакция его не имеет |
| bigint | работает аналогично txid_current(), но возвращает NULL, не присваивая новый идентификатор транзакции, если он ещё не присвоен |
| txid_snapshot | получает код текущего снимка |
| setof bigint | возвращает идентификаторы выполняющихся транзакций в снимке |
| bigint | возвращает значение xmax для заданного снимка |
| bigint | возвращает значение xmin для заданного снимка |
| boolean | видима ли транзакция с указанным идентификатором в данном снимке? (коды подтранзакций не поддерживаются) |
| text | возвращает состояние заданной транзакции — committed (зафиксирована), aborted (прервана), in progress (выполняется) или NULL, если идентификатор транзакции слишком старый |
В Postgres Pro Enterprise идентификаторы транзакций представлены 64-битными счётчиками для предотвращения зацикливания этих идентификаторов. Следующие функции выдают 64-битные значения, так что эти значения останутся уникальными на протяжении всей жизни сервера. Используемый этими функциями тип данных txid_snapshot, сохраняет информацию о видимости транзакций в определённый момент времени. Его состав описан в Таблице 9.70.
Таблица 9.70. Состав информации о снимке
| Имя | Описание |
|---|---|
xmin | Идентификатор самой ранней транзакции (txid) из активных. Все предыдущие транзакции либо зафиксированы и видимы, либо отменены и мертвы. |
xmax | Первый txid из ещё не назначенных. На момент снимка не было запущенных (а значит и видимых) транзакций с идентификатором, большим или равным данному. |
xip_list | Список идентификаторов транзакций, активных в момент снимка. Он включает только идентификаторы с номерами от xmin до xmax; хотя уже могут быть транзакции с идентификаторами больше xmax. Если в этом списке не оказывается идентификатора транзакции xmin <= txid < xmax, это означает, что она уже не выполнялась к моменту снимка и, таким образом, видима или мертва, в зависимости от типа завершения. Идентификаторы подтранзакций в этот список не включаются. |
В текстовом виде txid_snapshot представляется как . Например, xmin:xmax:xip_list10:20:10,14,15 означает xmin=10, xmax=20, xip_list=10, 14, 15.
Функция txid_status(bigint) выдаёт состояние фиксации последней транзакции. Проверяя его, приложения могут определить, была ли транзакция зафиксирована или прервана, когда приложение отключается от сервера баз данных в процессе выполнения COMMIT. Состояние транзакции может быть следующим: in progress (выполняется), committed (зафиксирована) и aborted (прервана), если только транзакция не настолько стара, чтобы система удалила информация о её состоянии фиксирования. Если же она так стара, что упоминаний о ней в системе не осталось и информация о фиксации потеряна, эта функция возвращает NULL. Заметьте, что для подготовленных транзакций возвращается состояние in progress; приложения должны проверять pg_prepared_xacts, если им нужно определить, является ли транзакция «txid» подготовленной.
Функции, показанные в Таблице 9.71, выдают информацию об уже зафиксированных транзакциях. Они возвращают полезные данные, только когда включён параметр конфигурации track_commit_timestamp и только для транзакций, зафиксированных после его включения.
Таблица 9.71. Информация о фиксации транзакций
Функции, перечисленные в Таблице 9.72, выводят свойства, установленные командой initdb, например, версию каталога. Они также выводят сведения о работе журнала предзаписи и контрольных точках. Эта информация относится ко всему кластеру, а не к отдельной базе данных. Данные функции выдают практически всю ту же информацию, и из того же источника, что и pg_controldata, но в форме, более подходящей для функций SQL.
Таблица 9.72. Функции управления данными
Функция pg_control_checkpoint возвращает запись, показанную в Таблице 9.73.
Таблица 9.73. Столбцы результата pg_control_checkpoint
| Имя столбца | Тип данных |
|---|---|
checkpoint_lsn | pg_lsn |
prior_lsn | pg_lsn |
redo_lsn | pg_lsn |
redo_wal_file | text |
timeline_id | integer |
prev_timeline_id | integer |
full_page_writes | boolean |
next_xid | text |
next_oid | oid |
next_multixact_id | xid |
next_multi_offset | xid |
oldest_xid | xid |
oldest_xid_dbid | oid |
oldest_active_xid | xid |
oldest_multi_xid | xid |
oldest_multi_dbid | oid |
oldest_commit_ts_xid | xid |
newest_commit_ts_xid | xid |
checkpoint_time | timestamp with time zone |
Функция pg_control_system возвращает запись, показанную в Таблице 9.74.
Таблица 9.74. Столбцы результата pg_control_system
| Имя столбца | Тип данных |
|---|---|
pg_control_version | integer |
catalog_version_no | integer |
system_identifier | bigint |
pg_control_last_modified | timestamp with time zone |
pg_control_edition | text |
Функция pg_control_init возвращает запись, показанную в Таблице 9.75.
Таблица 9.75. Столбцы результата pg_control_init
| Имя столбца | Тип данных |
|---|---|
max_data_alignment | integer |
database_block_size | integer |
blocks_per_segment | integer |
wal_block_size | integer |
bytes_per_wal_segment | integer |
max_identifier_length | integer |
max_index_columns | integer |
max_toast_chunk_size | integer |
large_object_chunk_size | integer |
float4_pass_by_value | boolean |
float8_pass_by_value | boolean |
data_page_checksum_version | integer |
icu_version | text |
Функция pg_control_recovery возвращает запись, показанную в Таблице 9.76
Таблица 9.76. Столбцы результата pg_control_recovery
| Имя столбца | Тип данных |
|---|---|
min_recovery_end_lsn | pg_lsn |
min_recovery_end_timeline | integer |
backup_start_lsn | pg_lsn |
backup_end_lsn | pg_lsn |
end_of_backup_record_required | boolean |
9.25. System Information Functions
Table 9.60 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 28.2.2 for more information.
Table 9.60. Session Information Functions
| Name | Return Type | Description |
|---|---|---|
| name | name of current database (called “catalog” in the SQL standard) |
| name | name of current database |
| text | text of the currently executing query, as submitted by the client (might contain more than one statement) |
| name | equivalent to current_user |
| name | name of current schema |
| name[] | names of schemas in search path, optionally including implicit schemas |
| name | user name of current execution context |
| inet | address of the remote connection |
| int | port of the remote connection |
| inet | address of the local connection |
| int | port of the local connection |
| int | Process ID of the server process attached to the current session |
| int[] | Process ID(s) that are blocking specified server process ID from acquiring a lock |
| timestamp with time zone | configuration load time |
| text | Primary log file name, or log in the requested format, currently in use by the logging collector |
| oid | OID of session's temporary schema, or 0 if none |
| boolean | is schema another session's temporary schema? |
| setof text | channel names that the session is currently listening on |
| double | fraction of the asynchronous notification queue currently occupied (0-1) |
| timestamp with time zone | server start time |
| int[] | Process ID(s) that are blocking specified server process ID from acquiring a safe snapshot |
| int | current nesting level of Postgres Pro triggers (0 if not called, directly or indirectly, from inside a trigger) |
| name | session user name |
| name | equivalent to current_user |
| text | PostgreSQL version information. See also server_version_num for a machine-readable version. |
| text | Postgres Pro version information |
| text | name of Postgres Pro edition |
| text | 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.)
current_schema 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(boolean) returns an array of the names of all schemas presently in the search path. The Boolean option determines whether or not implicitly included system schemas such as pg_catalog are included in the returned search path.
Note
The search path can be altered at run time. The command is:
SET search_path TOschema[,schema, ...]
inet_client_addr returns the IP address of the current client, and inet_client_port returns the port number. inet_server_addr returns the IP address on which the server accepted the current connection, and inet_server_port returns the port number. All these functions return NULL if the current connection is via a Unix-domain socket.
pg_blocking_pids returns an array of the process IDs of the sessions that are blocking the server process with the specified process ID, 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 in the result of this function. 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 returns the timestamp with time zone 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 returns, as text, the path of the log file(s) currently in use by the logging collector. The path includes the log_directory directory and the log file name. Log collection must be enabled or the return value is NULL. When multiple log files exist, each in a different format, pg_current_logfile called without arguments returns the path of the file having the first format found in the ordered list: stderr, csvlog. NULL is returned when no log file has any of these formats. To request a specific file format supply, as text, either csvlog or stderr as the value of the optional parameter. The return value is NULL when the log format requested is not a configured log_destination. The pg_current_logfile reflects the contents of the current_logfiles file.
pg_my_temp_schema 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 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_listening_channels returns a set of names of asynchronous notification channels that the current session is listening to. pg_notification_queue_usage returns the fraction of the total available space for notifications currently occupied by notifications that are waiting to be processed, as a double in the range 0-1. See LISTEN and NOTIFY for more information.
pg_postmaster_start_time returns the timestamp with time zone when the server started.
pg_safe_snapshot_blocking_pids returns an array of the process IDs 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.
version returns a string describing the Postgres Pro server's version. You can also get this information from server_version or for a machine-readable version, server_version_num. Software developers should use server_version_num (available since 8.2) or PQserverVersion instead of parsing the text version.
returns a string, describing Postgres Pro edition i.e. pgpro_edition()standard or enterprise.
returns a string, describing Postgres Pro version information.pgpro_version()
Table 9.61 lists functions that allow the user to query object access privileges programmatically. See Section 5.6 for more information about privileges.
Table 9.61. Access Privilege Inquiry Functions
| Name | Return Type | Description |
|---|---|---|
| boolean | does user have privilege for any column of table |
| boolean | does current user have privilege for any column of table |
| boolean | does user have privilege for column |
| boolean | does current user have privilege for column |
| boolean | does user have privilege for database |
| boolean | does current user have privilege for database |
| boolean | does user have privilege for foreign-data wrapper |
| boolean | does current user have privilege for foreign-data wrapper |
| boolean | does user have privilege for function |
| boolean | does current user have privilege for function |
| boolean | does user have privilege for language |
| boolean | does current user have privilege for language |
| boolean | does user have privilege for schema |
| boolean | does current user have privilege for schema |
| boolean | does user have privilege for sequence |
| boolean | does current user have privilege for sequence |
| boolean | does user have privilege for foreign server |
| boolean | does current user have privilege for foreign server |
| boolean | does user have privilege for table |
| boolean | does current user have privilege for table |
| boolean | does user have privilege for tablespace |
| boolean | does current user have privilege for tablespace |
| boolean | does user have privilege for type |
| boolean | does current user have privilege for type |
| boolean | does user have privilege for role |
| boolean | does current user have privilege for role |
| boolean | does current user have row level security active for table |
has_table_privilege checks whether a user can access a table in a particular way. The user can be specified by name, by OID (pg_authid.oid), public to indicate the PUBLIC pseudo-role, or if the argument is omitted current_user is assumed. The table can be specified by name or by OID. (Thus, there are actually six variants of has_table_privilege, which can be distinguished by the number and types of their arguments.) When specifying by name, the name can be schema-qualified if necessary. The desired access privilege type is specified by a text string, which must evaluate to one of the values SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, or TRIGGER. 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');
has_sequence_privilege checks whether a user can access a sequence in a particular way. The possibilities for its arguments are analogous to has_table_privilege. The desired access privilege type must evaluate to one of USAGE, SELECT, or UPDATE.
has_any_column_privilege checks whether a user can access any column of a table in a particular way. Its argument possibilities are analogous to has_table_privilege, except that the desired access privilege type must evaluate to some combination of SELECT, INSERT, UPDATE, or REFERENCES. Note that having any of these privileges at the table level implicitly grants it for each column of the table, so has_any_column_privilege will always return true if has_table_privilege does for the same arguments. But has_any_column_privilege also succeeds if there is a column-level grant of the privilege for at least one column.
has_column_privilege checks whether a user can access a column in a particular way. Its argument possibilities are analogous to has_table_privilege, with the addition that the column can be specified either by name or attribute number. The desired access privilege type must evaluate to some combination of SELECT, INSERT, UPDATE, or REFERENCES. Note that having any of these privileges at the table level implicitly grants it for each column of the table.
has_database_privilege checks whether a user can access a database in a particular way. Its argument possibilities are analogous to has_table_privilege. The desired access privilege type must evaluate to some combination of CREATE, CONNECT, TEMPORARY, or TEMP (which is equivalent to TEMPORARY).
has_function_privilege checks whether a user can access a function in a particular way. Its argument possibilities are analogous to has_table_privilege. When specifying a function by a text string rather than by OID, the allowed input is the same as for the regprocedure data type (see Section 8.18). The desired access privilege type must evaluate to EXECUTE. An example is:
SELECT has_function_privilege('joeuser', 'myfunc(int, text)', 'execute');
has_foreign_data_wrapper_privilege checks whether a user can access a foreign-data wrapper in a particular way. Its argument possibilities are analogous to has_table_privilege. The desired access privilege type must evaluate to USAGE.
has_language_privilege checks whether a user can access a procedural language in a particular way. Its argument possibilities are analogous to has_table_privilege. The desired access privilege type must evaluate to USAGE.
has_schema_privilege checks whether a user can access a schema in a particular way. Its argument possibilities are analogous to has_table_privilege. The desired access privilege type must evaluate to some combination of CREATE or USAGE.
has_server_privilege checks whether a user can access a foreign server in a particular way. Its argument possibilities are analogous to has_table_privilege. The desired access privilege type must evaluate to USAGE.
has_tablespace_privilege checks whether a user can access a tablespace in a particular way. Its argument possibilities are analogous to has_table_privilege. The desired access privilege type must evaluate to CREATE.
has_type_privilege checks whether a user can access a type in a particular way. Its argument possibilities are analogous to has_table_privilege. When specifying a type by a text string rather than by OID, the allowed input is the same as for the regtype data type (see Section 8.18). The desired access privilege type must evaluate to USAGE.
pg_has_role checks whether a user can access a role in a particular way. Its argument possibilities are analogous to has_table_privilege, except that public is not allowed as a user name. The desired access privilege type must evaluate to some combination of MEMBER or USAGE. MEMBER denotes direct or indirect membership in the role (that is, the right to do SET ROLE), while USAGE denotes whether the privileges of the role are immediately available without doing SET ROLE.
row_security_active checks whether row level security is active for the specified table in the context of the current_user and environment. The table can be specified by name or by OID.
Table 9.62 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. To list the names of all visible tables:
SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
Table 9.62. Schema Visibility Inquiry Functions
| Name | Return Type | Description |
|---|---|---|
| boolean | is collation visible in search path |
| boolean | is conversion visible in search path |
| boolean | is function visible in search path |
| boolean | is operator class visible in search path |
| boolean | is operator visible in search path |
| boolean | is operator family visible in search path |
| boolean | is statistics object visible in search path |
| boolean | is table visible in search path |
| boolean | is text search configuration visible in search path |
| boolean | is text search dictionary visible in search path |
| boolean | is text search parser visible in search path |
| boolean | is text search template visible in search path |
| boolean | is type (or domain) visible in search path |
Each function performs the visibility check for one type of database object. Note that pg_table_is_visible can also be used with views, materialized views, indexes, sequences and foreign tables; pg_type_is_visible can also be used with domains. For functions and operators, an object in the search path is visible if there is no object of the same name and argument data type(s) earlier in the path. For operator classes, both name and associated index access method are considered.
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.
Table 9.63 lists functions that extract information from the system catalogs.
Table 9.63. System Catalog Information Functions
| Name | Return Type | Description |
|---|---|---|
| text | get SQL name of a data type |
| text | get definition of a constraint |
| text | get definition of a constraint |
| text | decompile internal form of an expression, assuming that any Vars in it refer to the relation indicated by the second parameter |
| text | decompile internal form of an expression, assuming that any Vars in it refer to the relation indicated by the second parameter |
| text | get definition of a function |
| text | get argument list of function's definition (with default values) |
| text | get argument list to identify a function (without default values) |
| text | get RETURNS clause for function |
| text | get CREATE INDEX command for index |
| text | get CREATE INDEX command for index, or definition of just one index column when column_no is not zero |
| setof record | get list of SQL keywords and their categories |
| text | get CREATE RULE command for rule |
| text | get CREATE RULE command for rule |
| text | get name of the sequence that a serial or identity column uses |
| text | get CREATE STATISTICS command for extended statistics object |
pg_get_triggerdef(trigger_oid) | text | get CREATE [ CONSTRAINT ] TRIGGER command for trigger |
pg_get_triggerdef(trigger_oid, pretty_bool) | text | get CREATE [ CONSTRAINT ] TRIGGER command for trigger |
| name | get role name with given OID |
| text | get underlying SELECT command for view or materialized view (deprecated) |
| text | get underlying SELECT command for view or materialized view (deprecated) |
| text | get underlying SELECT command for view or materialized view |
| text | get underlying SELECT command for view or materialized view |
| text | get underlying SELECT command for view or materialized view; lines with fields are wrapped to specified number of columns, pretty-printing is implied |
| boolean | test whether an index column has a specified property |
| boolean | test whether an index has a specified property |
| boolean | test whether an index access method has a specified property |
| setof record | get the set of storage option name/value pairs |
| setof oid | get the set of database OIDs that have objects in the tablespace |
| text | get the path in the file system that this tablespace is located in |
| regtype | get the data type of any value |
| text | get the collation of the argument |
| regclass | get the OID of the named relation |
| regproc | get the OID of the named function |
| regprocedure | get the OID of the named function |
| regoper | get the OID of the named operator |
| regoperator | get the OID of the named operator |
| regtype | get the OID of the named type |
| regnamespace | get the OID of the named schema |
| regrole | get the OID of the named role |
format_type returns the SQL name of 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_get_keywords 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 unreserved, C for column name, T for type or function name, or R for reserved. The catdesc column contains a possibly-localized string describing the category.
pg_get_constraintdef, pg_get_indexdef, pg_get_ruledef, pg_get_statisticsobjdef, and pg_get_triggerdef, respectively reconstruct the creating command for a constraint, index, rule, extended statistics object, or trigger. (Note that this is a decompiled reconstruction, not the original text of the command.) pg_get_expr decompiles the internal form of an individual expression, such as the default value for a column. It can be useful when examining the contents of system catalogs. If the expression might contain Vars, specify the OID of the relation they refer to as the second parameter; if no Vars are expected, zero is sufficient. pg_get_viewdef reconstructs the SELECT query that defines a view. Most of these functions come in two variants, one of which can optionally “pretty-print” the result. 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; avoid using pretty-printed output for dump purposes. Passing false for the pretty-print parameter yields the same result as the variant that does not have the parameter at all.
pg_get_functiondef returns a complete CREATE OR REPLACE FUNCTION statement for a function. pg_get_function_arguments returns the argument list of a function, in the form it would need to appear in within CREATE FUNCTION. pg_get_function_result similarly returns the appropriate RETURNS clause for the function. pg_get_function_identity_arguments returns the argument list necessary to identify a function, in the form it would need to appear in within ALTER FUNCTION, for instance. This form omits default values.
pg_get_serial_sequence 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 the identity 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, this association can be modified or removed with ALTER SEQUENCE OWNED BY. (The function probably should have been called pg_get_owned_sequence; its current name reflects the fact that it has typically been used with serial or bigserial columns.) The first input parameter is a table name with optional schema, and the second parameter is a column name. Because the first parameter is potentially a schema and table, it is not treated as a double-quoted identifier, meaning it is lower cased by default, while the second parameter, being just a column name, is treated as double-quoted and has its case preserved. The function returns a value suitably formatted for passing to sequence functions (see Section 9.16). A typical use is in reading the current value of a sequence for an identity or serial column, for example:
SELECT currval(pg_get_serial_sequence('sometable', 'id'));
pg_get_userbyid extracts a role's name given its OID.
pg_index_column_has_property, pg_index_has_property, and pg_indexam_has_property return whether the specified index column, index, or index access method possesses the named property. 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. Refer to Table 9.64 for column properties, Table 9.65 for index properties, and Table 9.66 for access method properties. (Note that extension access methods can define additional property names for their indexes.)
Table 9.64. Index Column Properties
| Name | Description |
|---|---|
asc | Does the column sort in ascending order on a forward scan? |
desc | Does the column sort in descending order on a forward scan? |
nulls_first | Does the column sort with nulls first on a forward scan? |
nulls_last | Does the column sort with nulls last on a forward scan? |
orderable | Does the column possess any defined sort ordering? |
distance_orderable | Can the column be scanned in order by a “distance” operator, for example ORDER BY col <-> constant ? |
returnable | Can the column value be returned by an index-only scan? |
search_array | Does the column natively support col = ANY(array) searches? |
search_nulls | Does the column support IS NULL and IS NOT NULL searches? |
Table 9.65. Index Properties
| Name | Description |
|---|---|
clusterable | Can the index be used in a CLUSTER command? |
index_scan | Does the index support plain (non-bitmap) scans? |
bitmap_scan | Does the index support bitmap scans? |
backward_scan | Can the scan direction be changed in mid-scan (to support FETCH BACKWARD on a cursor without needing materialization)? |
Table 9.66. Index Access Method Properties
| Name | Description |
|---|---|
can_order | Does the access method support ASC, DESC and related keywords in CREATE INDEX? |
can_unique | Does the access method support unique indexes? |
can_multi_col | Does the access method support indexes with multiple columns? |
can_exclude | Does the access method support exclusion constraints? |
pg_options_to_table returns the set of storage option name/value pairs (option_name/option_value) when passed pg_class.reloptions or pg_attribute.attoptions.
pg_tablespace_databases allows a tablespace to be examined. It returns the set of OIDs of databases that have objects stored in the tablespace. If this function returns any rows, the tablespace is not empty and cannot be dropped. To display the specific objects populating the tablespace, you will need to connect to the databases identified by pg_tablespace_databases and query their pg_class catalogs.
pg_typeof 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.18); 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
(1 row)
SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
typlen
--------
4
(1 row)
The expression collation for returns the collation of the value that is passed to it. Example:
SELECT collation for (description) FROM pg_description LIMIT 1;
pg_collation_for
------------------
"default"
(1 row)
SELECT collation for ('foo' COLLATE "de_DE");
pg_collation_for
------------------
"de_DE"
(1 row)
The value might be quoted and schema-qualified. If no collation is derived for the argument expression, then a null value is returned. If the argument is not of a collatable data type, then an error is raised.
The to_regclass, to_regproc, to_regprocedure, to_regoper, to_regoperator, to_regtype, to_regnamespace, and to_regrole functions translate relation, function, operator, type, schema, and role names (given as text) to objects of type regclass, regproc, regprocedure, regoper, regoperator, regtype, regnamespace, and regrole respectively. These functions differ from a cast from text in that they don't accept a numeric OID, and that they return null rather than throwing an error if the name is not found (or, for to_regproc and to_regoper, if the given name matches multiple objects).
Table 9.67 lists functions related to database object identification and addressing.
Table 9.67. Object Information and Addressing Functions
| Name | Return Type | Description |
|---|---|---|
| text | get description of a database object |
| type text, schema text, name text, identity text | get identity of a database object |
| type text, object_names text[], object_args text[] | get external representation of a database object's address |
| classid oid, objid oid, objsubid integer | get address of a database object from its external representation |
pg_describe_object returns a textual description of a database object specified 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 useful to determine the identity of an object as stored in the pg_depend catalog.
pg_identify_object 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.
pg_identify_object_as_address 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. This function is the inverse of pg_get_object_address.
pg_get_object_address returns a row containing enough information to uniquely identify the database object specified by its type and object name and argument arrays. The returned values are the ones that would be used in system catalogs such as pg_depend and can be passed to other system functions such as pg_identify_object or pg_describe_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.
The functions shown in Table 9.68 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.68. Comment Information Functions
| Name | Return Type | Description |
|---|---|---|
| text | get comment for a table column |
| text | get comment for a database object |
| text | get comment for a database object (deprecated) |
| text | get comment for a shared database object |
col_description 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.)
The two-parameter form of obj_description 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. The one-parameter form of obj_description requires only the object OID. It is deprecated since there is no guarantee that OIDs are unique across different system catalogs; therefore, the wrong comment might be returned.
shobj_description is used just like obj_description except it is used for retrieving comments on shared objects. Some system catalogs are global to all databases within each cluster, and the descriptions for objects in them are stored globally as well.
The functions shown in Table 9.69 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.69. Transaction IDs and Snapshots
| Name | Return Type | Description |
|---|---|---|
| bigint | get current transaction ID, assigning a new one if the current transaction does not have one |
| bigint | same as txid_current() but returns null instead of assigning a new transaction ID if none is already assigned |
| txid_snapshot | get current snapshot |
| setof bigint | get in-progress transaction IDs in snapshot |
| bigint | get xmax of snapshot |
| bigint | get xmin of snapshot |
| boolean | is transaction ID visible in snapshot? (do not use with subtransaction ids) |
| text | report the status of the given transaction: committed, aborted, in progress, or null if the transaction ID is too old |
In Postgres Pro Enterprise, transaction IDs are implemented as 64-bit counters to prevent transaction ID wraparound. The following functions export a 64-bit format, so it will not wrap around during the life of an installation. The data type used by these functions, txid_snapshot, stores information about transaction ID visibility at a particular moment in time. Its components are described in Table 9.70.
Table 9.70. Snapshot Components
| Name | Description |
|---|---|
xmin | Earliest transaction ID (txid) that is still active. All earlier transactions will either be committed and visible, or rolled back and dead. |
xmax | First as-yet-unassigned txid. All txids greater than or equal to this are not yet started as of the time of the snapshot, and thus invisible. |
xip_list | Active txids at the time of the snapshot. The list includes only those active txids between xmin and xmax; there might be active txids higher than xmax. A txid that is xmin <= txid < xmax and not in this list was already completed at the time of the snapshot, and thus either visible or dead according to its commit status. The list does not include txids of subtransactions. |
txid_snapshot's textual representation is . For example xmin:xmax:xip_list10:20:10,14,15 means xmin=10, xmax=20, xip_list=10, 14, 15.
txid_status(bigint) reports the commit status of a recent transaction. Applications may use it to determine whether a transaction committed or aborted when the application and database server become disconnected while a COMMIT is in progress. The status of a transaction will be reported as either in progress, committed, or aborted, provided that the transaction is recent enough that the system retains the commit status of that transaction. If is old enough that no references to that transaction survive in the system and the commit status information has been discarded, this function will return NULL. Note that prepared transactions are reported as in progress; applications must check pg_prepared_xacts if they need to determine whether the txid is a prepared transaction.
The functions shown in Table 9.71 provide information about transactions that have been already committed. These functions mainly provide information about when the transactions were committed. They only provide useful data when track_commit_timestamp configuration option is enabled and only for transactions that were committed after it was enabled.
Table 9.71. Committed transaction information
The functions shown in Table 9.72 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, and not specific to any one database. They provide most of the same information, from the same source, as pg_controldata, although in a form better suited to SQL functions.
Table 9.72. Control Data Functions
pg_control_checkpoint returns a record, shown in Table 9.73
Table 9.73. pg_control_checkpoint Columns
| Column Name | Data Type |
|---|---|
checkpoint_lsn | pg_lsn |
prior_lsn | pg_lsn |
redo_lsn | pg_lsn |
redo_wal_file | text |
timeline_id | integer |
prev_timeline_id | integer |
full_page_writes | boolean |
next_xid | text |
next_oid | oid |
next_multixact_id | xid |
next_multi_offset | xid |
oldest_xid | xid |
oldest_xid_dbid | oid |
oldest_active_xid | xid |
oldest_multi_xid | xid |
oldest_multi_dbid | oid |
oldest_commit_ts_xid | xid |
newest_commit_ts_xid | xid |
checkpoint_time | timestamp with time zone |
pg_control_system returns a record, shown in Table 9.74
Table 9.74. pg_control_system Columns
| Column Name | Data Type |
|---|---|
pg_control_version | integer |
catalog_version_no | integer |
system_identifier | bigint |
pg_control_last_modified | timestamp with time zone |
pg_control_edition | text |
pg_control_init returns a record, shown in Table 9.75
Table 9.75. pg_control_init Columns
| Column Name | Data Type |
|---|---|
max_data_alignment | integer |
database_block_size | integer |
blocks_per_segment | integer |
wal_block_size | integer |
bytes_per_wal_segment | integer |
max_identifier_length | integer |
max_index_columns | integer |
max_toast_chunk_size | integer |
large_object_chunk_size | integer |
float4_pass_by_value | boolean |
float8_pass_by_value | boolean |
data_page_checksum_version | integer |
icu_version | text |
pg_control_recovery returns a record, shown in Table 9.76
Table 9.76. pg_control_recovery Columns
| Column Name | Data Type |
|---|---|
min_recovery_end_lsn | pg_lsn |
min_recovery_end_timeline | integer |
backup_start_lsn | pg_lsn |
backup_end_lsn | pg_lsn |
end_of_backup_record_required | boolean |