-
Notifications
You must be signed in to change notification settings - Fork 2
/
null_int64.go
63 lines (57 loc) · 1.17 KB
/
null_int64.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
package gosql
import (
"database/sql/driver"
"encoding/json"
"strconv"
)
// NullInt64 holds an int64 value that might be null in the database.
type NullInt64 struct {
Int64 int64
Valid bool
}
// Scan implements the Scanner interface.
func (n *NullInt64) Scan(value interface{}) error {
if value == nil {
n.Valid = false
return nil
}
n.Valid = true
switch value.(type) {
case int64:
n.Int64 = value.(int64)
case []byte:
i, err := strconv.ParseInt(string(value.([]byte)), 10, 64)
if err != nil {
return err
}
n.Int64 = i
}
return nil
}
// Value implements the driver Valuer interface.
func (n NullInt64) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Int64, nil
}
// MarshalJSON implements the Marshaler interface.
func (n NullInt64) MarshalJSON() ([]byte, error) {
if n.Valid {
return json.Marshal(n.Int64)
}
return json.Marshal(nil)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (n *NullInt64) UnmarshalJSON(data []byte) error {
var i64 *int64
if err := json.Unmarshal(data, &i64); err != nil {
return err
}
if i64 != nil {
n.Int64, n.Valid = *i64, true
} else {
n.Valid = false
}
return nil
}