enhancement: auto-transaction #1093
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -28,5 +28,6 @@ temp_test.go
|
|||
.vscode
|
||||
xorm.test
|
||||
*.sqlite3
|
||||
test.db.sql
|
||||
|
||||
.idea/
|
||||
|
|
|
@ -4,8 +4,8 @@
|
|||
|
||||
package xorm
|
||||
|
||||
// AutoTransaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
|
||||
func AutoTransaction(f func(*Session) (interface{}, error), engine *Engine) (interface{}, error) {
|
||||
// Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
|
||||
func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {
|
||||
session := engine.NewSession()
|
||||
defer session.Close()
|
||||
|
||||
|
|
|
@ -15,38 +15,38 @@ import (
|
|||
func TestAutoTransaction(t *testing.T) {
|
||||
assert.NoError(t, prepareEngine())
|
||||
|
||||
type Test struct {
|
||||
type TestTx struct {
|
||||
Id int64 `xorm:"autoincr pk"`
|
||||
Msg string `xorm:"varchar(255)"`
|
||||
Created time.Time `xorm:"created"`
|
||||
}
|
||||
|
||||
assert.NoError(t, testEngine.Sync2(new(Test)))
|
||||
assert.NoError(t, testEngine.Sync2(new(TestTx)))
|
||||
|
||||
engine := testEngine.(*Engine)
|
||||
|
||||
// will success
|
||||
AutoTransaction(func(session *Session) (interface{}, error) {
|
||||
_, err := session.Insert(Test{Msg: "hi"})
|
||||
engine.Transaction(func(session *Session) (interface{}, error) {
|
||||
_, err := session.Insert(TestTx{Msg: "hi"})
|
||||
assert.NoError(t, err)
|
||||
|
||||
return nil, nil
|
||||
}, engine)
|
||||
})
|
||||
|
||||
has, err := engine.Exist(&Test{Msg: "hi"})
|
||||
has, err := engine.Exist(&TestTx{Msg: "hi"})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, true, has)
|
||||
|
||||
// will rollback
|
||||
_, err = AutoTransaction(func(session *Session) (interface{}, error) {
|
||||
_, err := session.Insert(Test{Msg: "hello"})
|
||||
_, err = engine.Transaction(func(session *Session) (interface{}, error) {
|
||||
_, err := session.Insert(TestTx{Msg: "hello"})
|
||||
assert.NoError(t, err)
|
||||
|
||||
return nil, fmt.Errorf("rollback")
|
||||
}, engine)
|
||||
})
|
||||
assert.Error(t, err)
|
||||
|
||||
has, err = engine.Exist(&Test{Msg: "hello"})
|
||||
has, err = engine.Exist(&TestTx{Msg: "hello"})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, false, has)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user