dao.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package dao
  2. import (
  3. "context"
  4. "go-common/app/admin/main/growup/conf"
  5. "go-common/library/database/orm"
  6. "go-common/library/database/sql"
  7. "go-common/library/log"
  8. httpx "go-common/library/net/http/blademaster"
  9. "github.com/jinzhu/gorm"
  10. )
  11. // Dao dao
  12. type Dao struct {
  13. c *conf.Config
  14. db *gorm.DB
  15. rddb *sql.DB
  16. client *httpx.Client
  17. VideoURL string
  18. ColumnURL string
  19. }
  20. // New fn
  21. func New(c *conf.Config) (d *Dao) {
  22. d = &Dao{
  23. c: c,
  24. db: orm.NewMySQL(c.ORM.Growup),
  25. rddb: sql.NewMySQL(c.ORM.Allowance),
  26. client: httpx.NewClient(c.HTTPClient),
  27. VideoURL: c.Host.VideoType + "/videoup/types",
  28. ColumnURL: c.Host.ColumnType + "/x/article/categories",
  29. }
  30. d.initORM()
  31. return
  32. }
  33. func (d *Dao) initORM() {
  34. d.db.LogMode(true)
  35. }
  36. // Ping check conn of db
  37. func (d *Dao) Ping(c context.Context) (err error) {
  38. if d.db != nil {
  39. err = d.db.DB().PingContext(c)
  40. }
  41. return
  42. }
  43. // Close close conn of db
  44. func (d *Dao) Close() {
  45. if d.db != nil {
  46. d.db.Close()
  47. }
  48. }
  49. // BeginTran begin tran
  50. func (d *Dao) BeginTran(c context.Context) (tx *sql.Tx, err error) {
  51. return d.rddb.Begin(c)
  52. }
  53. // Exec do exec
  54. func (d *Dao) Exec(c context.Context, sql string) (rows int64, err error) {
  55. res, err := d.rddb.Exec(c, sql)
  56. if err != nil {
  57. return
  58. }
  59. return res.RowsAffected()
  60. }
  61. // DoInTx .
  62. func (d *Dao) DoInTx(c context.Context, txFunc func(*sql.Tx) error) (err error) {
  63. tx, err := d.rddb.Begin(c)
  64. if err != nil {
  65. log.Error("d.rddb.Begin err(%v)", err)
  66. return
  67. }
  68. defer func() {
  69. if err != nil {
  70. if err1 := tx.Rollback(); err1 != nil {
  71. log.Error("tx.Rollback err(%v)", err1)
  72. }
  73. return
  74. }
  75. }()
  76. err = txFunc(tx)
  77. if err != nil {
  78. return
  79. }
  80. if err = tx.Commit(); err != nil {
  81. log.Error("tx.Commit err(%v)", err)
  82. }
  83. return
  84. }