mysql.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package config
  2. import (
  3. "gorm.io/gorm/logger"
  4. "strings"
  5. )
  6. type Mysql struct {
  7. GeneralDB `yaml:",inline" mapstructure:",squash"`
  8. }
  9. func (m *Mysql) Dsn() string {
  10. return m.Username + ":" + m.Password + "@tcp(" + m.Path + ":" + m.Port + ")/" + m.Dbname + "?" + m.Config
  11. }
  12. // GeneralDB 也被 Pgsql 和 Mysql 原样使用
  13. type GeneralDB struct {
  14. Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 数据库前缀
  15. Port string `mapstructure:"port" json:"port" yaml:"port"` // 数据库端口
  16. Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
  17. Dbname string `mapstructure:"db-name" json:"db-name" yaml:"db-name"` // 数据库名
  18. Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库账号
  19. Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
  20. Path string `mapstructure:"path" json:"path" yaml:"path"` // 数据库地址
  21. Engine string `mapstructure:"engine" json:"engine" yaml:"engine" default:"InnoDB"` // 数据库引擎,默认InnoDB
  22. LogMode string `mapstructure:"log-mode" json:"log-mode" yaml:"log-mode"` // 是否开启Gorm全局日志
  23. MaxIdleConns int `mapstructure:"max-idle-conns" json:"max-idle-conns" yaml:"max-idle-conns"` // 空闲中的最大连接数
  24. MaxOpenConns int `mapstructure:"max-open-conns" json:"max-open-conns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
  25. Singular bool `mapstructure:"singular" json:"singular" yaml:"singular"` // 是否开启全局禁用复数,true表示开启
  26. LogZap bool `mapstructure:"log-zap" json:"log-zap" yaml:"log-zap"` // 是否通过zap写入日志文件
  27. }
  28. func (c GeneralDB) LogLevel() logger.LogLevel {
  29. switch strings.ToLower(c.LogMode) {
  30. case "silent", "Silent":
  31. return logger.Silent
  32. case "error", "Error":
  33. return logger.Error
  34. case "warn", "Warn":
  35. return logger.Warn
  36. case "info", "Info":
  37. return logger.Info
  38. default:
  39. return logger.Info
  40. }
  41. }