Skip to content

Commit 36e26e3

Browse files
lunnypeihexian
andcommitted
解决Conversion接口ToDB() ([]byte, error)方法返回*Type值为nil时,数据类型为[]byte(nil)的… (go-xorm#1296)
add test 解决Conversion接口ToDB() ([]byte, error)方法返回*Type值为nil时,数据类型为[]byte(nil)的bug,解决*Type值为nil时插入数据变为""的bug Co-authored-by: peihexian <[email protected]> Reviewed-on: https://gitea.com/xorm/xorm/pulls/1296
1 parent f13883a commit 36e26e3

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

internal/statements/values.go

+3
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ func (statement *Statement) Value2Interface(col *schemas.Column, fieldValue refl
4444
if col.SQLType.IsBlob() {
4545
return data, nil
4646
}
47+
if nil == data {
48+
return nil, nil
49+
}
4750
return string(data), nil
4851
}
4952

types_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,17 @@ type ConvConfig struct {
119119
}
120120

121121
func (s *ConvConfig) FromDB(data []byte) error {
122+
if data == nil {
123+
s = nil
124+
return nil
125+
}
122126
return json.DefaultJSONHandler.Unmarshal(data, s)
123127
}
124128

125129
func (s *ConvConfig) ToDB() ([]byte, error) {
130+
if s == nil {
131+
return nil, nil
132+
}
126133
return json.DefaultJSONHandler.Marshal(s)
127134
}
128135

@@ -184,6 +191,30 @@ func TestConversion(t *testing.T) {
184191
assert.EqualValues(t, 2, len(c1.Slice))
185192
assert.EqualValues(t, *c.Slice[0], *c1.Slice[0])
186193
assert.EqualValues(t, *c.Slice[1], *c1.Slice[1])
194+
195+
cnt, err := testEngine.Where("1=1").Delete(new(ConvStruct))
196+
assert.NoError(t, err)
197+
assert.EqualValues(t, 1, cnt)
198+
199+
c.Cfg2 = nil
200+
201+
_, err = testEngine.Insert(c)
202+
assert.NoError(t, err)
203+
204+
c2 := new(ConvStruct)
205+
has, err = testEngine.Get(c2)
206+
assert.NoError(t, err)
207+
assert.True(t, has)
208+
assert.EqualValues(t, "prefix---tttt", string(c2.Conv))
209+
assert.NotNil(t, c2.Conv2)
210+
assert.EqualValues(t, "prefix---"+s, *c2.Conv2)
211+
assert.EqualValues(t, c.Cfg1, c2.Cfg1)
212+
assert.Nil(t, c2.Cfg2)
213+
assert.NotNil(t, c2.Cfg3)
214+
assert.EqualValues(t, *c.Cfg3.(*ConvConfig), *c2.Cfg3.(*ConvConfig))
215+
assert.EqualValues(t, 2, len(c2.Slice))
216+
assert.EqualValues(t, *c.Slice[0], *c2.Slice[0])
217+
assert.EqualValues(t, *c.Slice[1], *c2.Slice[1])
187218
}
188219

189220
type MyInt int

0 commit comments

Comments
 (0)