Fix: FindInBatches ignores errors (#4203)

This commit is contained in:
Genta Kamitani 2021-03-22 15:11:07 +09:00 committed by GitHub
parent 8c92d9694a
commit 26dd4c980a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View File

@ -190,6 +190,8 @@ func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, bat
if result.Error == nil && result.RowsAffected != 0 {
tx.AddError(fc(result, batch))
} else if result.Error != nil {
tx.AddError(result.Error)
}
if tx.Error != nil || int(result.RowsAffected) < batchSize {

View File

@ -292,6 +292,34 @@ func TestFindInBatches(t *testing.T) {
}
}
func TestFindInBatchesWithError(t *testing.T) {
var users = []User{
*GetUser("find_in_batches_with_error", Config{}),
*GetUser("find_in_batches_with_error", Config{}),
*GetUser("find_in_batches_with_error", Config{}),
*GetUser("find_in_batches_with_error", Config{}),
*GetUser("find_in_batches_with_error", Config{}),
*GetUser("find_in_batches_with_error", Config{}),
}
DB.Create(&users)
var (
results []User
totalBatch int
)
if result := DB.Table("wrong_table").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error {
totalBatch += batch
return nil
}); result.Error == nil || result.RowsAffected > 0 {
t.Fatal("expected errors to have occurred, but nothing happened")
}
if totalBatch != 0 {
t.Fatalf("incorrect total batch, expected: %v, got: %v", 0, totalBatch)
}
}
func TestFillSmallerStruct(t *testing.T) {
user := User{Name: "SmallerUser", Age: 100}
DB.Save(&user)