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

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `nst`.`nodeRecalc`(IN `vScheme` VARCHAR(45), IN `vTable` VARCHAR(45))
BEGIN
	CALL util.exec(CONCAT (
		'UPDATE ', vScheme, '.', vTable, ' d',
		'	JOIN (SELECT',
		'			node.id,',
		'			COUNT(parent.id) - 1 as depth,',
		'			cast((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons',
		'		FROM ',
		'			', vScheme, '.', vTable, ' AS node,',
		'			', vScheme, '.', vTable, ' AS parent',
		'		WHERE node.lft BETWEEN parent.lft AND parent.rgt',
		'		GROUP BY node.id',
		'		ORDER BY node.lft) n ON n.id = d.id ',
		'	SET d.`depth` = n.depth, d.sons = n.sons'
	));
END$$

DELIMITER ;

