Goose 是一个用于管理数据库迁移的工具,类似于 Flyway 和 Liquibase。它可以方便地管理数据库模式的版本,并应用相应的 SQL 脚本。你提到在 db/migrations/ 目录下有多个 SQL 文件,这些文件通常是用来管理数据库迁移的。
使用 Goose 进行数据库迁移
以下是如何使用 Goose 进行数据库迁移的步骤:
- 安装 Goose
首先,你需要安装 Goose。你可以使用 go install 命令安装 Goose:
go install /pressly/goose/v3/cmd/goose@latest
确保 GOPATH/bin 在你的 PATH 中,以便可以直接运行 goose 命令。
- 配置数据库连接
你需要一个配置文件或环境变量来设置数据库连接信息。例如,使用一个 .env 文件来存储数据库连接信息:
DB_DRIVER=postgres
DB_STRING="user=beaconchain password=root dbname=beaconchain sslmode=disable"
- 创建迁移脚本
迁移脚本通常存放在 db/migrations/ 目录中。迁移文件的命名格式通常是 timestamp_description.sql 或 timestamp_description.go,例如:
db/migrations/
├── 20230521123000_create_users_table.sql
├── 20230521124500_add_email_to_users.sql - 运行数据库迁移
运行迁移命令之前,确保在你的 Docker 容器中包含 Goose 并能访问数据库。例如,可以通过以下命令在 Docker 容器中运行 Goose 迁移:
docker run --rm -v $(pwd)/db/migrations:/migrations -v $(pwd)/.env:/app/.env --network host pressly/goose -dir /migrations postgres "$DB_STRING" up
完整示例
安装 Goose:
go install /pressly/goose/v3/cmd/goose@latest
准备迁移脚本:
db/migrations/20230521123000_create_users_table.sql
编写 .env 文件:
DB_DRIVER=postgres
DB_STRING="user=beaconchain password=root dbname=beaconchain sslmode=disable"
运行迁移:
source .env
goose -dir db/migrations $DB_DRIVER "$DB_STRING" up
通过这些步骤,你可以使用 Goose 管理数据库迁移,确保数据库结构与代码的变化同步。