@@ -12,6 +12,7 @@ def self.call(*args)
1212 attribute :rows , Array [ Row ]
1313 attribute :when_invalid , Symbol
1414 attribute :after_save_blocks , Array [ Proc ] , default : [ ]
15+ attribute :sql_transaction , Symbol
1516
1617 attribute :report , Report , default : proc { Report . new }
1718
@@ -41,38 +42,48 @@ def abort_when_invalid?
4142 when_invalid == :abort
4243 end
4344
45+ def sql_transaction_all_rows?
46+ sql_transaction == :all_rows
47+ end
48+
49+ def sql_transaction_one_row?
50+ sql_transaction == :each_row
51+ end
52+
4453 def persist_rows!
45- transaction do
54+ full_transaction do
4655 rows . each do |row |
47- tags = [ ]
56+ transaction do
57+ tags = [ ]
4858
49- if row . model . persisted?
50- tags << :update
51- else
52- tags << :create
53- end
54-
55- if row . skip?
56- tags << :skip
57- elsif row . errors . size > 0
58- tags << :failure
59- else
60- if row . model . save
61- tags << :success
59+ if row . model . persisted?
60+ tags << :update
6261 else
62+ tags << :create
63+ end
64+
65+ if row . skip?
66+ tags << :skip
67+ elsif row . errors . size > 0
6368 tags << :failure
69+ else
70+ if row . model . save
71+ tags << :success
72+ else
73+ tags << :failure
74+ end
6475 end
65- end
6676
67- add_to_report ( row , tags )
77+ add_to_report ( row , tags )
6878
69- after_save_blocks . each do |block |
70- case block . arity
71- when 0 then block . call
72- when 1 then block . call ( row . model )
73- when 2 then block . call ( row . model , row . csv_attributes )
74- else
75- raise ArgumentError , "after_save block of arity #{ block . arity } is not supported"
79+ after_save_blocks . each do |block |
80+ case block . arity
81+ when 0 then block . call
82+ when 1 then block . call ( row . model )
83+ when 2 then block . call ( row . model , row . csv_attributes )
84+ else
85+ raise ArgumentError , "after_save block of arity #{ block . arity } is not supported"
86+ end
7687 end
7788 end
7889 end
@@ -102,8 +113,20 @@ def add_to_report(row, tags)
102113 raise ImportAborted if abort_when_invalid? && tags [ 1 ] == :failure
103114 end
104115
116+ def full_transaction ( &block )
117+ if sql_transaction_all_rows?
118+ rows . first . model . class . transaction ( &block )
119+ else
120+ block . call
121+ end
122+ end
123+
105124 def transaction ( &block )
106- rows . first . model . class . transaction ( &block )
125+ if sql_transaction_one_row?
126+ rows . first . model . class . transaction ( &block )
127+ else
128+ block . call
129+ end
107130 end
108131 end
109132end
0 commit comments