[fix] 修复 converting NULL to string is unsupported 错误

This commit is contained in:
what 2023-06-21 13:12:09 +08:00
parent 28d9dcbd4d
commit 5740d11240
2 changed files with 27 additions and 22 deletions

47
scan.go
View File

@ -4,7 +4,6 @@ import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"reflect"
)
@ -115,6 +114,9 @@ func sStructSlice(rows *sql.Rows, dest any) (result RowScan) {
case reflect.Slice, reflect.Struct, reflect.Map:
scanArgs[i] = &[]uint8{}
jFields[i] = v.Field(f)
case reflect.String:
scanArgs[i] = &sql.NullString{}
jFields[i] = v.Field(f)
default:
scanArgs[i] = v.Field(f).Addr().Interface()
}
@ -129,15 +131,16 @@ func sStructSlice(rows *sql.Rows, dest any) (result RowScan) {
// json 字符串 反序列化
for i, rv := range jFields {
v := rv.Addr().Interface()
data := *scanArgs[i].(*[]uint8)
if len(data) == 0 {
continue
}
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
switch rv.Kind() {
case reflect.String:
rv.SetString(scanArgs[i].(*sql.NullString).String)
default:
if data := *scanArgs[i].(*[]uint8); len(data) > 0 {
v := rv.Addr().Interface()
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
}
}
}
}
@ -185,8 +188,9 @@ func sStruct(rows *sql.Rows, dest any) (result RowScan) {
case reflect.Slice, reflect.Struct, reflect.Map:
scanArgs[i] = &[]uint8{}
jFields[i] = v.Field(f)
fmt.Printf("123 %+#v \n", v.Field(f))
case reflect.String:
scanArgs[i] = &sql.NullString{}
jFields[i] = v.Field(f)
default:
scanArgs[i] = v.Field(f).Addr().Interface()
}
@ -201,15 +205,16 @@ func sStruct(rows *sql.Rows, dest any) (result RowScan) {
// json 字符串 反序列化
for i, rv := range jFields {
v := rv.Addr().Interface()
data := *scanArgs[i].(*[]uint8)
if len(data) == 0 {
continue
}
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
switch rv.Kind() {
case reflect.String:
rv.SetString(scanArgs[i].(*sql.NullString).String)
default:
if data := *scanArgs[i].(*[]uint8); len(data) > 0 {
v := rv.Addr().Interface()
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
}
}
}
}

View File

@ -70,7 +70,7 @@ func TestScanJsonFieldStruct(t *testing.T) {
Arr []int64 `db:"arr"`
}{}
myConn.Select(`select 0 as id, 'test' as code, '{"a":1}' as map, '[3, 4]' as arr`, []any{}, &dest)
myConn.Select(`select 0 as id, NULL as code, '{"a":1}' as map, '[3, 4]' as arr`, []any{}, &dest)
t.Log(dest)
}