-- steg/sql/tgeo.sql

set search_path to generic, public;

-- *** common tables ***

-- datatypes

create table datatypes (
    id smallint not null primary key,
    name text not null unique
);

insert into datatypes (id, name) values (10, 'text');
insert into datatypes (id, name) values (16, 'date');
insert into datatypes (id, name) values (20, 'int');
insert into datatypes (id, name) values (21, 'bool');
insert into datatypes (id, name) values (25, 'valuelist');
insert into datatypes (id, name) values (30, 'decimal');
insert into datatypes (id, name) values (35, 'timestamp');

create index idx_datatype_name on datatypes using btree (name);

-- properties

create table properties (
    id serial not null primary key,
    name text,
    label text,
    description text,
    datatype smallint not null references datatypes,
    domain text,
    pattern text
);

-- for data see properties.sql

create index idx_prop_label on properties using btree (label);

-- valuelists

create table valuelists (
    id bigserial not null primary key,
    property int not null references properties,
    value text,
    pattern text
);

-- *** GIS-specific tables ***

-- geotypes

create table geotypes (
    id smallint not null primary key,
    name text not null unique
);

insert into geotypes (id, name) values
    (0, 'area'),
    (1, 'realestate'),
    (2, 'building'),
    (10, 'line'),
    (20, 'point');

-- geoitems

create table geoitems (
    id bigserial not null primary key,
    geom geometry(geometry, 25832) not null,    -- unique?
    type smallint not null references geotypes,
    name text,
    description text,
    community int not null
);

create index fki_item_type on geoitems using btree (type);
create index idx_item_geom on geoitems using brin (geom);
create index idx_item_community on geoitems using btree (community);

-- geoattrs

create table geoattrs (
    id bigserial not null primary key,
    item bigint not null references geoitems,
    property int not null references properties,
    txtvalue text,
    intvalue bigint
);

create index fki_attr_item on geoattrs using btree (item);
create index fki_attr_prop on geoattrs using btree (property);
create index idx_attr_txtv on geoattrs using btree (property, txtvalue);
create index idx_attr_intv on geoattrs using btree (property, intvalue);
