From 111a9b90b50150ac45733e78fba3670a0e64f636 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Thu, 27 Jan 2022 13:14:03 +0200 Subject: [PATCH] support scanning slice of pointers --- query_test.go | 11 +++++++++++ rows.go | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/query_test.go b/query_test.go index a40f94e..e1df4af 100644 --- a/query_test.go +++ b/query_test.go @@ -121,6 +121,17 @@ func TestQuery_Rows(t *testing.T) { assert.Equal(t, customers[2].Status, 2, "customers[2].Status") } + // Query.All() with slice of pointers + var customersPtrSlice []*Customer + sql = `SELECT * FROM customer ORDER BY id` + err = db.NewQuery(sql).All(&customersPtrSlice) + if assert.Nil(t, err) { + assert.Equal(t, len(customersPtrSlice), 3, "len(customersPtrSlice)") + assert.Equal(t, customersPtrSlice[2].ID, 3, "customersPtrSlice[2].ID") + assert.Equal(t, customersPtrSlice[2].Email, `user3@example.com`, "customersPtrSlice[2].Email") + assert.Equal(t, customersPtrSlice[2].Status, 2, "customersPtrSlice[2].Status") + } + var customers2 []NullStringMap err = db.NewQuery(sql).All(&customers2) if assert.Nil(t, err) { diff --git a/rows.go b/rows.go index b5758de..107f9f9 100644 --- a/rows.go +++ b/rows.go @@ -124,6 +124,12 @@ func (r *Rows) all(slice interface{}) error { return r.Close() } + var isSliceOfPointers bool + if et.Kind() == reflect.Ptr { + isSliceOfPointers = true + et = et.Elem() + } + if et.Kind() != reflect.Struct { return VarTypeError("must be a slice of struct or NullStringMap") } @@ -144,6 +150,11 @@ func (r *Rows) all(slice interface{}) error { if err := r.Scan(refs...); err != nil { return err } + + if isSliceOfPointers { + ev = ev.Addr() + } + v.Set(reflect.Append(v, ev)) }