Add additional nil checks to the eager loading code

- Needed a couple nil checks in the eager loading code. The tests didn't
  (and now do) cover the case where an eager load function returns
  empty or nil things.
- Fix #66
This commit is contained in:
Aaron L 2016-11-15 21:28:13 -08:00
parent a8330b18ad
commit b7cd6f3f99
2 changed files with 36 additions and 1 deletions

View file

@ -167,7 +167,11 @@ func (l loadRelationshipState) callLoadFunction(depth int, loadingFrom reflect.V
if val.Len() == 0 {
return nil
}
val = reflect.Indirect(val.Index(0))
val = val.Index(0)
if val.IsNil() {
return nil
}
val = reflect.Indirect(val)
}
methodArgs := []reflect.Value{
@ -197,6 +201,9 @@ func (l loadRelationshipState) loadRelationshipsRecurse(depth int, obj reflect.V
}
loadedObject := reflect.Indirect(r).FieldByName(key)
if loadedObject.IsNil() {
return nil
}
bkind := kindStruct
if reflect.Indirect(loadedObject).Kind() != reflect.Struct {

View file

@ -299,6 +299,34 @@ func TestEagerLoadZeroParents(t *testing.T) {
}
}
func TestEagerLoadZeroParentsMany(t *testing.T) {
t.Parallel()
obj := []*testEager{
&testEager{},
&testEager{},
}
toLoad := []string{"ZeroMany.NestedMany", "ZeroOne.NestedOne", "ZeroMany.NestedMany", "ZeroOne.NestedOne"}
err := eagerLoad(nil, toLoad, &obj, kindPtrSliceStruct)
if err != nil {
t.Fatal(err)
}
if len(obj[0].R.ZeroMany) != 0 {
t.Error("should have loaded nothing")
}
if obj[0].R.ZeroOne != nil {
t.Error("should have loaded nothing")
}
if len(obj[1].R.ZeroMany) != 0 {
t.Error("should have loaded nothing")
}
if obj[1].R.ZeroOne != nil {
t.Error("should have loaded nothing")
}
}
func checkChildOne(c *testEagerChild) {
if c == nil {
panic("c was nil")