自动迁移规划
自动迁移规划
自动迁移的便捷特性之一是开发者无需编写用于创建或修改数据库模式的 SQL 语句。为了实现类似优势,我们现在将在项目中添加一个脚本,该脚本会根据模式变更自动为我们规划迁移文件。
为此,Ent 使用了 Atlas——一个由 Ent 原班团队开发的开源数据库模式管理工具。
如果您一直遵循我们的示例仓库,此前我们使用的是 SQLite 数据库。为了演示更接近真实的使用场景,我们现在将切换至 MySQL。具体变更请参见 PR #3。
使用 Atlas CLI 规划迁移
本节将演示如何使用 Atlas CLI 自动规划数据库模式迁移。过去用户需要创建自定义 Go 程序来实现此功能(如此文档所述)。而在最新版本的 Atlas 中,这已不再是必要条件:Atlas 可以直接从 Ent 模式加载目标数据库模式。
To install the latest release of Atlas, simply run one of the following commands in your terminal, or check out the Atlas website:
- macOS + Linux
- Homebrew
- Docker
- Windows
curl -sSf https://atlasgo.sh | sh
brew install ariga/tap/atlas
docker pull arigaio/atlas
docker run --rm arigaio/atlas --help
If the container needs access to the host network or a local directory, use the --net=host flag and mount the desired
directory:
docker run --rm --net=host \
-v $(pwd)/migrations:/migrations \
arigaio/atlas migrate apply
--url "mysql://root:pass@:3306/test"
Download the latest release and move the atlas binary to a file location on your system PATH.
随后运行以下命令,为您的 Ent 模式自动生成迁移文件:
- MySQL
- MariaDB
- PostgreSQL
- SQLite
atlas migrate diff migration_name \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "docker://mysql/8/ent"
atlas migrate diff migration_name \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "docker://mariadb/latest/test"
atlas migrate diff migration_name \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/test?search_path=public"
atlas migrate diff migration_name \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "sqlite://file?mode=memory&_fk=1"
Atlas 通过将迁移目录中的 SQL 文件执行到提供的开发数据库中来加载当前状态。随后它会将此状态与由 ent/schema 包定义的目标状态进行对比,并编写出从当前状态转换到目标状态的迁移计划。
接下来,让我们了解如何升级现有的生产数据库以使用版本化迁移进行管理。