-- tables

CREATE TABLE namespaces (
    id serial NOT NULL primary key,
    iri text NOT NULL,
    prefix text
);

CREATE TABLE datatypes (
    id smallserial NOT NULL primary key,
    dtname text NOT NULL,
    tablename text
);

CREATE TABLE nodes (
    id bigserial NOT NULL primary key,
    namespace bigint REFERENCES namespaces,
    name text
);

CREATE TABLE events (
    id bigserial NOT NULL primary key,
    tstamp timestamptz default current_timestamp
);

CREATE TABLE triples (
    id bigserial NOT NULL primary key,
    stype smallint NOT NULL REFERENCES datatypes,
    svalue bigint NOT NULL,
    predicate bigint NOT NULL REFERENCES nodes,
    otype smallint NOT NULL REFERENCES datatypes,
    ovalue bigint,
    creation bigint NOT NULL REFERENCES events,
    deletion bigint REFERENCES events
);

CREATE TABLE texts (
    id bigserial NOT NULL primary key,
    language bigint REFERENCES nodes,
    text text NOT NULL
);

-- set table owner

ALTER TABLE nodes OWNER TO cco;
ALTER TABLE datatypes OWNER TO cco;
ALTER TABLE namespaces OWNER TO cco;
ALTER TABLE triples OWNER TO cco;
ALTER TABLE events OWNER TO cco;
ALTER TABLE texts OWNER TO cco;

-- indexes

CREATE INDEX idx_iri ON namespaces USING btree (iri);
CREATE INDEX idx_prefix ON namespaces USING btree (prefix);

CREATE INDEX idx_dtname ON datatypes USING btree (dtname);

CREATE INDEX idx_node_name ON nodes USING btree (namespace, name);

CREATE INDEX fki_creation ON triples USING btree (creation);
CREATE INDEX fki_deletion ON triples USING btree (deletion);
CREATE INDEX idx_spo ON triples USING btree 
    (stype, svalue, predicate, otype, ovalue);
CREATE INDEX idx_po ON triples USING btree (predicate, otype, ovalue);
CREATE INDEX idx_os ON triples USING btree (otype, ovalue, stype, svalue);

CREATE INDEX fki_language ON texts USING btree (language);
