-
Notifications
You must be signed in to change notification settings - Fork 0
/
int.go
61 lines (54 loc) · 1.19 KB
/
int.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
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/json"
)
// Int holds a nullable int.
type Int struct {
// Int is the actual value when Valid.
Int int `exhaustruct:"optional"`
// Valid when no NULL-value is represented.
Valid bool
}
// NewInt returns a valid Int with the given value.
func NewInt(i int) Int {
return Int{
Int: i,
Valid: true,
}
}
// MarshalJSON marshals the int. If not valid, a NULL-value is returned.
func (i Int) MarshalJSON() ([]byte, error) {
if !i.Valid {
return json.Marshal(nil)
}
return json.Marshal(i.Int)
}
// UnmarshalJSON as int or sets Valid to false if null.
func (i *Int) UnmarshalJSON(data []byte) error {
if isNull(data) {
i.Valid = false
return nil
}
i.Valid = true
return json.Unmarshal(data, &i.Int)
}
// Scan to int value or not valid if nil.
func (i *Int) Scan(src any) error {
var sqlInt sql.NullInt64
err := sqlInt.Scan(src)
if err != nil {
return err
}
i.Valid = sqlInt.Valid
i.Int = int(sqlInt.Int64)
return nil
}
// Value returns the value for satisfying the driver.Valuer interface.
func (i Int) Value() (driver.Value, error) {
return sql.NullInt64{
Int64: int64(i.Int),
Valid: i.Valid,
}.Value()
}