From 62fdc2bb3b4f991a8ed1ec2fdb47571a64fd18ef Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 11 Jul 2022 11:51:05 +0800 Subject: [PATCH] Fix serializer with empty string --- schema/serializer.go | 10 +++++++--- tests/go.mod | 4 ++-- tests/serializer_test.go | 8 ++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/schema/serializer.go b/schema/serializer.go index 758a6421..21be3c35 100644 --- a/schema/serializer.go +++ b/schema/serializer.go @@ -88,7 +88,9 @@ func (JSONSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, return fmt.Errorf("failed to unmarshal JSONB value: %#v", dbValue) } - err = json.Unmarshal(bytes, fieldValue.Interface()) + if len(bytes) > 0 { + err = json.Unmarshal(bytes, fieldValue.Interface()) + } } field.ReflectValueOf(ctx, dst).Set(fieldValue.Elem()) @@ -142,8 +144,10 @@ func (GobSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, default: return fmt.Errorf("failed to unmarshal gob value: %#v", dbValue) } - decoder := gob.NewDecoder(bytes.NewBuffer(bytesValue)) - err = decoder.Decode(fieldValue.Interface()) + if len(bytesValue) > 0 { + decoder := gob.NewDecoder(bytes.NewBuffer(bytesValue)) + err = decoder.Decode(fieldValue.Interface()) + } } field.ReflectValueOf(ctx, dst).Set(fieldValue.Elem()) return diff --git a/tests/go.mod b/tests/go.mod index f3e9d260..7a788a43 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -10,11 +10,11 @@ require ( github.com/lib/pq v1.10.6 github.com/mattn/go-sqlite3 v1.14.14 // indirect golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect - gorm.io/driver/mysql v1.3.4 + gorm.io/driver/mysql v1.3.5 gorm.io/driver/postgres v1.3.8 gorm.io/driver/sqlite v1.3.6 gorm.io/driver/sqlserver v1.3.2 - gorm.io/gorm v1.23.7 + gorm.io/gorm v1.23.8 ) replace gorm.io/gorm => ../ diff --git a/tests/serializer_test.go b/tests/serializer_test.go index 7232f9df..95d25699 100644 --- a/tests/serializer_test.go +++ b/tests/serializer_test.go @@ -113,6 +113,14 @@ func TestSerializer(t *testing.T) { } AssertEqual(t, result, data) + + if err := DB.Model(&result).Update("roles", "").Error; err != nil { + t.Fatalf("failed to update data's roles, got error %v", err) + } + + if err := DB.First(&result, data.ID).Error; err != nil { + t.Fatalf("failed to query data, got error %v", err) + } } func TestSerializerAssignFirstOrCreate(t *testing.T) {