DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_doRecalc`()
proc: BEGIN
/**
 * Recalculates modified orders.
 */
	DECLARE vDone BOOL;
	DECLARE vOrderFk INT;

	DECLARE cCur CURSOR FOR
		SELECT DISTINCT orderFk FROM tOrder;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK('hedera.order_doRecalc');
		ROLLBACK;
		RESIGNAL;
	END;

	IF !GET_LOCK('hedera.order_doRecalc', 0) THEN
		LEAVE proc;
	END IF;

	DROP TEMPORARY TABLE IF EXISTS tOrder;
	CREATE TEMPORARY TABLE tOrder
		ENGINE = MEMORY
		SELECT id, orderFk FROM orderRecalc;

	OPEN cCur;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cCur INTO vOrderFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		CALL order_recalc(vOrderFk);
	END LOOP;

	CLOSE cCur;

	DELETE o FROM orderRecalc o JOIN tOrder t ON t.id = o.id;

	DROP TEMPORARY TABLE tOrder;

	DO RELEASE_LOCK('hedera.order_doRecalc');
END$$
DELIMITER ;
