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

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

	NEW.value = COALESCE(NEW.value, OLD.value);

	IF NEW.value IS DISTINCT FROM OLD.value THEN
		_changed = TRUE;
	END IF;

	IF _changed THEN
		UPDATE admin.follow SET
			value = NEW.value,
			modified = clock_timestamp()
			WHERE id = OLD.id;
	END IF;

	RETURN NEW;
END
$BODY$;

GRANT EXECUTE ON FUNCTION _api.follow_update()
	TO rest_user;
GRANT UPDATE ON TABLE api.follow
	TO rest_user;
GRANT UPDATE ON TABLE admin.follow
	TO rest_user;

CREATE TRIGGER api_follow_update_trgr
	INSTEAD OF UPDATE
			ON api.follow
			FOR EACH ROW
				EXECUTE PROCEDURE _api.follow_update();
