Database Locks
Table of Contents
:ID: D111FFA2-4A9D-41F4-87DC-E59F3D6E8564
See also https://www.postgresql.org/docs/current/explicit-locking.html
# Lock Timeout
In order to prevent transaction from waiting a long time to obtain a lock, use
the lock_timeout
parameter. It can be set globally or per transaction.
# lock timeout
BEGIN; SET LOCAL lock_timeout = '5s'; ALTER TABLE things ADD COLUMN foo_id INTEGER; END;
This will timeout after 5 seconds if the transaction cannot obtain a lock. It will throw:
ERROR: canceling statement due to lock timeout
# Row locking
# FOR UPDATE
This clause is used as part of a select query and can define:
- The lock strength. See also https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS
- Name the specific tables in the query whose rows should be locked. If no table is specified, all tables used in the query are locked.
- What action to take if encountering lock contention
See also https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE
# Advisory Locks
These aren’t row locks, but worth mentioning. You can use these to control concurrency in general, even things not explicitly tied to data in the database. See also:
- https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS
- https://www.postgresql.org/docs/current/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
For using advisory locks in RoR, see https://github.com/ClosureTree/with_advisory_lock