Created
September 16, 2021 19:20
-
-
Save pmalmgren/9b0307e681f07cfe7b67b3dcf350e21d to your computer and use it in GitHub Desktop.
gating migrations in SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION raise_notice(text) | |
RETURNS void AS $$ | |
BEGIN | |
RAISE NOTICE '%', $1; | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE OR REPLACE FUNCTION acquire_lock(bigint) | |
RETURNS bool AS $$ | |
BEGIN | |
IF (SELECT pg_try_advisory_lock($1) = 't') THEN | |
PERFORM raise_notice('acquired lock, continuing.'); | |
RETURN 't'; | |
ELSE | |
PERFORM raise_notice('failed to acquire lock.'); | |
PERFORM pg_advisory_lock($1); | |
PERFORM raise_notice('lock finished, good bye'); | |
PERFORM pg_advisory_unlock_all(); | |
RAISE EXCEPTION 'refusing to perform migration'; | |
RETURN 'f'; | |
END IF; | |
END; | |
$$ LANGUAGE plpgsql; | |
\set ON_ERROR_STOP on | |
SELECT acquire_lock(12); | |
\set ON_ERROR_STOP off | |
SELECT raise_notice('running migration'); | |
SELECT pg_sleep(15); | |
SELECT raise_notice('finished migration'); | |
SELECT pg_advisory_unlock_all(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment