CREATE TABLE project_entities(
    project_id INTEGER NOT NULL,
    entity_id INTEGER NOT NULL,
    PRIMARY KEY(project_id,entity_id) ON CONFLICT IGNORE,
    FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE,
    FOREIGN KEY(entity_id) REFERENCES entities(id) ON DELETE CASCADE
) WITHOUT ROWID;


CREATE TRIGGER
    project_entities_ai_1
AFTER INSERT ON
    project_entities
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.project_id,
        NEW.entity_id
    );


    INSERT INTO
        project_related_changes(
            project_id,
            prefix,
            change_id,
            sha1
        )
    SELECT DISTINCT
        NEW.project_id,
        SUBSTR(c.uuid, 1, 1),
        c.id,
        c.uuid
    FROM
        nodes_tree nt
    INNER JOIN
        nodes n
    ON
        n.id = nt.child
    INNER JOIN
        changes_tree ct
    ON
        ct.parent = n.first_change_id
    INNER JOIN
        changes c
    ON
        c.id = ct.child
    WHERE
        nt.parent = NEW.entity_id
    ;

END;


CREATE TRIGGER
    project_entities_ad_1
AFTER DELETE ON
    project_entities
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.project_id,
        OLD.entity_id
    );


    DELETE FROM
        project_related_changes
    WHERE
        project_id = OLD.project_id AND change_id IN (
            SELECT DISTINCT
                ct.child
            FROM
                nodes_tree nt
            INNER JOIN
                nodes n
            ON
                n.id = nt.child
            INNER JOIN
                changes_tree ct
            ON
                ct.parent = n.first_change_id
            WHERE
                nt.parent = OLD.entity_id
        )
    ;

END;
