mirror of
https://github.com/etcd-io/bbolt.git
synced 2025-05-31 11:42:30 +00:00
Read-only transactional block.
This commit is contained in:
parent
f8fd84b2be
commit
459b8eb4ab
18
db.go
18
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.
|
||||
|
@ -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
|
||||
|
2
node.go
2
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
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user