Skip to content

Commit

Permalink
✨ add support for time.Time
Browse files Browse the repository at this point in the history
  • Loading branch information
Kawin Viriyaprasopsook committed Feb 15, 2024
1 parent 6c14e57 commit 6de43a1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
7 changes: 7 additions & 0 deletions gonull.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"reflect"
"time"
)

var (
Expand Down Expand Up @@ -114,6 +115,12 @@ func convertToDriverValue(v any) (driver.Value, error) {
case reflect.String:
return rv.String(), nil

case reflect.Struct:
if t, ok := v.(time.Time); ok {
return t, nil
}
return nil, fmt.Errorf("unsupported struct type: %s", rv.Type())

default:
return nil, fmt.Errorf("unsupported type: %T", v)
}
Expand Down
9 changes: 9 additions & 0 deletions gonull_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"reflect"
"testing"
"time"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -344,6 +345,10 @@ func TestConvertToTypeWithNilValue(t *testing.T) {
name: "Nil to string",
expected: "",
},
{
name: "Nil to time.Time",
expected: time.Time{},
},
}

for _, tc := range tests {
Expand Down Expand Up @@ -380,6 +385,8 @@ func TestConvertToTypeWithNilValue(t *testing.T) {
result, err = convertToType[bool](nil)
case string:
result, err = convertToType[string](nil)
case time.Time:
result, err = convertToType[time.Time](nil)
}

assert.NoError(t, err)
Expand Down Expand Up @@ -531,6 +538,7 @@ func TestConvertToDriverValue(t *testing.T) {
float64Val float64 = 123.456
boolVal bool = true
stringVal string = "test"
timeVal time.Time = time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC)
byteSlice []byte = []byte("byte slice")
ptrToInt *int = &intVal
nilPtr *int = nil
Expand Down Expand Up @@ -560,6 +568,7 @@ func TestConvertToDriverValue(t *testing.T) {
{"Bool", boolVal, boolVal, false},
{"String", stringVal, stringVal, false},
{"ByteSlice", byteSlice, byteSlice, false},
{"Time", timeVal, timeVal, false},
{"PointerToInt", ptrToInt, int64(*ptrToInt), false},
{"NilPointer", nilPtr, nil, false},
{"UnsupportedType", struct{}{}, nil, true},
Expand Down

0 comments on commit 6de43a1

Please sign in to comment.