orm.go 1001 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package orm
  2. import (
  3. "strings"
  4. "time"
  5. "go-common/library/ecode"
  6. "go-common/library/log"
  7. xtime "go-common/library/time"
  8. // database driver
  9. _ "github.com/go-sql-driver/mysql"
  10. "github.com/jinzhu/gorm"
  11. )
  12. // Config mysql config.
  13. type Config struct {
  14. DSN string // data source name.
  15. Active int // pool
  16. Idle int // pool
  17. IdleTimeout xtime.Duration // connect max life time.
  18. }
  19. type ormLog struct{}
  20. func (l ormLog) Print(v ...interface{}) {
  21. log.Info(strings.Repeat("%v ", len(v)), v...)
  22. }
  23. func init() {
  24. gorm.ErrRecordNotFound = ecode.NothingFound
  25. }
  26. // NewMySQL new db and retry connection when has error.
  27. func NewMySQL(c *Config) (db *gorm.DB) {
  28. db, err := gorm.Open("mysql", c.DSN)
  29. if err != nil {
  30. log.Error("db dsn(%s) error: %v", c.DSN, err)
  31. panic(err)
  32. }
  33. db.DB().SetMaxIdleConns(c.Idle)
  34. db.DB().SetMaxOpenConns(c.Active)
  35. db.DB().SetConnMaxLifetime(time.Duration(c.IdleTimeout) / time.Second)
  36. db.SetLogger(ormLog{})
  37. return
  38. }