Optimistic Locking for Datamapper

Posted by Moser on 01 Oct 2008

Update(2009-3-3): dm-optlock now on github

Update(2009-1-10): New version

I should be learning for my test on next tuesday, but coding helps keeping me in a good mood. Here is a little gem I will need in a future project for which I’ve choosen merb + datamapper. Datamapper doesn’t support any row level locking. My code checks if the record you want to save was changed since you loaded it. If it was changed it raises an exception (DataMapper::StaleObjectError). It works quite like ActiveRecord’s optimistic locking. You need to define this column in your model you want to be locked:

property :lock_version, Integer, :default => 0

Anywhere in your code where you update your objects you should be prepared to handle the exception:

  if @obj.update_attributes({:dummy => 123})
    #successful
  else
    #validation errors?
  end
rescue DataMapper::StaleObjectError
  #tell the user that he was too slow
  #or even better: show him the conflicts and let him merge the changes
end

The gem can be downloaded here: dm-optlock-0.1.0.gem Please let me know what you think of it. I’ll try and put it on RubyForge, too.

(00:27) Little update: I added a ‘set_locking_column’ method. dm-optlock-0.1.2.gem

Update: dm-optlock is on Rubyforge. Now you can get it like this: gem install dm-optlock