CREATE TABLE func_new_hub(
    change_id INTEGER NOT NULL,
    id INTEGER NOT NULL,
    location VARCHAR NOT NULL,
    uuid VARCHAR(40)
);

CREATE TRIGGER
    func_new_hub_bi_1
BEFORE INSERT ON
    func_new_hub
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.change_id,
        NEW.id,
        NEW.location,
        NEW.uuid
    );

    UPDATE
        changes
    SET
        yaml = yaml
            || '-' || x'0A'
            || '  _delta: new_hub' || x'0A'
            || CASE WHEN
                instr(NEW.location, ' ')
            THEN
                '  location: ''' || NEW.location || '''' || x'0A'
            ELSE
                '  location: ' || NEW.location || x'0A'
            END
    WHERE
        id = NEW.change_id
    ;

    UPDATE
        nodes
    SET
        kind = 'hub'
    WHERE
        id = NEW.id
    ;

    INSERT INTO
        hubs(
            id,
            location
        )
    VALUES(
        NEW.id,
        NEW.location
    );


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

    INSERT INTO node_deltas(
        id,
        change_id,
        node_id
    )
    VALUES(
        currval('deltas'),
        NEW.change_id,
        NEW.id
    );

    INSERT INTO
        hub_deltas(
            id,
            change_id,
            hub_id,
            new,
            location
        )
    VALUES(
        currval('deltas'),
        NEW.change_id,
        NEW.id,
        1,
        NEW.location
    );

    INSERT INTO
        project_hubs(
            project_id,
            hub_id
        )
    VALUES(
        NEW.id,
        NEW.id
    );

    SELECT RAISE(IGNORE);
END;
