From 74e07b049c446bd0f1102c9f7c164558648850bd Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 11 Apr 2022 22:07:40 +0800 Subject: [PATCH] Serializer unixtime support ptr of int --- schema/serializer.go | 8 ++++---- tests/serializer_test.go | 3 +++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/schema/serializer.go b/schema/serializer.go index 09da6d9e..758a6421 100644 --- a/schema/serializer.go +++ b/schema/serializer.go @@ -108,8 +108,8 @@ type UnixSecondSerializer struct { // Scan implements serializer interface func (UnixSecondSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error) { t := sql.NullTime{} - if err = t.Scan(dbValue); err == nil { - err = field.Set(ctx, dst, t.Time) + if err = t.Scan(dbValue); err == nil && t.Valid { + err = field.Set(ctx, dst, t.Time.Unix()) } return @@ -118,8 +118,8 @@ func (UnixSecondSerializer) Scan(ctx context.Context, field *Field, dst reflect. // Value implements serializer interface func (UnixSecondSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (result interface{}, err error) { switch v := fieldValue.(type) { - case int64, int, uint, uint64, int32, uint32, int16, uint16: - result = time.Unix(reflect.ValueOf(v).Int(), 0) + case int64, int, uint, uint64, int32, uint32, int16, uint16, *int64, *int, *uint, *uint64, *int32, *uint32, *int16, *uint16: + result = time.Unix(reflect.Indirect(reflect.ValueOf(v)).Int(), 0) default: err = fmt.Errorf("invalid field type %#v for UnixSecondSerializer, only int, uint supported", v) } diff --git a/tests/serializer_test.go b/tests/serializer_test.go index ce60280e..ee14841a 100644 --- a/tests/serializer_test.go +++ b/tests/serializer_test.go @@ -21,6 +21,7 @@ type SerializerStruct struct { Contracts map[string]interface{} `gorm:"serializer:json"` JobInfo Job `gorm:"type:bytes;serializer:gob"` CreatedTime int64 `gorm:"serializer:unixtime;type:time"` // store time in db, use int as field type + UpdatedTime *int64 `gorm:"serializer:unixtime;type:time"` // store time in db, use int as field type EncryptedString EncryptedString } @@ -58,6 +59,7 @@ func TestSerializer(t *testing.T) { } createdAt := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + updatedAt := createdAt.Unix() data := SerializerStruct{ Name: []byte("jinzhu"), @@ -65,6 +67,7 @@ func TestSerializer(t *testing.T) { Contracts: map[string]interface{}{"name": "jinzhu", "age": 10}, EncryptedString: EncryptedString("pass"), CreatedTime: createdAt.Unix(), + UpdatedTime: &updatedAt, JobInfo: Job{ Title: "programmer", Number: 9920,