Skip to content

Instantly share code, notes, and snippets.

@calmh
Created June 14, 2015 20:10
Show Gist options
  • Save calmh/8dd3c9548677b12cadc3 to your computer and use it in GitHub Desktop.
Save calmh/8dd3c9548677b12cadc3 to your computer and use it in GitHub Desktop.
package db
import (
"os"
"testing"
"github.com/boltdb/bolt"
)
func TestBoltTransactions(t *testing.T) {
os.Remove("testdata/test.db")
defer os.Remove("testdata/test.db")
db, err := bolt.Open("testdata/test.db", 0644, nil)
if err != nil {
t.Fatal(err)
}
defer db.Close()
// Set an initial value in a bucket
err = db.Update(func(tx *bolt.Tx) error {
bkt, err := tx.CreateBucket([]byte("test"))
if err != nil {
return err
}
return bkt.Put([]byte("key"), []byte("avalue"))
})
if err != nil {
t.Fatal(err)
}
// Start a routine that can perform an update in the background when
// requested to
start := make(chan struct{})
done := make(chan struct{})
go func() {
<-start
err := db.Update(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte("test"))
return bkt.Put([]byte("key"), []byte("differentvalue"))
})
if err != nil {
t.Fatal(err)
}
done <- struct{}{}
}()
// Start a read transaction, read back the value we set before, allow the
// other write transaction to happen in the meantime, and verify we do not
// see that write in our transaction.
err = db.View(func(tx *bolt.Tx) error {
// Read back the value
bkt := tx.Bucket([]byte("test"))
val := bkt.Get([]byte("key"))
if string(val) != "avalue" {
t.Fatal("%q %= %q", val, "avalue")
}
// Run an update on a different goroutine
start <- struct{}{}
<-done
// We should not see the change
val = bkt.Get([]byte("key"))
if string(val) != "avalue" {
t.Fatal("%q %= %q", val, "avalue")
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment