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, + } +}