This repository was archived by the owner on Jan 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathbatch.go
More file actions
93 lines (76 loc) · 1.9 KB
/
batch.go
File metadata and controls
93 lines (76 loc) · 1.9 KB
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
85
86
87
88
89
90
91
92
93
//go:build sqliteBackend
// +build sqliteBackend
package sqlite
import (
"database/sql"
"fmt"
)
type batchAction int
const (
batchActionSet batchAction = 0
batchActionDel batchAction = 1
)
type batchOp struct {
action batchAction
storeKey string
key, value []byte
}
type Batch struct {
tx *sql.Tx
ops []batchOp
size int
version int64
}
func NewBatch(storage *sql.DB, version int64) (*Batch, error) {
tx, err := storage.Begin()
if err != nil {
return nil, fmt.Errorf("failed to create SQL transaction: %w", err)
}
return &Batch{
tx: tx,
ops: make([]batchOp, 0),
version: version,
}, nil
}
func (b *Batch) Size() int {
return b.size
}
func (b *Batch) Reset() {
b.ops = nil
b.ops = make([]batchOp, 0)
b.size = 0
}
func (b *Batch) Set(storeKey string, key, value []byte) error {
b.size += len(key) + len(value)
b.ops = append(b.ops, batchOp{action: batchActionSet, storeKey: storeKey, key: key, value: value})
return nil
}
func (b *Batch) Delete(storeKey string, key []byte) error {
b.size += len(key)
b.ops = append(b.ops, batchOp{action: batchActionDel, storeKey: storeKey, key: key})
return nil
}
func (b *Batch) Write() error {
_, err := b.tx.Exec(latestVersionStmt, reservedStoreKey, keyLatestHeight, b.version, 0, b.version)
if err != nil {
return fmt.Errorf("failed to exec SQL statement: %w", err)
}
for _, op := range b.ops {
switch op.action {
case batchActionSet:
_, err := b.tx.Exec(upsertStmt, op.storeKey, op.key, op.value, b.version, op.value)
if err != nil {
return fmt.Errorf("failed to exec SQL statement: %w", err)
}
case batchActionDel:
_, err := b.tx.Exec(delStmt, b.version, op.storeKey, op.key, b.version)
if err != nil {
return fmt.Errorf("failed to exec SQL statement: %w", err)
}
}
}
if err := b.tx.Commit(); err != nil {
return fmt.Errorf("failed to write SQL transaction: %w", err)
}
return nil
}