对复合类型的约束

Vin*_*non 7 postgresql constraint postgresql-9.2

如何在复合类型的子字段上创建约束?

伪代码

create type axis(
    major_axis float,
    minor_axis float,
    angle float constraint angle_constraint check(angle between -90 and 90)
);

create table sample(
    axis1 axis,
    axis2 axis
);
Run Code Online (Sandbox Code Playgroud)

这在 PostgreSQL 9.2 中可能吗?正如这里提到的那样,在 9.1 中似乎是不可能的。

Mik*_*ll' 11

使用带有 CHECK 约束的 CREATE DOMAIN。这适用于 PostgreSQL 9.1。它被记录为至少在 8.0 + 中工作。“部分解决方法是使用域类型作为复合类型的成员。”

create domain angle as float check (value between -90 and 90);

create type axis as (
    major_axis float,
    minor_axis float,
    angle angle
);

create table sample(
    axis1 axis,
    axis2 axis
);
Run Code Online (Sandbox Code Playgroud)

此 INSERT 语句应该会成功。

insert into sample values
(row(0, 0, 35), row(0, 0, 35));
Run Code Online (Sandbox Code Playgroud)

但这个应该失败。

insert into sample values
(row(0, 0, 93), row(0, 0, 35));
ERROR: value for domain angle violates check constraint "angle_check"
SQL state: 23514
Run Code Online (Sandbox Code Playgroud)