-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
61 lines (51 loc) · 1.06 KB
/
database.go
File metadata and controls
61 lines (51 loc) · 1.06 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
package kvdb
import (
"sync"
. "github.com/tinywasm/fmt"
)
type pair struct {
Key string
Value string
}
// LoggerFunc is a simple logger that accepts any values (like fmt.Println).
// Use a nil LoggerFunc when you want no-op logging; New will set a safe default.
type LoggerFunc func(...any)
type TinyDB struct {
name string
data []pair
log LoggerFunc
store Store
raw *Conv
mu sync.RWMutex
}
// New creates or loads a database
func New(name string, log LoggerFunc, store Store) (*TinyDB, error) {
if log == nil {
log = func(...any) {}
}
db := &TinyDB{
name: name,
data: make([]pair, 0),
log: log,
store: store,
raw: Convert(),
}
// try to load DB from Store
raw, err := store.GetFile(name)
if err == nil && len(raw) > 0 {
lines := Convert(string(raw)).Split("\n")
for _, line := range lines {
if Convert(line).TrimSpace().String() == "" {
continue
}
kv := Convert(line).Split("=")
if len(kv) == 2 {
db.data = append(db.data, pair{
Key: kv[0],
Value: kv[1],
})
}
}
}
return db, nil
}