Skip to content

Instantly share code, notes, and snippets.

@buhrmi
Created January 29, 2011 10:57
Show Gist options
  • Save buhrmi/801746 to your computer and use it in GitHub Desktop.
Save buhrmi/801746 to your computer and use it in GitHub Desktop.
Pessimistic Locking Strategy support for DataMapper (FOR UPDATE)
# This Patch makes it possible to retrieve row-locked records from data-objects repositories
# Sample Usage: User.locked.get(1)
# #=> SELECT [...] WHERE `id` = 1 ORDER BY `id` LIMIT 1 FOR UPDATE
# In user.rb
def self.locked
all(:with_locking => true)
end
# The actual patch
module DataMapper
# Add Pessimistic Locking
module Adapters
class DataObjectsAdapter
module PessimisticLocking
def select_statement query
statement, bind_values = super query
statement << ' FOR UPDATE' if query.locked?
return statement, bind_values
end
end
include PessimisticLocking
end
end
class Query
OPTIONS += [:with_locking]
OPTIONS.freeze
def locked?
@options[:with_locking]
end
def assert_valid_options_with_locking options
assert_valid_options_without_locking options.except(:with_locking)
end
alias_method_chain :assert_valid_options, :locking
end
end
@dkubb
Copy link

dkubb commented Jan 30, 2011

This is awesome! What do you think about packaging this up into a dm-* plugin? I know there's dm-optlock for optimistic locking (and probably a few others), but I'm not aware of any that do pessimistic locking.

@MarcWeber
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment