db.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package storage
  2. import (
  3. "github.com/astaxie/beego/orm"
  4. )
  5. type DbaTasker interface {
  6. Exec(db orm.Ormer) error
  7. Rollback(db orm.Ormer) error
  8. }
  9. type Task func(db orm.Ormer) error
  10. func (t *Task) Exec(db orm.Ormer) error {
  11. return (*t)(db)
  12. }
  13. func (t *Task) Rollback(db orm.Ormer) error {
  14. return nil
  15. }
  16. func GenerateDbaTask(task Task) DbaTasker {
  17. return &task
  18. }
  19. func ExecTrans(tasks ...DbaTasker) error {
  20. mysqlORM := orm.NewOrm()
  21. successTask := make([]DbaTasker, 0)
  22. isCommit := false
  23. defer func() {
  24. // 捕获异常,并执行回滚操作
  25. if v := recover(); v != nil || !isCommit {
  26. for _, task := range successTask {
  27. task.Rollback(mysqlORM)
  28. }
  29. mysqlORM.Rollback()
  30. //向上层抛出异常
  31. if v != nil {
  32. panic(v)
  33. }
  34. }
  35. }()
  36. if err := mysqlORM.Begin(); err != nil {
  37. panic("db error")
  38. }
  39. for _, task := range tasks {
  40. if task != nil {
  41. if err := task.Exec(mysqlORM); err != nil {
  42. if err == EXIT_QUERY {
  43. return err
  44. }
  45. panic(err)
  46. }
  47. }
  48. successTask = append(successTask, task)
  49. }
  50. mysqlORM.Commit()
  51. isCommit = true
  52. return nil
  53. }