CREATE TRIGGER ai_hub_updates_1
AFTER INSERT ON
    hub_updates
FOR EACH ROW
BEGIN

    SELECT debug(
        'TRIGGER ai_hub_updates_1',
        NEW.update_id,
        NEW.related_update_uuid,
        NEW.hub_id,
        NEW.default_location_id
    );

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

    UPDATE
        updates_pending
    SET
        terms = terms || (
            SELECT
                'hub_update:' || x'0A'
                || '  hub_uuid:' || COALESCE(topics.uuid, '') || x'0A'
                || '  related_update_uuid:'
                    || COALESCE(NEW.related_update_uuid, '') || x'0A'
                || '  default_location_uuid:' || COALESCE(location.uuid, '')
                    || x'0A'
            FROM
                topics
            LEFT JOIN
                topics AS location
            ON
                location.id = NEW.default_location_id
            WHERE
                topics.id = NEW.hub_id
        )
    WHERE
        update_id = NEW.update_id
    ;

    INSERT INTO
        hub_related_updates(
            update_id,
            hub_id
        )
    VALUES (
        NEW.update_id,
        NEW.hub_id
    );


    INSERT OR IGNORE INTO
        hub_tomerge(hub_id) VALUES (NEW.hub_id);

    UPDATE
        hub_tomerge
    SET
        default_location_id = default_location_id +
        (NEW.default_location_id IS NOT NULL)
    WHERE
        hub_id = NEW.hub_id
    ;

END;