Skip to content

Commit

Permalink
Fix to skip nil values in arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
lafriks committed Nov 5, 2021
1 parent 6aa81d4 commit ea1169d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
13 changes: 10 additions & 3 deletions collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,15 @@ func (c Collection) PrimaryValues() []interface{} {
if index != nil {
for i := range index {
var (
values = make([]interface{}, c.rv.Len())
idxLen = c.rv.Len()
values = make([]interface{}, 0, idxLen)
)

for j := range values {
values[j] = c.rvIndex(j).Field(index[i]).Interface()
for j := 0; j < idxLen; j++ {
if item := c.rv.Index(j); item.Kind() == reflect.Ptr && item.IsNil() {
continue
}
values = append(values, c.rvIndex(j).Field(index[i]).Interface())
}

pValues[i] = values
Expand All @@ -89,6 +93,9 @@ func (c Collection) PrimaryValues() []interface{} {
)

for i := 0; i < c.rv.Len(); i++ {
if item := c.rv.Index(i); item.Kind() == reflect.Ptr && item.IsNil() {
continue
}
for j, id := range c.rvIndex(i).Interface().(primary).PrimaryValues() {
tmp[j] = append(tmp[j], id)
}
Expand Down
18 changes: 18 additions & 0 deletions collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,24 @@ func TestCollection_Primary_usingElemInterface(t *testing.T) {
primariesCache.Delete(rt)
}

func TestCollection_Primary_usingElemInterface_ptrElem(t *testing.T) {
var (
records = []*Item{
{UUID: "abc123"},
{UUID: "def456"},
nil,
}
rt = reflect.TypeOf(records).Elem()
col = NewCollection(&records)
)

// infer primary key
assert.Equal(t, "_uuid", col.PrimaryField())
assert.Equal(t, []interface{}{"abc123", "def456"}, col.PrimaryValue())

primariesCache.Delete(rt)
}

func TestCollection_Primary_usingTag(t *testing.T) {
var (
records = []struct {
Expand Down
2 changes: 1 addition & 1 deletion repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2953,7 +2953,7 @@ func TestRepository_DeleteAll_ptrElem(t *testing.T) {
var (
adapter = &testAdapter{}
repo = New(adapter)
users = []*User{{ID: 1}}
users = []*User{{ID: 1}, nil}
)

adapter.On("Delete", From("users").Where(In("id", users[0].ID))).Return(1, nil).Once()
Expand Down

0 comments on commit ea1169d

Please sign in to comment.