db: hold a lock during all foreach execution time

Maybe we need to release/acquire it for every item, or for X items, to
allow other operations.