-
Notifications
You must be signed in to change notification settings - Fork 0
/
tempdb.go
131 lines (98 loc) · 2.21 KB
/
tempdb.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package tempdb
import (
"errors"
"io"
"log/slog"
"sync"
"github.com/btcsuite/btcwallet/walletdb"
)
var ErrUnimplemented = errors.New("unimplemented")
// Ensure `DB` complies with the `walletdb.DB` interface.
var _ walletdb.DB = (*DB)(nil)
var Logger *slog.Logger
type DB struct {
Path string
State *State
lock sync.Mutex
}
func (db *DB) BeginReadTx() (walletdb.ReadTx, error) {
Logger.Debug("begin read transaction")
return newTransaction(db.State, nil), nil
}
func (db *DB) BeginReadWriteTx() (walletdb.ReadWriteTx, error) {
Logger.Debug("begin read/write transaction")
return newTransaction(db.State, &db.lock), nil
}
func (db *DB) View(f func(tx walletdb.ReadTx) error, reset func()) error {
Logger.Debug("new view")
reset()
tx, err := db.BeginReadTx()
if err != nil {
return err
}
return f(tx)
}
func (db *DB) Update(fn func(tx walletdb.ReadWriteTx) error, reset func()) error {
Logger.Debug("new update")
reset()
tx, err := db.BeginReadWriteTx()
if err != nil {
return err
}
err = fn(tx)
if err != nil {
tx.Rollback()
return err
}
// cast to a TempDB transaction.
ttx := tx.(*Transaction)
if ttx.Rolledback {
return nil
}
return tx.Commit()
}
func (db *DB) Batch(fn func(tx walletdb.ReadWriteTx) error) error {
Logger.Debug("new batch")
return db.Update(fn, func() {})
}
func (sl *DB) Close() error {
return nil
}
// unimplemented.
func (sl *DB) Copy(w io.Writer) error {
return ErrUnimplemented
}
// unimplemented.
func (sl *DB) PrintStats() string {
return ErrUnimplemented.Error()
}
func New(args ...any) (walletdb.DB, error) {
if Logger == nil {
Logger = slog.New(slog.NewTextHandler(io.Discard, nil))
}
if len(args) < 1 {
return nil, errors.New("path argument is required")
}
path, ok := args[0].(string)
if !ok {
return nil, errors.New("path argument is not a string")
}
return &DB{
Path: path,
State: &State{},
}, nil
}
// Open always returns `walletdb.ErrDbDoesNotExist` because tempdb is not persistent.
func Open(args ...any) (walletdb.DB, error) {
return nil, walletdb.ErrDbDoesNotExist
}
func init() {
err := walletdb.RegisterDriver(walletdb.Driver{
DbType: "tempdb",
Create: New,
Open: Open,
})
if err != nil {
panic(err)
}
}