-
Notifications
You must be signed in to change notification settings - Fork 346
/
db.go
111 lines (99 loc) · 2.34 KB
/
db.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
package builtin
import (
"context"
"fmt"
"github.com/boltdb/bolt"
"github.com/micromdm/micromdm/platform/profile"
"github.com/pkg/errors"
)
const (
ProfileBucket = "mdm.Profile"
)
type DB struct {
*bolt.DB
}
func NewDB(db *bolt.DB) (*DB, error) {
err := db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(ProfileBucket))
return err
})
if err != nil {
return nil, errors.Wrapf(err, "creating %s bucket", ProfileBucket)
}
datastore := &DB{
DB: db,
}
return datastore, nil
}
func (db *DB) List() ([]profile.Profile, error) {
// TODO add filter/limit with ForEach
var list []profile.Profile
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(ProfileBucket))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
var p profile.Profile
if err := profile.UnmarshalProfile(v, &p); err != nil {
return err
}
list = append(list, p)
}
return nil
})
return list, err
}
func (db *DB) Save(p *profile.Profile) error {
err := p.Validate()
if err != nil {
return err
}
tx, err := db.DB.Begin(true)
if err != nil {
return errors.Wrap(err, "begin transaction")
}
bkt := tx.Bucket([]byte(ProfileBucket))
if bkt == nil {
return fmt.Errorf("bucket %q not found!", ProfileBucket)
}
pproto, err := profile.MarshalProfile(p)
if err != nil {
return errors.Wrap(err, "marshalling profile")
}
if err := bkt.Put([]byte(p.Identifier), pproto); err != nil {
return errors.Wrap(err, "put profile to boltdb")
}
return tx.Commit()
}
func (db *DB) ProfileById(ctx context.Context, id string) (*profile.Profile, error) {
var p profile.Profile
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(ProfileBucket))
v := b.Get([]byte(id))
if v == nil {
return ¬Found{"Profile", fmt.Sprintf("id %s", id)}
}
return profile.UnmarshalProfile(v, &p)
})
return &p, err
}
func (db *DB) Delete(id string) error {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(ProfileBucket))
v := b.Get([]byte(id))
if v == nil {
return ¬Found{"Profile", fmt.Sprintf("id %s", id)}
}
return b.Delete([]byte(id))
})
return err
}
type notFound struct {
ResourceType string
Message string
}
func (e *notFound) Error() string {
return fmt.Sprintf("not found: %s %s", e.ResourceType, e.Message)
}
func (e *notFound) NotFound() bool {
return true
}