Aucune description
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

db_factory.go 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package database
  2. import (
  3. "fmt"
  4. "log"
  5. "sync"
  6. "git.x2erp.com/qdy/go-base/config"
  7. "git.x2erp.com/qdy/go-base/ctx"
  8. "git.x2erp.com/qdy/go-base/types"
  9. "git.x2erp.com/qdy/go-db/drivers"
  10. "git.x2erp.com/qdy/go-db/functions"
  11. "github.com/jmoiron/sqlx"
  12. )
  13. type DBFactory struct {
  14. db *sqlx.DB
  15. name string // 记录数据库配置名称
  16. }
  17. var (
  18. // 多实例存储:配置名称 -> DBFactory 实例
  19. instances = make(map[string]*DBFactory)
  20. // 每个配置名称对应的once,确保线程安全
  21. onceMap = make(map[string]*sync.Once)
  22. // 保护instances和onceMap的读写锁
  23. instancesMutex sync.RWMutex
  24. )
  25. // GetDBFactory 获取指定名称的数据库工厂单例
  26. func GetDBFactory(dbName string) (*DBFactory, error) {
  27. // 获取或创建该名称的once对象
  28. instancesMutex.Lock()
  29. once, exists := onceMap[dbName]
  30. if !exists {
  31. once = &sync.Once{}
  32. onceMap[dbName] = once
  33. }
  34. instancesMutex.Unlock()
  35. var initErr error
  36. var instance *DBFactory
  37. var msg = fmt.Sprintf("DBFactory '%s' instance retrieved from memory.\n", dbName)
  38. once.Do(func() {
  39. // 使用配置单例
  40. cfg, err := config.GetConfig()
  41. if err != nil {
  42. initErr = fmt.Errorf("failed to load config: %v", err)
  43. return
  44. }
  45. // 获取指定名称的数据库配置
  46. dbConfig := cfg.GetDatabaseConfig(dbName)
  47. if dbConfig == nil {
  48. initErr = fmt.Errorf("database configuration '%s' not found", dbName)
  49. return
  50. }
  51. // // 检查数据库配置是否完整
  52. // if !dbConfig.IsConfigured() {
  53. // initErr = fmt.Errorf("database configuration '%s' is incomplete", dbName)
  54. // return
  55. // }
  56. // 获取数据库类型
  57. dbType := dbConfig.Type
  58. log.Printf("Creating database connection for '%s' with type: %s\n", dbName, dbType)
  59. // 获取对应的驱动
  60. dbDriver, err := drivers.Get(dbType)
  61. if err != nil {
  62. initErr = fmt.Errorf("failed to get database driver: %v", err)
  63. return
  64. }
  65. // 将内部 DBConfig 转换为 drivers.DBConfig
  66. driverConfig := drivers.DBConfig{
  67. Type: dbConfig.Type,
  68. Host: dbConfig.Host,
  69. Port: dbConfig.Port,
  70. Username: dbConfig.Username,
  71. Password: dbConfig.Password,
  72. Database: dbConfig.Database,
  73. MaxOpenConns: dbConfig.MaxOpenConns,
  74. MaxIdleConns: dbConfig.MaxIdleConns,
  75. ConnMaxLifetime: dbConfig.ConnMaxLifetime,
  76. }
  77. // 创建数据库连接
  78. db, err := dbDriver.Open(driverConfig)
  79. if err != nil {
  80. initErr = fmt.Errorf("failed to open database connection for '%s': %v", dbName, err)
  81. return
  82. }
  83. // 测试连接
  84. if err := functions.TestConnection(db, dbType); err != nil {
  85. db.Close()
  86. initErr = fmt.Errorf("database connection test failed for '%s': %v", dbName, err)
  87. return
  88. }
  89. msg = fmt.Sprintf("DBFactory '%s' is successfully created.\n", dbName)
  90. instance = &DBFactory{
  91. db: db,
  92. name: dbName,
  93. }
  94. // 保存实例到map
  95. instancesMutex.Lock()
  96. instances[dbName] = instance
  97. instancesMutex.Unlock()
  98. })
  99. if initErr != nil {
  100. return nil, initErr
  101. }
  102. log.Print(msg)
  103. // 从map中获取实例
  104. instancesMutex.RLock()
  105. instance = instances[dbName]
  106. instancesMutex.RUnlock()
  107. return instance, nil
  108. }
  109. // GetDefaultDBFactory 获取默认数据库工厂(向后兼容)
  110. func GetDefaultDBFactory() (*DBFactory, error) {
  111. return GetDBFactory("default")
  112. }
  113. // GetAllDBFactories 获取所有已创建的数据库工厂实例
  114. func GetAllDBFactories() map[string]*DBFactory {
  115. instancesMutex.RLock()
  116. defer instancesMutex.RUnlock()
  117. // 创建副本,避免外部修改
  118. result := make(map[string]*DBFactory)
  119. for k, v := range instances {
  120. result[k] = v
  121. }
  122. return result
  123. }
  124. // GetDBFactoryNames 获取所有可用的数据库配置名称
  125. func GetDBFactoryNames() []string {
  126. cfg, err := config.GetConfig()
  127. if err != nil {
  128. return []string{}
  129. }
  130. dbs := cfg.GetDatabases()
  131. if dbs == nil {
  132. return []string{}
  133. }
  134. return dbs.GetAllDatabaseNames()
  135. }
  136. // CloseInstance 关闭指定名称的数据库连接
  137. func CloseInstance(dbName string) error {
  138. instancesMutex.Lock()
  139. defer instancesMutex.Unlock()
  140. if instance, exists := instances[dbName]; exists {
  141. err := instance.Close()
  142. delete(instances, dbName)
  143. delete(onceMap, dbName)
  144. return err
  145. }
  146. return fmt.Errorf("database instance '%s' not found", dbName)
  147. }
  148. // CloseAll 关闭所有数据库连接
  149. func CloseAll() {
  150. instancesMutex.Lock()
  151. defer instancesMutex.Unlock()
  152. for name, instance := range instances {
  153. if err := instance.Close(); err != nil {
  154. log.Printf("Error closing database instance '%s': %v\n", name, err)
  155. }
  156. delete(instances, name)
  157. delete(onceMap, name)
  158. }
  159. // 重新初始化maps
  160. instances = make(map[string]*DBFactory)
  161. onceMap = make(map[string]*sync.Once)
  162. log.Println("All database connections closed gracefully")
  163. }
  164. // ========== DBFactory 实例方法 ==========
  165. // GetDB 获取数据库连接(线程安全)
  166. func (f *DBFactory) GetDB() interface{} {
  167. return f.db
  168. }
  169. // Close 关闭数据库连接
  170. func (f *DBFactory) Close() error {
  171. if f.db != nil {
  172. err := f.db.Close()
  173. f.db = nil
  174. log.Printf("Database connection '%s' closed gracefully\n", f.name)
  175. return err
  176. }
  177. return nil
  178. }
  179. // GetDBType 得到当前使用数据库类型
  180. func (f *DBFactory) GetDBType() string {
  181. // 通过配置获取当前数据库的类型
  182. cfg, err := config.GetConfig()
  183. if err != nil {
  184. return ""
  185. }
  186. dbConfig := cfg.GetDatabaseConfig(f.name)
  187. if dbConfig == nil {
  188. return ""
  189. }
  190. return dbConfig.Type
  191. }
  192. // GetDBName 获取数据库配置名称
  193. func (f *DBFactory) GetDBName() string {
  194. return f.name
  195. }
  196. // QueryToJSON 快捷查询,直接返回 JSON 字节流
  197. func (f *DBFactory) QueryToJSON(sql string, reqCtx *ctx.RequestContext) *types.QueryResult[[]map[string]interface{}] {
  198. return functions.QueryToJSON(f.db, sql, reqCtx)
  199. }
  200. // QueryParamsToJSON 位置参数查询并返回 JSON 字节数据
  201. func (f *DBFactory) QueryPositionalToJSON(sql string, params []interface{}, reqCtx *ctx.RequestContext) *types.QueryResult[[]map[string]interface{}] {
  202. return functions.QueryPositionalToJSON(f.db, sql, params, reqCtx)
  203. }
  204. // QueryParamsNameToJSON 命名参数查询并返回 JSON 字节数据
  205. // params 可以是 map[string]interface{} 或结构体
  206. func (f *DBFactory) QueryParamsNameToJSON(sql string, params map[string]interface{}, reqCtx *ctx.RequestContext) *types.QueryResult[[]map[string]interface{}] {
  207. return functions.QueryParamsNameToJSON(f.db, sql, params, reqCtx)
  208. }
  209. // QueryToCSV 快捷查询,直接返回 CSV 字符串(包含表头)
  210. func (f *DBFactory) QueryToCSV(sql string, writerHeader bool, reqCtx *ctx.RequestContext) ([]byte, error) {
  211. return functions.QueryToCSV(f.db, sql, writerHeader, reqCtx)
  212. }
  213. // QueryParamsToCSV 位置参数查询并返回 CSV 字节数据
  214. func (f *DBFactory) QueryPositionalToCSV(sql string, writerHeader bool, params []interface{}, reqCtx *ctx.RequestContext) ([]byte, error) {
  215. return functions.QueryPositionalToCSV(f.db, sql, writerHeader, params, reqCtx)
  216. }
  217. // QueryParamsNameToCSV 命名参数查询并返回 CSV 字节数据
  218. // params 可以是 map[string]interface{} 或结构体
  219. func (f *DBFactory) QueryParamsNameToCSV(sql string, writerHeader bool, params map[string]interface{}, reqCtx *ctx.RequestContext) ([]byte, error) {
  220. return functions.QueryParamsNameToCSV(f.db, sql, writerHeader, params, reqCtx)
  221. }
  222. // ExecuteDDL 快捷执行DDL语句
  223. func (f *DBFactory) ExecuteDDL(ddlSQL string) error {
  224. return functions.ExecuteDDL(f.db, ddlSQL)
  225. }
  226. // ExecuteDDLWithTx 快捷在事务中执行DDL语句
  227. func (f *DBFactory) ExecuteDDLWithTx(ddlSQL string) error {
  228. return functions.ExecuteDDLWithTx(f.db, ddlSQL)
  229. }
  230. // ExecuteMultipleDDL 快捷执行多个DDL语句
  231. func (f *DBFactory) ExecuteMultipleDDL(ddlSQLs []string) error {
  232. return functions.ExecuteMultipleDDL(f.db, ddlSQLs)
  233. }
  234. // GetAvailableDrivers 获取可用的数据库驱动
  235. func (f *DBFactory) GetAvailableDrivers() []string {
  236. return drivers.GetAllDrivers()
  237. }
  238. func (f *DBFactory) TestConnection(dbType string) error {
  239. return functions.TestConnection(f.db, dbType)
  240. }