CREATE FUNCTION _api.user_delete()
RETURNS TRIGGER
LANGUAGE plpgsql VOLATILE
AS $BODY$
DECLARE
	_user_id INTEGER;
BEGIN
	_user_id = _api.get_user_id();

	IF OLD.id <> _user_id THEN
		PERFORM _api.raise_deny();
	END IF;

	DELETE FROM admin.user
	WHERE id = _user_id;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.user_delete()
	TO rest_user;
GRANT DELETE ON TABLE api.user
	TO rest_user;
GRANT DELETE ON TABLE admin.user
	TO rest_user;

CREATE TRIGGER api_user_delete_trgr
	INSTEAD OF DELETE
			ON api.user
			FOR EACH ROW
				EXECUTE PROCEDURE _api.user_delete();
