diff --git a/README.md b/README.md index b833757..d4c0686 100644 --- a/README.md +++ b/README.md @@ -318,6 +318,18 @@ db.Bolt.View(func(tx *bolt.Tx) error { }) ``` +A transaction can be also be passed to Storm + +```go +db.Bolt.Update(func(tx *bolt.Tx) error { + ... + dbx := db.WithTransaction(tx) + err = dbx.Save(&user) + ... + return nil +}) +``` + ## TODO - Search diff --git a/node.go b/node.go index 61d2301..e6e5b4b 100644 --- a/node.go +++ b/node.go @@ -19,3 +19,9 @@ func (n Node) From(addend ...string) *Node { n.rootBucket = append(n.rootBucket, addend...) return &n } + +// WithTransaction returns a New Storm node that will use the given transaction. +func (n Node) WithTransaction(tx *bolt.Tx) *Node { + n.tx = tx + return &n +} diff --git a/node_test.go b/node_test.go index e437d74..cd62541 100644 --- a/node_test.go +++ b/node_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "testing" + "github.com/boltdb/bolt" "github.com/stretchr/testify/assert" ) @@ -22,5 +23,26 @@ func TestNode(t *testing.T) { assert.Equal(t, []string{"b", "c"}, n1.rootBucket) n2 := n1.From("d", "e") assert.Equal(t, []string{"b", "c", "d", "e"}, n2.rootBucket) +} + +func TestNodeWithTransaction(t *testing.T) { + dir, _ := ioutil.TempDir(os.TempDir(), "storm") + defer os.RemoveAll(dir) + db, _ := Open(filepath.Join(dir, "storm.db"), Root("a")) + defer db.Close() + + var user User + db.Bolt.Update(func(tx *bolt.Tx) error { + dbx := db.WithTransaction(tx) + err := dbx.Save(&User{ID: 10, Name: "John"}) + assert.NoError(t, err) + err = dbx.One("ID", 10, &user) + assert.NoError(t, err) + assert.Equal(t, "John", user.Name) + return nil + }) + + err := db.One("ID", 10, &user) + assert.NoError(t, err) } diff --git a/storm.go b/storm.go index 1525096..01ea2e2 100644 --- a/storm.go +++ b/storm.go @@ -102,3 +102,8 @@ func (s *DB) From(root ...string) *Node { newNode.rootBucket = root return &newNode } + +// WithTransaction returns a New Storm node that will use the given transaction. +func (s *DB) WithTransaction(tx *bolt.Tx) *Node { + return s.root.WithTransaction(tx) +}