我试图在关系数据库中捕获子类/超类关系的概念。如果我从
开始abstract class A {
id: UUID
}
class B extends A {
data: String
}
class C extends A {
data: Int
}
我可以写:
create table taba (id uuid not null unique, typ char not null);
create table tabb (id uuid not null unique references taba(id),
data varchar);
create table tabc (id uuid not null unique references taba(id),
data int);
references
子句在一个方向上保证其关系完整性:每个派生实例B或C必须具有其基本实例A.
但是另一个方向呢?我想保证每个基本实例A都有它的派生实例B或C,理想情况下它与给定的typ
匹配。
我想过在一张桌子里做这件事,就像这样:
create table taball (id uuid not null unique, typ char not null,
b_data varchar,
c_ data int);
但这似乎违反了open/closed principle:每次添加A的新子类时,我都要重写taball。
我根本不知道这是否可行(特别是因为在实际插入过程中必然会违反完整性),但我会很感激任何建议吗?
答案 0 :(得分:0)
PostgreSQL支持表inheritance,因此你可以像在代码中一样完成数据库:
create table taba (id uuid not null unique);
create table tabb (data varchar) inherits (taba);
create table tabc (data int) inherits (taba);
这样,当您插入tabb
或tabc
时,taba
中也会有一行可用。如果这是一个好的方式,取决于情况。