CREATE TRIGGER ai_issue_updates_1
AFTER INSERT ON
    issue_updates
FOR EACH ROW
BEGIN

    SELECT debug(
        'TRIGGER ai_issue_updates_1',
        NEW.update_id,
        NEW.issue_id,
        NEW.status_id,
        NEW.title
    );

    UPDATE
        updates
    SET
        ucount = ucount + 1
    WHERE
        id = NEW.update_id
    ;

    UPDATE
        updates_pending
    SET
        terms = terms || (
            SELECT
                'issue_update:' || x'0A'
                || '  issue_uuid:' || COALESCE(topics.uuid, '') || x'0A'
                || '  project_uuid:' || COALESCE(projects.uuid, '') || x'0A'
                || '  status_uuid:' || COALESCE(status.uuid, '') || x'0A'
                || '  title:' || COALESCE(NEW.title, '') || x'0A'
            FROM
                topics
            INNER JOIN
                topics AS projects
            ON
                projects.id = NEW.project_id
            LEFT JOIN
                topics AS status
            ON
                status.id = NEW.status_id
            WHERE
                topics.id = NEW.issue_id
        )
    WHERE
        update_id = NEW.update_id
    ;

    INSERT INTO
        project_related_updates(
            update_id,
            project_id
        )
    SELECT -- This catches the existing projects for the issue
        NEW.update_id,
        project_id
    FROM
        project_issues
    WHERE
        project_issues.issue_id = NEW.issue_id
    UNION SELECT   -- This catches the (possibly new) project of this update
        NEW.update_id,
        NEW.project_id
    ;

    INSERT OR IGNORE INTO
        issues_tomerge(issue_id)
    VALUES
        (NEW.issue_id)
    ;

    UPDATE
        issues_tomerge
    SET
        title = title + (NEW.title IS NOT NULL)
    WHERE
        issue_id = NEW.issue_id
    ;

END;