Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is a pessimistic lock released in rails?

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.

like image 799
user26270 Avatar asked Jul 08 '10 15:07

user26270


People also ask

How do you release a pessimistic lock?

Pessimistic locks are automatically released at the end of the transaction (using either commit. See JavaDoc Reference Page... or rollback. See JavaDoc Reference Page...).

What is pessimistic locking rails?

What is pessimistic locking? When one user is editing a record and we maintain an exclusive lock on that record, another user is prevented from modifying this record until the lock is released or the transaction is completed. This explicit locking is known as a pessimistic lock.

What is pessimistic lock exception?

PessimisticLockException indicates that obtaining a lock or converting a shared to exclusive lock fails and results in a transaction-level rollback. LockTimeoutException indicates that obtaining a lock or converting a shared lock to exclusive times out and results in a statement-level rollback.

What is optimistic locking in database?

Optimistic locking is a technique for SQL database applications that does not hold row locks between selecting and updating or deleting a row. The application is written to optimistically assume that unlocked rows are unlikely to change before the update or delete operation.


1 Answers

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

like image 63
Geoff Lanotte Avatar answered Oct 12 '22 15:10

Geoff Lanotte