[Ruby on Rails (RoR)] Pessimistic Locking in Rails
Optimistic locking
Locking::Pessimistic provides support for row-level locking using SELECT … FOR UPDATE and other lock types.
Chain ActiveRecord::Base#find
to ActiveRecord::QueryMethods#lock
to obtain an exclusive lock on the selected rows:
1 | # select * from accounts where id=1 for update |
Call lock(‘some locking clause’) to use a database-specific locking clause of your own such as ‘LOCK IN SHARE MODE’ or ‘FOR UPDATE NOWAIT’. Example:
Account.transaction do
select * from accounts where name = ‘shugo’ limit 1 for update nowait
shugo = Account.lock(“FOR UPDATE NOWAIT”).find_by(name: “shugo”)
yuko = Account.lock(“FOR UPDATE NOWAIT”).find_by(name: “yuko”)
shugo.balance -= 100
shugo.save!
yuko.balance += 100
yuko.save!
end
1 |
|
You can start a transaction and acquire the lock in one go by calling with_lock
with a block. The block is called from within a transaction, the object is already locked. Example:
1 | account = Account.first |
Combie with_lock
and lock!
:
1 | def like(id) |
Since we are already in a database transaction (the first lock), we cannot use another with_lock
block because it itself is a transaction. what we can do inside of this with_lock block is call .lock!
.
Database-specific information on row locking
MySQL
PostgreSQL
Instance Public methods
lock!(lock = true)
Obtain a row lock on this record. Reloads the record to obtain the requested lock. Pass an SQL locking clause to append the end of the SELECT statement or pass true for “FOR UPDATE” (the default, an exclusive row lock). Returns the locked record.
with_lock(lock = true)
Wraps the passed block in a transaction, locking the object before yielding. You can pass the SQL locking clause as argument (see lock!
).
References
[3] Rails: Pessimistic Locking - DEV Community - https://dev.to/nodefiend/rails-pessimistic-locking-45ak