CREATE TABLE func_new_hub(
    change_id INTEGER NOT NULL,
    id INTEGER NOT NULL,
    set_default INTEGER DEFAULT 0,
    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.set_default
    );

    UPDATE
        changes
    SET
        yaml = yaml
            || '-' || x'0A'
            || '  _delta: new_hub' || x'0A'
    WHERE
        id = NEW.change_id
    ;


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

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

    UPDATE
        projects
    SET
        hub_id = id
    WHERE
        id = NEW.id
    ;


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


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


    INSERT INTO
        bifkv(
            key,
            hub_id
        )
    SELECT
        'local_hub',
        NEW.id
    WHERE
        NEW.set_default
    ;

    SELECT RAISE(IGNORE);
END;
