-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
68 lines (54 loc) · 1.13 KB
/
database.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
package main
import (
"encoding/json"
bolt "go.etcd.io/bbolt"
)
func OpenDatabase(filename string) error {
var err error
App.db, err = bolt.Open(filename, 0600, nil)
if err != nil {
return err
}
err = App.db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists([]byte("messages"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("questions"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("teams"))
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
if App.config.MigrateToTeam != "" {
return migrateDatabase()
}
return nil
}
func migrateDatabase() error {
return App.db.Update(func(tx *bolt.Tx) error {
questions := tx.Bucket([]byte("questions"))
return questions.ForEach(func(k, v []byte) error {
var question Question
err := json.Unmarshal(v, &question)
if err != nil {
return err
}
if question.TeamID == "" {
question.TeamID = App.config.MigrateToTeam
}
data, err := json.Marshal(question)
if err != nil {
return err
}
return questions.Put(k, data)
})
})
}