gdb_model_transaction.go 905 B

12345678910111213141516171819202122232425262728
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdb
  7. import (
  8. "context"
  9. )
  10. // Transaction wraps the transaction logic using function `f`.
  11. // It rollbacks the transaction and returns the error from function `f` if
  12. // it returns non-nil error. It commits the transaction and returns nil if
  13. // function `f` returns nil.
  14. //
  15. // Note that, you should not Commit or Rollback the transaction in function `f`
  16. // as it is automatically handled by this function.
  17. func (m *Model) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error) {
  18. if ctx == nil {
  19. ctx = m.GetCtx()
  20. }
  21. if m.tx != nil {
  22. return m.tx.Transaction(ctx, f)
  23. }
  24. return m.db.Transaction(ctx, f)
  25. }