Skip to content

Commit

Permalink
Merge pull request #12 from maku693/fix-uint64-scan
Browse files Browse the repository at this point in the history
Fix Uint64.Scan() to convert negative int64 to uint64
  • Loading branch information
aarondl authored Feb 22, 2021
2 parents c1106c4 + 057ceb6 commit 6ee82df
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
github.com/friendsofgo/errors v0.9.2 h1:X6NYxef4efCBdwI7BgS820zFaN7Cphrmb+Pljdzjtgk=
github.com/friendsofgo/errors v0.9.2/go.mod h1:yCvFW5AkDIL9qn7suHVLiI/gH228n7PC4Pn44IGoTOI=
github.com/gofrs/uuid v3.2.0+incompatible h1:y12jRkkFxsd7GpqdSZ+/KCs/fJbqpEXSGd4+jfEaewE=
github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/volatiletech/inflect v0.0.1 h1:2a6FcMQyhmPZcLa+uet3VJ8gLn/9svWhJxJYwvE8KsU=
github.com/volatiletech/inflect v0.0.1/go.mod h1:IBti31tG6phkHitLlr5j7shC5SOo//x0AjDzaJU1PLA=
Expand Down
7 changes: 7 additions & 0 deletions uint64.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@ func (u *Uint64) Scan(value interface{}) error {
return nil
}
u.Valid = true

// If value is negative int64, convert it to uint64
if i, ok := value.(int64); ok && i < 0 {
return convert.ConvertAssign(&u.Uint64, uint64(i))
}

return convert.ConvertAssign(&u.Uint64, value)
}

Expand All @@ -118,6 +124,7 @@ func (u Uint64) Value() (driver.Value, error) {
return nil, nil
}

// If u.Uint64 overflows the range of int64, convert it to string
if u.Uint64 >= 1<<63 {
return strconv.FormatUint(u.Uint64, 10), nil
}
Expand Down
9 changes: 6 additions & 3 deletions uint64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,13 @@ func TestUint64Scan(t *testing.T) {
maybePanic(err)
assertUint64(t, i, "scanned uint64")

var null Uint64
err = null.Scan(nil)
err = i.Scan(int64(-2))
maybePanic(err)
assertUint64(t, i, "scanned int64")

err = i.Scan(nil)
maybePanic(err)
assertNullUint64(t, null, "scanned null")
assertNullUint64(t, i, "scanned null")
}

func assertUint64(t *testing.T, i Uint64, from string) {
Expand Down

0 comments on commit 6ee82df

Please sign in to comment.