CREATE TABLE nodes_tomerge(
    node_id INTEGER NOT NULL UNIQUE,
    parent_id INTEGER DEFAULT 0,
    name INTEGER DEFAULT 0,
    resolve INTEGER,
    FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE
);


CREATE TRIGGER
    nodes_tomerge_bu_2
BEFORE UPDATE OF
    resolve
ON
    nodes_tomerge
FOR EACH ROW WHEN
    NEW.resolve = 1 AND
    OLD.parent_id != 0
BEGIN

    SELECT debug(
        OLD.node_id
    );

    UPDATE
        nodes
    SET
        parent_id = (
            SELECT
                nd.parent_id
            FROM
                node_deltas nd
            INNER JOIN
                changes c
            ON
                c.id = nd.change_id
            WHERE
                nd.node_id = OLD.node_id AND
                nd.parent_id IS NOT NULL
            ORDER BY
                c.mtime DESC,
                c.uuid
            LIMIT
                1
        )
    WHERE
        id = OLD.node_id
    ;

END;


CREATE TRIGGER
    nodes_tomerge_bu_1
BEFORE UPDATE OF
    resolve
ON
    nodes_tomerge
FOR EACH ROW WHEN
    NEW.resolve = 1 AND
    OLD.name != 0
BEGIN

    SELECT debug(
        OLD.node_id
    );

    UPDATE
        nodes
    SET
        name = (
            SELECT
                nd.name
            FROM
                node_deltas nd
            INNER JOIN
                changes c
            ON
                c.id = nd.change_id
            WHERE
                nd.node_id = OLD.node_id AND
                nd.name IS NOT NULL
            ORDER BY
                c.mtime DESC,
                c.uuid
            LIMIT
                1
        )
    WHERE
        id = OLD.node_id
    ;

END;


CREATE TRIGGER
    nodes_tomerge_au_1
AFTER UPDATE OF
    resolve
ON
    nodes_tomerge
FOR EACH ROW WHEN
    NEW.resolve = 1
BEGIN

    SELECT debug(
        OLD.node_id
    );

    UPDATE
        nodes
    SET
        mtime = (
            SELECT
                c.mtime
            FROM
                node_deltas nd
            INNER JOIN
                changes c
            ON
                c.id = nd.change_id
            WHERE
                nd.node_id = OLD.node_id
            ORDER BY
                c.mtime DESC,
                c.uuid
            LIMIT
                1
        )
    WHERE
        id = OLD.node_id
    ;

    DELETE FROM
        nodes_tomerge
    WHERE
        node_id = OLD.node_id
    ;

END;
