gorm.go 1.7 KB

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