forked from tendermint/tm-db
/
batch.go
81 lines (71 loc) · 1.66 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
package remotedb
import (
"fmt"
tmdb "github.com/klyed/tm-db"
protodb "github.com/klyed/tm-db/remotedb/proto"
)
type batch struct {
db *RemoteDB
ops []*protodb.Operation
}
var _ tmdb.Batch = (*batch)(nil)
func newBatch(rdb *RemoteDB) *batch {
return &batch{
db: rdb,
ops: []*protodb.Operation{},
}
}
// Set implements Batch.
func (b *batch) Set(key, value []byte) error {
if b.ops == nil {
return tmdb.ErrBatchClosed
}
op := &protodb.Operation{
Entity: &protodb.Entity{Key: key, Value: value},
Type: protodb.Operation_SET,
}
b.ops = append(b.ops, op)
return nil
}
// Delete implements Batch.
func (b *batch) Delete(key []byte) error {
if b.ops == nil {
return tmdb.ErrBatchClosed
}
op := &protodb.Operation{
Entity: &protodb.Entity{Key: key},
Type: protodb.Operation_DELETE,
}
b.ops = append(b.ops, op)
return nil
}
// Write implements Batch.
func (b *batch) Write() error {
if b.ops == nil {
return tmdb.ErrBatchClosed
}
_, err := b.db.dc.BatchWrite(b.db.ctx, &protodb.Batch{Ops: b.ops})
if err != nil {
return fmt.Errorf("remoteDB.BatchWrite: %w", 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 {
if b.ops == nil {
return tmdb.ErrBatchClosed
}
_, err := b.db.dc.BatchWriteSync(b.db.ctx, &protodb.Batch{Ops: b.ops})
if err != nil {
return fmt.Errorf("RemoteDB.BatchWriteSync: %w", err)
}
// Make sure batch cannot be used afterwards. Callers should still call Close(), for errors.
return b.Close()
}
// Close implements Batch.
func (b *batch) Close() error {
b.ops = nil
return nil
}