Skip to content

Commit

Permalink
Query.All() will init the slice as an empty slice if no result is ret…
Browse files Browse the repository at this point in the history
…urned
  • Loading branch information
qiangxue committed Feb 4, 2018
1 parent 244ab54 commit 21ba863
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ func (q *Query) One(a interface{}) error {
// All executes the SQL statement and populates all the resulting rows into a slice of struct or NullStringMap.
// The slice must be given as a pointer. Each slice element must be either a struct or a NullStringMap.
// Refer to Rows.ScanStruct() and Rows.ScanMap() for more details on how each slice element can be.
// If the query returns no row, the slice will be an empty slice (not nil).
func (q *Query) All(slice interface{}) error {
rows, err := q.Rows()
if err != nil {
Expand Down
7 changes: 7 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,13 @@ func TestQuery_Rows(t *testing.T) {
err = db.NewQuery(sql).All(&customers4)
assert.NotNil(t, err)

var customers5 []Customer
err = db.NewQuery(`SELECT * FROM customer WHERE id=999`).All(&customers5)
if assert.Nil(t, err) {
assert.NotNil(t, customers5)
assert.Zero(t, len(customers5))
}

// One
var customer Customer
sql = `SELECT * FROM customer WHERE id={:id}`
Expand Down
5 changes: 5 additions & 0 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ func (r *Rows) all(slice interface{}) error {
return VarTypeError("must be a slice of struct or NullStringMap")
}

if v.IsNil() {
// create an empty slice
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
}

et := v.Type().Elem()

if et.Kind() == reflect.Map {
Expand Down

0 comments on commit 21ba863

Please sign in to comment.