-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- System & game updates status
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------

--
-- System status
--
CREATE TABLE sys.status(
	next_tick			BIGINT NOT NULL
							DEFAULT 0 ,
	current_tick		BIGINT ,

	last_msg_recap		TIMESTAMP WITHOUT TIME ZONE
							NOT NULL
							DEFAULT now( ) ,
	last_admin_recap	TIMESTAMP WITHOUT TIME ZONE
							NOT NULL
							DEFAULT now( ) ,
	last_error_recap	TIMESTAMP WITHOUT TIME ZONE
							NOT NULL
							DEFAULT now( ) ,

	maintenance_start	TIMESTAMP WITHOUT TIME ZONE ,
	maintenance_end		TIMESTAMP WITHOUT TIME ZONE ,
	maintenance_text	TEXT
);

INSERT INTO sys.status DEFAULT VALUES;

GRANT SELECT ON sys.status TO :dbuser;



--
-- Ticker status
--

CREATE TYPE ticker_task_status
	AS ENUM( 'RUNNING' , 'STOPPED' , 'AUTO' );

CREATE TABLE sys.ticker(
	id				SERIAL PRIMARY KEY ,
	task_name		VARCHAR(64) NOT NULL UNIQUE ,
	status			ticker_task_status NOT NULL ,
	auto_start		TIMESTAMP WITHOUT TIME ZONE
);

INSERT INTO sys.ticker( task_name , status )
	VALUES ( 'Game update' , 'STOPPED' );

GRANT SELECT ON sys.ticker TO :dbuser;



--
-- Updates
--
CREATE TABLE sys.updates(
	id					BIGSERIAL NOT NULL PRIMARY KEY ,
	gu_type				update_type NOT NULL ,
	status				processing_status NOT NULL DEFAULT 'FUTURE' ,
	last_tick			BIGINT NOT NULL DEFAULT -1
);

CREATE INDEX idx_updates_finder
	ON sys.updates (gu_type, status, last_tick);


--
-- Planet updates
--
CREATE TABLE verse.updates(
	update_id			BIGINT NOT NULL PRIMARY KEY ,
	planet_id			INT NOT NULL
);

CREATE INDEX idx_planetupdates_planet
	ON verse.updates (planet_id);

ALTER TABLE verse.updates
	ADD CONSTRAINT fk_planetupdates_update
		FOREIGN KEY ( update_id ) REFERENCES sys.updates ,
	ADD CONSTRAINT fk_planetupdates_planet
		FOREIGN KEY ( planet_id ) REFERENCES verse.planets;


--
-- Empire updates
--
CREATE TABLE emp.updates(
	update_id			BIGINT NOT NULL PRIMARY KEY ,
	empire_id			INT NOT NULL
);

CREATE INDEX idx_empireupdates_empire
	ON emp.updates( empire_id );

ALTER TABLE emp.updates
	ADD CONSTRAINT fk_empireupdates_update
		FOREIGN KEY ( update_id ) REFERENCES sys.updates ,
	ADD CONSTRAINT fk_empireupdates_empire
		FOREIGN KEY ( empire_id ) REFERENCES emp.empires
			ON DELETE CASCADE;
