forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.go
66 lines (56 loc) · 1.29 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
package utils
import (
"database/sql/driver"
"encoding/json"
"errors"
)
// NullMap is a one level deep dictionary that is represented as JSON in the database
type NullMap struct {
Map map[string]interface{}
Valid bool
}
// Scan implements the Scanner interface for decoding from a database
func (n *NullMap) Scan(src interface{}) error {
if src == nil {
return nil
}
var source []byte
switch src.(type) {
case string:
source = []byte(src.(string))
case []byte:
source = src.([]byte)
default:
return errors.New("Incompatible type for NullDict")
}
// 0 length is same as nil
if len(source) == 0 {
return nil
}
n.Map = make(map[string]interface{})
n.Valid = true
return json.Unmarshal(source, &n.Map)
}
// Value implements the driver Valuer interface
func (n *NullMap) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return json.Marshal(n.Map)
}
// MarshalJSON decodes our dictionary from the passed in bytes
func (n *NullMap) MarshalJSON() ([]byte, error) {
if !n.Valid {
return nil, nil
}
return json.Marshal(n.Map)
}
// UnmarshalJSON sets our dict from the passed in data
func (n *NullMap) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return nil
}
n.Map = make(map[string]interface{})
n.Valid = true
return json.Unmarshal(data, &n.Map)
}