Skip to content

Instantly share code, notes, and snippets.

@tkhn
Forked from toke/advisory_locks_example.sql
Created January 18, 2022 21:32
Show Gist options
  • Save tkhn/08441f5f29f88608c518efbedadeca8e to your computer and use it in GitHub Desktop.
Save tkhn/08441f5f29f88608c518efbedadeca8e to your computer and use it in GitHub Desktop.
Example for advisory locks in postgresql
do $$
DECLARE
ADV_LOCK BOOLEAN DEFAULT FALSE;
LOCK_ID INTEGER DEFAULT 50;
BEGIN
-- EARLY LOCK
-- LOCK_ID := 'tablename'::regclass::integer;
SELECT pg_try_advisory_lock(LOCK_ID) into ADV_LOCK;
RAISE NOTICE 'LOCK_ID: %', LOCK_ID;
IF ADV_LOCK THEN
RAISE INFO 'Start function';
ELSE
RAISE INFO 'Another function running, exiting';
RETURN;
END IF;
RAISE INFO 'BEGIN CODE BLOCK, start waiting';
-- Don't forget to call `PERFORM pg_advisory_unlock(LOCK_ID);` before returning.
PERFORM pg_sleep(5);
RAISE INFO 'END CODE BLOCK, stop waiting';
-- UNLOCK
PERFORM pg_advisory_unlock(LOCK_ID);
exception when QUERY_CANCELED then
-- Cleanup lock
PERFORM pg_advisory_unlock(LOCK_ID);
END$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment