From 3209cfe83029781d2ddc6d4193d0b78a6f64a5af Mon Sep 17 00:00:00 2001 From: maguodong Date: Sat, 28 Mar 2026 13:57:31 +0800 Subject: [PATCH] =?UTF-8?q?feat(database):=20=E6=B7=BB=E5=8A=A0=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E5=88=9D=E5=A7=8B=E5=8C=96=E5=92=8C=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E7=AE=A1=E7=90=86=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现了数据库连接初始化,支持 MySQL 和 SQLite 两种类型 - 添加了 GORM 配置构建,包含事务控制和命名策略设置 - 集成了查询日志功能,可配置是否开启 GORM 日志 - 创建了数据库配置管理模块,使用 Viper 进行配置读取 - 添加了配置文件自动生成和默认值设置功能 - 实现了配置变更监听和热更新机制 - 定义了基础配置结构体,包含服务器、数据库和 JWT 配置 --- config/fun.go | 1 + config/structs.go | 5 +++-- database/database.go | 23 ++++++++++++++++++----- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/config/fun.go b/config/fun.go index c037e68..fdc8dba 100644 --- a/config/fun.go +++ b/config/fun.go @@ -60,6 +60,7 @@ func SetDefault() { viper.Set("SERVER.mode", "release") viper.Set("DATABASE.type", "sqlite") 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.expire", 86400) } diff --git a/config/structs.go b/config/structs.go index a2906d8..ff1aaad 100644 --- a/config/structs.go +++ b/config/structs.go @@ -15,8 +15,9 @@ type ServerConfig struct { // DataBaseConfig 数据库配置 type DataBaseConfig struct { - Dns string `mapstructure:"dns"` - Type string `mapstructure:"type"` + Dns string `mapstructure:"dns"` + Type string `mapstructure:"type"` + Debug bool `mapstructure:"debug"` // 是否开启 GORM 查询日志 } // JwtConfig JWT配置 diff --git a/database/database.go b/database/database.go index 5ce41e7..3a0e89c 100644 --- a/database/database.go +++ b/database/database.go @@ -11,6 +11,7 @@ import ( "github.com/gogf/gf/v2/os/gfile" "gorm.io/driver/mysql" "gorm.io/gorm" + "gorm.io/gorm/logger" "gorm.io/gorm/schema" ) @@ -24,24 +25,36 @@ var ( func init() { if g.IsEmpty(dns) { - log.Error("gormDns未配置", "请检查配置文件") + log.Error("gormDns 未配置", "请检查配置文件") return } switch config.GetConfigValue("database.type", "sqlite").String() { case "mysql": - log.Info("使用mysql数据库") + log.Info("使用 mysql 数据库") mysqlInit() case "sqlite": - log.Info("使用sqlite数据库") + log.Info("使用 sqlite 数据库") sqliteInit() } - Db, err = gorm.Open(Type, &gorm.Config{ + + // 构建 GORM 配置 + gormConfig := &gorm.Config{ SkipDefaultTransaction: true, // 命名策略:保持与模型一致,避免字段/表名转换问题 NamingStrategy: schema.NamingStrategy{ 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 { log.Error("数据库连接失败: ", err) return