mysqlpool.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package mysqlpool
  2. import (
  3. "errors"
  4. "strings"
  5. "sync"
  6. "golang-fave/engine/sqlw"
  7. )
  8. type MySqlPool struct {
  9. sync.RWMutex
  10. connections map[string]*sqlw.DB
  11. }
  12. func New() *MySqlPool {
  13. r := MySqlPool{}
  14. r.connections = map[string]*sqlw.DB{}
  15. return &r
  16. }
  17. func (this *MySqlPool) Get(key string) *sqlw.DB {
  18. // TODO: return nil if context canceled!
  19. this.Lock()
  20. defer this.Unlock()
  21. if value, ok := this.connections[key]; ok == true {
  22. return value
  23. }
  24. return nil
  25. }
  26. func (this *MySqlPool) Set(key string, value *sqlw.DB) {
  27. this.Lock()
  28. defer this.Unlock()
  29. this.connections[key] = value
  30. }
  31. func (this *MySqlPool) Del(key string) {
  32. if _, ok := this.connections[key]; ok {
  33. delete(this.connections, key)
  34. }
  35. }
  36. func (this *MySqlPool) Close() error {
  37. this.Lock()
  38. defer this.Unlock()
  39. var errs []string
  40. for _, c := range this.connections {
  41. if c != nil {
  42. if err := c.Close(); err != nil {
  43. errs = append(errs, err.Error())
  44. }
  45. }
  46. }
  47. if len(errs) > 0 {
  48. return errors.New(strings.Join(errs, ", "))
  49. }
  50. return nil
  51. }