-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch.go
77 lines (66 loc) · 1.64 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
package remotedb
import (
"github.com/pkg/errors"
db "github.com/evoblockchain/evochain/libs/tm-db"
protodb "github.com/evoblockchain/evochain/libs/tm-db/remotedb/proto"
)
type batch struct {
db *RemoteDB
ops []*protodb.Operation
}
var _ db.Batch = (*batch)(nil)
func newBatch(rdb *RemoteDB) *batch {
return &batch{
db: rdb,
ops: []*protodb.Operation{},
}
}
func (b *batch) assertOpen() {
if b.ops == nil {
panic("batch has been written or closed")
}
}
// Set implements Batch.
func (b *batch) Set(key, value []byte) {
b.assertOpen()
op := &protodb.Operation{
Entity: &protodb.Entity{Key: key, Value: value},
Type: protodb.Operation_SET,
}
b.ops = append(b.ops, op)
}
// Delete implements Batch.
func (b *batch) Delete(key []byte) {
b.assertOpen()
op := &protodb.Operation{
Entity: &protodb.Entity{Key: key},
Type: protodb.Operation_DELETE,
}
b.ops = append(b.ops, op)
}
// Write implements Batch.
func (b *batch) Write() error {
b.assertOpen()
_, err := b.db.dc.BatchWrite(b.db.ctx, &protodb.Batch{Ops: b.ops})
if err != nil {
return errors.Errorf("remoteDB.BatchWrite: %v", err)
}
// Make sure batch cannot be used afterwards. Callers should still call Close(), for errors.
b.Close()
return nil
}
// WriteSync implements Batch.
func (b *batch) WriteSync() error {
b.assertOpen()
_, err := b.db.dc.BatchWriteSync(b.db.ctx, &protodb.Batch{Ops: b.ops})
if err != nil {
return errors.Errorf("RemoteDB.BatchWriteSync: %v", err)
}
// Make sure batch cannot be used afterwards. Callers should still call Close(), for errors.
b.Close()
return nil
}
// Close implements Batch.
func (b *batch) Close() {
b.ops = nil
}