Fix serializer with empty string

This commit is contained in:
Jinzhu 2022-07-11 11:51:05 +08:00
parent b13d1757fa
commit 62fdc2bb3b
3 changed files with 17 additions and 5 deletions

View File

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

View File

@ -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 => ../

View File

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