diff --git a/query.go b/query.go index df19e62..6c33f05 100644 --- a/query.go +++ b/query.go @@ -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 { diff --git a/query_test.go b/query_test.go index 6ca95ce..a40f94e 100644 --- a/query_test.go +++ b/query_test.go @@ -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}` diff --git a/rows.go b/rows.go index 84bc06a..b5758de 100644 --- a/rows.go +++ b/rows.go @@ -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 {