Skip to content
Browse files

Made increment_counter/decrement_counter play nicely with optimistic …

…locking, and added a more general update_counters method

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6139 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent f458b37 commit 83752373b9c83bf585b5fe44836c65612b680cf9 @jamis jamis committed Feb 7, 2007
View
2 activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method [Jamis Buck]
+
* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however [Tobias Luetke]
Task.cache { Task.find(1); Task.find(1) } #=> 1 query
View
23 activerecord/lib/active_record/base.rb
@@ -519,18 +519,37 @@ def count_by_sql(sql)
connection.select_value(sql, "#{name} Count").to_i
end
+ # A generic "counter updater" implementation, intended primarily to be
+ # used by increment_counter and decrement_counter, but which may also
+ # be useful on its own. It simply does a direct SQL update for the record
+ # with the given ID, altering the given hash of counters by the amount
+ # given by the corresponding value:
+ #
+ # Post.update_counters 5, :comment_count => -1, :action_count => 1
+ # # UPDATE posts
+ # # SET comment_count = comment_count - 1,
+ # # action_count = action_count + 1
+ # # WHERE id = 5
+ def update_counters(id, counters)
+ updates = counters.inject([]) { |list, (counter_name, increment)|
+ sign = increment < 0 ? "-" : "+"
+ list << "#{counter_name} = #{counter_name} #{sign} #{increment.abs}"
+ }.join(", ")
+ update_all(updates, "#{primary_key} = #{quote_value(id)}")
+ end
+
# Increments the specified counter by one. So <tt>DiscussionBoard.increment_counter("post_count",
# discussion_board_id)</tt> would increment the "post_count" counter on the board responding to discussion_board_id.
# This is used for caching aggregate values, so that they don't need to be computed every time. Especially important
# for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard
# that needs to list both the number of posts and comments.
def increment_counter(counter_name, id)
- update_all "#{counter_name} = #{counter_name} + 1", "#{primary_key} = #{quote_value(id)}"
+ update_counters(id, counter_name => 1)
end
# Works like increment_counter, but decrements instead.
def decrement_counter(counter_name, id)
- update_all "#{counter_name} = #{counter_name} - 1", "#{primary_key} = #{quote_value(id)}"
+ update_counters(id, counter_name => -1)
end
View
25 activerecord/lib/active_record/locking/optimistic.rb
@@ -31,14 +31,14 @@ def self.included(base) #:nodoc:
base.alias_method_chain :update, :lock
base.alias_method_chain :attributes_from_column_definition, :lock
-
+
class << base
alias_method :locking_column=, :set_locking_column
end
end
def locking_enabled? #:nodoc:
- lock_optimistically && respond_to?(self.class.locking_column)
+ self.class.locking_enabled?
end
def attributes_from_column_definition_with_lock
@@ -80,6 +80,20 @@ def update_with_lock #:nodoc:
module ClassMethods
DEFAULT_LOCKING_COLUMN = 'lock_version'
+ def self.extended(base)
+ class <<base
+ alias_method_chain :update_counters, :lock
+ end
+ end
+
+ # Is optimistic locking enabled for this table? Returns true if the
+ # #lock_optimistically flag is set to true (which it is, by default)
+ # and the table includes the #locking_column column (defaults to
+ # lock_version).
+ def locking_enabled?
+ lock_optimistically && columns_hash[locking_column]
+ end
+
# Set the column to use for optimistic locking. Defaults to lock_version.
def set_locking_column(value = nil, &block)
define_attr_method :locking_column, value, &block
@@ -100,6 +114,13 @@ def quoted_locking_column
def reset_locking_column
set_locking_column DEFAULT_LOCKING_COLUMN
end
+
+ # make sure the lock version column gets updated when counters are
+ # updated.
+ def update_counters_with_lock(id, counters)
+ counters = counters.merge(locking_column => 1) if locking_enabled?
+ update_counters_without_lock(id, counters)
+ end
end
end
end
View
51 activerecord/test/locking_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'fixtures/person'
+require 'fixtures/reader'
require 'fixtures/legacy_thing'
class LockWithoutDefault < ActiveRecord::Base; end
@@ -12,6 +13,11 @@ class LockWithCustomColumnWithoutDefault < ActiveRecord::Base
class OptimisticLockingTest < Test::Unit::TestCase
fixtures :people, :legacy_things
+ # need to disable transactional fixtures, because otherwise the sqlite3
+ # adapter (at least) chokes when we try and change the schema in the middle
+ # of a test (see test_increment_counter_*).
+ self.use_transactional_fixtures = false
+
def test_lock_existing
p1 = Person.find(1)
p2 = Person.find(1)
@@ -73,6 +79,51 @@ def test_lock_with_custom_column_without_default_sets_version_to_zero
t1 = LockWithCustomColumnWithoutDefault.new
assert_equal 0, t1.custom_lock_version
end
+
+ { :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model|
+ define_method("test_increment_counter_updates_#{name}") do
+ counter_test model, 1 do |id|
+ model.increment_counter :test_count, id
+ end
+ end
+
+ define_method("test_decrement_counter_updates_#{name}") do
+ counter_test model, -1 do |id|
+ model.decrement_counter :test_count, id
+ end
+ end
+
+ define_method("test_update_counters_updates_#{name}") do
+ counter_test model, 1 do |id|
+ model.update_counters id, :test_count => 1
+ end
+ end
+ end
+
+ private
+
+ def add_counter_column_to(model)
+ model.connection.add_column model.table_name, :test_count, :integer, :null => false, :default => 0
+ model.reset_column_information
+ end
+
+ def remove_counter_column_from(model)
+ model.connection.remove_column model.table_name, :test_count
+ model.reset_column_information
+ end
+
+ def counter_test(model, expected_count)
+ add_counter_column_to(model)
+ object = model.find(:first)
+ assert_equal 0, object.test_count
+ assert_equal 0, object.send(model.locking_column)
+ yield object.id
+ object.reload
+ assert_equal expected_count, object.test_count
+ assert_equal 1, object.send(model.locking_column)
+ ensure
+ remove_counter_column_from(model)
+ end
end

0 comments on commit 8375237

Please sign in to comment.
Something went wrong with that request. Please try again.