-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstats_store.go
More file actions
78 lines (64 loc) · 1.68 KB
/
Copy pathstats_store.go
File metadata and controls
78 lines (64 loc) · 1.68 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
package leaf
import (
"encoding/json"
"fmt"
"io"
bolt "go.etcd.io/bbolt"
)
// StatsStore defines storage interface that is used for storing review stats.
type StatsStore interface {
io.Closer
// RangeStats iterates over all stats in a Store. DB records will be boxed to provide algoritm.
RangeStats(deck string, srs SRS, rangeFunc func(card string, stats *Stats) bool) error
// SaveStats saves stats for a card.
SaveStats(deck string, card string, stats *Stats) error
}
type boltStore struct {
bolt *bolt.DB
}
// OpenBoltStore returns a new StatsStore implemented on top of BoltDB.
func OpenBoltStore(filename string) (StatsStore, error) {
db, err := bolt.Open(filename, 0600, nil)
if err != nil {
return nil, fmt.Errorf("db: %s", db)
}
return &boltStore{db}, nil
}
func (db *boltStore) RangeStats(
deck string,
srs SRS,
rangeFunc func(card string, stats *Stats) bool,
) error {
return db.bolt.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(deck))
if err != nil {
return err
}
return b.ForEach(func(card, stats []byte) error {
s := NewStats(srs)
if err := json.Unmarshal(stats, s); err != nil {
return fmt.Errorf("json: %s", err)
}
if !rangeFunc(string(card), s) {
return nil
}
return nil
})
})
}
func (db *boltStore) SaveStats(deck string, card string, stats *Stats) error {
return db.bolt.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(deck))
if err != nil {
return err
}
data, err := json.Marshal(stats)
if err != nil {
return fmt.Errorf("json: %s", err)
}
return b.Put([]byte(card), data)
})
}
func (db *boltStore) Close() error {
return db.bolt.Close()
}