ActiveRecord::Transaction#open? returns false if the transaction is finalized

Followup: https://github.com/rails/rails/pull/52104
This commit is contained in:
Jean Boussier 2024-06-13 10:41:33 +02:00
parent 1eb5761327
commit 884af53be2
2 changed files with 27 additions and 2 deletions

@ -94,12 +94,14 @@ def after_rollback(&block)
@internal_transaction&.after_rollback(&block)
end
# Returns true if the transaction exists and isn't finalized yet
def open?
@internal_transaction&.open?
!closed?
end
# Returns true if the transaction doesn't exists or is finalized (committed or rolled back)
def closed?
!open?
@internal_transaction.nil? || @internal_transaction.state.finalized?
end
alias_method :blank?, :closed?

@ -12,6 +12,29 @@
require "models/cpk"
module TransactionCallbacksTests
SomeError = Class.new(StandardError)
def test_transaction_open?
assert_predicate Topic.current_transaction, :closed?
committed_transaction = nil
Topic.transaction do
assert_predicate Topic.current_transaction, :open?
committed_transaction = Topic.current_transaction
end
assert_predicate committed_transaction, :closed?
rolledback_transaction = nil
assert_raises SomeError do
Topic.transaction do
assert_predicate Topic.current_transaction, :open?
rolledback_transaction = Topic.current_transaction
raise SomeError
end
end
assert_predicate rolledback_transaction, :closed?
end
def test_after_all_transactions_commit
called = 0
ActiveRecord.after_all_transactions_commit { called += 1 }