Skip to content

Commit 75a2c7f

Browse files
committed
Don't fail lock release if the connection was disconnected
If the connection is broken, then the lock was released because the session is aborted. Thus there is no need to fail.
1 parent 00f1cfe commit 75a2c7f

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

lib/with_advisory_lock/postgresql.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ def release_lock
1414
pg_function = "pg_advisory_unlock#{shared ? '_shared' : ''}"
1515
execute_successful?(pg_function)
1616
rescue ActiveRecord::StatementInvalid => e
17+
# If something goes real bad, pg will close the connection. in that case the lock is no longer held
18+
return if e.message =~ /PG::ConnectionBad:/
1719
raise unless e.message =~ / ERROR: +current transaction is aborted,/
1820

1921
begin

test/lock_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@
5656

5757
thread_with_lock.kill
5858
end
59+
60+
it 'handles lost connection gracefully' do
61+
Tag.with_advisory_lock(lock_name) { Tag.connection.disconnect! }
62+
63+
assert_nil(Tag.current_advisory_lock)
64+
end
5965
end
6066

6167
describe '.with_advisory_lock!' do

test/test_helper.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ def env_db
3737
module MiniTest
3838
class Spec
3939
before do
40+
ActiveRecord::Base.establish_connection
4041
ENV['FLOCK_DIR'] = Dir.mktmpdir
4142
Tag.delete_all
4243
TagAudit.delete_all

0 commit comments

Comments
 (0)