From 8d1e6bc0f8e9710dcba60a1b8e4ec3f47e8bf8ea Mon Sep 17 00:00:00 2001 From: Dmitry Zenovich Date: Fri, 19 Apr 2019 14:41:30 +0300 Subject: [PATCH] remove old elements from the output parameter of Pluck() --- main_test.go | 31 +++++++++++++++++++++++++++++++ scope.go | 4 ++++ 2 files changed, 35 insertions(+) diff --git a/main_test.go b/main_test.go index 1dc30093..4100c7f8 100644 --- a/main_test.go +++ b/main_test.go @@ -1110,6 +1110,37 @@ func TestCountWithHaving(t *testing.T) { } } +func TestPluck(t *testing.T) { + db := DB.New() + db.Delete(User{}) + defer db.Delete(User{}) + + DB.Create(&User{Id: 1, Name: "user1"}) + DB.Create(&User{Id: 2, Name: "user2"}) + DB.Create(&User{Id: 3, Name: "user3"}) + + var ids []int64 + err := db.Model(User{}).Order("id").Pluck("id", &ids).Error + + if err != nil { + t.Error("Unexpected error on pluck") + } + + if len(ids) != 3 || ids[0] != 1 || ids[1] != 2 || ids[2] != 3 { + t.Error("Unexpected result on pluck") + } + + err = db.Model(User{}).Order("id").Pluck("id", &ids).Error + + if err != nil { + t.Error("Unexpected error on pluck again") + } + + if len(ids) != 3 || ids[0] != 1 || ids[1] != 2 || ids[2] != 3 { + t.Error("Unexpected result on pluck again") + } +} + func BenchmarkGorm(b *testing.B) { b.N = 2000 for x := 0; x < b.N; x++ { diff --git a/scope.go b/scope.go index 7fa64b19..0767bb66 100644 --- a/scope.go +++ b/scope.go @@ -984,6 +984,10 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope { return scope } + if dest.Len() > 0 { + dest.Set(reflect.Zero(dest.Type())) + } + if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) { scope.Search.Select(column) }