From c9c2b726f07ac83fa8de39d7bc120249c24a9d1d Mon Sep 17 00:00:00 2001 From: Luka Giorgadze <6573695+LukaGiorgadze@users.noreply.github.com> Date: Sun, 7 May 2023 16:23:20 +0400 Subject: [PATCH] Bugfix/int64 (#6) * handle int64 * int64 fix v2 * remove driver * int64 comment --- gonull.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/gonull.go b/gonull.go index 4bf3975..b20a29e 100644 --- a/gonull.go +++ b/gonull.go @@ -6,6 +6,7 @@ import ( "database/sql/driver" "encoding/json" "errors" + "reflect" ) var ( @@ -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. @@ -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 }