跳到内容
光环标志
光环基地

协议

模式、列、RLS 策略、身份验证帮助程序、索引的命名。稳定、记录在案的约定,让您的团队拥有一种命名方式。

参考6分钟 读取级别 初学者修改于 2026年4月15日

该页面已自动翻译。英文版具有权威性。

每个域一个前缀#

每个项目都会收到四个前缀为 project_{uuid}的子模式。您的业​​务表进入主模式;永远不要在系统模式中创建对象。

模式业主使用
project_{uuid}你表、视图和业务功能。这是您的非限定 SQL (create table posts …) 所在的模式;它仅在使用 aura db backup download 和 schema/dump导出的 SQL 上命名为 public ,这些 SQL 是可移植的。
project_{uuid}_authaura-auth用户、会话和 MFA。请勿修改。
project_{uuid}_storageaura-storage桶、对象和存储策略
project_{uuid}_platform平台函数、作业、cron 和秘密

Snake_case,复数,id uuid#

  • 复数 表: posts、 comments、 invoices
  • snake_case中的 列: created_at、 user_id、 last_seen_at
  • 主键 id uuid primary key default gen_random_uuid() — 无 uuid_generate_v4()。当 ids 暴露给客户端时,更喜欢 uuid 而不是 bigint generated always as identity (不可猜测,JavaScript 中不存在 2^53 精度问题);身份列也可以工作,备份和恢复可以处理它。
  • 时间戳 timestamptz,从不 timestamp 裸露
  • FK 后缀 _id: author_id, tenant_id
  • 布尔值 前缀为 is_ 或 has_
  • 无列 project_id — 原理图已经是绝缘体
exemplesql
create table posts (
  id            uuid primary key default gen_random_uuid(),
  author_id     uuid not null references users(id) on delete cascade,
  title         text not null,
  is_published  boolean not null default false,
  created_at    timestamptz not null default now()
);
注意

切勿添加 project_id 列。隔离已经来自模式,这样的列将添加索引而不增加安全性。

每个会话中注入三个函数#

网关打开指定 request.jwt.claims 的 Postgres 连接。下面的三个助手可以阅读这些声明,并且可以在您的保单中的任何位置使用。

  • auth.uid() — 当前用户的 uuid,如果匿名则为 NULL
  • auth.role() — 文本 · 匿名/已验证/service_role
  • auth.tenant() — 当前租户的 uuid(多租户 RBAC)
  • auth.has_role(name) — 布尔值 · 如果用户具有此应用程序角色,则为 true
  • auth.email() — 文本 · 用户电子邮件,从 JWT 读取
  • auth.claim(key) — jsonb · 对自定义声明的原始访问

可预测的名称、操作、角色#

约定: <table>_<scope>_<operation>。示例: posts_own_read、 orders_admin_delete。始终指定 to aura_authenticated 或 to aura_anon。

namingsql
-- ✓ 好:table_scope_op
create policy "posts_own_read"   on posts for select …
create policy "orders_admin_all" on orders for all …

-- ✗ 避免
create policy "allow_stuff"    -- 太模糊
create policy "new_policy_42" -- 不具有描述性

命名和何时建立索引#

  • 名称: idx_<table>_<colonnes> 或 uq_<table>_<colonnes> (唯一)
  • 始终索引:FK、频繁 filter/order_by 列、RLS 策略的 where
  • 不要索引:具有高基数低的布尔列(使用部分索引),表 < 1000 行
  • pgvector: using hnsw 对于 > 100k 向量,ivfflat 否则

为了走得更远#