Skip to content

ONE-346: nav 迁移账本化 — 迁移列表 + 账本 runner + 收敛 schema 定义 - #6

Merged
mapxn merged 2 commits into
mainfrom
agent/daniel/0a97164a0d41
Oct 25, 2026
Merged

mapxn merged 2 commits into
mainfrom
agent/daniel/0a97164a0d41

Conversation

@mapxn

@mapxn mapxn commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes ONE-346(子单 ONE-357)

把 nav 的裸建表式 schema 初始化改成 shortlink 的账本式:版本化迁移列表 + 账本表 _nav_schema_migrations。

改了什么

  • worker/src/lib/migrations.ts(新增,schema 唯一可信源)
    • migrationsTable(prefix):账本表名唯一生成处,公式 _ + 前缀核 + _schema_migrations,前缀核 = 生效前缀去掉尾部下划线、大小写原值保留(nav_→_nav_schema_migrations、app_→_app_schema_migrations、abc123→_abc123_schema_migrations、""→_schema_migrations)。
    • createMigrationsTableSql(prefix):name TEXT PRIMARY KEY, applied_at INTEGER NOT NULL DEFAULT (unixepoch())。
    • getMigrations(prefix):迁移列表,schema_v1 = 原 schema.sql 的全部表/索引 DDL + setup_completed='0' 种子(种子留在迁移内,不另设后置步骤)。
  • worker/src/lib/migrations-runner.ts(新增)
    • runMigrations(env):getTablePrefix 三态解析 → 防静默切换冲突探测 → 建账本表 → 读已应用集合 → 按序执行未记录项、成功后立即记账 → 首错即停、失败项不落账、后续不执行;返回 { prefix, migrations: [{ name, status, error? }] };前缀冲突抛 TablePrefixConflictError。
    • 冲突探测两路:nav 业务表族(*_passkey_credentials + *_search_engines + *_login_attempts 三者同前缀才判定,避免共享 D1 他项目表误判)+ 账本表 _<前缀>_schema_migrations 形态扫描。非空前缀下只用业务表族判定(账本名无法归属项目,共享库里 _sl_schema_migrations 之类不该拦 nav 首装);空前缀下账本扫描参与判定(更保守)。
    • 迁移 SQL 用 D1 原生 exec() 执行,注释剥离 + 单行化沿用 shortlink 做法(exec() 只处理多行串首行)。
    • applyMigrationList(db, prefix, migrations) 独立可测(失败注入用)。
  • 接入
    • worker/src/routes/auth.ts:POST /api/auth/setup 改走 applyMigrations(),响应在 { success, user, tablePrefix } 形状上追加 migrations: [{name,status}](applied/skipped);TablePrefixConflictError → 409 { error: "table prefix conflict", detail }。
    • worker/src/lib/migrate.ts:ensureSchema() 保留 per-isolate schemaReady 快路径,内部改走 runner;读路径首次建表行为不变。
  • 收敛第二份 schema 定义:删除 worker/src/db/schema.sql、worker/scripts/gen-schema.mjs、生成的 worker/src/db/schema.generated.ts、worker/package.json 的 codegen 步骤(dev/build/typecheck/test/deploy 均去掉 codegen),以及只服务建表的 splitStatements/runScript;同步 .gitignore、biome.json、.github/workflows/deploy.yml 注释。
  • 文档:README.md 新增「数据库迁移账本」小节(表名公式、schema_v1 塌缩说明、runner 语义、今后著述规则);docs/api-contract.md 补 setup 响应的 migrations/409 说明。

不新增依赖、不新增 PRAGMA 探测式升级代码、不动 TABLE_PREFIX 三态语义、不动对外 API 契约与鉴权逻辑。

测试

  • 新增 worker/test/migrations-ledger.test.ts:migrationsTable() 三态 + 大小写原值保留;空库首跑 applied 且账本恰含 schema_v1;第二跑全 skipped 且 sqlite_master(表 + 索引)与账本行完全不变;前缀冲突(nav_→无前缀、nav_→app_、无前缀→nav_)均抛错且不建第二套;共享库他项目表/账本(eNotify_*、SL_*、ZETA_*、_sl_schema_migrations)不误判;失败注入时失败项不落账、后续不执行、重跑重试该项。
  • 存量测试全部保留更新(import 改到 runner、返回形状随笔本契约更新),auth.test.ts 增 setup 响应账本字段与 409 冲突用例。

本地结果:

pnpm --filter worker test   # 5 files, 38 tests passed(改造前基线 27 tests)
pnpm typecheck              # web + worker 均通过
pnpm lint                   # exit 0(仅 web 既有 warnings)
pnpm format:check           # clean

合并关口(用户执行,团队不碰线上 D1)

重初始化时只删本项目表(生效前缀 nav_):

nav_users、nav_passkey_credentials、nav_sessions、nav_login_attempts、nav_challenges、nav_categories、nav_links、nav_search_engines、nav_settings、_nav_schema_migrations

顺序:删表 → 调 POST /api/auth/setup → 核对 _nav_schema_migrations 恰含 schema_v1 → 重建唯一所有者。不整库删除、不动 eNotify_* / SL_* / ZETA_* / post_*。

评审返工(ONE-363 打回,提交 4709dc2)

  • 🔴 Blocking 修复:detectTablePrefixConflict 用前缀核比对(prefixCore(prefix).toLowerCase()),migrations.ts 导出 prefixCore 与账本表名公式共用同一定义。存量 nav_* 库(有业务表、无账本)首跑不再被误判为冲突:正常识别、schema_v1 记账为 applied。
  • 🟡 Should-fix:空前缀分支扫到全局账本的报错文案改为提示配置 nav 自身前缀(e.g. TABLE_PREFIX=nav_),并注明扫到的账本可能属于共享 D1 的其他项目,不再建议 sl_ 之类的他项目前缀。
  • ⚪ Nit:detectLedgerPrefixes 不捕获空前缀账本,按评审结论保持现状(业务表族兜底闭环)。
  • 新增回归单测:初始化 nav_* 后删掉 _nav_schema_migrations 再跑,验证 schema_v1 正常 applied 并记账、不抛 TablePrefixConflictError(未修复时该用例失败,已本地验证)。

本地:pnpm --filter worker test 5 files / 39 tests passed;pnpm typecheck、pnpm lint(exit 0)、pnpm format:check clean。

mapxn added 2 commits October 25, 2026 23:24
Replace nav's bare "CREATE TABLE IF NOT EXISTS" schema replay with the
shortlink-style ledger: a versioned migration list plus a
`_<prefix>_schema_migrations` ledger table recording what has run.

- lib/migrations.ts: single source of truth for the schema. migrationsTable()
  is the only place the ledger name is derived (`_` + prefix core without its
  trailing underscore + `_schema_migrations`), and getMigrations() collapses
  nav v1's schema into one baseline `schema_v1`.
- lib/migrations-runner.ts: runMigrations() resolves the three-state prefix,
  guards against a silent prefix switch (nav business-table family + ledger
  table scan), creates the ledger, skips recorded migrations, records each
  success and stops at the first failure without recording it.
- setup (POST /api/auth/setup) and the read-path guard ensureSchema() share the
  runner; setup now also reports tablePrefix + per-migration applied/skipped and
  maps a prefix conflict to 409.
- Removed the second schema definition: db/schema.sql, scripts/gen-schema.mjs,
  the generated module, the `codegen` steps and the codegen-only SQL helpers.

Refs ONE-346
Review of PR #6 (ONE-363) found the conflict probe comparing a table-derived
prefix core ("nav") with the raw configured prefix ("nav_"), so an existing
nav_* database without the ledger was rejected as a prefix conflict on the
first run (500 on read paths, 409 on setup).

- lib/migrations.ts: export prefixCore() — the ledger name and the conflict
  probe now share one definition of "prefix without its trailing underscore".
- lib/migrations-runner.ts: compare detected cores against
  prefixCore(prefix), so a pre-ledger nav_* schema is adopted and recorded as
  schema_v1 instead of being refused.
- lib/migrations-runner.ts: the no-prefix/ledger-present hint now points at
  nav's own prefix (TABLE_PREFIX=nav_) instead of suggesting whichever ledger
  happened to be scanned first (could be another project's SL_/ZETA_ in the
  shared D1).
- test: regression case — drop the ledger from an initialised nav_* database
  and re-run; schema_v1 is applied and recorded, no TablePrefixConflictError.

Refs ONE-346
@mapxn
mapxn merged commit 1181b4f into main Oct 25, 2026
1 check passed
@mapxn
mapxn deleted the agent/daniel/0a97164a0d41 branch October 25, 2026 23:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant