github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/tm-db/remotedb/batch.go (about) 1 package remotedb 2 3 import ( 4 "github.com/pkg/errors" 5 6 db "github.com/fibonacci-chain/fbc/libs/tm-db" 7 protodb "github.com/fibonacci-chain/fbc/libs/tm-db/remotedb/proto" 8 ) 9 10 type batch struct { 11 db *RemoteDB 12 ops []*protodb.Operation 13 } 14 15 var _ db.Batch = (*batch)(nil) 16 17 func newBatch(rdb *RemoteDB) *batch { 18 return &batch{ 19 db: rdb, 20 ops: []*protodb.Operation{}, 21 } 22 } 23 24 func (b *batch) assertOpen() { 25 if b.ops == nil { 26 panic("batch has been written or closed") 27 } 28 } 29 30 // Set implements Batch. 31 func (b *batch) Set(key, value []byte) { 32 b.assertOpen() 33 op := &protodb.Operation{ 34 Entity: &protodb.Entity{Key: key, Value: value}, 35 Type: protodb.Operation_SET, 36 } 37 b.ops = append(b.ops, op) 38 } 39 40 // Delete implements Batch. 41 func (b *batch) Delete(key []byte) { 42 b.assertOpen() 43 op := &protodb.Operation{ 44 Entity: &protodb.Entity{Key: key}, 45 Type: protodb.Operation_DELETE, 46 } 47 b.ops = append(b.ops, op) 48 } 49 50 // Write implements Batch. 51 func (b *batch) Write() error { 52 b.assertOpen() 53 _, err := b.db.dc.BatchWrite(b.db.ctx, &protodb.Batch{Ops: b.ops}) 54 if err != nil { 55 return errors.Errorf("remoteDB.BatchWrite: %v", err) 56 } 57 // Make sure batch cannot be used afterwards. Callers should still call Close(), for errors. 58 b.Close() 59 return nil 60 } 61 62 // WriteSync implements Batch. 63 func (b *batch) WriteSync() error { 64 b.assertOpen() 65 _, err := b.db.dc.BatchWriteSync(b.db.ctx, &protodb.Batch{Ops: b.ops}) 66 if err != nil { 67 return errors.Errorf("RemoteDB.BatchWriteSync: %v", err) 68 } 69 // Make sure batch cannot be used afterwards. Callers should still call Close(), for errors. 70 b.Close() 71 return nil 72 } 73 74 // Close implements Batch. 75 func (b *batch) Close() { 76 b.ops = nil 77 }