表、视图与数据
表是 PostgreSQL 中存储业务数据的核心对象。设计表结构时,需要同时考虑字段类型、主键、约束、索引、权限策略和后续迁移成本。
表结构设计
创建业务表时,建议至少明确以下信息:
| 设计项 | 建议 |
|---|---|
| 主键 | 使用 bigint generated by default as identity 或 uuid,避免使用业务字段作为主键 |
| 必填字段 | 对必须存在的数据设置 not null |
| 默认值 | 对创建时间、状态、归属用户等字段设置默认值 |
| 唯一约束 | 对邮箱、外部订单号等唯一业务键设置 unique |
| 归属字段 | 多用户数据表建议保留 user_id,便于 RLS 权限控制 |
create table public.todos (
id bigint generated by default as identity primary key,
user_id varchar(64) not null default auth.uid(),
title text not null,
done boolean not null default false,
priority int not null default 0,
created_at timestamptz not null default now()
);
常用字段类型
| 类型 | 适用场景 |
|---|---|
text | 标题、描述、昵称等文本 |
boolean | 开关状态,如是否完成、是否启用 |
int / bigint | 数量、排序值、自增主键 |
numeric | 金额、精确小数 |
timestamptz | 带时区时间,建议用于创建时间和更新时间 |
jsonb | 灵活属性、扩展配置、第三方回调原文 |
uuid | 分布式 ID、公开 ID |
enum | 小而稳定的固定取值,如订单状态、流程阶段 |
需要数组类型可参考 数组,需要固定取值集合可参考 枚举类型,需要非结构化字段可参考 JSON 与非结构化数据。