Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

数据库迁移

启用 migrate feature 可使用迁移 API 和 afastorm CLI。迁移文件成对命名:

<version>_<name>.up.sql
<version>_<name>.down.sql

同一迁移目录中的版本必须唯一。请将两个文件纳入版本控制,并在执行前审查 SQL。

创建手写迁移

cargo run --no-default-features --features derive,sqlite,migrate --bin afastorm -- \
  --dir migrations makemigrations add_user_bio

该命令创建空的 up/down SQL 模板,不会读取数据库或模型代码。

根据模型元数据生成迁移

在应用辅助代码中导出当前已注册模型 schema:

orm.write_schema_snapshot("schema.json")?;

再将快照交给 CLI:

cargo run --no-default-features --features derive,sqlite,migrate --bin afastorm -- \
  --dir migrations --schema schema.json makemigrations add_user_bio

生成器将新快照与上次生成的 migrations/schema.json 比较。若没有旧快照,会为新快照中的模型 生成建表 SQL。生成迁移后会更新 migrations/schema.json,请将它与迁移历史一起保存。生成过程 不会执行迁移。

目前支持新增表、添加可空且非唯一列,以及删除部分无其他约束的可空非唯一列。列定义解析能力 有限:SQLite 删除列支持生成的 INTEGER、REAL 和 TEXT;PostgreSQL 删除/类型比较当前识别 INTEGER、BIGINT、REAL、DOUBLE PRECISION、TEXT、BOOLEAN、JSONB。即使是可空列, 其他声明也需要手写并审查迁移。

生成器拒绝删除表、主键或唯一约束变更、添加非空列、SQLite 类型变更及其他含糊或破坏性变更。 PostgreSQL 类型变更还要求约束集合不变且列没有主键或唯一约束。生成语句会显式转换类型,应用 前应检查数据及可能的数据丢失。恢复已删除列的 down migration 无法恢复已删除列值。

执行、查看和回滚

cargo run --no-default-features --features derive,sqlite,migrate --bin afastorm -- \
  --database-url 'sqlite://app.db?mode=rwc' --dir migrations migrate

cargo run --no-default-features --features derive,sqlite,migrate --bin afastorm -- \
  --database-url 'sqlite://app.db?mode=rwc' status

cargo run --no-default-features --features derive,sqlite,migrate --bin afastorm -- \
  --database-url 'sqlite://app.db?mode=rwc' --dir migrations rollback VERSION

数据库命令支持 --database-url URL 或 DATABASE_URL。status 在需要时会创建 _afastorm_migrations 跟踪表。独立 CLI 不会加载应用配置文件,并拒绝 --config。

runner 按文件名/版本顺序执行未运行的迁移,并记录成功版本。SQLite 和 PostgreSQL 的每个迁移 (包括跟踪记录)都在单独事务中执行。回滚会事务性地执行对应 .down.sql 并删除跟踪记录; 缺少 down 文件或 SQL 执行失败都会报告错误。

需要与框架命令集成时可调用公开的 migration API。后端差异见SQLite 类型和 PostgreSQL 类型。