Last active
July 30, 2023 15:17
-
-
Save walkermatt/4cc463c66e36f3971462a46a3a38ae57 to your computer and use it in GitHub Desktop.
Postgres testing utilities
This file contains 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
-- Raises an exception with `failure_message` if `sql_text` does not throw an exception at all. | |
-- If an exception is thrown but it's SQLSTATE doesn't match `expected_sql_state` then that | |
-- exception is RE-RAISED | |
CREATE OR REPLACE FUNCTION pg_temp.test__throws_exception(sql_text text, expected_sql_state text, failure_message text) RETURNS void AS $$ | |
DECLARE | |
sql_state text; | |
BEGIN | |
EXECUTE sql_text; | |
RAISE EXCEPTION '%', failure_message; | |
EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS sql_state = RETURNED_SQLSTATE; | |
IF sql_state = expected_sql_state THEN | |
-- Swallow the expected exception | |
ELSE | |
-- Ensure we RE-RAISE the exception as something else might be wrong such as a syntax error in sql_text | |
RAISE; | |
END IF; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment