feat(database): 添加数据库初始化和配置管理功能

- 实现了数据库连接初始化,支持 MySQL 和 SQLite 两种类型
- 添加了 GORM 配置构建,包含事务控制和命名策略设置
- 集成了查询日志功能,可配置是否开启 GORM 日志
- 创建了数据库配置管理模块,使用 Viper 进行配置读取
- 添加了配置文件自动生成和默认值设置功能
- 实现了配置变更监听和热更新机制
- 定义了基础配置结构体,包含服务器、数据库和 JWT 配置
main v1.0.1022
maguodong 2026-03-28 13:57:31 +08:00
parent ed7d18a72a
commit 3209cfe830
3 changed files with 22 additions and 7 deletions

View File

@ -60,6 +60,7 @@ func SetDefault() {
viper.Set("SERVER.mode", "release") viper.Set("SERVER.mode", "release")
viper.Set("DATABASE.type", "sqlite") viper.Set("DATABASE.type", "sqlite")
viper.Set("DATABASE.dns", gfile.Join(gfile.Pwd(), "db", "database.db")) viper.Set("DATABASE.dns", gfile.Join(gfile.Pwd(), "db", "database.db"))
viper.Set("DATABASE.debug", true)
viper.Set("JWT.secret", "SET-YOUR-SECRET") viper.Set("JWT.secret", "SET-YOUR-SECRET")
viper.Set("JWT.expire", 86400) viper.Set("JWT.expire", 86400)
} }

View File

@ -17,6 +17,7 @@ type ServerConfig struct {
type DataBaseConfig struct { type DataBaseConfig struct {
Dns string `mapstructure:"dns"` Dns string `mapstructure:"dns"`
Type string `mapstructure:"type"` Type string `mapstructure:"type"`
Debug bool `mapstructure:"debug"` // 是否开启 GORM 查询日志
} }
// JwtConfig JWT配置 // JwtConfig JWT配置

View File

@ -11,6 +11,7 @@ import (
"github.com/gogf/gf/v2/os/gfile" "github.com/gogf/gf/v2/os/gfile"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema" "gorm.io/gorm/schema"
) )
@ -24,24 +25,36 @@ var (
func init() { func init() {
if g.IsEmpty(dns) { if g.IsEmpty(dns) {
log.Error("gormDns未配置", "请检查配置文件") log.Error("gormDns 未配置", "请检查配置文件")
return return
} }
switch config.GetConfigValue("database.type", "sqlite").String() { switch config.GetConfigValue("database.type", "sqlite").String() {
case "mysql": case "mysql":
log.Info("使用mysql数据库") log.Info("使用 mysql 数据库")
mysqlInit() mysqlInit()
case "sqlite": case "sqlite":
log.Info("使用sqlite数据库") log.Info("使用 sqlite 数据库")
sqliteInit() sqliteInit()
} }
Db, err = gorm.Open(Type, &gorm.Config{
// 构建 GORM 配置
gormConfig := &gorm.Config{
SkipDefaultTransaction: true, SkipDefaultTransaction: true,
// 命名策略:保持与模型一致,避免字段/表名转换问题 // 命名策略:保持与模型一致,避免字段/表名转换问题
NamingStrategy: schema.NamingStrategy{ NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 表名禁用复数形式(例如 User 对应 user 表,而非 users SingularTable: true, // 表名禁用复数形式(例如 User 对应 user 表,而非 users
}, },
}) }
// 根据配置决定是否开启 GORM 查询日志
if config.GetConfigValue("database.debug", false).Bool() {
log.Info("已开启 GORM 查询日志")
gormConfig.Logger = logger.Default.LogMode(logger.Info)
} else {
gormConfig.Logger = logger.Default.LogMode(logger.Silent)
}
Db, err = gorm.Open(Type, gormConfig)
if err != nil { if err != nil {
log.Error("数据库连接失败: ", err) log.Error("数据库连接失败: ", err)
return return