Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial commit to select_and_update_all.

  • Loading branch information...
commit 899b2796b4e34f820c1160d3ec0c909c244cf8cc 0 parents
@neglectedvalue authored
5 .document
@@ -0,0 +1,5 @@
+lib/**/*.rb
+bin/*
+-
+features/**/*.feature
+LICENSE.txt
42 .gitignore
@@ -0,0 +1,42 @@
+# rcov generated
+coverage
+
+# rdoc generated
+rdoc
+
+# yard generated
+doc
+.yardoc
+
+# bundler
+.bundle
+
+# jeweler generated
+pkg
+
+# Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore:
+#
+# * Create a file at ~/.gitignore
+# * Include files you want ignored
+# * Run: git config --global core.excludesfile ~/.gitignore
+#
+# After doing this, these files will be ignored in all your git projects,
+# saving you from having to 'pollute' every project you touch with them
+#
+# Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line)
+#
+# For MacOS:
+#
+#.DS_Store
+#
+# For TextMate
+#*.tmproj
+#tmtags
+#
+# For emacs:
+#*~
+#\#*
+#.\#*
+#
+# For vim:
+#*.swp
17 Gemfile
@@ -0,0 +1,17 @@
+source "http://rubygems.org"
+
+gem "activerecord", "~>2.3"
+gem "activesupport", "~>2.3"
+
+group :development do
+ gem "bundler", "~> 1.0.0"
+ gem "jeweler", "~> 1.5.2"
+ gem "sqlite3"
+ gem "memprof" if RUBY_VERSION < '1.9'
+end
+
+group :test do
+ gem "shoulda", ">= 0"
+ gem "shoulda-context", ">= 0"
+ gem "rcov", ">= 0"
+end
29 Gemfile.lock
@@ -0,0 +1,29 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ activerecord (2.3.11)
+ activesupport (= 2.3.11)
+ activesupport (2.3.11)
+ git (1.2.5)
+ jeweler (1.5.2)
+ bundler (~> 1.0.0)
+ git (>= 1.2.5)
+ rake
+ rake (0.8.7)
+ rcov (0.9.9)
+ shoulda (2.11.3)
+ shoulda-context (1.0.0.beta1)
+ sqlite3 (1.3.3)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ activerecord (~> 2.3)
+ activesupport (~> 2.3)
+ bundler (~> 1.0.0)
+ jeweler (~> 1.5.2)
+ rcov
+ shoulda
+ shoulda-context
+ sqlite3
20 LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2011 Denis Sukhonin
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 README.rdoc
@@ -0,0 +1,19 @@
+= select_and_update_all
+
+Description goes here.
+
+== Contributing to select_and_update_all
+
+* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
+* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
+* Fork the project
+* Start a feature/bugfix branch
+* Commit and push until you are happy with your contribution
+* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
+* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
+
+== Copyright
+
+Copyright (c) 2011 Denis Sukhonin. See LICENSE.txt for
+further details.
+
48 Rakefile
@@ -0,0 +1,48 @@
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development, :test)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require 'rake'
+
+require 'jeweler'
+Jeweler::Tasks.new do |gem|
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
+ gem.name = "select_and_update_all"
+ gem.homepage = "http://github.com/neglectedvalue/select_and_update_all"
+ gem.license = "MIT"
+ gem.description = gem.summary = "Adds select_and_update_all which do update_all with callbacks."
+ gem.email = "d.sukhonin@gmail.com"
+ gem.authors = ["Denis Sukhonin"]
+end
+Jeweler::RubygemsDotOrgTasks.new
+
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+ test.libs << 'lib' << 'test'
+ test.pattern = 'test/**/test_*.rb'
+ test.verbose = true
+end
+
+require 'rcov/rcovtask'
+Rcov::RcovTask.new do |test|
+ test.libs << 'test'
+ test.pattern = 'test/**/test_*.rb'
+ test.verbose = true
+end
+
+task :default => :test
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
+
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "select_and_update_all #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
80 lib/select_and_update_all.rb
@@ -0,0 +1,80 @@
+require 'continuation' if RUBY_VERSION > '1.9'
+
+module SelectAndUpdateAll
+ def self.included(base)
+ base.send :alias_method_chain, :update, :callbacks
+ end
+
+ def update_with_callbacks(*args)
+ return false if callback(:before_update) == false
+ kk = callcc { |k| return k }
+ result = self.class.instance_method(:update_without_callbacks).bind(self).call(*args)
+ kk = callcc { |k| kk.call(k) }
+ callback(:after_update)
+ kk.call(result)
+ end
+end
+
+class ActiveRecord::Base
+ def self.select_and_update_all(updates, conditions = nil, options = {})
+ changed_fields = sanitize_sql_for_assignment(updates).split(', ').
+ reduce({}) do |h, sql|
+ sql =~ /([a-zA-Z0-9_]+)\s+=\s+(.*)/
+ h[$1] = $2; h
+ end
+
+ model = model_name.constantize
+ hash_for_select = model.column_names.reduce({}) do |h, name|
+ h[name] = name; h
+ end
+ select_clause = changed_fields.reduce(hash_for_select) do |h, (field, value)|
+ h["#{field}_new"] = value; h
+ end.map do |field, value|
+ "#{value} AS #{field}"
+ end.join(', ')
+
+ model.find_in_batches(options.merge({:select => select_clause, :conditions => conditions, :batch_size => 1000})) do |objs|
+ objs.map! do |o|
+ o.tap do |o|
+ class << o
+ include SelectAndUpdateAll
+ end
+
+ changed_fields.keys.each do |field|
+ o.send("#{field}=", o.send("#{field}_new"))
+ end
+ end
+ end
+
+ # Run before callbacks.
+ ks = objs.map {|o| o.send :update}
+
+ # Undirty attributes the will be modified by update_all.
+ objs.each do |o|
+ changed_fields.keys.each do |field|
+ (o.send :changed_attributes).delete(field)
+ end
+ end
+
+ # Run actually update_all.
+ # result = update_all(updates, conditions, options)
+ result = update_all(updates, {:id => objs.map(&:id)}, options)
+
+ # Run objects' update.
+ ks.map! do |k|
+ callcc do |kk|
+ k.call(kk)
+ end
+ end
+
+ # Run after callbacks.
+ ks.map! do |k|
+ callcc do |kk|
+ k.call(kk)
+ end
+ end
+
+ result
+ end
+ end
+end
17 test/database.example.yml
@@ -0,0 +1,17 @@
+sqlite:
+ adapter: sqlite
+ database: ":memory:"
+sqlite3:
+ adapter: sqlite3
+ database: ":memory:"
+postgresql:
+ adapter: postgresql
+ database: ancestry_test
+ username: ancestry
+ password: ancestry
+mysql:
+ adapter: mysql
+ host: localhost
+ database: ancestry_test
+ username: ancestry
+ password: ancestry
39 test/helper.rb
@@ -0,0 +1,39 @@
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development, :test)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require 'active_support/test_case'
+require 'test/unit'
+require 'shoulda'
+Gem.activate 'activerecord', '~>2.3'
+require 'active_record'
+require 'sqlite3'
+
+if RUBY_VERSION < '1.9'
+ require 'memprof'
+else
+ class Memprof
+ class << self
+ def method_missing(*args)
+ true
+ end
+ end
+ end
+end
+
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+$LOAD_PATH.unshift(File.dirname(__FILE__))
+require 'select_and_update_all'
+
+ActiveRecord::Base.logger = Logger.new File.new('test.log', 'w+'), Logger::INFO
+ActiveRecord::Base.establish_connection YAML.load(File.open(File.join(File.dirname(__FILE__), 'database.yml')).read)[ENV['db'] || 'sqlite3']
+
+ActiveRecord::Base.connection.create_table 'test_entries' do |t|
+ t.string :name
+ t.integer :number
+end
94 test/test_select_and_update_all.rb
@@ -0,0 +1,94 @@
+require 'helper'
+
+class TestEntry < ActiveRecord::Base
+ @@before_called = 0
+ @@after_called = 0
+
+ def self.before_called
+ @@before_called
+ end
+ def self.after_called
+ @@after_called
+ end
+
+ def before_update
+ @@before_called += 1
+ self.name = self.number.to_s if self.number_changed?
+ end
+ def after_update
+ @@after_called += 1
+ end
+end
+
+N = 10
+(1..N).each {|i| TestEntry.create!(:name => i.to_s, :number => i ** 2) }
+
+class TestSelectAndUpdateAll < ActiveSupport::TestCase
+ context "with #{N} entries in test_entries" do
+ should "have squares in test_entries.number" do
+ squares = (1..N).map {|x| x ** 2 }
+
+ numbers = TestEntry.all.map(&:number)
+ assert_equal numbers.to_set, squares.to_set
+ assert_equal numbers.size, squares.size
+ end
+
+ should "update all test_entries.number to id^3 with calling callbacks" do
+ assert_difference 'TestEntry.before_called', N do
+ assert_difference 'TestEntry.after_called', N do
+ # Memprof.start
+ TestEntry.select_and_update_all("number = id * id * id")
+ # GC.start
+ # Memprof.stats
+ # Memprof.dump
+ # Memprof.stop
+
+ ids = TestEntry.all.map(&:id)
+ cubes = ids.map {|x| x ** 3}
+
+ numbers = TestEntry.all.map(&:number)
+ assert_equal numbers.to_set, cubes.to_set
+ assert_equal numbers.size, cubes.size
+
+ names = TestEntry.all.map(&:name).sort
+ assert_equal names.to_set, cubes.map(&:to_s).to_set
+ assert_equal names.size, cubes.size
+ end
+ end
+ end
+
+ should "update all test_entries.number to id^4 without calling callbacks" do
+ assert_no_difference 'TestEntry.before_called' do
+ assert_no_difference 'TestEntry.after_called' do
+ names_was = TestEntry.all.map(&:name).sort
+
+ TestEntry.update_all("number = id * id * id * id")
+ ids = TestEntry.all.map(&:id)
+ tetras = ids.map {|x| x ** 4}
+
+ numbers = TestEntry.all.map(&:number)
+ assert_equal numbers.to_set, tetras.to_set
+ assert_equal numbers.size, tetras.size
+
+ names = TestEntry.all.map(&:name).sort
+ assert_equal names.to_set, names_was.to_set
+ assert_equal names.size, names_was.size
+ end
+ end
+ end
+
+ should "update a test_entries.number to id^5 with calling callbacks" do
+ assert_difference 'TestEntry.before_called', 1 do
+ assert_difference 'TestEntry.after_called', 1 do
+ entry = TestEntry.last
+ entry.number = entry.id ** 5
+ entry.save
+
+ entry.reload
+ assert_equal entry.number, entry.id ** 5
+ assert_equal entry.name, entry.number.to_s
+ end
+ end
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.