8.21. Псевдотипы

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

Таблица 8.27. Псевдотипы

ИмяОписание
anyУказывает, что функция принимает любой вводимый тип данных.
anyelementУказывает, что функция принимает любой тип данных (см. Подраздел 37.2.5).
anyarrayУказывает, что функция принимает любой тип массива (см. Подраздел 37.2.5).
anynonarrayУказывает, что функция принимает любой тип данных, кроме массивов (см. Подраздел 37.2.5).
anyenumУказывает, что функция принимает любое перечисление (см. Подраздел 37.2.5 и Раздел 8.7).
anyrangeУказывает, что функция принимает любой диапазонный тип данных (см. Подраздел 37.2.5 и Раздел 8.17).
anymultirangeУказывает, что функция принимает любой мультидиапазонный тип данных (см. Подраздел 37.2.5 и Раздел 8.17).
anycompatibleУказывает, что функция принимает любой тип данных и может автоматически приводить различные аргументы к общему типу данных (см. Подраздел 37.2.5).
anycompatiblearrayУказывает, что функция принимает любой тип массива и может автоматически приводить различные аргументы к общему типу данных (см. Подраздел 37.2.5).
anycompatiblenonarrayУказывает, что функция принимает любой тип, отличный от массива, и может автоматически приводить различные аргументы к общему типу данных (см. Подраздел 37.2.5).
anycompatiblerangeУказывает, что функция принимает любой тип диапазонный данных и может автоматически приводить различные аргументы к общему типу данных (см. Подраздел 37.2.5 и Раздел 8.17).
anycompatiblemultirangeУказывает, что функция принимает любой мультидиапазонный тип данных и может автоматически приводить различные аргументы к общему типу данных (см. Подраздел 37.2.5 и Раздел 8.17).
cstringУказывает, что функция принимает или возвращает строку в стиле C.
internalУказывает, что функция принимает или возвращает внутренний серверный тип данных.
language_handlerОбработчик процедурного языка объявляется как возвращающий тип language_handler.
fdw_handlerОбработчик обёртки сторонних данных объявляется как возвращающий тип fdw_handler.
table_am_handlerОбработчик табличного метода доступа объявляется как возвращающий тип table_am_handler.
index_am_handlerОбработчик метода доступа индекса объявляется как возвращающий тип index_am_handler.
tsm_handlerОбработчик метода выборки из таблицы объявляется как возвращающий тип tsm_handler.
recordУказывает, что функция принимает или возвращает неопределённый тип строки.
triggerТриггерная функция объявляется как возвращающая тип trigger.
event_triggerФункция событийного триггера объявляется как возвращающая тип event_trigger.
pg_ddl_commandОбозначает представление команд DDL, доступное событийным триггерам.
voidУказывает, что функция не возвращает значение.
unknownОбозначает ещё не распознанный тип, например простую строковую константу.

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

Функции, написанные на процедурных языках, могут использовать псевдотипы, только если это позволяет соответствующий язык. В настоящее время большинство процедурных языков запрещают использовать псевдотипы в качестве типа аргумента и позволяют использовать для результатов только типы void и recordtrigger или event_trigger, когда функция реализует триггер или событийный триггер). Некоторые языки также поддерживают полиморфные функции с полиморфными псевдотипами, подробно рассмотренными в Подразделе 37.2.5.

Псевдотип internal используется в объявлениях функций, предназначенных только для внутреннего использования в СУБД, но не для прямого вызова в запросах SQL. Если у функции есть как хотя бы один аргумент типа internal, её нельзя будет вызывать из SQL. Чтобы сохранить типобезопасность при таком ограничении, следуйте важному правилу: не создавайте функцию, возвращающую результат типа internal, если у неё нет ни одного аргумента internal.

8.21. Pseudo-Types

The Postgres Pro type system contains a number of special-purpose entries that are collectively called pseudo-types. A pseudo-type cannot be used as a column data type, but it can be used to declare a function's argument or result type. Each of the available pseudo-types is useful in situations where a function's behavior does not correspond to simply taking or returning a value of a specific SQL data type. Table 8.27 lists the existing pseudo-types.

Table 8.27. Pseudo-Types

NameDescription
anyIndicates that a function accepts any input data type.
anyelementIndicates that a function accepts any data type (see Section 37.2.5).
anyarrayIndicates that a function accepts any array data type (see Section 37.2.5).
anynonarrayIndicates that a function accepts any non-array data type (see Section 37.2.5).
anyenumIndicates that a function accepts any enum data type (see Section 37.2.5 and Section 8.7).
anyrangeIndicates that a function accepts any range data type (see Section 37.2.5 and Section 8.17).
anymultirangeIndicates that a function accepts any multirange data type (see Section 37.2.5 and Section 8.17).
anycompatibleIndicates that a function accepts any data type, with automatic promotion of multiple arguments to a common data type (see Section 37.2.5).
anycompatiblearrayIndicates that a function accepts any array data type, with automatic promotion of multiple arguments to a common data type (see Section 37.2.5).
anycompatiblenonarrayIndicates that a function accepts any non-array data type, with automatic promotion of multiple arguments to a common data type (see Section 37.2.5).
anycompatiblerangeIndicates that a function accepts any range data type, with automatic promotion of multiple arguments to a common data type (see Section 37.2.5 and Section 8.17).
anycompatiblemultirangeIndicates that a function accepts any multirange data type, with automatic promotion of multiple arguments to a common data type (see Section 37.2.5 and Section 8.17).
cstringIndicates that a function accepts or returns a null-terminated C string.
internalIndicates that a function accepts or returns a server-internal data type.
language_handlerA procedural language call handler is declared to return language_handler.
fdw_handlerA foreign-data wrapper handler is declared to return fdw_handler.
table_am_handlerA table access method handler is declared to return table_am_handler.
index_am_handlerAn index access method handler is declared to return index_am_handler.
tsm_handlerA tablesample method handler is declared to return tsm_handler.
recordIdentifies a function taking or returning an unspecified row type.
triggerA trigger function is declared to return trigger.
event_triggerAn event trigger function is declared to return event_trigger.
pg_ddl_commandIdentifies a representation of DDL commands that is available to event triggers.
voidIndicates that a function returns no value.
unknownIdentifies a not-yet-resolved type, e.g., of an undecorated string literal.

Functions coded in C (whether built-in or dynamically loaded) can be declared to accept or return any of these pseudo-types. It is up to the function author to ensure that the function will behave safely when a pseudo-type is used as an argument type.

Functions coded in procedural languages can use pseudo-types only as allowed by their implementation languages. At present most procedural languages forbid use of a pseudo-type as an argument type, and allow only void and record as a result type (plus trigger or event_trigger when the function is used as a trigger or event trigger). Some also support polymorphic functions using the polymorphic pseudo-types, which are shown above and discussed in detail in Section 37.2.5.

The internal pseudo-type is used to declare functions that are meant only to be called internally by the database system, and not by direct invocation in an SQL query. If a function has at least one internal-type argument then it cannot be called from SQL. To preserve the type safety of this restriction it is important to follow this coding rule: do not create any function that is declared to return internal unless it has at least one internal argument.