fix eager load issue when 1st loadingFrom value is nil

This commit is contained in:
Ivan Hranat 2020-08-16 15:10:54 +03:00
parent 256a6d4225
commit c253358870

View file

@ -5,9 +5,9 @@ import (
"reflect"
"strings"
"github.com/pkg/errors"
"github.com/lbryio/sqlboiler/boil"
"github.com/lbryio/sqlboiler/strmangle"
"github.com/pkg/errors"
)
type loadRelationshipState struct {
@ -167,7 +167,7 @@ func (l loadRelationshipState) callLoadFunction(depth int, loadingFrom reflect.V
if val.Len() == 0 {
return nil
}
val = val.Index(0)
val = firstNonNilValue(val)
if val.IsNil() {
return nil
}
@ -190,6 +190,21 @@ func (l loadRelationshipState) callLoadFunction(depth int, loadingFrom reflect.V
return nil
}
// firstNonNilValue returns the first non nil value of input. If all are nil, return the value with index 0.
func firstNonNilValue(val reflect.Value) reflect.Value {
length := val.Len()
if length == 0 {
// return val itself if val.Len() = 0
return val
}
for i := 0; i < length; i++ {
if !val.Index(i).IsNil() {
return val.Index(i)
}
}
return val.Index(0)
}
// loadRelationshipsRecurse is a helper function for taking a reflect.Value and
// Basically calls loadRelationships with: obj.R.EagerLoadedObj
// Called with an obj of *struct