mercredi 1 juin 2016

Rails find_in_batches with locking

I need to process large number of records in batches. And each batch should be processed in it's own transaction. Is there way to wrap each batch in transaction and lock all records in batch at the same time?

Model.scheduled_now.lock.find_in_batches do |batch|
  model_ids = batch.map(&:id)
  Model.update_all({status: 'delivering'}, {"id IN (?)" , model_ids})

  # creates and updates other DB records
  # and triggers background job
  perform_delivery_actions(batch)
end

Does SELECT FOR UPDATE in this example commits transaction after each batch? Or I need to put internal transaction block and lock records manually inside each batch (which means one more query)?

The reason I don't want to put outer transaction block is that I want to commit each batch separately, not a whole thing at once.

Aucun commentaire:

Enregistrer un commentaire