-
Notifications
You must be signed in to change notification settings - Fork 66
/
database.go
79 lines (62 loc) · 1.15 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
69
70
71
72
73
74
75
76
77
78
79
package util
import (
"database/sql/driver"
"encoding/json"
"fmt"
"github.com/filecoin-project/go-address"
"github.com/ipfs/go-cid"
)
type DbAddr struct {
Addr address.Address
}
func (dba *DbAddr) Scan(v interface{}) error {
s, ok := v.(string)
if !ok {
return fmt.Errorf("DbAddrs must be strings")
}
addr, err := address.NewFromString(s)
if err != nil {
return err
}
dba.Addr = addr
return nil
}
func (dba DbAddr) Value() (driver.Value, error) {
return dba.Addr.String(), nil
}
type DbCID struct {
CID cid.Cid
}
func (dbc *DbCID) Scan(v interface{}) error {
b, ok := v.([]byte)
if !ok {
return fmt.Errorf("dbcids must get bytes!")
}
if len(b) == 0 {
return nil
}
c, err := cid.Cast(b)
if err != nil {
return err
}
dbc.CID = c
return nil
}
func (dbc DbCID) Value() (driver.Value, error) {
return dbc.CID.Bytes(), nil
}
func (dbc DbCID) MarshalJSON() ([]byte, error) {
return json.Marshal(dbc.CID.String())
}
func (dbc *DbCID) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
c, err := cid.Decode(s)
if err != nil {
return err
}
dbc.CID = c
return nil
}