36.2. Система типов Postgres Pro
Типы данных Postgres Pro делятся на базовые, типы-контейнеры, составные, доменные и псевдотипы.
36.2.1. Базовые типы
Базовые типы — это типы, такие как integer
, которые реализуются ниже уровня языка SQL (обычно на низкоуровневом языке, например C). В общих чертах они соответствуют так называемым абстрактным типам данных. Postgres Pro может работать с такими типами только через функции, предоставленные пользователем, и понимать их поведение только в той степени, в какой его опишет пользователь. Встроенные базовые типы описываются в Главе 8.
Типы-перечисления (enum) можно считать подкатегорией базовых типов. Они отличаются от других типов тем, что их можно создавать просто командами SQL, обходясь без низкоуровневого программирования. За подробностями обратитесь к Разделу 8.7.
36.2.2. Типы-контейнеры
В Postgres Pro есть три вида «типов-контейнеров», то есть типов, которые могут содержать в себе несколько значений других типов. Это массивы, составные типы и диапазоны.
Массивы могут содержать множество значений, имеющих один тип. Тип массива автоматически создаётся для каждого базового и составного типа, диапазона и домена, но не для массивов — массивы массивов не существуют. Для системы типов многомерные массивы не отличаются от одномерных. За дополнительными сведениями обратитесь к Разделу 8.15.
Составные типы, или типы строк, образуются при создании любой таблицы. С помощью команды CREATE TYPE также можно определить «независимый» составной тип, не связанный с таблицей. Составной тип представляет собой просто список типов с определёнными именами полей. Значением составного типа является строка таблицы или запись из значений полей. За дополнительными сведениями обратитесь к Разделу 8.16.
Диапазонный тип может содержать два значения одного типа, которые определяют нижнюю и верхнюю границу диапазона. Диапазонные типы создаются пользователем, хотя существует и несколько встроенных. За дополнительными сведениями обратитесь к Разделу 8.17.
36.2.3. Домены
Домен основывается на определённом нижележащем типе и во многих аспектах взаимозаменяем с ним. Однако домен может иметь ограничения, уменьшающие множество допустимых для него значений относительно нижележащего типа. Домены создаются SQL-командой CREATE DOMAIN. За дополнительными сведениями обратитесь к Разделу 8.18.
36.2.4. Псевдотипы
Для специальных целей существует также несколько «псевдотипов». Псевдотипы нельзя задействовать в столбцах таблицы или в типах-контейнерах, но их можно использовать в объявлениях аргументов и результатов функций. Это даёт возможность выделить в системе типов специальные классы функций. Все существующие псевдотипы перечислены в Таблице 8.25.
36.2.5. Полиморфные типы
Особый интерес представляют пять псевдотипов: anyelement
, anyarray
, anynonarray
, anyenum
и anyrange
, которые называются полиморфными типами. Функция, в объявлении которой используются эти типы, называется полиморфной. Полиморфная функция может работать со множеством различных типов данных; конкретный тип определяется в зависимости от значения, переданного при вызове.
Полиморфные аргументы и результаты связываются друг с другом и сводятся к определённому типу данных при разборе запроса, вызывающего полиморфную функцию. В каждой позиции (в аргументах или возвращаемом значении), объявленной как anyelement
, может передаваться любой фактический тип данных, но в каждом конкретном вызове все эти фактические типы должны быть одинаковыми. Аналогичным образом, в каждой позиции, объявленной как anyarray
, может передаваться любой тип данных массива, но все фактические типы должны совпадать. Так же и во всех позициях, объявленных как anyrange
, должен передаваться одинаковый диапазонный тип. Более того, если некоторые позиции объявлены как anyarray
, а другие как anyelement
, то фактическим типом в позициях anyarray
должен быть массив, элементы которого имеют тот же тип, что и значения в позициях anyelement
. Подобным образом, если одни позиции объявлены как anyrange
, а другие как anyelement
или anyarray
, фактическим типом в позициях anyrange
должен быть диапазон, подтип которого совпадает с типом элементов в позициях anyelement
и с типом, передаваемым в позициях anyarray
. Псевдотип anynonarray
обрабатывается так же, как anyelement
, но с дополнительным ограничением — фактический тип не должен быть типом массива. Псевдотип anyenum
тоже обрабатывается как anyelement
, но его фактические типы ограничиваются перечислениями.
Таким образом, когда с полиморфным типом объявлено несколько аргументов, в итоге допускаются только определённые комбинации фактических типов. Например, функция, объявленная как equal(anyelement, anyelement)
, примет в аргументах любые два значения, но только если их типы данных совпадают.
Когда с полиморфным типом объявлено возвращаемое значение функции, так же полиморфным должен быть минимум один аргумент, и фактический тип результата при конкретном вызове определится по типу фактически переданного аргумента. Например, если бы отсутствовал механизм обращения к элементам массива, его можно было бы реализовать, создав функцию subscript(anyarray, integer) returns anyelement
. С таким объявлением первым фактическим аргументом должен быть массив, и из него будет выведен правильный тип результата при разборе запроса. В качестве другого примера можно привести функцию f(anyarray) returns anyenum
, которая будет принимать только массивы перечислений.
В большинстве случаев при разборе функции фактический тип данных для полиморфного результата может быть выведен из аргументов, имеющих другой полиморфный тип; например, подтип anyarray
может выводиться из anyelement
и наоборот. Исключение представляет полиморфный результат типа anyrange
— для него требуется аргумент типа anyrange
; вывести его фактический тип из типа аргументов anyarray
или anyelement
нельзя. Это объясняется тем, что на одном подтипе могут базироваться несколько диапазонных типов.
Заметьте, что anynonarray
и anyenum
представляют не отдельные типы переменных; это те же типы, что и anyelement
, но с дополнительными ограничениями. Например, объявление функции f(anyelement, anyenum)
равнозначно объявлению f(anyenum, anyenum)
: оба фактических аргумента должны быть одинаковыми типами-перечислениями.
Функции с переменным числом аргументом (описанные в Подразделе 36.5.5) тоже могут быть полиморфными: для этого их последний параметр описывается как VARIADIC
anyarray
. Для целей сопоставления аргументов и определения фактического типа результата такая функция представляется так же, как если бы в ней явно объявлялось нужное число параметров anynonarray
.
36.2. The Postgres Pro Type System
Postgres Pro data types can be divided into base types, container types, domains, and pseudo-types.
36.2.1. Base Types
Base types are those, like integer
, that are implemented below the level of the SQL language (typically in a low-level language such as C). They generally correspond to what are often known as abstract data types. Postgres Pro can only operate on such types through functions provided by the user and only understands the behavior of such types to the extent that the user describes them. The built-in base types are described in Chapter 8.
Enumerated (enum) types can be considered as a subcategory of base types. The main difference is that they can be created using just SQL commands, without any low-level programming. Refer to Section 8.7 for more information.
36.2.2. Container Types
Postgres Pro has three kinds of “container” types, which are types that contain multiple values of other types. These are arrays, composites, and ranges.
Arrays can hold multiple values that are all of the same type. An array type is automatically created for each base type, composite type, range type, and domain type. But there are no arrays of arrays. So far as the type system is concerned, multi-dimensional arrays are the same as one-dimensional arrays. Refer to Section 8.15 for more information.
Composite types, or row types, are created whenever the user creates a table. It is also possible to use CREATE TYPE to define a “stand-alone” composite type with no associated table. A composite type is simply a list of types with associated field names. A value of a composite type is a row or record of field values. Refer to Section 8.16 for more information.
A range type can hold two values of the same type, which are the lower and upper bounds of the range. Range types are user-created, although a few built-in ones exist. Refer to Section 8.17 for more information.
36.2.3. Domains
A domain is based on a particular underlying type and for many purposes is interchangeable with its underlying type. However, a domain can have constraints that restrict its valid values to a subset of what the underlying type would allow. Domains are created using the SQL command CREATE DOMAIN. Refer to Section 8.18 for more information.
36.2.4. Pseudo-Types
There are a few “pseudo-types” for special purposes. Pseudo-types cannot appear as columns of tables or components of container types, but they can be used to declare the argument and result types of functions. This provides a mechanism within the type system to identify special classes of functions. Table 8.25 lists the existing pseudo-types.
36.2.5. Polymorphic Types
Five pseudo-types of special interest are anyelement
, anyarray
, anynonarray
, anyenum
, and anyrange
, which are collectively called polymorphic types. Any function declared using these types is said to be a polymorphic function. A polymorphic function can operate on many different data types, with the specific data type(s) being determined by the data types actually passed to it in a particular call.
Polymorphic arguments and results are tied to each other and are resolved to a specific data type when a query calling a polymorphic function is parsed. Each position (either argument or return value) declared as anyelement
is allowed to have any specific actual data type, but in any given call they must all be the same actual type. Each position declared as anyarray
can have any array data type, but similarly they must all be the same type. And similarly, positions declared as anyrange
must all be the same range type. Furthermore, if there are positions declared anyarray
and others declared anyelement
, the actual array type in the anyarray
positions must be an array whose elements are the same type appearing in the anyelement
positions. Similarly, if there are positions declared anyrange
and others declared anyelement
or anyarray
, the actual range type in the anyrange
positions must be a range whose subtype is the same type appearing in the anyelement
positions and the same as the element type of the anyarray
positions. anynonarray
is treated exactly the same as anyelement
, but adds the additional constraint that the actual type must not be an array type. anyenum
is treated exactly the same as anyelement
, but adds the additional constraint that the actual type must be an enum type.
Thus, when more than one argument position is declared with a polymorphic type, the net effect is that only certain combinations of actual argument types are allowed. For example, a function declared as equal(anyelement, anyelement)
will take any two input values, so long as they are of the same data type.
When the return value of a function is declared as a polymorphic type, there must be at least one argument position that is also polymorphic, and the actual data type supplied as the argument determines the actual result type for that call. For example, if there were not already an array subscripting mechanism, one could define a function that implements subscripting as subscript(anyarray, integer) returns anyelement
. This declaration constrains the actual first argument to be an array type, and allows the parser to infer the correct result type from the actual first argument's type. Another example is that a function declared as f(anyarray) returns anyenum
will only accept arrays of enum types.
In most cases, the parser can infer the actual data type for a polymorphic result type from arguments that are of a different polymorphic type; for example anyarray
can be deduced from anyelement
or vice versa. The exception is that a polymorphic result of type anyrange
requires an argument of type anyrange
; it cannot be deduced from anyarray
or anyelement
arguments. This is because there could be multiple range types with the same subtype.
Note that anynonarray
and anyenum
do not represent separate type variables; they are the same type as anyelement
, just with an additional constraint. For example, declaring a function as f(anyelement, anyenum)
is equivalent to declaring it as f(anyenum, anyenum)
: both actual arguments have to be the same enum type.
A variadic function (one taking a variable number of arguments, as in Section 36.5.5) can be polymorphic: this is accomplished by declaring its last parameter as VARIADIC
anyarray
. For purposes of argument matching and determining the actual result type, such a function behaves the same as if you had written the appropriate number of anynonarray
parameters.