gorm.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package initialize
  2. import (
  3. "gorm.io/driver/mysql"
  4. "gorm.io/gorm/logger"
  5. "gorm.io/gorm/schema"
  6. "log"
  7. "os"
  8. "time"
  9. "lcfns/global"
  10. "gorm.io/gorm"
  11. )
  12. func Gorm() *gorm.DB {
  13. m := global.Config.Mysql
  14. if m.Dbname == "" {
  15. return nil
  16. }
  17. mysqlConfig := mysql.Config{
  18. DSN: m.Dsn(), // DSN data source name
  19. DefaultStringSize: 191, // string 类型字段的默认长度
  20. SkipInitializeWithVersion: false, // 根据版本自动配置
  21. }
  22. if db, err := gorm.Open(mysql.New(mysqlConfig), config(m.Prefix, m.Singular)); err != nil {
  23. log.Fatalln("29:", err)
  24. return nil
  25. } else {
  26. db.InstanceSet("gorm:table_options", "ENGINE="+m.Engine)
  27. sqlDB, _ := db.DB()
  28. sqlDB.SetMaxIdleConns(m.MaxIdleConns)
  29. sqlDB.SetMaxOpenConns(m.MaxOpenConns)
  30. return db
  31. }
  32. }
  33. type DBBASE interface {
  34. GetLogMode() string
  35. }
  36. func config(prefix string, singular bool) *gorm.Config {
  37. config := &gorm.Config{
  38. NamingStrategy: schema.NamingStrategy{
  39. TablePrefix: prefix,
  40. SingularTable: singular,
  41. },
  42. DisableForeignKeyConstraintWhenMigrating: true,
  43. }
  44. _default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
  45. SlowThreshold: 200 * time.Millisecond,
  46. LogLevel: logger.Warn,
  47. Colorful: true,
  48. })
  49. var logMode DBBASE
  50. logMode = &global.Config.Mysql
  51. switch logMode.GetLogMode() {
  52. case "silent", "Silent":
  53. config.Logger = _default.LogMode(logger.Silent)
  54. case "error", "Error":
  55. config.Logger = _default.LogMode(logger.Error)
  56. case "warn", "Warn":
  57. config.Logger = _default.LogMode(logger.Warn)
  58. case "info", "Info":
  59. config.Logger = _default.LogMode(logger.Info)
  60. default:
  61. config.Logger = _default.LogMode(logger.Info)
  62. }
  63. return config
  64. }