diff --git a/go.mod b/go.mod index 114c7e6..7b0a980 100644 --- a/go.mod +++ b/go.mod @@ -1,15 +1,17 @@ module github.com/Fs02/grimoire +go 1.14 + require ( github.com/Fs02/go-paranoid v0.0.0-20180516074805-ab50069def7d github.com/azer/snakecase v0.0.0-20161028114325-c818dddafb5c - github.com/davecgh/go-spew v1.1.0 + github.com/davecgh/go-spew v1.1.0 // indirect github.com/go-sql-driver/mysql v1.3.0 github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2 github.com/mattn/go-sqlite3 v1.6.0 - github.com/pmezard/go-difflib v1.0.0 - github.com/stretchr/objx v0.1.0 + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/objx v0.1.0 // indirect github.com/stretchr/testify v1.2.1 github.com/tidwall/gjson v1.1.3 - github.com/tidwall/match v1.0.0 + github.com/tidwall/match v1.0.0 // indirect ) diff --git a/query.go b/query.go index 3be2690..211dc9c 100644 --- a/query.go +++ b/query.go @@ -560,7 +560,7 @@ func collectPreloadTarget(preload []preloadTarget, refIndex []int) (map[interfac // reset to zero if slice. if fv.Kind() == reflect.Slice || fv.Kind() == reflect.Array { - fv.Set(reflect.Zero(fv.Type())) + fv.Set(reflect.MakeSlice(fv.Type(), 0, 0)) } addrs[id] = append(addrs[id], fv) diff --git a/query_test.go b/query_test.go index 6592431..7d36269 100644 --- a/query_test.go +++ b/query_test.go @@ -1208,6 +1208,23 @@ func TestQuery_Preload_hasMany(t *testing.T) { mock.AssertExpectations(t) } +func TestQuery_Preload_hasManyNoResult(t *testing.T) { + mock := new(TestAdapter) + repo := Repo{adapter: mock} + + user := User{ID: 10} + result := []Transaction{} + + query := repo.From("transactions") + + mock.Result(result).On("All", query.Where(In("user_id", 10)), &[]Transaction{}).Return(2, nil) + + assert.Nil(t, query.Preload(&user, "Transactions")) + assert.Equal(t, result, user.Transactions) + assert.NotPanics(t, func() { query.MustPreload(&user, "Transactions") }) + mock.AssertExpectations(t) +} + func TestQuery_Preload_sliceHasMany(t *testing.T) { mock := new(TestAdapter) repo := Repo{adapter: mock} @@ -1251,6 +1268,23 @@ func TestQuery_Preload_nestedHasMany(t *testing.T) { mock.AssertExpectations(t) } +func TestQuery_Preload_nestedHasManyNoResult(t *testing.T) { + mock := new(TestAdapter) + repo := Repo{adapter: mock} + + address := Address{User: &User{ID: 10}} + result := []Transaction{} + + query := repo.From("transactions") + + mock.Result(result).On("All", query.Where(In("user_id", 10)), &[]Transaction{}).Return(2, nil) + + assert.Nil(t, query.Preload(&address, "User.Transactions")) + assert.Equal(t, result, address.User.Transactions) + assert.NotPanics(t, func() { query.MustPreload(&address, "User.Transactions") }) + mock.AssertExpectations(t) +} + func TestQuery_Preload_nestedNullHasMany(t *testing.T) { mock := new(TestAdapter) repo := Repo{adapter: mock}