From 394e42e3ebd70b10488aa791894db28e9410077c Mon Sep 17 00:00:00 2001 From: Ben Johnson Date: Fri, 4 Apr 2014 07:51:01 -0600 Subject: Add Tx.OnCommit() handler. This commit adds the ability to execute a function after a transaction has successfully committed. --- tx_test.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'tx_test.go') diff --git a/tx_test.go b/tx_test.go index 4a6c329..3372dff 100644 --- a/tx_test.go +++ b/tx_test.go @@ -1,6 +1,7 @@ package bolt import ( + "errors" "fmt" "math/rand" "os" @@ -484,6 +485,33 @@ func TestTxCursorIterateReverse(t *testing.T) { fmt.Fprint(os.Stderr, "\n") } +// Ensure that Tx commit handlers are called after a transaction successfully commits. +func TestTx_OnCommit(t *testing.T) { + var x int + withOpenDB(func(db *DB, path string) { + db.Update(func(tx *Tx) error { + tx.OnCommit(func() { x += 1 }) + tx.OnCommit(func() { x += 2 }) + return tx.CreateBucket("widgets") + }) + }) + assert.Equal(t, 3, x) +} + +// Ensure that Tx commit handlers are NOT called after a transaction rolls back. +func TestTx_OnCommit_Rollback(t *testing.T) { + var x int + withOpenDB(func(db *DB, path string) { + db.Update(func(tx *Tx) error { + tx.OnCommit(func() { x += 1 }) + tx.OnCommit(func() { x += 2 }) + tx.CreateBucket("widgets") + return errors.New("rollback this commit") + }) + }) + assert.Equal(t, 0, x) +} + // Benchmark the performance iterating over a cursor. func BenchmarkTxCursor(b *testing.B) { indexes := rand.Perm(b.N) -- cgit v1.2.3