transaction.go 655 B

1234567891011121314151617181920212223242526
  1. // Copyright 2018 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. // Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
  6. func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {
  7. session := engine.NewSession()
  8. defer session.Close()
  9. if err := session.Begin(); err != nil {
  10. return nil, err
  11. }
  12. result, err := f(session)
  13. if err != nil {
  14. return nil, err
  15. }
  16. if err := session.Commit(); err != nil {
  17. return nil, err
  18. }
  19. return result, nil
  20. }