Last active
May 13, 2019 15:01
-
-
Save dgellow/5ec252572699bb917ba4c77697ee1dde to your computer and use it in GitHub Desktop.
Golang implementation of sql.NullInt64 for int 32 (aka nullInt32)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NullInt32 is the equivalent of sql.NullInt64 but for 32-bits integers. It offers the guarantee that integers | |
// serialized or deserialized are in the range of math.MinInt32 to math.MaxInt32. Errors are returned by Scan() if | |
// that's not the case. | |
type NullInt32 struct { | |
Int32 int | |
Valid bool // Valid is true if Int32 is not NULL | |
} | |
func (n *NullInt32) Scan(value interface{}) error { | |
var n64 sql.NullInt64 | |
if err := n64.Scan(value); err != nil { | |
return err | |
} | |
if !n64.Valid { | |
n.Int32 = 0 | |
n.Valid = false | |
return nil | |
} | |
i64 := n64.Int64 | |
if i64 > math.MaxInt32 { | |
return errors.New("value higher than max int32") | |
} | |
if i64 < math.MinInt32 { | |
return errors.New("value lower than min int32") | |
} | |
n.Int32 = (int)(n64.Int64) | |
n.Valid = true | |
return nil | |
} | |
func (n NullInt32) Value() (driver.Value, error) { | |
if !n.Valid { | |
return nil, nil | |
} | |
return int64(n.Int32), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment