Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rails `with_lock` block reads?

Suppose I have an Article that I want to perform some changes on.

If I use with_lock, will it block other processes from reading that row in the Articles table?

E.g.

 @article = Article.find(1)
 Article.with_lock
   #do something
 end

 # In another process
 @article = Article.find(1) # will this lookup be blocked by the first process?
like image 801
jay Avatar asked Sep 23 '14 00:09

jay


1 Answers

Per the documentation, it does a SELECT ... FOR UPDATE by default.

A SELECT ... FOR UPDATE on a row does not block other sessions from reading the row. It only blocks other sessions from obtaining a FOR UPDATE (write) or FOR SHARE (read) lock on the row. The row remains normally readable to sessions that do a SELECT without any FOR UPDATE or FOR SHARE clause.

So in this case, you'd need to find the row, then do a lock('FOR SHARE') on it if you wanted to be sure nobody else had a FOR UPDATE lock on it.

For more detail see the PostgreSQL documentation on explicit locking.

like image 135
Craig Ringer Avatar answered Sep 28 '22 17:09

Craig Ringer