db_list.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package config
  2. import (
  3. "gorm.io/gorm/logger"
  4. "strings"
  5. )
  6. type DsnProvider interface {
  7. Dsn() string
  8. }
  9. // Embeded 结构体可以压平到上一层,从而保持 config 文件的结构和原来一样
  10. // 见 playground: https://go.dev/play/p/KIcuhqEoxmY
  11. // GeneralDB 也被 Pgsql 和 Mysql 原样使用
  12. type GeneralDB struct {
  13. Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 数据库前缀
  14. Port string `mapstructure:"port" json:"port" yaml:"port"` // 数据库端口
  15. Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
  16. Dbname string `mapstructure:"db-name" json:"db-name" yaml:"db-name"` // 数据库名
  17. Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库账号
  18. Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
  19. Path string `mapstructure:"path" json:"path" yaml:"path"` // 数据库地址
  20. Engine string `mapstructure:"engine" json:"engine" yaml:"engine" default:"InnoDB"` // 数据库引擎,默认InnoDB
  21. LogMode string `mapstructure:"log-mode" json:"log-mode" yaml:"log-mode"` // 是否开启Gorm全局日志
  22. MaxIdleConns int `mapstructure:"max-idle-conns" json:"max-idle-conns" yaml:"max-idle-conns"` // 空闲中的最大连接数
  23. MaxOpenConns int `mapstructure:"max-open-conns" json:"max-open-conns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
  24. Singular bool `mapstructure:"singular" json:"singular" yaml:"singular"` // 是否开启全局禁用复数,true表示开启
  25. LogZap bool `mapstructure:"log-zap" json:"log-zap" yaml:"log-zap"` // 是否通过zap写入日志文件
  26. }
  27. func (c GeneralDB) LogLevel() logger.LogLevel {
  28. switch strings.ToLower(c.LogMode) {
  29. case "silent", "Silent":
  30. return logger.Silent
  31. case "error", "Error":
  32. return logger.Error
  33. case "warn", "Warn":
  34. return logger.Warn
  35. case "info", "Info":
  36. return logger.Info
  37. default:
  38. return logger.Info
  39. }
  40. }
  41. type SpecializedDB struct {
  42. Type string `mapstructure:"type" json:"type" yaml:"type"`
  43. AliasName string `mapstructure:"alias-name" json:"alias-name" yaml:"alias-name"`
  44. GeneralDB `yaml:",inline" mapstructure:",squash"`
  45. Disable bool `mapstructure:"disable" json:"disable" yaml:"disable"`
  46. }