No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

database_common.go 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package subconfigs
  2. import (
  3. "fmt"
  4. "log"
  5. )
  6. // DbConfig 单个数据库配置(共享结构)
  7. type DbConfig struct {
  8. Type string `yaml:"type"`
  9. Host string `yaml:"host"`
  10. Port int `yaml:"port"`
  11. Username string `yaml:"username"`
  12. Password string `yaml:"password"`
  13. Database string `yaml:"database"`
  14. MaxOpenConns int `yaml:"max_open_conns"`
  15. MaxIdleConns int `yaml:"max_idle_conns"`
  16. ConnMaxLifetime int `yaml:"conn_max_lifetime"`
  17. }
  18. // SetDbDefaults 设置数据库配置默认值
  19. func SetDbDefaults(c *DbConfig) {
  20. if c.Type == "" {
  21. c.Type = "mysql"
  22. }
  23. if c.Port == 0 {
  24. c.Port = 3306
  25. }
  26. if c.MaxOpenConns == 0 {
  27. c.MaxOpenConns = 100
  28. }
  29. if c.MaxIdleConns == 0 {
  30. c.MaxIdleConns = 20
  31. }
  32. if c.ConnMaxLifetime == 0 {
  33. c.ConnMaxLifetime = 3600
  34. }
  35. }
  36. // ValidateDbConfig 验证数据库配置
  37. func ValidateDbConfig(c *DbConfig) error {
  38. if c.Type == "" {
  39. return fmt.Errorf("database type is required")
  40. }
  41. if c.Host == "" {
  42. return fmt.Errorf("database host is required")
  43. }
  44. if c.Port <= 0 || c.Port > 65535 {
  45. return fmt.Errorf("invalid database port: %d", c.Port)
  46. }
  47. if c.Database == "" {
  48. return fmt.Errorf("database name is required")
  49. }
  50. return nil
  51. }
  52. // IsDbConfigured 判断数据库是否已配置
  53. func IsDbConfigured(c *DbConfig, name string) bool {
  54. if c.Host == "" {
  55. if name != "" {
  56. log.Printf("⚠️ 警告: 数据库 '%s' Host 未配置", name)
  57. } else {
  58. log.Println("⚠️ 警告: 数据库 Host 未配置")
  59. }
  60. return false
  61. }
  62. if c.Port <= 0 {
  63. if name != "" {
  64. log.Printf("⚠️ 警告: 数据库 '%s' Port 未配置或无效", name)
  65. } else {
  66. log.Println("⚠️ 警告: 数据库 Port 未配置或无效")
  67. }
  68. return false
  69. }
  70. if c.Username == "" {
  71. if name != "" {
  72. log.Printf("⚠️ 警告: 数据库 '%s' Username 未配置", name)
  73. } else {
  74. log.Println("⚠️ 警告: 数据库 Username 未配置")
  75. }
  76. return false
  77. }
  78. if c.Database == "" {
  79. if name != "" {
  80. log.Printf("⚠️ 警告: 数据库 '%s' 名称未配置", name)
  81. } else {
  82. log.Println("⚠️ 警告: 数据库名称未配置")
  83. }
  84. return false
  85. }
  86. return true
  87. }