关于设计设计数据库的原则

40 天前
 wenerme

平时总结的自己做开发时设计 Schema 的一些原则,大家有什么这方面的分享么? 这里放不下太多内容,贴一些主要的

column for
id 主键 - ULID, tagged ID
sid 租户维度单调递增 - 用户友好
uid UUID
tid 租户 ID
eid 用于导入数据关联 - tid+eid 唯一
cid 外部系统租户 ID - Colocate ID/Corp ID - tid+cid+rid 唯一
rid 外部系统资源 ID - Ref ID/Relative ID
created_at
updated_at
deleted_at
version 基于版本的乐观锁
metadata 补充数据
attributes 使用端自定义数据 - 客户端 读写
properties 服务端自定义数据 - 客户端 只读
extensions 内部扩展数据 - 客户端 不可见
owner_id 所有者
owner_type User, Team, Department, Organization
owner_user_id case owner_type when 'User' then owner_id end
owner_team_id case owner_type when 'Team' then owner_id end
entity_id 关联任意实体
entity_type
created_by_id
updated_by_id
deleted_by_id
state 状态 - 面向系统,不可自定义
status 业务状态、阶段、原因、细节 - 可自定义
create table tpl_res
(
    -- 基础
    id                  text        not null default gen_ulid(),
    tid                 bigint      not null default current_tenant_id(), -- 租户
    uid                 uuid        not null default gen_random_uuid(),
    sid                 bigint      not null default (next_res_sid('tpl_pri_resources')),
    eid                 text        null , -- 用于导入数据关联
    created_at          timestamptz not null default current_timestamp,
    updated_at          timestamptz not null default current_timestamp,
    deleted_at          timestamptz,
    -- auditor 信息
    created_by_id       text                 default current_setting('app.user.id'),
    updated_by_id       text                 default current_setting('app.user.id'),
    deleted_by_id       text,
    -- 按需附加任意层面的数据
    -- 例如: attributes 允许客户端修改, properties 不允许客户端修改, extensions 客户端不可见
    extensions          jsonb,
    properties          jsonb,
    attributes          jsonb,
    -- 业务 owner 信息
    owner_id            text,
    owner_type          text,
    owner_uid           uuid,
    owner_id            text,
    owner_type          text, -- User, Team, Department
    owner_user_id       text generated always as ( case owner_type when 'User' then owner_id end ) stored,
    owner_team_id       text generated always as ( case owner_type when 'Team' then owner_id end ) stored,
    owner_department_id text,
    primary key (tid, id),
    unique (tid, sid),
    unique (tid, uid)
);

FAQ

created_at vs create_time

扩展 {#extension}

单数还是复数表名 {#plural}

推荐单数形式。 部分关键词使用复数: users, groups 。

尽量使用外键 {#fk}


1317 次点击
所在节点    程序员
1 条回复
v2webdev
31 天前
笔记写的太简洁了,估计只有 OP 自己能看懂啊。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1031660

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX