-
-
Notifications
You must be signed in to change notification settings - Fork 263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ActiveRecord::Base.transaction with requires_new: true is recommended #400
Comments
I don't really know how hard it is to implement this but I like the idea of adding this cop. |
A potential for bugs when using If a nested transaction is created with In our case, we send record changes using For demonstration: class User < ApplicationRecord
after_commit :emit_change_message
def emit_change_mess
puts "Changing the user's name: #{first_name} #{last_name}"
# Log changes to kafka
...
end
end
ActiveRecord::Base.transaction(joinable: false, requires_new: true) do
User.last.update(first_name: "Transaction 1")
ActiveRecord::Base.transaction(joinable: false, requires_new: true) do
User.last.update(last_name: "Transaction 2")
raise ActiveRecord::Rollback
end
end
# => Changing user's name: first_name: Transaction 1, last_name: Doe
# => Changing user's name: first_name: Transaction 1, last_name: Transaction 2
User.last.first_name
# => "John"
User.last.last_name
# => "Doe" In the above example, the changes are rollbacked as expected but After noticing this, I think it best's to not recommend using Instead of recommending |
@tsrivishnu I have experienced the behavior you describe queuing sidekiq jobs in It does seem however the
|
Is your feature request related to a problem? Please describe.
Not all databases support nested transactions. Therefore, Rails will sometimes silently ignore a nested transaction and simply reuse the other transaction. However, a ActiveRecord::Rollback within the nested transaction will be caught by the block of the nested transaction. Therefore it will be ignored by the outer transaction, and not cause a roll back!
To avoid this unexpected behaviour, you have to explicitly tell rails for each transaction to indeed use proper nesting:
This is a safer default for working with custom transactions.
Source: https://makandracards.com/makandra/42885-nested-activerecord-transaction-pitfalls
Describe the solution you'd like
A rubocop Cop that would highlight
.transaction
withoutrequires_new: true
argument. I think it should be doable to implement it with autocorrect.Describe alternatives you've considered
I didn't consider any alternatives to implementing this as
rubocop-rails
cop.Additional context
This may be hard because Cop would need to check class hierarchy to see if for example
Email.transaction
is ActiveRecord transaction or is it SMTP or other type of transaction.The text was updated successfully, but these errors were encountered: