对复合类型的 Postgres 约束

Postgres constraints on Composite Types

提问人:Iamterribleatcoding 提问时间:11/4/2022 更新时间:11/4/2022 访问量:127

问:

理想情况下,我想对复合类型进行检查,以验证无论在哪里使用此复合类型,其中至少有一个字段是非空的

我有以下代码来设置我的类型和表

CREATE TYPE public.foo AS (
    min real,
    max real,
    other real,
    extra bool
);


create table public.bar (
    a foo not null check (num_nonnulls((a).min, (a).max, (a).other) > 0)
    b foo not null,
    c foo not null
);

在上面,我想检查在使用 foo 类型的地方,最小值、最大值或其他至少一个是非空的。到目前为止,我能够实现此目的的唯一方法是添加对列定义的检查,如上所示,这非常麻烦,因为我必须在使用复合类型的任何地方执行此操作,最糟糕的是,它可能会被遗忘添加。但它确实有效..

此外,鉴于他们支持对类型的检查,我曾考虑在这里使用域来代替,但是,不幸的是,据我所知,它们不支持复合类型。

有没有另一种简单的方法可以解决这个问题,我错过了?

PostgreSQL 复合类型

评论


答:

1赞 user330315 11/4/2022 #1

域可以使用自定义类型:

create domain foo_domain as foo
   not null
   constraint check_num_nulls 
     check (num_nonnulls ((value)."min", (value)."max", (value).other) > 0);

create table bar (
    a foo_domain,
    b foo_domain,
    c foo_domain
);