Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 4 commits into from Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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")
}
}