-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgorm_rangefunc.go
More file actions
39 lines (33 loc) · 868 Bytes
/
gorm_rangefunc.go
File metadata and controls
39 lines (33 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright 2023 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build goexperiment.rangefunc
package iter
import (
"iter"
"gorm.io/gorm"
)
// GormBatch returns a function that corporate with range-over-func syntax
// to iterate over a slice in batches.
//
// Example:
//
// var users []user
// for i, batch := range iter.GormBatch[user](db, 1<<10) {
// users = append(users, batch...)
// }
func GormBatch[E any](tx *gorm.DB, batchSize int) iter.Seq2[int, []E] {
it := NewBatchFromGorm[E](tx, batchSize)
return func(yield func(int, []E) bool) {
defer it.Stop()
n := 0
for batch, ok := it.Next(); ok; batch, ok = it.Next() {
if !yield(n, batch) {
return
}
n += len(batch)
}
}
}