Optimistic Locking for Datamapper

Posted by on October 1, 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:

begin
  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

Comments

Respond | Trackback

  1. adam french October 1, 2008 11:01 pm

    really excited about this, dude. We’d like to make this part of dm-core, if your up for it.

  2. dm-optlock v 0.1.4 - Moserei January 10, 2009 6:23 pm

    [...] released a new version of dm-optlock. It is NOT compatible with v [...]

Comments

Comments: