dao.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/admin/main/push/conf"
  5. "go-common/library/database/orm"
  6. sqlx "go-common/library/database/sql"
  7. xhttp "go-common/library/net/http/blademaster"
  8. "github.com/jinzhu/gorm"
  9. )
  10. // Dao struct user of Dao.
  11. type Dao struct {
  12. c *conf.Config
  13. db *sqlx.DB
  14. DB *gorm.DB
  15. httpClient *xhttp.Client
  16. }
  17. // New create a instance of Dao and return.
  18. func New(c *conf.Config) (d *Dao) {
  19. d = &Dao{
  20. c: c,
  21. db: sqlx.NewMySQL(c.MySQL),
  22. DB: orm.NewMySQL(c.ORM),
  23. httpClient: xhttp.NewClient(c.HTTPClient),
  24. }
  25. d.initORM()
  26. return
  27. }
  28. func (d *Dao) initORM() {
  29. gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
  30. if defaultTableName == "push_business" {
  31. return defaultTableName
  32. }
  33. return "push_" + defaultTableName
  34. }
  35. d.DB.LogMode(true)
  36. }
  37. // Ping check connection of db , mc.
  38. func (d *Dao) Ping(c context.Context) (err error) {
  39. if d.DB != nil {
  40. err = d.DB.DB().PingContext(c)
  41. }
  42. return
  43. }
  44. // Close close connection of db , mc.
  45. func (d *Dao) Close() {
  46. if d.DB != nil {
  47. d.DB.Close()
  48. }
  49. }