Passing external transaction to Storm

This commit is contained in:
Asdine El Hrychy
2016-04-24 14:36:23 +02:00
parent 203d88c63c
commit b5486fd5cd
4 changed files with 45 additions and 0 deletions

View File

@@ -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

View File

@@ -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
}

View File

@@ -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)
}

View File

@@ -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)
}