| 266 | } |
| 267 | |
| 268 | func TestFindInBatches(t *testing.T) { |
| 269 | users := []User{ |
| 270 | *GetUser("find_in_batches", Config{}), |
| 271 | *GetUser("find_in_batches", Config{}), |
| 272 | *GetUser("find_in_batches", Config{}), |
| 273 | *GetUser("find_in_batches", Config{}), |
| 274 | *GetUser("find_in_batches", Config{}), |
| 275 | *GetUser("find_in_batches", Config{}), |
| 276 | } |
| 277 | |
| 278 | DB.Create(&users) |
| 279 | |
| 280 | var ( |
| 281 | results []User |
| 282 | totalBatch int |
| 283 | ) |
| 284 | |
| 285 | if result := DB.Table("users as u").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error { |
| 286 | totalBatch += batch |
| 287 | |
| 288 | if tx.RowsAffected != 2 { |
| 289 | t.Errorf("Incorrect affected rows, expects: 2, got %v", tx.RowsAffected) |
| 290 | } |
| 291 | |
| 292 | if len(results) != 2 { |
| 293 | t.Errorf("Incorrect users length, expects: 2, got %v", len(results)) |
| 294 | } |
| 295 | |
| 296 | for idx := range results { |
| 297 | results[idx].Name = results[idx].Name + "_new" |
| 298 | } |
| 299 | |
| 300 | if err := tx.Save(results).Error; err != nil { |
| 301 | t.Fatalf("failed to save users, got error %v", err) |
| 302 | } |
| 303 | |
| 304 | return nil |
| 305 | }); result.Error != nil || result.RowsAffected != 6 { |
| 306 | t.Errorf("Failed to batch find, got error %v, rows affected: %v", result.Error, result.RowsAffected) |
| 307 | } |
| 308 | |
| 309 | if totalBatch != 6 { |
| 310 | t.Errorf("incorrect total batch, expects: %v, got %v", 6, totalBatch) |
| 311 | } |
| 312 | |
| 313 | var count int64 |
| 314 | DB.Model(&User{}).Where("name = ?", "find_in_batches_new").Count(&count) |
| 315 | if count != 6 { |
| 316 | t.Errorf("incorrect count after update, expects: %v, got %v", 6, count) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | func TestFindInBatchesWithOffsetLimit(t *testing.T) { |
| 321 | users := []User{ |