-
Notifications
You must be signed in to change notification settings - Fork 1
/
batch.go
82 lines (63 loc) · 1.19 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package boltdb
import (
"sync"
"github.com/coreos/bbolt"
"github.com/dtynn/winston/pkg/storage"
)
type batchOp struct {
put [][2][]byte
del [][]byte
}
// Batch batch operation
type Batch struct {
s *Storage
batchOp
closed bool
sync.Mutex
}
// Put update a key
func (b *Batch) Put(key, val []byte) error {
b.batchOp.put = append(b.batchOp.put, [2][]byte{key, val})
return nil
}
// Del delete a key
func (b *Batch) Del(key []byte) error {
b.batchOp.del = append(b.batchOp.del, key)
return nil
}
// Commit commit the changes
func (b *Batch) Commit() error {
b.Lock()
defer b.Unlock()
if b.closed {
return storage.ErrBatchClosed
}
if err := b.s.db.Batch(func(tx *bolt.Tx) error {
bucket := tx.Bucket(b.s.bucket)
for _, pair := range b.batchOp.put {
if err := bucket.Put(pair[0], pair[1]); err != nil {
return err
}
}
for _, key := range b.batchOp.del {
if err := bucket.Delete(key); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
b.closed = true
return nil
}
// Close close the batch
func (b *Batch) Close() error {
b.Lock()
defer b.Unlock()
if b.closed {
return storage.ErrBatchClosed
}
b.closed = true
return nil
}