db.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. }