go 版本的Flyway sql版本管理

7 篇文章 0 订阅

按照惯例 首先是传送门 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,
		}
	}

 

参数说明:

编号名字类型说明备注
1Hoststring数据库ip 
2Portstring数据库端口号 
3Userstring数据库登陆用户名 
4Passwordstring数据库密码 
5DbNamestring数据库名 
6SearchPathstringPostgrepSQL schemaPostgrepSQL可以换成mysql, 但是需要修改源码
7Tablestringsql 保存的数据库表名 
8Pathstringsql 保存地址 

我自己的项目的结构是如下:

调用手动执行

配置好之后需要手动指定,调用

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值