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 EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK('stock.stock_sync');
		RESIGNAL;
	END;

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

	DELETE p FROM buyPick p JOIN buy b USING(buyFk);
	TRUNCATE TABLE buyLot;
	TRUNCATE TABLE buyOut;

	CALL buyLot_refresh(NULL, NULL);
	CALL buyOut_refreshSale(NULL, NULL);
	CALL buyOut_refreshBuy(NULL, NULL);
	CALL buyOut_refreshOrder(NULL, NULL);

	UPDATE buyOut SET isSync = TRUE;
	CALL stock_sync;

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