Created
April 7, 2018 10:46
-
-
Save klapuch/ecb459510552dc7094393e2c71da0614 to your computer and use it in GitHub Desktop.
Checks enum values
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
CREATE FUNCTION check_enum_value(in_enum text, in_value text, in_name text = NULL) RETURNS void AS $BODY$ | |
DECLARE | |
items text[]; | |
BEGIN | |
EXECUTE(format('SELECT enum_range(null::%I)::text', in_enum)) INTO items; | |
IF (NOT(items @> ARRAY[in_value])) THEN | |
RAISE EXCEPTION USING MESSAGE = format( | |
$$'%s' must be one of: %s - '%s' was given$$, | |
CASE WHEN in_name IS NOT NULL THEN in_name ELSE in_enum END, | |
array_to_string( | |
(SELECT array_agg(format($$'%s'$$, item)) FROM unnest(items) AS item), | |
', ' | |
), | |
in_value | |
); | |
END IF; | |
END $BODY$ LANGUAGE plpgsql VOLATILE; | |
CREATE FUNCTION is_enum_value(in_enum text, in_value text) RETURNS boolean AS $$ | |
BEGIN | |
PERFORM check_enum_value(in_enum, in_value); | |
RETURN TRUE; | |
EXCEPTION WHEN OTHERS THEN RETURN FALSE; | |
END $$ LANGUAGE plpgsql VOLATILE; | |
CREATE FUNCTION is_enum_value(in_enum json, in_value json) RETURNS boolean AS $$ | |
BEGIN | |
PERFORM check_enum_value(in_enum, in_value); | |
RETURN TRUE; | |
EXCEPTION WHEN OTHERS THEN RETURN FALSE; | |
END $$ LANGUAGE plpgsql VOLATILE; | |
CREATE FUNCTION check_enum_value(in_enum json, in_value json) RETURNS void AS $$ | |
DECLARE | |
object record; | |
BEGIN | |
IF (in_value::text = '{}'::text) THEN | |
RETURN; | |
END IF; | |
FOR object IN SELECT key, value FROM json_each_text(in_enum) | |
LOOP | |
IF (in_value::jsonb ? object.key) THEN | |
PERFORM check_enum_value(object.value, in_value->>object.key, object.key); | |
END IF; | |
END LOOP; | |
END $$ LANGUAGE plpgsql VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment