多租户数据库约束

cdm*_*kay 6 postgresql database-design constraint multi-tenant

我在 PostgreSQL 中有一个多租户应用程序,每个表中都有一个重复的tenant_id 列,以帮助将租户彼此隔离。

我的问题是,有什么方法可以使用数据库约束来确保tenant_ids与其父级一致。

例如,想象一个blog_posts有很多comments. 我想确保对于任何评论,tenant_id 与给定 blog_post_id 的tenant_id 相同。

这可以通过简单且可维护的方式完成吗?

cdm*_*kay 4

这就是我最终的结果:

create table blog_posts (
    id uuid not null,
    tenant_id uuid not null,
    title text not null,
    content text not null,
    primary key (id)
);

create unique index blog_posts_tenant_id_id_idx on blog_posts (tenant_id, id);

create table comments (
    id uuid not null,
    tenant_id uuid not null,
    blog_post_id uuid not null references blog_posts (id),
    content text not null,
    primary key (id)
);

alter table comments add foreign key (tenant_id, blog_post_id)
    references blog_posts (tenant_id, id)
    on update cascade;
Run Code Online (Sandbox Code Playgroud)

  • @TommCatt:这是一个人为的例子。实际的层次结构要复杂得多,所以是的,在很多情况下我不想执行连接。特别是在 SPA 的情况下,我会逐步刷新内容,但需要知道用户是否可以访问它们。 (2认同)