Files
jx-callback/globals/gormdb/gormdb.go
2018-09-06 22:29:08 +08:00

49 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gormdb
import (
"fmt"
"git.rosy.net.cn/jx-callback/business/model"
"github.com/astaxie/beego"
"github.com/jinzhu/gorm"
)
var (
dbStr string
singletonDB *gorm.DB
)
func Init() {
dbStr = beego.AppConfig.String("dbConnectStr")
AutoMigrate()
}
// todo gorm要求用单一的db如果每次重新调用Open会导致too many connection错误
func GetDB() *gorm.DB {
if singletonDB == nil {
db, err := gorm.Open("mysql", dbStr)
if err == nil {
singletonDB = db
return db
}
panic(fmt.Sprintf("AutoMigrate failed with error:%v", err))
}
return singletonDB
}
func AutoMigrate() {
db := GetDB()
db.SingularTable(true)
// db.DropTableIfExists(&model.Place{})
// db.DropTableIfExists(&model.Store{}, &model.StoreSub{}, &model.StoreMap{})
// db.DropTableIfExists(&model.SkuVendorCategory{}, &model.StoreSkuCategoryMap{}, &model.SkuName{}, &model.Sku{}, &model.SkuNamePlaceBind{}, &model.StoreSkuBind{}, &model.SkuCategory{})
db.AutoMigrate(&model.Place{})
db.AutoMigrate(&model.Store{}, &model.StoreSub{}, &model.StoreMap{})
db.AutoMigrate(&model.SkuVendorCategory{}, &model.StoreSkuCategoryMap{}, &model.SkuName{}, &model.Sku{}, &model.SkuNamePlaceBind{}, &model.StoreSkuBind{})
db.Set("gorm:table_options", "CHARSET=utf8mb4").AutoMigrate(&model.SkuCategory{})
db.AutoMigrate(&model.WeiXins{}, &model.JxBackendUser{})
// db.AutoMigrate(&model.DurableTask{}, &model.DurableTaskItem{})
}