forked from tendermint/tm-db
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatch.go
84 lines (73 loc) · 1.73 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
83
84
package remotedb
import (
"errors"
"fmt"
db "github.com/tendermint/tm-db"
protodb "github.com/tendermint/tm-db/remotedb/proto"
)
var errBatchClosed = errors.New("batch has been written or closed")
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{},
}
}
// Set implements Batch.
func (b *batch) Set(key, value []byte) error {
if b.ops == nil {
return 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 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 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 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
}