Delete deeply nested subtree with ON DELETE CASCADE

355 views Asked by At

I was looking into methods of deleting subtrees of trees stored in the adjacency list model. I set up this code, which deletes a complete tree using ON DELETE CASCADE. When I set max_ to a value > 14, MariaDB (Windows) throws this error:

Got error 193 'mydb.tree, CONSTRAINT tree_ibfk_1 FOREIGN KEY (parentid) REFERENCES tree (nodeid) ON DELETE CASCADE' from InnoDB

Is it my code or a limitation of the database?

DROP TABLE IF EXISTS tree;
DROP PROCEDURE IF EXISTS prepTree;

CREATE TABLE tree (
    name varchar(255) NOT NULL,
    nodeid INT NOT NULL AUTO_INCREMENT,
    parentid INT NULL,
    PRIMARY KEY(nodeid),
    FOREIGN KEY(parentid) REFERENCES tree(nodeid) ON DELETE CASCADE
) ENGINE=InnoDB;

DELIMITER // ;
CREATE PROCEDURE prepTree()
    BEGIN
        DECLARE i INT;
        DECLARE max_ INT;

        SET max_ = 15; -- >14 won't work

        INSERT INTO tree(name, parentid) VALUES("root", NULL);

        SET i = 1;  
        WHILE i <= max_ DO
            INSERT INTO tree(name, parentid) VALUES("child", i);        
            SET i = i + 1;
        END WHILE;

    END //
DELIMITER ; //

CALL prepTree; 

DELETE FROM tree WHERE name = "root";
SELECT * FROM tree; --table will be empty on success
1

There are 1 answers

0
wchiquito On

I understand that it applies equally to MariaDB.

15.8.1.6 InnoDB and FOREIGN KEY Constraints

...

Referential Actions

...

  • ... Cascading operations may not be nested more than 15 levels deep.

...