Skip to content

Commit

Permalink
add support for mulitple transactions on one session (go-xorm#1015)
Browse files Browse the repository at this point in the history
  • Loading branch information
lunny authored Jun 20, 2018
1 parent a8bd843 commit ee5b31e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
2 changes: 2 additions & 0 deletions session_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func (session *Session) Rollback() error {
if !session.isAutoCommit && !session.isCommitedOrRollbacked {
session.saveLastSQL(session.engine.dialect.RollBackStr())
session.isCommitedOrRollbacked = true
session.isAutoCommit = true
return session.tx.Rollback()
}
return nil
Expand All @@ -34,6 +35,7 @@ func (session *Session) Commit() error {
if !session.isAutoCommit && !session.isCommitedOrRollbacked {
session.saveLastSQL("COMMIT")
session.isCommitedOrRollbacked = true
session.isAutoCommit = true
var err error
if err = session.tx.Commit(); err == nil {
// handle processors after tx committed
Expand Down
63 changes: 63 additions & 0 deletions session_tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,66 @@ func TestCombineTransactionSameMapper(t *testing.T) {
err = session.Commit()
assert.NoError(t, err)
}

func TestMultipleTransaction(t *testing.T) {
assert.NoError(t, prepareEngine())

type MultipleTransaction struct {
Id int64
Name string
}

assertSync(t, new(MultipleTransaction))

session := testEngine.NewSession()
defer session.Close()

err := session.Begin()
assert.NoError(t, err)

m1 := MultipleTransaction{Name: "xiaoxiao2"}
_, err = session.Insert(&m1)
assert.NoError(t, err)

user2 := MultipleTransaction{Name: "zzz"}
_, err = session.Where("id = ?", 0).Update(&user2)
assert.NoError(t, err)

err = session.Commit()
assert.NoError(t, err)

var ms []MultipleTransaction
err = session.Find(&ms)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(ms))

err = session.Begin()
assert.NoError(t, err)

_, err = session.Where("id=?", m1.Id).Delete(new(MultipleTransaction))
assert.NoError(t, err)

err = session.Commit()
assert.NoError(t, err)

ms = make([]MultipleTransaction, 0)
err = session.Find(&ms)
assert.NoError(t, err)
assert.EqualValues(t, 0, len(ms))

err = session.Begin()
assert.NoError(t, err)

_, err = session.Insert(&MultipleTransaction{
Name: "ssss",
})
assert.NoError(t, err)

err = session.Rollback()
assert.NoError(t, err)

ms = make([]MultipleTransaction, 0)
err = session.Find(&ms)
assert.NoError(t, err)
assert.EqualValues(t, 0, len(ms))
}

0 comments on commit ee5b31e

Please sign in to comment.