From 2cfa43d84caf72214ed2a4a40fd3ceb9dd92bb65 Mon Sep 17 00:00:00 2001 From: Ryan Krage Date: Thu, 6 Jun 2024 20:17:19 +0000 Subject: [PATCH] Test to ensure lock is released after failed query --- spec/safe_statements_spec.rb | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/spec/safe_statements_spec.rb b/spec/safe_statements_spec.rb index 7d7f988..ea45578 100644 --- a/spec/safe_statements_spec.rb +++ b/spec/safe_statements_spec.rb @@ -4131,7 +4131,7 @@ def up ) end - it "releases the lock (even after an exception)" do + it "releases the lock even after an exception" do begin migration.safely_acquire_lock_for_table(table_name) do raise "bogus error" @@ -4142,6 +4142,32 @@ def up expect(locks_for_table(table_name, connection: alternate_connection)).to be_empty end + it "releases the lock even after a swallowed postgres exception" do + migration.safely_acquire_lock_for_table(table_name) do + expect(locks_for_table(table_name, connection: alternate_connection)).to contain_exactly( + having_attributes( + table: "bogus_table", + lock_type: "AccessExclusiveLock", + granted: true, + pid: kind_of(Integer), + ), + ) + + begin + migration.connection.execute("SELECT * FROM garbage") + rescue + end + + expect(locks_for_table(table_name, connection: alternate_connection)).to be_empty + + expect do + migration.connection.execute("SELECT * FROM bogus_table") + end.to raise_error(ActiveRecord::StatementInvalid, /PG::InFailedSqlTransaction/) + end + + expect(locks_for_table(table_name, connection: alternate_connection)).to be_empty + end + it "waits to acquire a lock if the table is already blocked" do block_call_count = 0 expect(PgHaMigrations::BlockingDatabaseTransactions).to receive(:find_blocking_transactions).exactly(3).times do |*args|