Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support scanning slice of pointers #99

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, `[email protected]`, "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) {
Expand Down
11 changes: 11 additions & 0 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand All @@ -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))
}

Expand Down