Fix uninitialized Valuer return time.Time, close #3214

This commit is contained in:
Jinzhu 2020-07-30 17:36:39 +08:00
parent 7c2ecdfc1c
commit 47a5196734
2 changed files with 32 additions and 14 deletions

View File

@ -213,6 +213,8 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field {
case reflect.Struct:
if _, ok := fieldValue.Interface().(*time.Time); ok {
field.DataType = Time
} else if fieldValue.Type().ConvertibleTo(reflect.TypeOf(time.Time{})) {
field.DataType = Time
} else if fieldValue.Type().ConvertibleTo(reflect.TypeOf(&time.Time{})) {
field.DataType = Time
}

View File

@ -124,20 +124,21 @@ func TestInvalidValuer(t *testing.T) {
type ScannerValuerStruct struct {
gorm.Model
Name sql.NullString
Gender *sql.NullString
Age sql.NullInt64
Male sql.NullBool
Height sql.NullFloat64
Birthday sql.NullTime
Password EncryptedData
Bytes []byte
Num Num
Strings StringsSlice
Structs StructsSlice
Role Role
UserID *sql.NullInt64
User User
Name sql.NullString
Gender *sql.NullString
Age sql.NullInt64
Male sql.NullBool
Height sql.NullFloat64
Birthday sql.NullTime
Password EncryptedData
Bytes []byte
Num Num
Strings StringsSlice
Structs StructsSlice
Role Role
UserID *sql.NullInt64
User User
EmptyTime EmptyTime
}
type EncryptedData []byte
@ -244,3 +245,18 @@ func (role Role) Value() (driver.Value, error) {
func (role Role) IsAdmin() bool {
return role.Name == "admin"
}
type EmptyTime struct {
time.Time
}
func (t *EmptyTime) Scan(v interface{}) error {
nullTime := sql.NullTime{}
err := nullTime.Scan(v)
t.Time = nullTime.Time
return err
}
func (t EmptyTime) Value() (driver.Value, error) {
return t.Time, nil
}