You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ims/util/db/dts/null_uint.go

74 lines
1.2 KiB

package dts
import (
"database/sql"
"database/sql/driver"
"encoding/json"
)
type NullUint struct {
Uint uint
Valid bool // Valid is true if Uint is not NULL
}
func NewNullUint(n uint) NullUint {
return NullUint{
Uint: n,
Valid: n > 0,
}
}
func (n NullUint) Any() any {
if n.Valid {
return n.Uint
}
return nil
}
// Scan implements the Scanner interface.
func (n *NullUint) Scan(value any) error {
if value == nil {
n.Uint, n.Valid = 0, false
return nil
}
ni := new(sql.NullInt64)
err := ni.Scan(value)
if err != nil {
return err
}
if !ni.Valid {
n.Uint, n.Valid = 0, false
return nil
}
n.Uint = uint(ni.Int64)
n.Valid = true
return nil
}
// Value implements the driver Valuer interface.
func (n NullUint) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// 注意:driver.Value 不支持 unit
return int64(n.Uint), nil
}
func (n NullUint) MarshalJSON() ([]byte, error) {
if n.Valid {
return json.Marshal(n.Uint)
}
return json.Marshal(nil)
}
func (n *NullUint) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
n.Valid = false
return nil
}
err := json.Unmarshal(b, &n.Uint)
if err == nil {
n.Valid = true
}
return err
}