Serializer unixtime support ptr of int

This commit is contained in:
Jinzhu 2022-04-11 22:07:40 +08:00
parent 41bef26f13
commit 74e07b049c
2 changed files with 7 additions and 4 deletions

View File

@ -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)
}

View File

@ -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,