feat:date migrate

This commit is contained in:
zhangwenjian
2020-09-12 01:27:39 +08:00
parent b8f8bfd400
commit d4b87c78a7
4 changed files with 41 additions and 9 deletions
+6 -5
View File
@@ -2,6 +2,7 @@ package models
import (
"fmt"
"gorm.io/gorm"
"io/ioutil"
"log"
"strings"
@@ -9,17 +10,17 @@ import (
"go-admin/common/global"
)
func InitDb() (err error) {
func InitDb(db *gorm.DB) (err error) {
filePath := "config/db.sql"
err = ExecSql(filePath)
err = ExecSql(db,filePath)
if global.Driver == "postgres" {
filePath = "config/pg.sql"
err = ExecSql(filePath)
err = ExecSql(db,filePath)
}
return err
}
func ExecSql(filePath string) error {
func ExecSql(db *gorm.DB,filePath string) error {
sql, err := Ioutil(filePath)
if err != nil {
fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
@@ -33,7 +34,7 @@ func ExecSql(filePath string) error {
}
sql := strings.Replace(sqlList[i]+";", "\n", "", 0)
sql = strings.TrimSpace(sql)
if err = global.Eloquent.Exec(sql).Error; err != nil {
if err = db.Exec(sql).Error; err != nil {
log.Printf("error sql: %s", sql)
if !strings.Contains(err.Error(), "Query was empty") {
return err
@@ -18,7 +18,7 @@ func init() {
}
func _1599190683659Tables(db *gorm.DB, version string) error {
err := db.Migrator().AutoMigrate(
err := db.Debug().Migrator().AutoMigrate(
new(models.CasbinRule),
new(models.SysDept),
new(models.SysConfig),
@@ -0,0 +1,31 @@
package version
import (
"go-admin/app/admin/models"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
"gorm.io/gorm"
"path/filepath"
"runtime"
)
func init() {
_, fileName, _, _ := runtime.Caller(0)
fileName = filepath.Base(fileName)
fileName = fileName[:len(fileName)-3]
migration.Migrate.SetVersion(fileName, _1599190683670Test)
}
func _1599190683670Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
if err := models.InitDb(tx); err != nil {
}
return tx.Create(&common.Migration{
Version: version,
}).Error
})
}
@@ -13,10 +13,10 @@ func init() {
_, fileName, _, _ := runtime.Caller(0)
fileName = filepath.Base(fileName)
fileName = fileName[:len(fileName)-3]
migration.Migrate.SetVersion(fileName, _1599190683660Test)
migration.Migrate.SetVersion(fileName, _1599190683680Test)
}
func _1599190683660Test(db *gorm.DB, version string) error {
func _1599190683680Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
var err error
@@ -48,7 +48,7 @@ func _1599190683660Test(db *gorm.DB, version string) error {
{MenuId: 521, MenuName: "", Title: "删除内容管理", Icon: "bug", Path: "/api/v1/syscontent/:id", Paths: "/0/63/516/521", MenuType: "A", Action: "DELETE", Permission: "", ParentId: 516, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "1", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
}
err = db.Create(list).Error
err = tx.Create(list).Error
if err != nil {
return err
}