go-wxhelper/internal/database/database.go

50 lines
1.1 KiB
Go
Raw Normal View History

2024-01-19 12:06:30 +08:00
package database
import (
"gitee.ltd/lxh/logger"
"gitee.ltd/lxh/logger/log"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"os"
"strconv"
"wechat-robot/config"
)
// Client 客户端
var Client *gorm.DB
// Init
// @description: 初始化数据库连接
func Init() {
var dialector gorm.Dialector
switch config.Conf.Database.Type {
case "mysql":
// MySQL
dialector = mysql.Open(config.Conf.Database.GetMysqlDSN())
case "postgresql":
// PostgreSQL
dialector = postgres.Open(config.Conf.Database.GetPostgreSQLDSN())
default:
log.Panic("未配置数据库或数据库类型不支持")
}
// gorm 配置
gormConfig := gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
}
// 是否开启调试模式
if flag, _ := strconv.ParseBool(os.Getenv("GORM_DEBUG")); flag {
gormConfig.Logger = logger.DefaultGormLogger()
}
// 初始化连接
conn, err := gorm.Open(dialector, &gormConfig)
if err != nil {
log.Panicf("数据库连接初始化失败: %v", err)
} else {
log.Debug("数据库连接初始化成功")
}
Client = conn
}