From 72f26a8777dae93fef93043df2eddf5fd72c7d14 Mon Sep 17 00:00:00 2001 From: Blizzard Date: Fri, 25 Apr 2025 23:58:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=A0=B9=E6=8D=AE=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E7=B1=BB=E5=9E=8B=E5=92=8C=E9=85=8D=E7=BD=AE=E7=94=9F?= =?UTF-8?q?=E6=88=90=20GORM=20=E7=9A=84=E9=85=8D=E7=BD=AE=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- initialize/internal/gorm.go | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 initialize/internal/gorm.go diff --git a/initialize/internal/gorm.go b/initialize/internal/gorm.go new file mode 100644 index 0000000..ce24cbe --- /dev/null +++ b/initialize/internal/gorm.go @@ -0,0 +1,56 @@ +package internal + +import ( + "gorm.io/gorm" + "gorm.io/gorm/logger" + "gorm.io/gorm/schema" + "sundynix-go/config" + "sundynix-go/global" + "time" +) + +var Gorm = new(_gorm) + +type _gorm struct{} + +// Config 函数用于根据数据库类型和配置生成 GORM 的配置对象 +// 该函数会根据全局配置中的数据库类型选择相应的通用配置,并返回一个配置好的 *gorm.Config 对象。 +// +// 参数: +// - prefix: 表名前缀,用于在生成表名时添加到表名前。 +// - singular: 是否禁用复数表名,true 表示禁用复数表名,false 表示使用复数表名。 +// +// 返回值: +// - *gorm.Config: 配置好的 GORM 配置对象,包含日志、命名策略等配置。 +func (g *_gorm) Config(prefix string, singular bool) *gorm.Config { + // 根据全局配置中的数据库类型选择相应的通用配置 + var general config.GeneralDB + switch global.Config.System.DbType { + case "mysql": + general = global.Config.Mysql.GeneralDB + case "pgsql": + general = global.Config.Pgsql.GeneralDB + case "sqlite": + general = global.Config.Sqlite.GeneralDB + default: + // 默认使用 MySQL 的通用配置 + general = global.Config.Mysql.GeneralDB + } + + // 返回配置好的 GORM 配置对象 + return &gorm.Config{ + // 配置日志记录器,使用自定义的日志写入器,并设置慢查询阈值、日志级别和颜色输出 + Logger: logger.New(NewWriter(general), logger.Config{ + SlowThreshold: 200 * time.Millisecond, + LogLevel: general.LogLevel(), + Colorful: true, + }), + // 配置命名策略,设置表前缀和是否禁用复数表名 + NamingStrategy: schema.NamingStrategy{ + TablePrefix: prefix, // 表前缀 + SingularTable: singular, // 禁用复数表名 + }, + // 禁用自动创建外键约束 + DisableForeignKeyConstraintWhenMigrating: true, + } +}