Skip to content

Instantly share code, notes, and snippets.

@walkermatt
Last active July 30, 2023 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkermatt/4cc463c66e36f3971462a46a3a38ae57 to your computer and use it in GitHub Desktop.
Save walkermatt/4cc463c66e36f3971462a46a3a38ae57 to your computer and use it in GitHub Desktop.
Postgres testing utilities
-- 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