aboutsummaryrefslogtreecommitdiffstats
path: root/models/db/iterate.go
blob: fc8c78d83ea3662d058c442fa36b7b6caf9b4763 (plain)
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
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package db

import (
	"context"

	"code.gitea.io/gitea/modules/setting"

	"xorm.io/builder"
)

// Iterate iterate all the Bean object
func Iterate[Bean any](ctx context.Context, cond builder.Cond, f func(ctx context.Context, bean *Bean) error) error {
	var start int
	batchSize := setting.Database.IterateBufferSize
	sess := GetEngine(ctx)
	for {
		beans := make([]*Bean, 0, batchSize)
		if cond != nil {
			sess = sess.Where(cond)
		}
		if err := sess.Limit(batchSize, start).Find(&beans); err != nil {
			return err
		}
		if len(beans) == 0 {
			return nil
		}
		start += len(beans)

		for _, bean := range beans {
			if err := f(ctx, bean); err != nil {
				return err
			}
		}
	}
}