feat(database): 添加数据库初始化和配置管理功能
- 实现了数据库连接初始化,支持 MySQL 和 SQLite 两种类型 - 添加了 GORM 配置构建,包含事务控制和命名策略设置 - 集成了查询日志功能,可配置是否开启 GORM 日志 - 创建了数据库配置管理模块,使用 Viper 进行配置读取 - 添加了配置文件自动生成和默认值设置功能 - 实现了配置变更监听和热更新机制 - 定义了基础配置结构体,包含服务器、数据库和 JWT 配置main v1.0.1022
parent
ed7d18a72a
commit
3209cfe830
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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配置
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in New Issue