Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.2KB

  1. // Copyright 2017 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. import (
  6. "fmt"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func TestAutoTransaction(t *testing.T) {
  12. assert.NoError(t, prepareEngine())
  13. type TestTx struct {
  14. Id int64 `xorm:"autoincr pk"`
  15. Msg string `xorm:"varchar(255)"`
  16. Created time.Time `xorm:"created"`
  17. }
  18. assert.NoError(t, testEngine.Sync2(new(TestTx)))
  19. engine := testEngine.(*Engine)
  20. // will success
  21. engine.Transaction(func(session *Session) (interface{}, error) {
  22. _, err := session.Insert(TestTx{Msg: "hi"})
  23. assert.NoError(t, err)
  24. return nil, nil
  25. })
  26. has, err := engine.Exist(&TestTx{Msg: "hi"})
  27. assert.NoError(t, err)
  28. assert.EqualValues(t, true, has)
  29. // will rollback
  30. _, err = engine.Transaction(func(session *Session) (interface{}, error) {
  31. _, err := session.Insert(TestTx{Msg: "hello"})
  32. assert.NoError(t, err)
  33. return nil, fmt.Errorf("rollback")
  34. })
  35. assert.Error(t, err)
  36. has, err = engine.Exist(&TestTx{Msg: "hello"})
  37. assert.NoError(t, err)
  38. assert.EqualValues(t, false, has)
  39. }