Skip to content

Commit

Permalink
解决Conversion接口ToDB() ([]byte, error)方法返回*Type值为nil时,数据类型为[]byte(nil)的… (
Browse files Browse the repository at this point in the history
go-xorm#1296)

add test

解决Conversion接口ToDB() ([]byte, error)方法返回*Type值为nil时,数据类型为[]byte(nil)的bug,解决*Type值为nil时插入数据变为""的bug

Co-authored-by: peihexian <peihexian@qq.com>
Reviewed-on: https://gitea.com/xorm/xorm/pulls/1296
  • Loading branch information
lunny and peihexian committed Mar 10, 2020
1 parent f13883a commit 36e26e3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions internal/statements/values.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ func (statement *Statement) Value2Interface(col *schemas.Column, fieldValue refl
if col.SQLType.IsBlob() {
return data, nil
}
if nil == data {
return nil, nil
}
return string(data), nil
}

Expand Down
31 changes: 31 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,17 @@ type ConvConfig struct {
}

func (s *ConvConfig) FromDB(data []byte) error {
if data == nil {
s = nil
return nil
}
return json.DefaultJSONHandler.Unmarshal(data, s)
}

func (s *ConvConfig) ToDB() ([]byte, error) {
if s == nil {
return nil, nil
}
return json.DefaultJSONHandler.Marshal(s)
}

Expand Down Expand Up @@ -184,6 +191,30 @@ func TestConversion(t *testing.T) {
assert.EqualValues(t, 2, len(c1.Slice))
assert.EqualValues(t, *c.Slice[0], *c1.Slice[0])
assert.EqualValues(t, *c.Slice[1], *c1.Slice[1])

cnt, err := testEngine.Where("1=1").Delete(new(ConvStruct))
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)

c.Cfg2 = nil

_, err = testEngine.Insert(c)
assert.NoError(t, err)

c2 := new(ConvStruct)
has, err = testEngine.Get(c2)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, "prefix---tttt", string(c2.Conv))
assert.NotNil(t, c2.Conv2)
assert.EqualValues(t, "prefix---"+s, *c2.Conv2)
assert.EqualValues(t, c.Cfg1, c2.Cfg1)
assert.Nil(t, c2.Cfg2)
assert.NotNil(t, c2.Cfg3)
assert.EqualValues(t, *c.Cfg3.(*ConvConfig), *c2.Cfg3.(*ConvConfig))
assert.EqualValues(t, 2, len(c2.Slice))
assert.EqualValues(t, *c.Slice[0], *c2.Slice[0])
assert.EqualValues(t, *c.Slice[1], *c2.Slice[1])
}

type MyInt int
Expand Down

0 comments on commit 36e26e3

Please sign in to comment.