-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Stellar systems and planets
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------


--
-- Stellar systems
--
CREATE TABLE verse.systems(
	id		SERIAL NOT NULL PRIMARY KEY ,
	x		INT NOT NULL ,
	y		INT NOT NULL
);

CREATE UNIQUE INDEX idx_systems_coordinates
	ON verse.systems( x , y );

--
-- Planets
--
CREATE TABLE verse.planets(
	name_id		INT NOT NULL PRIMARY KEY ,
	system_id	INT NOT NULL ,
	orbit		INT NOT NULL
					CHECK( orbit BETWEEN 1 AND 5 ) ,
	picture		INT NOT NULL ,
	population	REAL NOT NULL
					CHECK( population >= 0 )
);

CREATE UNIQUE INDEX idx_planets_coordinates
	ON verse.planets( system_id , orbit );
	
ALTER TABLE verse.planets
	ADD CONSTRAINT fk_planets_name
		FOREIGN KEY (name_id) REFERENCES naming.map_names ,
	ADD CONSTRAINT fk_planets_system
		FOREIGN KEY (system_id) REFERENCES verse.systems;


--
-- Happiness
--
CREATE TABLE verse.planet_happiness(
	planet_id	INT NOT NULL PRIMARY KEY ,
	target		REAL NOT NULL
					CHECK( target BETWEEN 0.0 AND 1.0 ) ,
	current		REAL NOT NULL
					CHECK( current > 0 )
);

ALTER TABLE verse.planet_happiness
	ADD CONSTRAINT fk_planethappiness_planet
		FOREIGN KEY (planet_id) REFERENCES verse.planets;


--
-- Money
--
CREATE TABLE verse.planet_money(
	planet_id	INT NOT NULL PRIMARY KEY ,
	income		REAL NOT NULL
					CHECK( income >= 0 ) ,
	upkeep		REAL NOT NULL
					CHECK( upkeep >= 0 )
);

ALTER TABLE verse.planet_money
	ADD CONSTRAINT fk_planetmoney_planet
		FOREIGN KEY (planet_id) REFERENCES verse.planets;


--
-- Buildings
--
CREATE TABLE verse.planet_buildings(
	planet_id		INT NOT NULL ,
	building_id		INT NOT NULL ,
	amount			INT NOT NULL CHECK( amount >= 0 ) ,
	damage			REAL NOT NULL CHECK( damage >= 0 ) ,
	PRIMARY KEY( planet_id , building_id )
);

CREATE INDEX idx_planetbuildings_building
	ON verse.planet_buildings (building_id);

ALTER TABLE verse.planet_buildings
	ADD CONSTRAINT fk_planetbuildings_planet
		FOREIGN KEY (planet_id) REFERENCES verse.planets ,
	ADD CONSTRAINT fk_planetbuildings_building
		FOREIGN KEY (building_id) REFERENCES tech.buildings;
