Create a new db in FindInBatches

This commit is contained in:
Jinzhu 2022-07-18 18:06:45 +08:00
parent 2ba599e8b7
commit 75720099b5
3 changed files with 7 additions and 4 deletions

View File

@ -202,7 +202,9 @@ func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, bat
batch++ batch++
if result.Error == nil && result.RowsAffected != 0 { if result.Error == nil && result.RowsAffected != 0 {
tx.AddError(fc(result, batch)) fcTx := result.Session(&Session{NewDB: true})
fcTx.RowsAffected = result.RowsAffected
tx.AddError(fc(fcTx, batch))
} else if result.Error != nil { } else if result.Error != nil {
tx.AddError(result.Error) tx.AddError(result.Error)
} }

View File

@ -300,7 +300,8 @@ func (db *DB) WithContext(ctx context.Context) *DB {
// Debug start debug mode // Debug start debug mode
func (db *DB) Debug() (tx *DB) { func (db *DB) Debug() (tx *DB) {
return db.Session(&Session{ tx = db.getInstance()
return tx.Session(&Session{
Logger: db.Logger.LogMode(logger.Info), Logger: db.Logger.LogMode(logger.Info),
}) })
} }

View File

@ -257,7 +257,7 @@ func TestFindInBatches(t *testing.T) {
totalBatch int totalBatch int
) )
if result := DB.Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error { if result := DB.Table("users as u").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error {
totalBatch += batch totalBatch += batch
if tx.RowsAffected != 2 { if tx.RowsAffected != 2 {
@ -273,7 +273,7 @@ func TestFindInBatches(t *testing.T) {
} }
if err := tx.Save(results).Error; err != nil { if err := tx.Save(results).Error; err != nil {
t.Errorf("failed to save users, got error %v", err) t.Fatalf("failed to save users, got error %v", err)
} }
return nil return nil