DROP procedure IF EXISTS `vn`.`worker_getHierarch`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`worker_getHierarch`(vBoss INT)
BEGIN
    DECLARE EXIT HANDLER FOR 1062 BEGIN
		CALL util.throw('INFINITE_LOOP');
    END;

	DROP TEMPORARY TABLE IF EXISTS workerHierarch;
	CREATE TEMPORARY TABLE workerHierarch
		(PRIMARY KEY (workerFk))
		ENGINE = MEMORY
		SELECT vBoss AS workerFk;
            
	DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchList;
	CREATE TEMPORARY TABLE tmp.workerHierarchList
		(PRIMARY KEY (workerFk))
		ENGINE = MEMORY
		SELECT vBoss AS workerFk, 0 AS isChecked;


    WHILE (SELECT COUNT(*) FROM tmp.workerHierarchList WHERE NOT isChecked) > 0 DO

	INSERT INTO tmp.workerHierarchList
		SELECT w.id, 0 
			FROM worker w
				JOIN workerHierarch wh ON wh.workerFk = w.bossFk;

	UPDATE tmp.workerHierarchList whl
			JOIN workerHierarch wh ON  wh.workerFk = whl.workerFk
		SET whl.isChecked = 1;

	TRUNCATE workerHierarch;

	INSERT INTO workerHierarch
		SELECT workerFk 
			FROM tmp.workerHierarchList
			WHERE NOT isChecked;

    END WHILE;
    
    DROP TEMPORARY TABLE IF EXISTS workerHierarch;
END$$

DELIMITER ;