create database cem_monitoring;
-- create extension timescaledb;



create table application_t (
    id serial not null primary key,
    app_id VARCHAR(32) NOT NULL UNIQUE,
    label varchar(128) not null unique
);

create table variable_t (
    id serial not null primary key,
    app integer references application_t(id),
    converter_id varchar(16) not null,
    device_id varchar(16) not null,
    variable_id varchar(16) not null,
    label varchar(128) not null unique,
    unit varchar(16),
    unique (app, converter_id, device_id, variable_id)
);

create table measurement_t (
    time timestamp without time zone not null,
    application varchar(128) not null,
    variable varchar(128) not null,
    unit varchar(16),
    value float
);

select create_hypertable('measurement_t', 'time');

insert into application_t (app_id, label) values('ku226', 'Kupferdreher Str. 226, Essen');
insert into variable_t (app, converter_id, device_id, variable_id, label, unit)
	values ((select id from application_t where app_id = 'ku226'), '1', 'bhkw', 'u', 'BHKW Spannung', 'V'),
	       ((select id from application_t where app_id = 'ku226'), '1', 'bhkw', 'p', 'BHKW Leistung', 'W'),
               ((select id from application_t where app_id = 'ku226'), '1', 'bhkw', 'import', 'BHKW Energie Export', 'Wh'),
               ((select id from application_t where app_id = 'ku226'), '1', 'bhkw', 'export', 'BHKW Energie Import', 'Wh'),
               ((select id from application_t where app_id = 'ku226'), '1', 'pv', 'u', 'PV Spannung', 'V'),
               ((select id from application_t where app_id = 'ku226'), '1', 'pv', 'p', 'PV Leistung', 'W'),
               ((select id from application_t where app_id = 'ku226'), '1', 'pv', 'import', 'PV Energie Export', 'Wh'),
               ((select id from application_t where app_id = 'ku226'), '1', 'pv', 'export', 'PV Energie Import', 'Wh')
	;




-- create user preprocessor password 'geheim';
grant select on application_t to preprocessor;
grant select on variable_t to preprocessor;
grant insert on measurement_t to preprocessor;

