Postgresql 中文操作指南
8.18. Domain Types #
_domain_是基于另一种 _underlying type_的用户定义数据类型。它可以选择具有约束,将有效值限制为底层类型允许的一组子集。否则,它的行为与底层类型类似 - 例如,可以应用于底层类型的任何运算符或函数都适用于域类型。底层类型可以是任何内置或用户定义的基本类型、枚举类型、数组类型、复合类型、区间类型或另一个域。
A domain is a user-defined data type that is based on another underlying type. Optionally, it can have constraints that restrict its valid values to a subset of what the underlying type would allow. Otherwise it behaves like the underlying type — for example, any operator or function that can be applied to the underlying type will work on the domain type. The underlying type can be any built-in or user-defined base type, enum type, array type, composite type, range type, or another domain.
例如,我们可以在仅接受正整数的整数上创建一个域:
For example, we could create a domain over integers that accepts only positive integers:
CREATE DOMAIN posint AS integer CHECK (VALUE > 0);
CREATE TABLE mytable (id posint);
INSERT INTO mytable VALUES(1); -- works
INSERT INTO mytable VALUES(-1); -- fails
将基础类型的某个运算符或函数应用于域值时,域会自动向下转换为基础类型。因此,例如,mytable.id - 1 的结果被视为 integer 类型的,而不是 posint 类型的。我们可以编写 (mytable.id - 1)::posint 来将结果转换回 posint,使域的约束得以重新检查。在这种情况下,如果表达式被应用于 1 值的 id,就会产生错误。允许将基础类型的某个值分配给域类型的某个字段或变量,而无需编写显式转换,但会检查域的约束。
When an operator or function of the underlying type is applied to a domain value, the domain is automatically down-cast to the underlying type. Thus, for example, the result of mytable.id - 1 is considered to be of type integer not posint. We could write (mytable.id - 1)::posint to cast the result back to posint, causing the domain’s constraints to be rechecked. In this case, that would result in an error if the expression had been applied to an id value of 1. Assigning a value of the underlying type to a field or variable of the domain type is allowed without writing an explicit cast, but the domain’s constraints will be checked.
有关更多信息,请参阅 CREATE DOMAIN 。
For additional information see CREATE DOMAIN.