Skip to content

Commit

Permalink
raise exception if not in transaction
Browse files Browse the repository at this point in the history
better message

add test

fix
  • Loading branch information
donbobka committed Apr 21, 2023
1 parent 00f1cfe commit e15bdfd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/with_advisory_lock/postgresql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ class PostgreSQL < Base
# See http://www.postgresql.org/docs/9.1/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
def try_lock
pg_function = "pg_try_advisory#{transaction ? '_xact' : ''}_lock#{shared ? '_shared' : ''}"

raise "#{pg_function} requires transaction" if transaction && !ActiveRecord::Base.connection.transaction_open?

execute_successful?(pg_function)
end

Expand Down
10 changes: 10 additions & 0 deletions test/transaction_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,15 @@ def pg_lock_count
end
assert_equal(0, pg_lock_count)
end

specify 'transaction level locks fail if not in transaction' do
exception = assert_raises do
Tag.with_advisory_lock 'test', transaction: true do
raise 'should not get here'
end
end

assert_match(/#{Regexp.escape('requires transaction')}/, exception.message)
end
end
end

0 comments on commit e15bdfd

Please sign in to comment.