0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-11-09 11:31:34 +01:00
gitea/models/db/iterate.go
6543 b2f828db5e
refactor: make db iterate context aware (#27710)
the iteration will run until finished atm.

this changes it by checking if if the context got canceled before each
run of a loop sequence is executed

[View this pull with now
whitespace](https://github.com/go-gitea/gitea/pull/27710/files?diff=unified&w=1)
2023-10-21 10:05:29 +08:00

43 lines
860 B
Go

// 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 {
select {
case <-ctx.Done():
return ctx.Err()
default:
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
}
}
}
}
}