Skip to content

Commit

Permalink
Merge pull request #137 from OpenGov/feature/optionSkipUpdateOnDup
Browse files Browse the repository at this point in the history
Allow for `:on_duplicate_key_update` to be turned off
  • Loading branch information
zdennis committed Jul 18, 2015
2 parents 50d39cb + 2fe222d commit 6c06b3c
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/activerecord-import/import.rb
Expand Up @@ -509,7 +509,7 @@ def add_special_rails_stamps( column_names, array_of_attributes, options )
array_of_attributes.each { |arr| arr << value }
end

if supports_on_duplicate_key_update?
if supports_on_duplicate_key_update? and options[:on_duplicate_key_update] != false
if options[:on_duplicate_key_update]
options[:on_duplicate_key_update] << key.to_sym if options[:on_duplicate_key_update].is_a?(Array) && !options[:on_duplicate_key_update].include?(key.to_sym)
options[:on_duplicate_key_update][key.to_sym] = key.to_sym if options[:on_duplicate_key_update].is_a?(Hash)
Expand Down
9 changes: 9 additions & 0 deletions test/support/mysql/assertions.rb
Expand Up @@ -39,6 +39,15 @@ def self.extended(klass)
assert_equal "johndoe@example.com", updated_topic.author_email_address
end

assertion(:should_raise_update_fields_mentioned) do
assert_raise ActiveRecord::RecordNotUnique do
perform_import
end

assert_equal "Book", updated_topic.title
assert_equal "john@doe.com", updated_topic.author_email_address
end

assertion(:should_update_fields_mentioned_with_hash_mappings) do
perform_import
assert_equal "johndoe@example.com", updated_topic.title
Expand Down
20 changes: 20 additions & 0 deletions test/support/mysql/import_examples.rb
Expand Up @@ -116,7 +116,27 @@ def should_support_mysql_import_functionality
should_update_fields_mentioned_with_hash_mappings
end
end

context "given array of model instances with :on_duplicate_key_update turned off" do
let(:columns){ %w( id title author_name author_email_address parent_id ) }
let(:values){ [ [ 100, "Book", "John Doe", "john@doe.com", 17 ] ] }
let(:updated_values){ [ [ 100, "Book - 2nd Edition", "This should raise an exception", "john@nogo.com", 57 ] ] }

macro(:perform_import) do |*opts|
# `:on_duplicate_key_update => false` is the tested feature
Topic.import columns, updated_values, opts.extract_options!.merge(:on_duplicate_key_update => false, :validate => false)
end

setup do
Topic.import columns, values, :validate => false
@topic = Topic.find 100
end

context "using string column names" do
let(:update_columns){ [ "title", "author_email_address", "parent_id" ] }
should_raise_update_fields_mentioned
end
end
end

describe "#import with :synchronization option" do
Expand Down

0 comments on commit 6c06b3c

Please sign in to comment.