Tag: datamapper

dm-optlock v 0.1.4

Posted by on January 10, 2009

Update: dm-optlock now on github

I released a new version of dm-optlock. It is NOT compatible with v 0.1.2’s code, because replaced the set_locking_column method by a method called add_locking_column. Your DB should be compatible.

class Model
  include DataMapper::Resource
  ...
  add_locking_column :my_version_col
end

It takes a options hash just like DataMapper’s property method does. I added it to enforce some options on the locking column.

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