diff options
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record/locking.rb | 29 |
1 files changed, 25 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/locking.rb b/activerecord/lib/active_record/locking.rb index 71a4666e17..28d55da6df 100644 --- a/activerecord/lib/active_record/locking.rb +++ b/activerecord/lib/active_record/locking.rb @@ -18,6 +18,8 @@ module ActiveRecord # You must ensure that your database schema defaults the lock_version column to 0. # # This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>. + # To override the name of the lock_version column, invoke the <tt>set_locking_column</tt> method. + # This method uses the same syntax as <tt>set_table_name</tt> module Locking def self.append_features(base) #:nodoc: super @@ -29,13 +31,15 @@ module ActiveRecord def update_with_lock #:nodoc: if locking_enabled? - previous_value = self.lock_version - self.lock_version = previous_value + 1 + lock_col = self.class.locking_column + previous_value = send(lock_col) + send(lock_col + '=', previous_value + 1) affected_rows = connection.update(<<-end_sql, "#{self.class.name} Update with optimistic locking") UPDATE #{self.class.table_name} SET #{quoted_comma_pair_list(connection, attributes_with_quotes(false))} - WHERE #{self.class.primary_key} = #{quote(id)} AND lock_version = #{quote(previous_value)} + WHERE #{self.class.primary_key} = #{quote(id)} + AND #{lock_col} = #{quote(previous_value)} end_sql unless affected_rows == 1 @@ -52,7 +56,24 @@ module ActiveRecord cattr_accessor :lock_optimistically def locking_enabled? #:nodoc: - lock_optimistically && respond_to?(:lock_version) + lock_optimistically && respond_to?(self.class.locking_column) end + + class << self + def set_locking_column( value=nil, &block ) + define_attr_method :locking_column, value, &block + end + + def locking_column + reset_locking_column + end + + def reset_locking_column + default = 'lock_version' + set_locking_column(default) + default + end + end + end end |