From 5740d112407fdbe77c133a4d4f7f589888b3ed30 Mon Sep 17 00:00:00 2001 From: what Date: Wed, 21 Jun 2023 13:12:09 +0800 Subject: [PATCH] =?UTF-8?q?[fix]=20=E4=BF=AE=E5=A4=8D=20converting=20NULL?= =?UTF-8?q?=20to=20string=20is=20unsupported=20=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scan.go | 47 ++++++++++++++++++++++++++--------------------- scan_test.go | 2 +- 2 files changed, 27 insertions(+), 22 deletions(-) diff --git a/scan.go b/scan.go index e963f8e..c78077b 100644 --- a/scan.go +++ b/scan.go @@ -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) + } + } } } diff --git a/scan_test.go b/scan_test.go index 1d0233b..50c9f2b 100644 --- a/scan_test.go +++ b/scan_test.go @@ -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) }