From 0d6f01d340ff3792ee61aec1fd5c7b45e95018ee Mon Sep 17 00:00:00 2001 From: jnfeinstein Date: Sat, 22 Nov 2014 01:43:47 -0800 Subject: [PATCH] Create empty slice when records are not found. There is a gotcha in golang (go figure!) resulting from the difference between a nil slice and an empty slice. While the length of both are 0, the JSON encoder will interpret the nil slice as 'null' and the empty slice as '[]'. Other libraries (i.e. ActiveRecord) will return an empty array when no values are found. I have found that this translates into better client-side code, since you don't have to protect against null arrays. See 'http://danott.co/posts/json-marshalling-empty-slices-to-empty-arrays-in-go.html' for more information. --- callback_query.go | 9 +++++++++ query_test.go | 14 ++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/callback_query.go b/callback_query.go index f46d6ad4..8e6348f6 100644 --- a/callback_query.go +++ b/callback_query.go @@ -77,6 +77,15 @@ func Query(scope *Scope) { } if !anyRecordFound { + if isSlice && dest.IsNil() { + var emptySliceType reflect.Type + if isPtr { + emptySliceType = reflect.SliceOf(reflect.PtrTo(destType)) + } else { + emptySliceType = reflect.SliceOf(destType) + } + dest.Set(reflect.MakeSlice(emptySliceType, 0, 0)) + } scope.Err(RecordNotFound) } } diff --git a/query_test.go b/query_test.go index d4a68aa1..052d698c 100644 --- a/query_test.go +++ b/query_test.go @@ -78,6 +78,20 @@ func TestFindAsSliceOfPointers(t *testing.T) { } } +func TestFindWontReturnNilSlices(t *testing.T) { + randomNum := rand.Intn(1000000000) + + var users []User + DB.Where("name = ?", randomNum).Find(&users) + + var userPointers []*User + DB.Where("name = ?", randomNum).Find(&userPointers) + + if reflect.ValueOf(users).IsNil() || reflect.ValueOf(userPointers).IsNil() { + t.Errorf("Should have returned empty slices") + } +} + func TestSearchWithPlainSQL(t *testing.T) { user1 := User{Name: "PlainSqlUser1", Age: 1, Birthday: now.MustParse("2000-1-1")} user2 := User{Name: "PlainSqlUser2", Age: 10, Birthday: now.MustParse("2010-1-1")}