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

View File

@ -70,7 +70,7 @@ func TestScanJsonFieldStruct(t *testing.T) {
Arr []int64 `db:"arr"` 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) t.Log(dest)
} }