-- This is the main DB, it should be automatically created --

BEGIN;

CREATE TABLE resource_types(
	id           text PRIMARY KEY, 
	name         text NOT NULL,
	content_type text NOT NULL DEFAULT 'text/plain'
);

INSERT INTO resource_types(id, name, content_type) VALUES 
	('transformation_rule_xslt', 'Transformation Rules (xslt)', 'application/xml'), 
	('transformation_rule_legacy', 'Transformation Rules (legacy)', 'text/plain'), 
	('cleaning_rule', 'Cleaning Rules', 'application/xml'),
	('hadoop_job_configuration', 'Hadoop Job Configurations', 'application/xml'),
	('dedup_configuration', 'Dedup Configurations', 'application/json'),
	('wf_template', 'Workflow Templates', 'application/json'),
	('email_template', 'Email Templates', 'application/json');

CREATE TABLE resources (
	id                text PRIMARY KEY,
	name              text NOT NULL,
	description       text,
	content           text NOT NULL DEFAULT '',
	type              text NOT NULL REFERENCES resource_types(id),
	subtype           text,
	creation_date     timestamp NOT NULL DEFAULT now(),
	modification_date timestamp NOT NULL DEFAULT now(),
	CONSTRAINT unique_name_type_constraint UNIQUE (name, type)
);

CREATE VIEW resource_types_view AS (
	SELECT 
		t.id           AS id, 
		t.name         AS name, 
		t.content_type AS content_type,
		count(r.id)    AS count,
		true           AS simple
	FROM resource_types t
	LEFT OUTER JOIN resources r ON (r.type = t.id)
	GROUP BY t.id, t.name
	ORDER BY t.name
);

COMMIT;
