DROP procedure IF EXISTS `nst`.`nodeDelete`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `nst`.`nodeDelete`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45), IN `vNodeId` INT)
BEGIN
	DECLARE vMyRight INT;
	DECLARE vMyLeft INT;
	DECLARE vMyWidth INT;

     	CALL util.exec(CONCAT(
			'SELECT t.rgt, t.lft,  t.rgt - t.lft + 1',
			'		INTO @vMyRight, @vMyLeft, @vMyWidth',
			'	FROM ', vScheme, '.', vTable, ' t',
			'	WHERE t.id = ', vNodeId
		));

		CALL util.exec(CONCAT(
			'DELETE FROM ', vScheme, '.', vTable, 
			'	WHERE lft BETWEEN @vMyLeft AND @vMyRight'
		));

		CALL util.exec(CONCAT(
			'UPDATE ', vScheme, '.', vTable, ' SET rgt = rgt - @vMyWidth'
			'	WHERE rgt > @vMyRight ORDER BY rgt'
		));

		CALL util.exec(CONCAT(
			'UPDATE ', vScheme, '.', vTable, ' SET lft = lft - @vMyWidth'
			'	WHERE lft > @vMyRight ORDER BY lft'
		));
END$$

DELIMITER ;

