You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.1 KiB

package initialize
import (
"log"
"os"
"pure/global"
"pure/model"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"go.uber.org/zap"
)
//@function: Gorm
//@description: 初始化数据库并产生数据库全局变量
//@return: *gorm.DB
func GormV1() *gorm.DB {
switch global.MG_CONFIG.System.DbType {
case "mysql":
return GormMysqlV1()
default:
return GormMysqlV1()
}
}
// MysqlTables
//@function: MysqlTables
//@description: 注册数据库表专用
//@param: db *gorm.DB
func MysqlTablesV1(db *gorm.DB) {
err := db.AutoMigrate(
model.Firmware{},
model.Terminal{},
model.User{},
//model.SysDictionary{},
//model.SysDictionaryDetail{},
//model.ExaFileUploadAndDownload{},
//model.ExaFile{},
//model.ExaFileChunk{},
//model.ExaCustomer{},
//model.ExaSimpleUploader{},
// Code generated by pure Begin; DO NOT EDIT.
// Code generated by pure End; DO NOT EDIT.
)
if err != nil {
global.MG_LOG.Error("register table failed", zap.Any("err", err))
os.Exit(0)
}
global.MG_LOG.Info("register table success")
}
// @function: GormMysql
// @description: 初始化Mysql数据库
// @return: *gorm.DB
func GormMysqlV1() *gorm.DB {
m := global.MG_CONFIG.Mysql
if m.Dbname == "" {
return nil
}
dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
mysqlDB, err := gorm.Open("mysql", dsn)
if err != nil {
mysqlDB.Close()
panic(err.Error())
}
mysqlDB.LogMode(m.LogMode)
if err != nil {
log.Panicln("connected to mysqlDB failed", err)
} else {
err = mysqlDB.DB().Ping() // Send a ping to make sure the database connection is alive.
if err != nil {
panic(err.Error())
}
}
//自动迁移表,生成的表名自动变成复数
// mysqlDB.AutoMigrate(&User{}) //
mysqlDB.DB().SetConnMaxLifetime(time.Minute * 5) //最多空闲5分钟
mysqlDB.DB().SetMaxIdleConns(m.MaxIdleConns) //数据库的空闲连接
mysqlDB.DB().SetMaxOpenConns(m.MaxOpenConns) //最大打开连接,即向Mysql服务端发出的所有连接的最大数目
return mysqlDB
}