database-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesedatabase-documentation
数据库文档
Document a database so completely and accurately that the docs are provably the schema, not a
plausible guess at it. A half-correct schema doc is worse than none: people trust it and write broken code.
生成完全准确的数据库文档,确保文档可被证明与数据库架构完全一致,而非合理猜测。半正确的架构文档不如没有:人们会信任它并编写错误的代码。
The one principle: grounded AND verified
核心原则:基于真实数据源且经过验证
Every statement in the output must be:
- grounded — traceable to a concrete source, preferring the live database (introspection of the system catalog). ORM models, migrations, generated types, and seeds are claims about the database, not the database; the catalog is what actually runs.
- verified — confirmed by re-introspecting the live database and diffing it against the generated docs until the diff is empty or every remaining difference is explicitly justified. Never write "documentation is complete" — instead make the diff empty and show it.
A frontier model left to itself reads the ORM, writes confident prose, and ships an incomplete and
partly hallucinated schema (missed check-constraint enums, wrong , omitted legacy tables,
invented columns). This skill exists to defeat exactly that. Two mechanisms do it: (1) the live DB is the
oracle, and (2) judgment is never one agent's call — independent adversaries hunt for what one pass misses.
ON DELETE输出中的每一条内容都必须满足:
- 基于真实数据源 — 可追溯到具体来源,优先选择实时数据库(对系统目录进行内省)。ORM模型、迁移脚本、生成的类型和种子数据只是对数据库的“声明”,而非数据库本身;系统目录才是实际运行的内容。
- 经过验证 — 通过重新内省实时数据库并将其与生成的文档进行差异对比,直到差异为空或所有剩余差异都得到明确说明。绝不要写“文档已完成”——而是要让差异为空并展示这一点。
仅依赖前沿模型的话,它会读取ORM模型,写出看似可信的内容,但交付的却是不完整且部分存在幻觉的架构文档(遗漏检查约束枚举、错误的配置、忽略遗留表、虚构列)。本技能正是为解决这一问题而生。通过两种机制实现:(1) 以实时数据库为权威来源;(2) 绝不依赖单一Agent的判断——由独立的“对抗者”寻找单次处理遗漏的内容。
ON DELETEScope (v1): relational/SQL only
适用范围(v1):仅关系型/SQL数据库
Targets PostgreSQL, MySQL, SQL Server, SQLite. If you detect a document store (MongoDB) or graph database,
say so and stop on that store — do not emit relational docs for it (silent mis-documentation is the
worst outcome). Note it as out of scope rather than guessing.
针对PostgreSQL、MySQL、SQL Server、SQLite。如果检测到文档型数据库(如MongoDB)或图数据库,请明确说明并停止处理该数据库——不要为其生成关系型文档(无声的错误文档是最糟糕的结果)。将其标记为超出范围,而非猜测。
Workflow
工作流程
Run these phases in order. Each names its exit artifact. Keep all scratch (intermediate extractions, the
working CSM) in a single scratch dir or your platform scratchpad — the only durable
deliverables are the docs and .
.database-documentation/schema.json按顺序执行以下阶段,每个阶段都会生成对应的输出产物。将所有临时文件(中间提取结果、工作中的CSM)保存在单个临时目录或平台草稿区中——唯一持久化的交付物是文档和。
.database-documentation/schema.jsonPhase 0 — Discover (read-only)
阶段0 — 发现(只读)
- Fingerprint the engine + version and the ORM(s): look for ,
schema.prisma+ datasource,*.entity.ts,drizzle.config.*+knexfile.*, Djangomigrations/, Railsmodels.py, raw SQL DDL. Find the engine + version from the datasource/provider,schema.rbimage tags, and connection URLs indocker-compose.yml..env* - Find the live-DB reachability path, trying in this order and stopping at the first that works:
a connected DB MCP server → /
docker compose execinto the DB container (read creds from compose env) → a local DB CLI (docker exec/psql/mysql/sqlcmd) against host:port fromsqlite3. Prove it with one trivial query (.env, list tables) before continuing. If the DB is down but a compose file defines it, offer to start it. Never print credentials: treat passwords/DSNs read fromSELECT 1/compose as secrets — keep them only in the command you execute, and redact them (.env) in anything you show or write to the docs.password=*** - Inventory every other surface: migrations dir (+count), generated client/, seeds/fixtures, and grep the app for raw SQL / query-builder calls. Note existing
*.d.ts— if present this is a refresh: load it to diff for drift and to match house style.docs/db/ - Announce the tier you reached (see Degradation ladder) so the reader knows the confidence level.
Exit: a short discovery note — engine, ORM, reachability tier, the exact verified live-DB command, surface paths.
- 识别数据库引擎+版本以及ORM:查找、
schema.prisma+ 数据源配置、*.entity.ts、drizzle.config.*+knexfile.*目录、Django的migrations/、Rails的models.py、原生SQL DDL文件。从数据源/提供者配置、schema.rb镜像标签、docker-compose.yml文件中的连接URL获取引擎+版本信息。.env* - 找到实时数据库的访问路径,按以下顺序尝试,找到第一个可行的路径后停止:
已连接的DB MCP服务器 → 通过**/
docker compose exec进入数据库容器(从compose环境变量读取凭据) → 使用本地DB CLI**(docker exec/psql/mysql/sqlcmd)连接sqlite3文件中指定的主机和端口。在继续之前,通过一个简单查询(如.env、列出表)验证连接有效性。如果数据库已停止但compose文件中定义了该数据库,可提供启动建议。绝不要打印凭据:将从SELECT 1/compose文件读取的密码/DSNs视为机密——仅在执行命令时使用,并且在展示或写入文档的内容中隐藏敏感信息(如.env)。password=*** - 盘点所有其他相关资源:迁移目录(+文件数量)、生成的客户端/文件、种子数据/测试数据,以及在应用中搜索原生SQL/查询构建器调用。注意现有的
*.d.ts目录——如果存在,说明这是一次刷新操作:加载现有文档以检测架构漂移并匹配现有风格。docs/db/ - 告知当前所处的层级(参考降级阶梯),让读者了解文档的置信度水平。
输出:简短的发现说明——数据库引擎、ORM、访问层级、已验证的实时数据库命令、相关资源路径。
Phase 1 — Extract every surface (parallel where possible)
阶段1 — 提取所有相关资源(尽可能并行处理)
Extract each available surface independently into the Canonical Schema Model shape
(see ). On platforms with subagents, run one extractor per surface in parallel,
and do not let them see each other's output — independent agreement is real evidence; shared context is
groupthink.
references/csm-contract.mdObject-class checklist — extract EVERY class; skipping one is the most common failure. Copy this list
and confirm each is present in with a live count:
schema.json- tables · [ ] columns (type+nullable+default+comment) · [ ] primary keys · [ ] foreign keys (+ON DELETE/UPDATE)
- unique constraints · [ ] check constraints · [ ] indexes (+partial/expression) · [ ] enums (+values)
- sequences · [ ] triggers · [ ] views (+definition) · [ ] routines (functions/procedures)
Sequences, triggers, and routines are routinely forgotten because they are not columns — extract them explicitly.
Capture view / trigger / routine bodies in full and verbatim — never abbreviate, summarize, or elide
with ; a truncated definition is an incomplete (wrong) doc.
= DB-NATIVE enum types only. A string column with a goes under
that table's (not ); an app-level-only value set goes in the column description
marked "app-enforced". Putting a non-native enum in is a hallucination against the live schema.
...schema.json.enumsCHECK (col IN (...))check_constraintsenumsenums- Live introspection (authoritative). Read the full catalog. See for the exact Postgres queries (and the MySQL/MSSQL/SQLite equivalents); they cover tables, columns (type with length/precision, nullability, default, identity, generated, collation, comment), primary keys, foreign keys with
references/introspection-postgres.md/ON DELETE, unique + check constraints, indexes (partial predicates and expression columns included), enums, domains, sequences, views/matviews, triggers, routines. Do NOT shell out to any benchmark/oracle script — write and run the introspection yourself.ON UPDATE - ORM models → CSM (intent + descriptions; per-ORM notes in ).
references/ - Migrations → fold them in timestamp order to reconstruct final state (do not eyeball 200 files).
- Generated types / seeds / app queries → corroborate; the app-query scan catches tables/columns used but absent from the ORM (legacy tables).
Exit: one partial CSM per surface.
将每个可用资源独立提取为标准架构模型(CSM)格式(详见)。在支持子Agent的平台上,为每个资源启动一个独立的提取器并行处理,不要让它们互相查看输出结果——独立的一致结果才是真实证据;共享上下文会导致群体思维。
references/csm-contract.md对象类别检查清单 — 提取所有类别;遗漏任何一个都是最常见的错误。复制此清单并确认每个类别都已在中存在并包含实时统计:
schema.json- 表 · [ ] 列(类型+可空性+默认值+注释) · [ ] 主键 · [ ] 外键(+/
ON DELETE配置)ON UPDATE - 唯一约束 · [ ] 检查约束 · [ ] 索引(+部分索引/表达式索引) · [ ] 枚举(+枚举值)
- 序列 · [ ] 触发器 · [ ] 视图(+定义) · [ ] 例程(函数/存储过程)
序列、触发器和例程通常会被遗忘,因为它们不是列——需要明确提取。完整且准确地捕获视图/触发器/例程的主体内容——绝不缩写、总结或用省略;截断的定义属于不完整(错误)的文档。
仅包含数据库原生枚举类型。带有约束的字符串列应归类到对应表的中(而非);仅在应用层面生效的取值集合应在列描述中标记为“应用层强制”。将非原生枚举放入属于对实时架构的幻觉式错误。
...schema.json.enumsCHECK (col IN (...))check_constraintsenumsenums- 实时内省(权威来源):读取完整的系统目录。详见中的PostgreSQL查询语句(以及MySQL/MSSQL/SQLite的等效语句);这些查询涵盖表、列(包含长度/精度、可空性、默认值、自增、生成列、排序规则、注释的类型)、主键、外键(包含
references/introspection-postgres.md/ON DELETE配置)、唯一约束+检查约束、索引(包含部分谓词和表达式列)、枚举、域、序列、视图/物化视图、触发器、例程。不要调用任何基准/权威脚本——自行编写并执行内省查询。ON UPDATE - ORM模型 → 转换为CSM格式(包含意图+描述;各ORM的注意事项详见目录)。
references/ - 迁移脚本 → 按时间戳顺序合并以重建最终状态(不要手动查看200个文件)。
- 生成的类型 / 种子数据 / 应用查询 → 进行验证;应用查询扫描可捕获ORM中未包含但实际被使用的表/列(遗留表)。
输出:每个资源对应的部分CSM。
Phase 2 — Reconcile to one CSM (precedence + drift)
阶段2 — 合并为单一CSM(优先级+漂移检测)
Merge into a master CSM, keying tables by physical DB name. Precedence:
- Live DB present → it wins, full stop. Any surface that disagrees produces a drift finding (recorded
in ), never a silent edit to the docs. The docs describe the live database.
issues/ - No live DB → consensus of migrations ⊕ ORM (migrations win structure, ORM wins intent); flag conflicts.
Tag each object's : (live-confirmed) / / / .
Where you have a live DB, cross-check it against itself via two methods (e.g. vs
) — the oracle must agree with itself before overruling other surfaces.
confidenceverifiedconsensussingle-sourceconflictinformation_schemapg_catalogExit: master CSM + a list.
discrepancies将所有部分CSM合并为一个主CSM,按数据库物理名称对表进行分组。优先级规则:
- 如果存在实时数据库 → 实时数据库结果优先,毫无例外。任何与之不符的资源都会生成漂移发现(记录在目录中),绝不要静默修改文档。文档应描述实时数据库的状态。
issues/ - 无实时数据库 → 迁移脚本与ORM的共识(迁移脚本决定结构,ORM决定意图);标记冲突内容。
为每个对象标记字段:(经实时数据库确认)/ (共识结果)/ (单一来源)/ (存在冲突)。如果有实时数据库,通过两种方法(如 vs )交叉验证实时数据库自身——在推翻其他资源结果之前,权威来源必须与自身一致。
confidenceverifiedconsensussingle-sourceconflictinformation_schemapg_catalog输出:主CSM + 差异列表。
discrepanciesPhase 3 — Generate docs + schema.json
阶段3 — 生成文档 + schema.json
Write all output into one dedicated docs directory — never scatter files across the repo. Default to
; if Phase 0 found an existing DB-docs directory (e.g. , ,
, or wherever the repo already keeps them), write there instead to match house style. Create
the directory if absent. Render the CSM (a pure function of it) into it, matching the template in
, sized to the schema:
docs/db/docs/db/docs/database/docs/schema/references/output-template.md- ≤ ~15 tables → a single (stats header, one mermaid ERD, per-table sections, an Issues section).
docs/db/DATABASE.md - larger → under :
docs/db/(index + stats) +README.md+ONBOARDING.mdper domain (mermaiddiagrams/<domain>.mdwith all columns+types + relationship lines, then per-table sections) +erDiagram(table-level only, so it stays renderable) +diagrams/full-erd.md+tables/entity-reference.md.issues/README.md
Emit into that same directory ().
schema.jsondocs/db/schema.jsonPer-table section: 1–2 sentence evidence-based description, a table, then Indexes: and Foreign Keys: (with ). Partition domains by ORM
module/folder → name prefix → FK clustering, with a Legacy/Misc catch-all. The follows the
shape in .
Column | Type | Nullable | Default | DescriptionON DELETEschema.jsonreferences/csm-contract.md将所有输出写入一个专用文档目录——不要将文件分散到仓库各处。默认使用;如果阶段0发现现有数据库文档目录(如、、或仓库中已有的其他数据库文档目录),则写入该目录以匹配现有风格。如果目录不存在则创建。根据CSM(纯函数转换)生成文档,匹配中的模板,根据架构规模调整格式:
docs/db/docs/db/docs/database/docs/schema/references/output-template.md- ≤约15张表 → 单个文件(包含统计头、一个mermaid ER图、每张表的详细章节、问题章节)。
docs/db/DATABASE.md - 更大规模 → 在目录下生成:
docs/db/(索引+统计) +README.md+ 每个领域对应的ONBOARDING.md(包含所有列+类型+关系线的mermaiddiagrams/<domain>.md,以及每张表的详细章节) +erDiagram(仅包含表级关系,确保可渲染) +diagrams/full-erd.md+tables/entity-reference.md。issues/README.md
将输出到同一目录()。
schema.jsondocs/db/schema.json每张表的章节:1-2句基于证据的描述、表格,然后是索引:和外键:(包含配置)。按ORM模块/文件夹→名称前缀→外键聚类划分领域,设置“遗留/其他”兜底分类。遵循中的格式。
列 | 类型 | 可空性 | 默认值 | 描述ON DELETEschema.jsonreferences/csm-contract.mdPhase 4 — Prove parity (the verified half)
阶段4 — 证明一致性(验证环节)
This is not optional and not a vibe. A claimed "looks complete" is worthless. Weak models in particular
will assert parity they did not achieve; do not trust the assertion, run the numbers.
- Count gate (early tripwire). For EVERY object class, count it in the live DB and compare to the count
in your . The count query MUST select the exact same population your extraction and the CSM define — otherwise a correct doc fails the gate and you will "fix" it by hallucinating. Two rules that bite on every real database: indexes exclude PK/unique-constraint-backing ones, and routines/objects exclude extension-owned ones (
schema.json). Use the population-matched count queries inpg_depend.deptype='e'("Count-gate queries") — NOT a naivereferences/introspection-postgres.md, and never a lossy view (e.g.count(*)is polluted with NOT NULL rows;information_schema.check_constraintsmay bereltuples). Print a-1table. A mismatch means investigate — it may be a real omission, or your count query selecting the wrong population. Counts matching is necessary, not sufficient (equal counts hide swapped types / wrongclass | live | documented | match?).ON DELETE - Identity-diff (the actual proof). Re-introspect fresh and diff identities and attributes, not just counts, over every class: tables, columns (name/type/nullable/default), PKs, FKs (+on_delete), uniques, checks, indexes (+partial/expression), enums (+values), views, triggers, routines, sequences.
- For every difference: fix the docs, or justify it (e.g. "live-only object listed under Drift").
- Repeat until the count table matches AND the identity-diff is empty or fully justified.
- Write a Parity Report (in or
README.md): the per-class count table + an explicit "0 undocumented, 0 invented". Only write "verified" when the identity-diff (step 2) is empty — not on a count match alone. With no live DB, run the diff against the consensus CSM and label every output file "consensus parity (UNVERIFIED against live DB)".issues/
这一步是必须的,不能凭感觉判断。声称“看起来完整”毫无价值。尤其是弱模型会断言并未达到的一致性;不要相信这种断言,要通过实际验证来确认。
- 统计校验(早期预警):对每个对象类别,统计实时数据库中的数量并与中的数量对比。统计查询必须选择与提取过程和CSM定义完全一致的对象集合——否则正确的文档也会在校验中失败,你会通过幻觉来“修复”它。在实际数据库中经常遇到的两个规则:索引排除主键/唯一约束背后的索引,例程/对象排除扩展所属的对象(
schema.json)。使用pg_depend.deptype='e'中的匹配对象集合的统计查询(“统计校验查询”)——不要使用简单的references/introspection-postgres.md,也不要使用有损耗的视图(如count(*)会包含NOT NULL行;information_schema.check_constraints可能为reltuples)。打印-1表格。不匹配意味着需要调查——可能是真实的遗漏,也可能是统计查询选择了错误的对象集合。数量匹配是必要条件,但不是充分条件(数量相等可能隐藏类型错误/类别 | 实时数量 | 已记录数量 | 是否匹配?配置错误)。ON DELETE - 身份差异对比(实际证明):重新进行实时内省,对每个类别对比身份和属性,而不仅仅是数量:表、列(名称/类型/可空性/默认值)、主键、外键(+配置)、唯一约束、检查约束、索引(+部分索引/表达式索引)、枚举(+枚举值)、视图、触发器、例程、序列。
on_delete - 对于每个差异:修复文档,或说明原因(如“仅存在于实时数据库的对象已标记为漂移”)。
- 重复上述步骤,直到统计表格完全匹配且身份差异对比为空或所有差异都已说明。
- 编写一致性报告(放在或
README.md目录中):包含按类别统计的表格 + 明确的“0个未记录对象,0个虚构对象”声明。只有当身份差异对比(步骤2)为空时,才能标记为“已验证”——不能仅依赖数量匹配。如果没有实时数据库,将文档与共识CSM进行差异对比,并在所有输出文件中标记“共识一致性(未与实时数据库验证)”。issues/
Phase 5 — Adversarial review (≥3 independent, never one)
阶段5 — 对抗式评审(≥3个独立评审,绝不单一评审)
Because the agent doing the judging is itself a frontier model with the same blind spots as the agent that
wrote the docs, a single review rubber-stamps. Convene ≥3 context-walled adversaries, each in a distinct
session with a must-find-fault mandate and a different lens:
- omission hunter — sample live tables: is each present with every column? Are legacy tables, every enum/CHECK, every index and FK documented?
- hallucination hunter — does every documented object/type/default//description trace to a real source? Flag anything invented.
ON DELETE - correctness hunter — do types, nullability, and FK cardinality match the live DB exactly?
Their union feeds another generation pass. Wherever judgment is needed, it is a panel decision.
因为进行判断的Agent本身也是前沿模型,与编写文档的Agent存在相同的盲点,单一评审只会走过场。召集**≥3个独立的“对抗者”**,每个评审在独立会话中进行,必须以找错为目标,且采用不同的视角:
- 遗漏检查者 — 抽样实时表:每个表是否都已记录且包含所有列?遗留表、每个枚举/检查约束、每个索引和外键是否都已记录?
- 幻觉检查者 — 每个已记录的对象/类型/默认值/配置/描述是否都能追溯到真实来源?标记任何虚构内容。
ON DELETE - 正确性检查者 — 类型、可空性、外键基数是否与实时数据库完全匹配?
他们的反馈将用于新一轮的文档生成。任何需要判断的内容都需经过评审小组的决策。
Degradation ladder (announce your tier)
降级阶梯(告知当前层级)
| Tier | Have | Confidence |
|---|---|---|
| T1 | live DB + parallel subagents + adversaries | verified, provable |
| T2 | live DB, single agent | verified, sequential |
| T3 | no live DB, subagents | consensus, unverified |
| T4 | no live DB, single agent | consensus, unverified |
| T5 | one static surface only | low — prominent "UNVERIFIED — no live DB" banner |
Subagents, MCP, and docker are optimizations, never requirements — the same phases run inline without them.
Never fabricate data you could not read: missing is flagged, not guessed.
| 层级 | 具备条件 | 置信度 |
|---|---|---|
| T1 | 实时数据库 + 并行子Agent + 对抗式评审 | 已验证,可证明 |
| T2 | 实时数据库,单一Agent | 已验证,串行处理 |
| T3 | 无实时数据库,子Agent | 共识结果,未验证 |
| T4 | 无实时数据库,单一Agent | 共识结果,未验证 |
| T5 | 仅单一静态资源 | 低置信度 — 显著标记“未验证 — 无实时数据库” |
子Agent、MCP和docker是优化手段,而非必需条件——即使没有这些,也可以按相同阶段串行执行。绝不要编造无法读取的数据:缺失内容要标记出来,不要猜测。
References
参考资料
- — the
references/csm-contract.mdshape (the verifiable output contract).schema.json - — exact catalog queries per engine.
references/introspection-postgres.md - — the human doc shape to reproduce.
references/output-template.md - — enums (native/CHECK/app), JSON columns, polymorphic relations, soft-deletes, composite keys, partial/expression indexes, views, multi-schema, citext/collation, legacy tables.
references/hard-cases.md
- —
references/csm-contract.md的格式(可验证的输出契约)。schema.json - — 各数据库引擎对应的系统目录查询语句。
references/introspection-postgres.md - — 需遵循的人类可读文档格式。
references/output-template.md - — 枚举(原生/检查约束/应用层)、JSON列、多态关联、软删除、复合键、部分/表达式索引、视图、多架构、citext/排序规则、遗留表。
references/hard-cases.md