From 75720099b5540a38fa9f7c26d8237df2cd1570a9 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 18 Jul 2022 18:06:45 +0800 Subject: [PATCH] Create a new db in FindInBatches --- finisher_api.go | 4 +++- gorm.go | 3 ++- tests/query_test.go | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/finisher_api.go b/finisher_api.go index 7a3f27ba..af9afb63 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -202,7 +202,9 @@ func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, bat batch++ 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 { tx.AddError(result.Error) } diff --git a/gorm.go b/gorm.go index 6a6bb032..c852e60c 100644 --- a/gorm.go +++ b/gorm.go @@ -300,7 +300,8 @@ func (db *DB) WithContext(ctx context.Context) *DB { // Debug start debug mode func (db *DB) Debug() (tx *DB) { - return db.Session(&Session{ + tx = db.getInstance() + return tx.Session(&Session{ Logger: db.Logger.LogMode(logger.Info), }) } diff --git a/tests/query_test.go b/tests/query_test.go index 253d8409..4569fe1a 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -257,7 +257,7 @@ func TestFindInBatches(t *testing.T) { 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 if tx.RowsAffected != 2 { @@ -273,7 +273,7 @@ func TestFindInBatches(t *testing.T) { } 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