CREATE PROCEDURE delete_node(in node int)
BEGIN
    declare parent_of_deleted int;
    select t.parent into parent_of_deleted from tree t where t.id = node;
    if parent_of_deleted is null then
        signal sqlstate '45000' set message_text = 'Cannot delete root';
    end if;
    -- First, all children of deleted node adopted by their grandparent:
    update tree t set t.parent = parent_of_deleted where t.parent = node;
    -- Then do the actual deletion
    delete from tree where id = node;
END