Cloudreve/models/init.go

62 lines
1.2 KiB
Go
Raw Normal View History

2019-11-06 09:35:31 -05:00
package model
import (
"cloudreve/pkg/conf"
"cloudreve/pkg/util"
2019-11-09 05:06:29 -05:00
"fmt"
2019-11-06 09:35:31 -05:00
"github.com/jinzhu/gorm"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// DB 数据库链接单例
var DB *gorm.DB
// Database 初始化 MySQL 链接
2019-11-07 02:56:05 -05:00
func Init() {
2019-11-13 04:22:45 -05:00
util.Log().Info("初始化数据库连接")
2019-11-09 05:06:29 -05:00
var (
db *gorm.DB
err error
)
if conf.DatabaseConfig.Type == "UNSET" {
//TODO 使用内置SQLite数据库
} else {
db, err = gorm.Open(conf.DatabaseConfig.Type, fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local",
conf.DatabaseConfig.User,
conf.DatabaseConfig.Password,
conf.DatabaseConfig.Host,
conf.DatabaseConfig.Name))
}
// 处理表前缀
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return conf.DatabaseConfig.TablePrefix + defaultTableName
}
// Debug 模式下,输出所有 SQL 日志
if conf.SystemConfig.Debug {
db.LogMode(true)
}
2019-11-08 05:29:12 -05:00
//db.SetLogger(util.Log())
2019-11-06 09:35:31 -05:00
if err != nil {
util.Log().Panic("连接数据库不成功", err)
}
2019-11-09 05:06:29 -05:00
2019-11-06 09:35:31 -05:00
//设置连接池
//空闲
db.DB().SetMaxIdleConns(50)
//打开
db.DB().SetMaxOpenConns(100)
//超时
db.DB().SetConnMaxLifetime(time.Second * 30)
DB = db
2019-11-09 05:06:29 -05:00
//执行迁移
2019-11-06 09:35:31 -05:00
migration()
}