-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbatch_in_transaction.rb
83 lines (74 loc) · 2.17 KB
/
batch_in_transaction.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true
module RuboCop
module Cop
module Migration
# Disable transaction in batch processing.
#
# To avoid locking the table.
#
# @safety
# There are some cases where transaction is really needed.
#
# @example
# # bad
# class AddSomeColumnToUsersThenBackfillSomeColumn < ActiveRecord::Migration[7.0]
# def change
# add_column :users, :some_column, :text
# User.update_all(some_column: 'some value')
# end
# end
#
# # good
# class AddSomeColumnToUsers < ActiveRecord::Migration[7.0]
# def change
# add_column :users, :some_column, :text
# end
# end
#
# class BackfillSomeColumnToUsers < ActiveRecord::Migration[7.0]
# disable_ddl_transaction!
#
# def up
# User.unscoped.in_batches do |relation|
# relation.update_all(some_column: 'some value')
# sleep(0.01)
# end
# end
# end
class BatchInTransaction < RuboCop::Cop::Base
extend AutoCorrector
include ::RuboCop::Migration::CopConcerns::BatchProcessing
include ::RuboCop::Migration::CopConcerns::DisableDdlTransaction
MSG = 'Disable transaction in batch processing.'
RESTRICT_ON_SEND = %i[
delete_all
update_all
].freeze
# @param node [RuboCop::AST::SendNode]
# @return [void]
def on_send(node)
return unless wrong?(node)
add_offense(node) do |corrector|
autocorrect(corrector, node)
end
end
private
# @param corrector [RuboCop::Cop::Corrector]
# @param node [RuboCop::AST::SendNode]
# @return [void]
def autocorrect(
corrector,
node
)
insert_disable_ddl_transaction(corrector, node)
end
# @param node [RuboCop::AST::SendNode]
# @return [Boolean]
def wrong?(node)
batch_processing?(node) &&
!within_disable_ddl_transaction?(node)
end
end
end
end
end