-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- User sessions tables
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------


--
-- Session client type definitions
--

CREATE TABLE defs.session_clients(
	id			SERIAL PRIMARY KEY ,
	name		VARCHAR( 16 ) NOT NULL UNIQUE ,
	exclusive	BOOLEAN NOT NULL
);

--
-- Default session client types
--

INSERT INTO defs.session_clients ( name , exclusive )
	VALUES( 'web' , TRUE );
INSERT INTO defs.session_clients ( name , exclusive )
	VALUES( 'vac_end' , FALSE );



--
-- Types of session termination
--

CREATE TYPE session_termination_type
	AS ENUM( 'MANUAL' , 'GONE' , 'EXPIRED' , 'EXCLUSIVE' , 'SERVER' );



--
-- User sessions start
--

CREATE TABLE users.session_starts(
	id				BIGSERIAL PRIMARY KEY ,
	credentials_id	INT NOT NULL ,
	client_id		INT NOT NULL ,
	session			VARCHAR( 64 ) NOT NULL ,
	started			TIMESTAMP WITHOUT TIME ZONE
						NOT NULL
						DEFAULT now( ) ,
	from_address	VARCHAR( 64 ) NOT NULL
);

CREATE INDEX idx_sessstart_credentials
	ON users.session_starts ( credentials_id );

CREATE INDEX idx_sessstart_client
	ON users.session_starts ( client_id );

CREATE INDEX idx_sessstart_started
	ON users.session_starts ( started );

ALTER TABLE users.session_starts
	ADD CONSTRAINT fk_sessstart_credentials
		FOREIGN KEY ( credentials_id ) REFERENCES users.credentials
			ON DELETE CASCADE ON UPDATE CASCADE ,
	ADD CONSTRAINT fk_sessstart_client
		FOREIGN KEY ( client_id ) REFERENCES defs.session_clients; 



--
-- User sessions end
--

CREATE TABLE users.session_ends(
	id			BIGINT NOT NULL PRIMARY KEY ,
	ended		TIMESTAMP WITHOUT TIME ZONE
					NOT NULL
					DEFAULT now( ) ,
	end_type	session_termination_type NOT NULL
);

CREATE INDEX idx_sessend_ended
	ON users.session_ends ( ended );

ALTER TABLE users.session_ends
	ADD CONSTRAINT fk_sessend_id
		FOREIGN KEY ( id ) REFERENCES users.session_starts
			ON DELETE CASCADE;

