Skip to content
This repository was archived by the owner on Mar 9, 2019. It is now read-only.

Commit 5261724

Browse files
committed
Explain Batch in README
1 parent b906f4e commit 5261724

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,45 @@ no mutating operations are allowed within a read-only transaction. You can only
125125
retrieve buckets, retrieve values, and copy the database within a read-only
126126
transaction.
127127

128+
129+
#### Batch read-write transactions
130+
131+
Each `DB.Update()` waits for disk to commit the writes. This overhead
132+
can be minimized by combining multiple updates with the `DB.Batch()`
133+
function:
134+
135+
```go
136+
err := db.Batch(func(tx *bolt.Tx) error {
137+
...
138+
return nil
139+
})
140+
```
141+
142+
Batch calls are opportunistically combined into larger transactions.
143+
The trade-off is that `Batch` can call the given function multiple
144+
times, if parts of the transaction fail. The function must be
145+
idempotent and side effects must take effect only after a successful
146+
return from `DB.Batch()`.
147+
148+
For example: don't display messages from inside the function, instead
149+
set variables in the enclosing scope:
150+
151+
```go
152+
var id uint64
153+
err := db.Batch(func(tx *bolt.Tx) error {
154+
// Find last key in bucket, decode as bigendian uint64, increment
155+
// by one, encode back to []byte, and add new key.
156+
...
157+
id = newValue
158+
return nil
159+
})
160+
if err != nil {
161+
return ...
162+
}
163+
fmt.Println("Allocated ID %d", id)
164+
```
165+
166+
128167
#### Managing transactions manually
129168

130169
The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`

0 commit comments

Comments
 (0)