fix(scan): array element is set to a zero value (#6890)

* fix(scan): array element is set to a zero value

* add test

* fix test

* optimization
This commit is contained in:
jessetang 2024-03-15 14:14:48 +08:00 committed by GitHub
parent e4e23d26d2
commit 7b1fb0bd73
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 22 additions and 1 deletions

View File

@ -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))

View File

@ -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")
}
}