package initialize import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm/logger" "gorm.io/gorm/schema" "log" "os" "time" "lc-fangdaosha/global" "gorm.io/gorm" ) func Gorm() *gorm.DB { m := global.Config.Mysql fmt.Println("mysql配置:", m) if m.Dbname == "" { return nil } mysqlConfig := mysql.Config{ DSN: m.Dsn(), // DSN data source name DefaultStringSize: 191, // string 类型字段的默认长度 SkipInitializeWithVersion: false, // 根据版本自动配置 } if db, err := gorm.Open(mysql.New(mysqlConfig), config(m.Prefix, m.Singular)); err != nil { log.Fatalln("29:", err) return nil } else { db.InstanceSet("gorm:table_options", "ENGINE="+m.Engine) sqlDB, _ := db.DB() sqlDB.SetMaxIdleConns(m.MaxIdleConns) sqlDB.SetMaxOpenConns(m.MaxOpenConns) return db } } type DBBASE interface { GetLogMode() string } func config(prefix string, singular bool) *gorm.Config { config := &gorm.Config{ NamingStrategy: schema.NamingStrategy{ TablePrefix: prefix, SingularTable: singular, }, DisableForeignKeyConstraintWhenMigrating: true, } _default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{ SlowThreshold: 200 * time.Millisecond, LogLevel: logger.Warn, Colorful: true, }) var logMode DBBASE logMode = &global.Config.Mysql switch logMode.GetLogMode() { case "silent", "Silent": config.Logger = _default.LogMode(logger.Silent) case "error", "Error": config.Logger = _default.LogMode(logger.Error) case "warn", "Warn": config.Logger = _default.LogMode(logger.Warn) case "info", "Info": config.Logger = _default.LogMode(logger.Info) default: config.Logger = _default.LogMode(logger.Info) } return config }