Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 342310f

Browse files
authoredNov 21, 2022
fix(FindInBatches): throw err if pk not exists (#5868)
1 parent b6836c2 commit 342310f

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed
 

‎finisher_api.go

+8-3
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,11 @@ func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, bat
231231
break
232232
}
233233

234-
primaryValue, _ := result.Statement.Schema.PrioritizedPrimaryField.ValueOf(tx.Statement.Context, resultsValue.Index(resultsValue.Len()-1))
234+
primaryValue, zero := result.Statement.Schema.PrioritizedPrimaryField.ValueOf(tx.Statement.Context, resultsValue.Index(resultsValue.Len()-1))
235+
if zero {
236+
tx.AddError(ErrPrimaryKeyRequired)
237+
break
238+
}
235239
queryDB = tx.Clauses(clause.Gt{Column: clause.Column{Table: clause.CurrentTable, Name: clause.PrimaryKey}, Value: primaryValue})
236240
}
237241

@@ -514,8 +518,9 @@ func (db *DB) Scan(dest interface{}) (tx *DB) {
514518
}
515519

516520
// Pluck queries a single column from a model, returning in the slice dest. E.g.:
517-
// var ages []int64
518-
// db.Model(&users).Pluck("age", &ages)
521+
//
522+
// var ages []int64
523+
// db.Model(&users).Pluck("age", &ages)
519524
func (db *DB) Pluck(column string, dest interface{}) (tx *DB) {
520525
tx = db.getInstance()
521526
if tx.Statement.Model != nil {

‎tests/query_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,13 @@ func TestFindInBatchesWithError(t *testing.T) {
408408
if totalBatch != 0 {
409409
t.Fatalf("incorrect total batch, expected: %v, got: %v", 0, totalBatch)
410410
}
411+
412+
if result := DB.Omit("id").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error {
413+
totalBatch += batch
414+
return nil
415+
}); result.Error != gorm.ErrPrimaryKeyRequired {
416+
t.Fatal("expected errors to have occurred, but nothing happened")
417+
}
411418
}
412419

413420
func TestFillSmallerStruct(t *testing.T) {

0 commit comments

Comments
 (0)
Please sign in to comment.