name: Transaction

sort: 7

Transaction

There are two ways to handle transaction in Beego. One is closure:

  1. // Beego will manage the transaction's lifecycle
  2. // if the @param task return error, the transaction will be rollback
  3. // or the transaction will be committed
  4. err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
  5. // data
  6. user := new(User)
  7. user.Name = "test_transaction"
  8. // insert data
  9. // Using txOrm to execute SQL
  10. _, e := txOrm.Insert(user)
  11. // if e != nil the transaction will be rollback
  12. // or it will be committed
  13. return e
  14. })

In this way, the first parameter is task, all DB operation should be inside the task.

If the task return error, Beego rollback the transaction.

We recommend you to use this way.

Another way is that users handle transaction manually:

  1. o := orm.NewOrm()
  2. to, err := o.Begin()
  3. if err != nil {
  4. logs.Error("start the transaction failed")
  5. return
  6. }
  7. user := new(User)
  8. user.Name = "test_transaction"
  9. // do something with to. to is an instance of TxOrm
  10. // insert data
  11. // Using txOrm to execute SQL
  12. _, err = to.Insert(user)
  13. if err != nil {
  14. logs.Error("execute transaction's sql fail, rollback.", err)
  15. err = to.Rollback()
  16. if err != nil {
  17. logs.Error("roll back transaction failed", err)
  18. }
  19. } else {
  20. err = to.Commit()
  21. if err != nil {
  22. logs.Error("commit transaction failed.", err)
  23. }
  24. }
  1. o := orm.NewOrm()
  2. to, err := o.Begin()
  3. // outside the txn
  4. o.Insert(xxx)
  5. // inside the txn
  6. to.Insert(xxx)