按照惯例 首先是传送门 poem/goway
- 修改记录:2019-01-14 23:15:10 加上事物管理 当sql文件中sql执行失败之后, 增加记录, 并且会回滚执行, 并且系统会停止启动;
- 修改记录:2019-01-24 15:20:24 修改排序 执行的顺序和需要的顺序执行不匹配
下载
使用go命令, 下载 go 库
go get github.com/poemp/goway
配置
需要重写我的默认的方法, 当前方法是基本的数据库配置和 sql 存放的地方
inter.DefaultTableDataSource = func() inter.WayConfigure {
return inter.WayConfigure{
Host: host,
Port: port,
User: user,
Password: password,
DbName: dbName,
SearchPath: searchPath,
Table: table,
Path: path,
}
}
参数说明:
编号 | 名字 | 类型 | 说明 | 备注 |
---|---|---|---|---|
1 | Host | string | 数据库ip | |
2 | Port | string | 数据库端口号 | |
3 | User | string | 数据库登陆用户名 | |
4 | Password | string | 数据库密码 | |
5 | DbName | string | 数据库名 | |
6 | SearchPath | string | PostgrepSQL schema | PostgrepSQL可以换成mysql, 但是需要修改源码 |
7 | Table | string | sql 保存的数据库表名 | |
8 | Path | string | sql 保存地址 |
我自己的项目的结构是如下:
调用手动执行
配置好之后需要手动指定,调用
way.Flyway{}.Execu()
支持其他数据库
如果需要支持其他数据, 需要修改源码
go/src/github.com/poemp/goway/internal/db/db_config.go
修改的源码是
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/lunny/log"
"github.com/poemp/goway/inter"
)
// 获取数据库连接
func GetWayBD() *gorm.DB {
defer func() {
if e := recover(); e != nil {
fmt.Println(fmt.Sprintf("recover from a fatal error : %v", e))
}
}()
c := inter.DefaultTableDataSource()
source := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=%s password=%s",
c.Host, c.Port, c.User, c.DbName, "disable", c.Password)
log.Info("way datasource :" + source)
// 支持其他的数据库, 需要修改这儿, 并且需要在代码中添加 其他数据库的驱动
// 就像我使用的 post 数据库 是需要在import中加入:
// _ "github.com/jinzhu/gorm/dialects/postgres"
db, err := gorm.Open("postgres", source)
db.SingularTable(true)
db.LogMode(true)
if err != nil {
panic(err)
}
return db
}
最后的代码
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/poemp/goway/inter"
"github.com/poemp/goway/way"
)
const (
host = "127.0.0.1"
port = "5432"
user = "postgres"
password = "123456"
dbName = "vs_tmp"
searchPath = "public"
table = "schema_history"
path = "sql"
)
func init() {
inter.DefaultTableDataSource = func() inter.WayConfigure {
return inter.WayConfigure{
Host: host,
Port: port,
User: user,
Password: password,
DbName: dbName,
SearchPath: searchPath,
Table: table,
Path: path,
}
}
way.Flyway{}.Execu()
MigrateDB()
}
启动会自动去执行, 并且执行sql, 并且会生成数据库库表
记住 , 需要的命名规则和Java的Flyway 配置一样, V0.1__initdb.sql