-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
142 lines (110 loc) · 2.23 KB
/
store.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
132
133
134
135
136
137
138
139
140
141
142
package dilawar
import (
"encoding/binary"
"encoding/json"
"fmt"
"os"
"path"
"time"
"github.com/boltdb/bolt"
"github.com/mitchellh/go-homedir"
)
type Store struct{}
const (
rcPath = "/.dilawar"
dbName = "data.db"
)
func itob(v int) []byte {
return uint64tob(uint64(v))
}
func uint64tob(v uint64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, v)
return b
}
func connect() (*bolt.DB, error) {
h, err := homedir.Dir()
if err != nil {
return nil, err
}
rc := path.Join(h, rcPath)
if _, err := os.Stat(rc); os.IsNotExist(err) {
os.Mkdir(rc, os.ModePerm)
}
return bolt.Open(path.Join(rc, dbName), 0600, &bolt.Options{Timeout: 1 * time.Second})
}
func NewStore() *Store {
return &Store{}
}
func (s *Store) Create(t *Transaction) error {
db, err := connect()
if err != nil {
return err
}
defer db.Close()
return db.Update(func(tx *bolt.Tx) error {
name := []byte("transactions")
b, err := tx.CreateBucketIfNotExists(name)
if err != nil {
return err
}
t.ID, err = b.NextSequence()
if err != nil {
return err
}
t.Time = time.Now()
buf, err := json.Marshal(t)
if err != nil {
return err
}
return b.Put(uint64tob(t.ID), []byte(buf))
})
}
func (s *Store) Read(id int) (*Transaction, error) {
db, err := connect()
if err != nil {
return nil, err
}
defer db.Close()
t := Transaction{}
if err := db.View(func(tx *bolt.Tx) error {
name := []byte("transactions")
b := tx.Bucket(name)
if b == nil {
return fmt.Errorf("no record found")
}
if buf := b.Get(itob(id)); buf != nil {
return json.Unmarshal(buf, &t)
}
return fmt.Errorf("no record found")
}); err != nil {
return nil, err
}
return &t, nil
}
func (s *Store) List() ([]Transaction, error) {
db, err := connect()
if err != nil {
return nil, err
}
defer db.Close()
list := []Transaction{}
if err := db.View(func(tx *bolt.Tx) error {
name := []byte("transactions")
b := tx.Bucket(name)
if b == nil {
return fmt.Errorf("no record found")
}
return b.ForEach(func(k, v []byte) error {
t := Transaction{}
if err := json.Unmarshal(v, &t); err != nil {
return err
}
list = append(list, t)
return nil
})
}); err != nil {
return nil, err
}
return list, nil
}