Created
January 29, 2011 10:57
-
-
Save buhrmi/801746 to your computer and use it in GitHub Desktop.
Pessimistic Locking Strategy support for DataMapper (FOR UPDATE)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.