Gem sequel-pg_advisory_lock
is an extension for ruby Sequel library
that allows using PostgreSQL advisory locks
for application-level mutexes.
Add this line to your application's Gemfile:
gem 'sequel-pg_advisory_lock'
and then execute:
$ bundle
Or install it yourself as:
$ gem install sequel-pg_advisory_lock
First, you should load an extension for Sequel::Database
instance:
DB.extension :pg_advisory_lock
Then, you should register new lock by specifying unique name:
DB.register_advisory_lock(:my_lock)
By default, pg_advisory_lock
PostgreSQL function will be associated with registered lock.
It's also possible to specify different function in second parameter of register_advisory_lock
method, for example:
DB.register_advisory_lock(:my_lock, :pg_try_advisory_lock)
All supported lock functions are described here.
Finally, you can use registered lock:
DB.with_advisory_lock(:my_lock) do
# do something
# this block works like application-level mutex,
# so code inside block is protected from concurrent execution
end
An optional 4-bytes integer parameter can be passed to with_advisory_lock
method call:
DB.with_advisory_lock(:my_lock, 1) do
# do something
# this block works like application-level mutex,
# so code inside block is protected from concurrent execution
end
There are 4 supported PostgreSQL lock functions which can be used in register_advisory_lock
:
-
pg_advisory_lock
(default)Waits of lock releasing if someone already owns requested lock.
-
pg_try_advisory_lock
Doesn't wait of lock releasing, returns nil if someone already owns requested lock.
-
pg_advisory_xact_lock
Waits of lock releasing if someone already owns requested lock.
Releases lock immediately after database transaction ends.
Requires manually opened transaction before using this lock. -
pg_try_advisory_xact_lock
Doesn't wait of lock releasing, returns nil if someone already owns requested lock.
Releases lock immediately after database transaction ends.
Requires manually opened transaction before using this lock.
For more information see PostgreSQL documentation.
- Fork the project (https://github.com/yuryroot/sequel-pg_advisory_lock).
- Create your feature branch (
git checkout -b my-new-feature
). - Implement your feature or bug fix.
- Add tests for your feature or bug fix.
- Run
rake
to make sure all tests pass. - Commit your changes (
git commit -am 'Add new feature'
). - Push to the branch (
git push origin my-new-feature
). - Create new pull request.