-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Buildings views and management functions
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------


--
-- Construct buildings on a planet
--
-- Parameters:
--	pid		Planet identifier
--	bid		Building type
--	bcnt	Amount of buildings
--

CREATE OR REPLACE FUNCTION verse.do_construct_buildings( pid INT , bid INT , bcnt INT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY INVOKER
	AS $$
BEGIN
	LOOP
		UPDATE verse.planet_buildings
			SET amount = amount + bcnt
			WHERE planet_id = pid AND building_id = bid;
		EXIT WHEN FOUND;
		
		BEGIN
			INSERT INTO verse.planet_buildings( planet_id , building_id , amount , damage )
				VALUES( pid , bid , bcnt , 0 );
			EXIT;
		EXCEPTION
			WHEN unique_violation THEN
				-- Do nothing, try updating again.
		END;
	END LOOP;
END;
$$ LANGUAGE plpgsql;



--
-- Destroy buildings on a planet
--
-- Parameters:
--	pid		Planet identifier
--	bid		Building type
--	bcnt	Amount of buildings
--
-- Returns:
--	amount of buildings that were destroyed
--

CREATE OR REPLACE FUNCTION verse.do_destroy_buildings( pid INT , bid INT , bcnt INT )
		RETURNS INT
		STRICT VOLATILE
		SECURITY INVOKER
	AS $$
DECLARE
	tmp	INT;
BEGIN
	UPDATE verse.planet_buildings
		SET amount = amount - bcnt
		WHERE planet_id = pid AND building_id = bid;

	IF FOUND THEN
		RETURN bcnt;
	END IF;

	RETURN 0;
EXCEPTION
	WHEN check_violation THEN
		SELECT INTO tmp amount FROM verse.planet_buildings
			WHERE planet_id = pid AND building_id = bid
			FOR UPDATE;
		UPDATE verse.planet_buildings
			SET amount = 0
			WHERE planet_id = pid AND building_id = bid;
		RETURN tmp;
END;
$$ LANGUAGE plpgsql;