9.7 KiB
步骤 1 · Alembic 迁移地基 / Step 1 · Migration Foundation
可独立执行 / Self-contained. 完整背景见设计文档
llm-integration-design.md§3;跨步骤约定见implementation-plan.md。 前置 / Prerequisite: 无(第一步)/ none. 产出 / Output: 一个可独立合入的 PR;不改任何业务 schema。A mergeable PR with zero business-schema change.
目标 / Goal
引入 Alembic 并安全接管现有生产库,schema 一点不改,所有现有测试保持绿。迁移与应用启动分离:启动只做只读校验 + fail-close,实际迁移由独立、幂等命令 python -m app.migrate 执行。
Introduce Alembic and safely adopt the existing prod DB with zero schema change; all tests stay green. Migration is separated from startup: boot only verifies (read-only) and fails closed; the actual migrating is done by a separate idempotent command python -m app.migrate.
必要背景 / Essential Context(仅凭本文件即可执行 / enough to execute from this file)
- 当前没有 Alembic。 唯一的"迁移"是
app/db.py::_sync_sqlite_image_columns()(启动时缺图片列就ALTER TABLE ADD COLUMN)。 No Alembic today; the only "migration" is the hand-rolled image-column sync inapp/db.py. app/db.py::init_db()在 FastAPI lifespan 启动时被create_app()调用,现在执行Base.metadata.create_all()+_sync_sqlite_image_columns()。本步把它改成只读校验(不再在启动时建表/迁移)。相关符号:Base、engine、SessionLocal、configure_database()。init_db()runs at lifespan startup and currently doescreate_all()+ the image-column sync. This step turns it into a read-only check (no table creation/migration at boot).tests/conftest.py的clientfixture:configure_database(tmp_url)→create_app()(触发init_db)。每个测试用临时 SQLite,互不污染。- models 在
app/models.py:Box/Item/SubItem三张表;每张含image_blob(BLOB) /image_mime_type/image_width/image_height,以及created_at/updated_at。 - DB URL 来自
app/config.py::get_settings().database_url(默认sqlite:///./data/app.db)。 - 生产库是当年
create_all建的、已装上千件数据、没有alembic_version表。
铁律 / The Invariant(不可违背 / non-negotiable)
- 所有数据库最终收敛到同一个
head。All DBs converge to the samehead. - V1 baseline 必须严格等于"今天的真实 schema"(三张表 + 现有图片列 + 索引),不多一列。新东西放后续 revision。 The V1 baseline must equal today's actual schema exactly — nothing more.
- 以下动作由迁移命令执行,不在应用启动时 / done by the migration command, not at boot:
- 老库且与 baseline 一致:
stamp V1(只写版本号,不建表、不碰数据)→upgrade head。 Existing DB matching baseline:stamp V1(no DDL, no data change) →upgrade head. - 老库但与 baseline 不一致:fail-close,不做任何改动。Mismatched existing DB → fail closed.
- 新库:跑
V1(真正建表)→upgrade head。Fresh DB: runV1→upgrade head.
- 老库且与 baseline 一致:
任务 / Tasks
requirements.txt增加alembic(钉一个明确版本 / pin a version)。- 初始化 Alembic 工程:
alembic.ini+migrations/(含env.py、versions/)。 - 配置
migrations/env.py:target_metadata = app.db.Base.metadata(确保导入app.models以注册三张表)。sqlalchemy.url从app.config.get_settings().database_url动态读取,不写死在alembic.ini。- 对 SQLite 设
render_as_batch=True(为未来改列/删列预留 batch 能力)。
- 生成 V1 baseline 迁移=当前 models 的完整建表(
boxes/items/subitems,含图片列与索引)。做法:对空库--autogenerate。 Author V1 by autogenerating against an empty DB. - 验证 baseline:对一份生产库副本跑
alembic check,确认无差异(印证可安全stamp;SQLite 偶有类型亲和/索引命名假差异,人眼复核)。 Verify withalembic checkagainst a copy of the prod DB → expect no diff. - 新增
app/migrate.py,承担两个职责 / two responsibilities:- (A) 迁移命令入口
python -m app.migrate(幂等 / idempotent):编程方式构造 AlembicConfig(script_location→ 打包进镜像的migrations/,sqlalchemy.url= 解析出的 URL),用 SQLAlchemy inspector 分情况:- 空库 / empty →
command.upgrade(cfg, "head") - 老库且与 baseline(V1) 一致 →
command.stamp(cfg, "<V1 rev>")→command.upgrade(cfg, "head") - 老库但与 baseline 不一致 → fail-close:非零退出 + 清晰日志 + 不做任何改动
- 已在
head→ 空操作、退出 0 <V1 rev>指 baseline 这个具体 revision(down_revision=None的那条),不是head。- "与 baseline 一致"的判定对照 baseline(V1) 的预期 schema(不是 head);SQLite 假差异需容忍或允许人工确认覆盖。
- 空库 / empty →
- (B) 启动校验
verify_schema_is_current(url)(只读 / read-only):比较 DB 当前 revision 与head;不一致返回失败/抛错,绝不改动 DB。
- (A) 迁移命令入口
- 改
app/db.py::init_db():改为调verify_schema_is_current(resolved_url)—— 一致才放行;不一致 fail-close(清晰日志,提示先跑python -m app.migrate)。不再在启动时建表/迁移。删除_sync_sqlite_image_columns()。保留configure_database()/ engine 装配。init_db()now only verifies and fails closed on mismatch (pointing the user topython -m app.migrate); remove_sync_sqlite_image_columns(). tests/conftest.py:fixture 改为先跑迁移命令把临时库带到head,再create_app()(这样启动校验通过)。 Fixture runs the migration first, thencreate_app().Dockerfile:加COPY alembic.ini .与COPY migrations ./migrations(否则容器内无迁移脚本)。- CI(可选 / optional):
.github/workflows/test.yml加一步alembic check,防止 model 与迁移漂移。 - Compose
db-migration闸门(可后续 / can be deferred):加一个一次性服务跑python -m app.migrate,web经depends_on: condition: service_completed_successfully等它成功(见设计 §3.5)。 Add a one-shotdb-migrationservice gatingweb(design §3.5); may be deferred.
涉及文件 / Files
requirements.txt、alembic.ini(新)、migrations/**(新)、app/migrate.py(新)、app/db.py、tests/conftest.py、Dockerfile、(可选).github/workflows/test.yml、(可后续)docker-compose.yml。
测试 / Tests
- 现有 ~83 个测试全绿(fixture 先跑迁移、再起 App,启动校验通过)。 All existing ~83 tests pass (fixture migrates first, then starts the app).
- 认领老库(2a):构造"有
boxes数据、无alembic_version"的库(可先用create_all造)→ 跑迁移命令 → 断言数据保留、版本到达head、未重复建表报错。 Adoption (2a): migrate an un-stamped populated DB → data preserved, version athead. - 全新库:空 URL → 跑迁移命令 → 三张表存在、版本到
head。 Fresh DB: empty URL → migrate → tables exist, version athead. - fail-close(启动):DB 未到
head时create_app()/init_db()启动应 fail-close(抛错/拒绝服务)、不改动 DB。 Startup fails closed when the DB is not athead; DB unchanged. - fail-close(2b):构造与 baseline 不一致的老库 → 跑迁移命令 → 断言非零退出、DB 不变。 Migration command fails closed on a 2b mismatch; DB unchanged.
验收 / Acceptance
- 迁移命令:空库建到
head;老库一致则认领并到head;老库不一致则 fail-close 不改动;已在head则幂等空操作。 Migration command: empty→head; matching existing→adopt+head; mismatch→fail closed; already-at-head→no-op. - 启动校验:DB 未到
head时拒绝启动并输出清晰日志;到head才正常起。 Startup refuses to boot (clear log) unless the DB is athead. - 模拟老库认领后数据无损。Adopted existing-like DB keeps data intact.
- 全部测试绿;schema 与本步骤前逐列一致(本步不改业务 schema)。 All tests green; schema identical to before (no business-schema change).
风险与缓解 / Risks & Mitigations
- baseline 与现状有偏差 →
stamp失真。 缓解:alembic check对生产副本校验 + 人眼复核 SQLite 假差异。 Baseline drift →alembic checkagainst a prod copy + manual eyeball. - 2b 一致性比对假阳性 → 合法老库被误 fail-close。 缓解:比对基准用 baseline(V1) 而非 head;容忍已知 SQLite 噪声,或提供"人工确认覆盖"的开关。 2b false positives wrongly fail a legit DB → compare against baseline (not head); tolerate known SQLite noise or offer a manual-confirm override.
- 容器内找不到迁移脚本。 缓解:确认
Dockerfile已COPYalembic.ini与migrations/;script_location用绝对/相对镜像 WORKDIR(/app) 正确解析。 Migrations missing in image → ensure they'reCOPY-ed andscript_locationresolves under/app.
相关约定 / Conventions(详见 implementation-plan.md)
- 不主动 push/commit,除非业主要求。Don't push/commit unless asked.
- 实现与设计若有偏差 → 回写设计文档 §3 与仓库简报
../repository-brief.md§10。