CREATE TABLE func_update_identity(
    change_id INTEGER NOT NULL,
    id INTEGER NOT NULL,
    name VARCHAR,
    shortname VARCHAR,
    contact_id INTEGER,
    default_contact_method_id INTEGER
);

CREATE TRIGGER
    func_update_identity_bi_1
BEFORE INSERT ON
    func_update_identity
FOR EACH ROW BEGIN

    SELECT debug(
        NEW.id,
        NEW.change_id,
        NEW.name,
        NEW.shortname,
        NEW.contact_id,
        NEW.default_contact_method_id
    );

    UPDATE
        changes
    SET
        yaml = yaml || (
            SELECT
                '-' || x'0A'
                || '  _delta: update_identity' || x'0A'
                || '  contact_uuid: ' || COALESCE(con.uuid,'~') || x'0A'
                || '  default_contact_method_uuid: '
                || COALESCE(dcm.uuid,'~') || x'0A'
                || '  name: ' || COALESCE(NEW.name,'~') || x'0A'
                || '  shortname: ' || COALESCE(NEW.shortname,'~') || x'0A'
                || '  uuid: ' || i.uuid || x'0A'
            FROM
                topics i
            LEFT JOIN
                topics con
            ON
                con.id = NEW.contact_id
            LEFT JOIN
                topics dcm
            ON
                dcm.id = NEW.default_contact_method_id
            WHERE
                i.id = NEW.id
        )
    WHERE
        id = NEW.change_id
    ;

    INSERT INTO deltas(
        id,
        change_id,
        action
    )
    VALUES(
        nextval('deltas'),
        NEW.change_id,
        'update_identity'
    );

    INSERT INTO
        entity_deltas(
            id,
            change_id,
            entity_id,
            name,
            contact_id,
            default_contact_method_id
        )
    VALUES(
        currval('deltas'),
        NEW.change_id,
        NEW.id,
        NEW.name,
        NEW.contact_id,
        NEW.default_contact_method_id
    );

    INSERT INTO
        identity_deltas(
            id,
            change_id,
            identity_id,
            shortname
        )
    VALUES(
        currval('deltas'),
        NEW.change_id,
        NEW.id,
        NEW.shortname
    );

    SELECT RAISE(IGNORE);

END;

