aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--db.go18
-rw-r--r--example_test.go22
-rw-r--r--node.go2
3 files changed, 37 insertions, 5 deletions
diff --git a/db.go b/db.go
index 0276d7a..b7338c3 100644
--- a/db.go
+++ b/db.go
@@ -359,15 +359,25 @@ func (db *DB) Do(fn func(*RWTransaction) error) error {
return t.Commit()
}
-// ForEach executes a function for each key/value pair in a bucket.
-// An error is returned if the bucket cannot be found.
-func (db *DB) ForEach(name string, fn func(k, v []byte) error) error {
+// With executes a function within the context of a Transaction.
+// Any error that is returned from the function is returned from the With() method.
+func (db *DB) With(fn func(*Transaction) error) error {
t, err := db.Transaction()
if err != nil {
return err
}
defer t.Close()
- return t.ForEach(name, fn)
+
+ // If an error is returned from the function then pass it through.
+ return fn(t)
+}
+
+// ForEach executes a function for each key/value pair in a bucket.
+// An error is returned if the bucket cannot be found.
+func (db *DB) ForEach(name string, fn func(k, v []byte) error) error {
+ return db.With(func(t *Transaction) error {
+ return t.ForEach(name, fn)
+ })
}
// Bucket retrieves a reference to a bucket.
diff --git a/example_test.go b/example_test.go
index 542109c..8747f94 100644
--- a/example_test.go
+++ b/example_test.go
@@ -87,6 +87,28 @@ func ExampleDB_Do() {
// The value of 'foo' is: bar
}
+func ExampleDB_With() {
+ // Open the database.
+ var db DB
+ db.Open("/tmp/bolt/db_foreach.db", 0666)
+ defer db.Close()
+
+ // Insert data into a bucket.
+ db.CreateBucket("people")
+ db.Put("people", []byte("john"), []byte("doe"))
+ db.Put("people", []byte("susy"), []byte("que"))
+
+ // Access data from within a read-only transactional block.
+ db.With(func(t *Transaction) error {
+ v, _ := t.Get("people", []byte("john"))
+ fmt.Printf("John's last name is %s.\n", string(v))
+ return nil
+ })
+
+ // Output:
+ // John's last name is doe.
+}
+
func ExampleDB_ForEach() {
// Open the database.
var db DB
diff --git a/node.go b/node.go
index ec49f11..68f651e 100644
--- a/node.go
+++ b/node.go
@@ -118,7 +118,7 @@ func (n *node) del(key []byte) {
index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 })
// Exit if the key isn't found.
- if !bytes.Equal(n.inodes[index].key, key) {
+ if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) {
return
}