DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`stock_refreshAll`()
BEGIN
/**
 * Recalculates the entire cache. It takes a considerable time,
 * please avoid calls to this procedure from commonly used operations.
 */
	DECLARE vDone BOOL;
	DECLARE vId INT;

	DECLARE vEntries CURSOR FOR
		SELECT DISTINCT e.id
			FROM vn.buy b
				JOIN vn.entry e ON b.entryFk = e.id
			WHERE b.isAlive;

	DECLARE vTickets CURSOR FOR
		SELECT id FROM vn.ticket WHERE isAlive;

	DECLARE vOrderRows CURSOR FOR
		SELECT lotFk FROM hedera.orderRow WHERE isReserved;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK('stock.stock_refreshAll');
		RESIGNAL;
	END;

	IF NOT GET_LOCK('stock.stock_refreshAll', 30) THEN
		CALL util.throw('Lock timeout exceeded');
	END IF;

	-- Prune cache

	DELETE p FROM buyPick p JOIN buyLot l USING(lotFk);
	TRUNCATE TABLE buyLot;
	TRUNCATE TABLE buyOut;

	-- Populate cache

	OPEN vEntries;
	buyLoop: LOOP
		SET vDone = FALSE;
		FETCH vEntries INTO vId;

		IF vDone THEN
			LEAVE buyLoop;
		END IF;

		CALL buyOut_refreshBuy('entry', vId);
	END LOOP;
	CLOSE vEntries;

	OPEN vOrderRows;
	orderLoop: LOOP
		SET vDone = FALSE;
		FETCH vOrderRows INTO vId;

		IF vDone THEN
			LEAVE orderLoop;
		END IF;

		CALL buyOut_refreshOrder('lot', vId);
	END LOOP;
	CLOSE vOrderRows;

	OPEN vTickets;
	saleLoop: LOOP
		SET vDone = FALSE;
		FETCH vTickets INTO vId;

		IF vDone THEN
			LEAVE saleLoop;
		END IF;

		CALL buyOut_refreshSale('ticket', vId);
	END LOOP;
	CLOSE vTickets;

	-- Synchronize

	UPDATE buyOut SET isSync = TRUE;
	CALL stock_sync;

	DO RELEASE_LOCK('stock.stock_refreshAll');
END$$
DELIMITER ;
