From 28d9dcbd4dcb0c6c60fbcd0c80adc6922a37ff99 Mon Sep 17 00:00:00 2001 From: what Date: Wed, 21 Jun 2023 11:07:25 +0800 Subject: [PATCH] =?UTF-8?q?[fix]=20struct=20=E4=B8=AD=E5=AD=98=E5=9C=A8sli?= =?UTF-8?q?ce=E5=AD=97=E6=AE=B5=E4=BC=9A=E6=8A=A5=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scan.go | 11 +++++------ scan_test.go | 6 ++++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/scan.go b/scan.go index 0169913..e963f8e 100644 --- a/scan.go +++ b/scan.go @@ -4,6 +4,7 @@ import ( "database/sql" "encoding/json" "errors" + "fmt" "reflect" ) @@ -128,7 +129,7 @@ func sStructSlice(rows *sql.Rows, dest any) (result RowScan) { // json 字符串 反序列化 for i, rv := range jFields { - v := rv.Interface() + v := rv.Addr().Interface() data := *scanArgs[i].(*[]uint8) if len(data) == 0 { @@ -138,8 +139,6 @@ func sStructSlice(rows *sql.Rows, dest any) (result RowScan) { if err := json.Unmarshal(data, &v); err != nil { panic(err) } - - rv.Set(reflect.ValueOf(v)) } if itemIsPtr { @@ -186,6 +185,8 @@ 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)) default: scanArgs[i] = v.Field(f).Addr().Interface() } @@ -200,7 +201,7 @@ func sStruct(rows *sql.Rows, dest any) (result RowScan) { // json 字符串 反序列化 for i, rv := range jFields { - v := rv.Interface() + v := rv.Addr().Interface() data := *scanArgs[i].(*[]uint8) if len(data) == 0 { @@ -210,8 +211,6 @@ func sStruct(rows *sql.Rows, dest any) (result RowScan) { if err := json.Unmarshal(data, &v); err != nil { panic(err) } - - rv.Set(reflect.ValueOf(v)) } if realDest.Kind() == reflect.Ptr { diff --git a/scan_test.go b/scan_test.go index ea3d0ab..1d0233b 100644 --- a/scan_test.go +++ b/scan_test.go @@ -67,9 +67,10 @@ func TestScanJsonFieldStruct(t *testing.T) { Id int `db:"id"` Code string `db:"code"` Map map[string]any `db:"map"` + Arr []int64 `db:"arr"` }{} - myConn.Select(`select 0 as id, 'test' as code, '{"a":1}' as map`, []any{}, &dest) + myConn.Select(`select 0 as id, 'test' as code, '{"a":1}' as map, '[3, 4]' as arr`, []any{}, &dest) t.Log(dest) } @@ -92,9 +93,10 @@ func TestScanJsonFieldStructSlice(t *testing.T) { Id int `db:"id"` Code string `db:"code"` Map map[string]any `db:"map"` + Arr []any `db:"arr"` }{} - myConn.Select(`select * from ((select 0 as id, 'test' as code, '{"a":1}' as map) union (select 1 as id, 'test1' as code, '{"a":2}' as map)) as t`, []any{}, &dest) + myConn.Select(`select * from ((select 0 as id, 'test' as code, '{"a":1}' as map, '[1, 2]' as arr) union (select 1 as id, 'test1' as code, '{"a":2}' as map, '[1, 2]' as arr)) as t`, []any{}, &dest) t.Log(dest) }