Search code examples
lockingrails-activerecordpessimistic

When is a pessimistic lock released in ActiveRecord?


Assuming I'm doing something like this (from the Active Record Querying guide)

Item.transaction do  
  i = Item.first(lock: true)  
  i.name = 'Jones'  
  i.save 
end 

Is the lock automatically released at the end of the transaction? I've looked at the Active Query guide and the ActiveRecord::Locking::Pessimistic docs, and couldn't find where it explicitly says where the lock is released.


Solution

  • Locking is not a function of rails, it is just adding the lock statement to the query, which will vary depending on the database that you are using. Pessimistic Locking takes a "pessimistic" view in thinking that every query is subject to corruption. So it is going to lock selected rows until you are finished with the transaction. so Lock > query > unlock. While these are fairly consistent database to database, it might be good to read up on the database documentation that you using for any database-specific things you should know.

    Here is a good thread on optimistic vs. pessimistic locking that explains it better than I can. Optimistic vs. Pessimistic locking