Skip to content

Commit

Permalink
Bugfix/int64 (#6)
Browse files Browse the repository at this point in the history
* handle int64

* int64 fix v2

* remove driver

* int64 comment
  • Loading branch information
LukaGiorgadze committed May 7, 2023
1 parent 0b0630d commit c9c2b72
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions gonull.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"database/sql/driver"
"encoding/json"
"errors"
"reflect"
)

var (
Expand Down Expand Up @@ -52,7 +53,7 @@ func (n Nullable[T]) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return driver.Value(n.Val), nil
return n.Val, nil
}

// UnmarshalJSON implements the json.Unmarshaler interface for Nullable, allowing it to be used as a nullable field in JSON operations.
Expand Down Expand Up @@ -96,8 +97,18 @@ func convertToType[T any](value interface{}) (T, error) {
switch v := value.(type) {
case T:
return v, nil
default:
var zero T
return zero, ErrUnsupportedConversion
case int64:
// This case handles the situation when the input value is of type int64.
// It attempts to convert the int64 value to the target numeric type T if possible.
// If the conversion is successful, it returns the converted value of type T and a nil error.
// If the conversion is not possible, the function will continue to the next case (return an error).
switch t := reflect.Zero(reflect.TypeOf((*T)(nil)).Elem()).Interface().(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
if reflect.TypeOf(t).ConvertibleTo(reflect.TypeOf((*T)(nil)).Elem()) {
return reflect.ValueOf(value).Convert(reflect.TypeOf((*T)(nil)).Elem()).Interface().(T), nil
}
}
}
var zero T
return zero, ErrUnsupportedConversion
}

0 comments on commit c9c2b72

Please sign in to comment.