golang数据库迁移工具插件sql-migrate支持嵌入式迁移文件的使用
Golang数据库迁移工具插件sql-migrate支持嵌入式迁移文件的使用
sql-migrate是一个基于gorp和goose的Go语言SQL模式迁移工具,它支持将迁移文件嵌入到应用程序中。
嵌入式迁移文件的使用方法
使用embed包嵌入迁移文件
- 首先在项目中创建迁移文件,例如在
migrations/
目录下创建SQL文件 - 使用Go 1.16+的embed功能嵌入这些文件:
import "embed"
//go:embed migrations/*
var dbMigrations embed.FS
- 创建迁移源:
migrations := migrate.EmbedFileSystemMigrationSource{
FileSystem: dbMigrations,
Root: "migrations",
}
完整示例
package main
import (
"database/sql"
"embed"
"fmt"
"log"
"github.com/rubenv/sql-migrate"
_ "github.com/mattn/go-sqlite3"
)
//go:embed migrations/*.sql
var migrationFS embed.FS
func main() {
// 打开数据库连接
db, err := sql.Open("sqlite3", "test.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// 设置迁移源
migrations := &migrate.EmbedFileSystemMigrationSource{
FileSystem: migrationFS,
Root: "migrations",
}
// 执行迁移
n, err := migrate.Exec(db, "sqlite3", migrations, migrate.Up)
if err != nil {
log.Fatal(err)
}
fmt.Printf("成功应用了%d个迁移!\n", n)
}
迁移文件示例
在migrations/
目录下创建SQL文件,例如1_initial.sql
:
-- +migrate Up
-- SQL in section 'Up' is executed when this migration is applied
CREATE TABLE people (id int);
-- +migrate Down
-- SQL section 'Down' is executed when this migration is rolled back
DROP TABLE people;
其他嵌入式方法
使用实现http.FileSystem的库
migrationSource := &migrate.HttpFileSystemMigrationSource{
FileSystem: httpFS, // 任何实现http.FileSystem的库
}
内存中的迁移
migrations := &migrate.MemoryMigrationSource{
Migrations: []*migrate.Migration{
&migrate.Migration{
Id: "123",
Up: []string{"CREATE TABLE people (id int)"},
Down: []string{"DROP TABLE people"},
},
},
}
特点
- 支持SQLite、PostgreSQL、MySQL、MSSQL和Oracle数据库
- 可以嵌入迁移到应用程序中
- 迁移使用SQL定义,灵活性高
- 原子性迁移
- 支持向上/向下迁移以允许回滚
- 支持一个项目中多种数据库类型
注意事项
- 迁移文件按文件名排序执行,建议使用递增版本号或时间戳作为文件名前缀
- 默认每个迁移在事务中运行以保证原子性
- 对于不能在事务中执行的SQL命令,可以使用
notransaction
选项
通过以上方法,你可以轻松地将数据库迁移文件嵌入到Go应用程序中,实现自包含的部署。
更多关于golang数据库迁移工具插件sql-migrate支持嵌入式迁移文件的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复