Skip to content

Commit 4a4b399

Browse files
authored
Merge pull request rails#52113 from Shopify/transaction-committed-open
`ActiveRecord::Transaction#open?` returns false if the transaction is finalized
2 parents 1eb5761 + 884af53 commit 4a4b399

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

activerecord/lib/active_record/transaction.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,14 @@ def after_rollback(&block)
9494
@internal_transaction&.after_rollback(&block)
9595
end
9696

97+
# Returns true if the transaction exists and isn't finalized yet
9798
def open?
98-
@internal_transaction&.open?
99+
!closed?
99100
end
100101

102+
# Returns true if the transaction doesn't exists or is finalized (committed or rolled back)
101103
def closed?
102-
!open?
104+
@internal_transaction.nil? || @internal_transaction.state.finalized?
103105
end
104106

105107
alias_method :blank?, :closed?

activerecord/test/cases/transactions_test.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,29 @@
1212
require "models/cpk"
1313

1414
module TransactionCallbacksTests
15+
SomeError = Class.new(StandardError)
16+
17+
def test_transaction_open?
18+
assert_predicate Topic.current_transaction, :closed?
19+
20+
committed_transaction = nil
21+
Topic.transaction do
22+
assert_predicate Topic.current_transaction, :open?
23+
committed_transaction = Topic.current_transaction
24+
end
25+
assert_predicate committed_transaction, :closed?
26+
27+
rolledback_transaction = nil
28+
assert_raises SomeError do
29+
Topic.transaction do
30+
assert_predicate Topic.current_transaction, :open?
31+
rolledback_transaction = Topic.current_transaction
32+
raise SomeError
33+
end
34+
end
35+
assert_predicate rolledback_transaction, :closed?
36+
end
37+
1538
def test_after_all_transactions_commit
1639
called = 0
1740
ActiveRecord.after_all_transactions_commit { called += 1 }

0 commit comments

Comments
 (0)