<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def oauth_link_external_id(user, external_id=None):
 """Link a user to an external id. :param user: A :class:`invenio_accounts.models.User` instance. :param external_id: The external id associated with the user. (Default: ``None``) :raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if already exists a link. """

    try:
        with db.session.begin_nested():
            db.session.add(UserIdentity(
                id=external_id['id'],
                method=external_id['method'],
                id_user=user.id
            ))
    except IntegrityError:
        raise AlreadyLinkedError(user, external_id)