Skip to content

Commit

Permalink
fix(scan): array element is set to a zero value (#6890)
Browse files Browse the repository at this point in the history
* fix(scan): array element is set to a zero value

* add test

* fix test

* optimization
  • Loading branch information
demoManito committed Mar 15, 2024
1 parent e4e23d2 commit 7b1fb0b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion scan.go
Expand Up @@ -274,7 +274,9 @@ func Scan(rows Rows, db *DB, mode ScanMode) {

if !update || reflectValue.Len() == 0 {
update = false
if !isArrayKind {
if isArrayKind {
db.Statement.ReflectValue.Set(reflect.Zero(reflectValue.Type()))
} else {
// if the slice cap is externally initialized, the externally initialized slice is directly used here
if reflectValue.Cap() == 0 {
db.Statement.ReflectValue.Set(reflect.MakeSlice(reflectValue.Type(), 0, 20))
Expand Down
19 changes: 19 additions & 0 deletions tests/query_test.go
Expand Up @@ -1409,3 +1409,22 @@ func TestQueryError(t *testing.T) {
}, Value: 1}).Scan(&p2).Error
AssertEqual(t, err, gorm.ErrModelValueRequired)
}

func TestQueryScanToArray(t *testing.T) {
err := DB.Create(&User{Name: "testname1", Age: 10}).Error
if err != nil {
t.Fatal(err)
}

users := [2]*User{{Name: "1"}, {Name: "2"}}
err = DB.Model(&User{}).Where("name = ?", "testname1").Find(&users).Error
if err != nil {
t.Fatal(err)
}
if users[0] == nil || users[0].Name != "testname1" {
t.Error("users[0] not covere")
}
if users[1] != nil {
t.Error("users[1] should be empty")
}
}

0 comments on commit 7b1fb0b

Please sign in to comment.