CREATE TABLE _api.err_map (
	err		INTEGER,
	pg_err	TEXT
);

ALTER TABLE _api.err_map OWNER TO xssbook;

ALTER TABLE ONLY _api.err_map
	ADD CONSTRAINT err_map_pkey PRIMARY KEY (err);

INSERT INTO _api.err_map (err, pg_err)
VALUES
	(400, 'P0001'),
	(401, '42501'),
	(403, '42501'),
	(404, '42883'),
	(409, '23505'),
	(500, 'XX001');

CREATE FUNCTION _api.raise(
	_msg TEXT DEFAULT '',
	_detail TEXT DEFAULT '',
	_hint TEXT DEFAULT '',
	_err INTEGER DEFAULT 400
)
RETURNS BOOLEAN
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_pg_err TEXT;
BEGIN

	SELECT pg_err INTO _pg_err
		FROM _api.err_map
		WHERE err = _err;

	RAISE EXCEPTION USING
		MESSAGE := _msg,
		DETAIL := _detail,
		HINT := _hint,
		ERRCODE := _pg_err;

	RETURN FALSE;
END
$BODY$;

GRANT SELECT ON TABLE _api.err_map
	TO rest_anon, rest_user;
GRANT EXECUTE ON FUNCTION _api.raise(TEXT, TEXT, TEXT, INTEGER)
	TO rest_anon, rest_user;
