Skip to content

Commit

Permalink
Fix to support activerecord-import
Browse files Browse the repository at this point in the history
  • Loading branch information
gussan committed Jun 4, 2018
1 parent 27d2b28 commit 3b4114b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
Expand Up @@ -3,10 +3,9 @@ module ActiveRecordExt
# activerecord-import extension
module ActiverecordImportExt
# @note override for sequencer injection
# @see https://github.com/zdennis/activerecord-import/blob/b325ebb644160a09db6e269e414f33561cb21272/lib/activerecord-import/import.rb#L661-L689
# @see https://github.com/zdennis/activerecord-import/blob/85586d052822b8d498ced6c900251997edbeee04/lib/activerecord-import/import.rb#L848-L883
private def values_sql_for_columns_and_attributes(columns, array_of_attributes)
connection_memo = connection
type_caster_memo = type_caster if respond_to?(:type_caster)

array_of_attributes.map do |arr|
my_values = arr.each_with_index.map do |val, j|
Expand All @@ -15,12 +14,16 @@ module ActiverecordImportExt
# be sure to query sequence_name *last*, only if cheaper tests fail, because it's costly
if val.nil? && column.name == primary_key && !sequence_name.blank?
if sequencer_enabled?
connection_memo.next_sequence_value(sequence_name)
self.next_sequence_value
else
connection_memo.next_value_for_sequence(sequence_name)
end
elsif val.respond_to?(:to_sql)
"(#{val.to_sql})"
elsif column
connection_memo.quote(type_caster_memo.type_cast_for_database(column.name, val))
type = type_for_attribute(column.name)
val = type.type == :boolean ? type.cast(val) : type.serialize(val)
connection_memo.quote(val)
end
end
"(#{my_values.join(',')})"
Expand All @@ -31,6 +34,8 @@ module ActiverecordImportExt
begin
require "activerecord-import"
require "activerecord-import/base"
require "activerecord-import/active_record/adapters/mysql2_adapter"
ActiveRecord::Turntable::ConnectionProxy.include(ActiveRecord::Import::Mysql2Adapter)
(class << ActiveRecord::Base; self; end).prepend(ActiverecordImportExt)
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
Expand Down
@@ -0,0 +1,28 @@
require "spec_helper"
require "active_record/turntable/active_record_ext/activerecord_import_ext"

describe ActiveRecord::Turntable::ActiveRecordExt::ActiverecordImportExt do
context "With sequencer enabled model" do
subject { -> { UserItem.import(rows) } }

let(:rows) do
[
build(:user_item, user: create(:user, :in_shard1)),
build(:user_item, user: create(:user, :in_shard2)),
]
end

it { is_expected.not_to raise_error }
it "creates one record on shard_1" do
subject.call
item_count = UserItem.with_shard(1) { UserItem.count }
expect(item_count).to eq(1)
end

it "creates one record on shard_2" do
subject.call
item_count = UserItem.with_shard(20001) { UserItem.count }
expect(item_count).to eq(1)
end
end
end

0 comments on commit 3b4114b

Please sign in to comment.