Нема описа
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 7.0KB

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