diff --git a/lib/with_advisory_lock/postgresql.rb b/lib/with_advisory_lock/postgresql.rb index ae369cb..343470a 100644 --- a/lib/with_advisory_lock/postgresql.rb +++ b/lib/with_advisory_lock/postgresql.rb @@ -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 diff --git a/test/transaction_test.rb b/test/transaction_test.rb index e0e224f..65fee52 100644 --- a/test/transaction_test.rb +++ b/test/transaction_test.rb @@ -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