-
Notifications
You must be signed in to change notification settings - Fork 179
/
batch.go
53 lines (44 loc) · 1 KB
/
batch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package badger
import (
"sync"
"github.com/dgraph-io/badger/v2"
)
type Batch struct {
writer *badger.WriteBatch
lock sync.RWMutex
callbacks []func()
}
func NewBatch(db *badger.DB) *Batch {
batch := db.NewWriteBatch()
return &Batch{
writer: batch,
callbacks: make([]func(), 0),
}
}
func (b *Batch) GetWriter() *badger.WriteBatch {
return b.writer
}
// OnSucceed adds a callback to execute after the batch has
// been successfully flushed.
// useful for implementing the cache where we will only cache
// after the batch has been successfully flushed
func (b *Batch) OnSucceed(callback func()) {
b.lock.Lock()
defer b.lock.Unlock()
b.callbacks = append(b.callbacks, callback)
}
// Flush will call the badger Batch's Flush method, in
// addition, it will call the callbacks added by
// OnSucceed
func (b *Batch) Flush() error {
err := b.writer.Flush()
if err != nil {
return err
}
b.lock.RLock()
defer b.lock.RUnlock()
for _, callback := range b.callbacks {
callback()
}
return nil
}