Açıklama Yok
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_config.go 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package subconfigs
  2. import (
  3. "fmt"
  4. "log"
  5. )
  6. type DatabasesConfig struct {
  7. BaseConfig
  8. Databases map[string]*DatabaseConfig `yaml:"databases"`
  9. }
  10. // DatabaseConfig 数据库配置
  11. type DatabaseConfig struct {
  12. BaseConfig
  13. Type string `yaml:"type"`
  14. Host string `yaml:"host"`
  15. Port int `yaml:"port"`
  16. Username string `yaml:"username"`
  17. Password string `yaml:"password"`
  18. Database string `yaml:"database"`
  19. MaxOpenConns int `yaml:"max_open_conns"`
  20. MaxIdleConns int `yaml:"max_idle_conns"`
  21. ConnMaxLifetime int `yaml:"conn_max_lifetime"`
  22. }
  23. // ========== DatabasesConfig 实现 ConfigLoader 接口 ==========
  24. // SetDefaults 设置默认值 - 实现 ConfigLoader 接口
  25. func (c *DatabasesConfig) SetDefaults() {
  26. if c.Databases == nil {
  27. c.Databases = make(map[string]*DatabaseConfig)
  28. log.Println("⚠️ 数据库配置为空,已初始化空的数据库配置")
  29. return
  30. }
  31. // 为每个数据库配置设置默认值
  32. for _, db := range c.Databases {
  33. if db != nil {
  34. db.SetDefaults()
  35. }
  36. }
  37. }
  38. func (c *DatabasesConfig) Load(data map[string]interface{}) error {
  39. // 初始化
  40. c.Databases = make(map[string]*DatabaseConfig)
  41. // 遍历所有数据库配置
  42. for dbName, dbData := range data {
  43. dbDataMap, ok := dbData.(map[interface{}]interface{})
  44. if !ok {
  45. return fmt.Errorf("database '%s' config is not a map", dbName)
  46. }
  47. // 转换为 map[string]interface{}
  48. stringMap := make(map[string]interface{})
  49. for k, v := range dbDataMap {
  50. if key, ok := k.(string); ok {
  51. stringMap[key] = v
  52. }
  53. }
  54. // 加载单个数据库配置
  55. dbConfig := &DatabaseConfig{}
  56. if err := dbConfig.Load(stringMap); err != nil {
  57. return fmt.Errorf("failed to load database '%s' config: %v", dbName, err)
  58. }
  59. c.Databases[dbName] = dbConfig
  60. }
  61. // 设置默认值和验证
  62. c.SetDefaults()
  63. return c.Validate()
  64. }
  65. // ========== DatabaseConfig 实现 ConfigLoader 接口 ==========
  66. // SetDefaults 设置默认值 - 实现 ConfigLoader 接口
  67. func (c *DatabaseConfig) SetDefaults() {
  68. if c.Type == "" {
  69. c.Type = "mysql"
  70. }
  71. if c.Port == 0 {
  72. c.Port = 3306
  73. }
  74. if c.MaxOpenConns == 0 {
  75. c.MaxOpenConns = 100
  76. }
  77. if c.MaxIdleConns == 0 {
  78. c.MaxIdleConns = 20
  79. }
  80. if c.ConnMaxLifetime == 0 {
  81. c.ConnMaxLifetime = 3600
  82. }
  83. }
  84. // Load 从yaml数据加载 - 实现 ConfigLoader 接口
  85. func (c *DatabaseConfig) Load(data map[string]interface{}) error {
  86. // 虽然可能不会被直接调用,但为了接口完整性还是要实现
  87. return c.LoadFromYAML(data, c)
  88. }
  89. // ========== 业务方法 ==========
  90. // Validate 验证配置(数据库配置)
  91. func (c *DatabaseConfig) Validate() error {
  92. if c.Type == "" {
  93. return fmt.Errorf("database type is required")
  94. }
  95. if c.Host == "" {
  96. return fmt.Errorf("database host is required")
  97. }
  98. if c.Port <= 0 || c.Port > 65535 {
  99. return fmt.Errorf("invalid database port: %d", c.Port)
  100. }
  101. if c.Database == "" {
  102. return fmt.Errorf("database name is required")
  103. }
  104. return nil
  105. }
  106. // Validate 验证配置(多数据库配置)
  107. func (c *DatabasesConfig) Validate() error {
  108. if c.Databases == nil || len(c.Databases) == 0 {
  109. log.Println("❌ 错误: 未找到任何数据库配置,请检查配置文件中的 'databases' 配置")
  110. return fmt.Errorf("no database configurations found")
  111. }
  112. // 必须要有默认数据库
  113. if _, exists := c.Databases["default"]; !exists {
  114. availableDBs := c.GetAllDatabaseNames()
  115. log.Printf("❌ 错误: 默认数据库未找到。可用的数据库: %v。请在配置文件中添加 'default' 数据库", availableDBs)
  116. return fmt.Errorf("default database not found")
  117. }
  118. // 验证每个数据库配置
  119. for name, db := range c.Databases {
  120. if db == nil {
  121. log.Printf("❌ 错误: 数据库 '%s' 配置为空", name)
  122. return fmt.Errorf("database '%s' configuration is nil", name)
  123. }
  124. if err := db.Validate(); err != nil {
  125. log.Printf("❌ 错误: 数据库 '%s' 验证失败: %v", name, err)
  126. return fmt.Errorf("database '%s' validation failed: %v", name, err)
  127. }
  128. }
  129. log.Printf("✅ 数据库配置验证通过,找到 %d 个数据库配置", len(c.Databases))
  130. return nil
  131. }
  132. // IsConfigured 判断是否已配置(数据库配置)
  133. func (c *DatabaseConfig) IsConfigured() bool {
  134. if c.Host == "" {
  135. log.Println("⚠️ 警告: 数据库 Host 未配置")
  136. return false
  137. }
  138. if c.Port <= 0 {
  139. log.Println("⚠️ 警告: 数据库 Port 未配置或无效")
  140. return false
  141. }
  142. if c.Username == "" {
  143. log.Println("⚠️ 警告: 数据库 Username 未配置")
  144. return false
  145. }
  146. if c.Database == "" {
  147. log.Println("⚠️ 警告: 数据库名称未配置")
  148. return false
  149. }
  150. return true
  151. }
  152. // IsConfigured 判断是否已配置(多数据库配置)
  153. func (c *DatabasesConfig) IsConfigured() bool {
  154. defaultDB := c.GetDefaultDatabase()
  155. if defaultDB == nil {
  156. log.Println("❌ 错误: 默认数据库不存在")
  157. return false
  158. }
  159. if !defaultDB.IsConfigured() {
  160. log.Println("❌ 错误: 默认数据库配置不完整")
  161. return false
  162. }
  163. return true
  164. }
  165. // GetDefaultDatabase 获取默认数据库(必须存在)
  166. func (c *DatabasesConfig) GetDefaultDatabase() *DatabaseConfig {
  167. if c.Databases == nil {
  168. log.Println("❌ 错误: 尝试获取默认数据库时,数据库配置为空")
  169. return nil
  170. }
  171. if db, exists := c.Databases["default"]; exists {
  172. return db
  173. }
  174. // 如果没有名为default的,尝试返回第一个(但会记录警告)
  175. for name, db := range c.Databases {
  176. log.Printf("⚠️ 警告: 未找到名为 'default' 的数据库,使用第一个数据库 '%s' 作为默认", name)
  177. return db
  178. }
  179. log.Println("❌ 错误: 数据库中没有任何配置")
  180. return nil
  181. }
  182. // GetDatabase 按名称获取数据库(为空时记录错误)
  183. func (c *DatabasesConfig) GetDatabase(name string) *DatabaseConfig {
  184. if c.Databases == nil {
  185. log.Printf("❌ 错误: 尝试获取数据库 '%s' 时,数据库配置为空", name)
  186. return nil
  187. }
  188. db := c.Databases[name]
  189. if db == nil {
  190. availableDBs := c.GetAllDatabaseNames()
  191. log.Printf("❌ 错误: 数据库 '%s' 不存在。可用的数据库: %v", name, availableDBs)
  192. }
  193. return db
  194. }
  195. // GetAllDatabaseNames 获取所有数据库名称
  196. func (c *DatabasesConfig) GetAllDatabaseNames() []string {
  197. if c.Databases == nil {
  198. log.Println("⚠️ 警告: 尝试获取数据库名称时,数据库配置为空")
  199. return []string{}
  200. }
  201. names := make([]string, 0, len(c.Databases))
  202. for name := range c.Databases {
  203. names = append(names, name)
  204. }
  205. return names
  206. }
  207. // GetDatabaseNamesWithoutDefault 获取除default外的所有数据库名称
  208. func (c *DatabasesConfig) GetDatabaseNamesWithoutDefault() []string {
  209. if c.Databases == nil {
  210. return []string{}
  211. }
  212. names := make([]string, 0, len(c.Databases)-1)
  213. for name := range c.Databases {
  214. if name != "default" {
  215. names = append(names, name)
  216. }
  217. }
  218. return names
  219. }
  220. // 自动注册
  221. func init() {
  222. Register("databases", &DatabasesConfig{})
  223. }