Transaction

More API refer Orm 增删改查

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

Either way, it should be noted that only SQL executed via TxOrm will be considered to be within a transaction.

  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)

Of course, QuerySeter and QueryM2Mer, RawSeter derived from TxOrm are also considered to be inside the transaction.

The methods related to transactions are:

  1. Begin() (TxOrmer, error)
  2. BeginWithCtx(ctx context.Context) (TxOrmer, error)
  3. BeginWithOpts(opts *sql.TxOptions) (TxOrmer, error)
  4. BeginWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions) (TxOrmer, error)
  5. // Beego closure
  6. DoTx(task func(ctx context.Context, txOrm TxOrmer) error) error
  7. DoTxWithCtx(ctx context.Context, task func(ctx context.Context, txOrm TxOrmer) error) error
  8. DoTxWithOpts(opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error
  9. DoTxWithCtxAndOpts(ctx context.Context, opts *sql.TxOptions, task func(ctx context.Context, txOrm TxOrmer) error) error