CREATE TABLE IF NOT EXISTS meta_subjects (
	id UUID DEFAULT gen_random_uuid(),
	document BPCHAR NOT NULL,
	pattern BPCHAR NOT NULL,
	redirect BPCHAR NOT NULL,

	PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS meta_aliases (
	id UUID DEFAULT gen_random_uuid(),
	document BPCHAR NOT NULL,
	pattern BPCHAR NOT NULL,
	alias BPCHAR NOT NULL,
	
	PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS meta_links (
	id UUID DEFAULT gen_random_uuid(),
	document BPCHAR NOT NULL,
	pattern BPCHAR NOT NULL,
	rel BPCHAR NOT NULL,
	type BPCHAR,
	href BPCHAR,
	template BPCHAR,
	
	CONSTRAINT either_href_or_template_not_null CHECK (
		(href IS NOT NULL AND template IS NULL)
		OR
		(href IS NULL AND template IS NOT NULL)
	),
	PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS meta_link_properties (
	id UUID DEFAULT gen_random_uuid(),
	meta_link_id UUID REFERENCES meta_links (id) NOT NULL,
	rel BPCHAR NOT NULL,
	value BPCHAR,
	
	PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS meta_properties (
	id UUID DEFAULT gen_random_uuid(),
	document BPCHAR NOT NULL,
	pattern BPCHAR NOT NULL,
	rel BPCHAR NOT NULL,
	value BPCHAR,
	
	PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS meta_link_titles (
	id UUID DEFAULT gen_random_uuid(),
	meta_link_id UUID REFERENCES meta_links (id) NOT NULL,
	language BPCHAR NOT NULL DEFAULT 'und',
	value BPCHAR NOT NULL,

	CONSTRAINT unique_languages UNIQUE (meta_link_id, language),
	PRIMARY KEY(id)
);
