Here is what i changed. It is a bit adapted to our model needs.
I also added converting the table to a hypertable and adding compression
DROP TABLE IF EXISTS model CASCADE;
DROP view IF EXISTS mother CASCADE;
CREATE TABLE model ( id TEXT NOT NULL, timestamp TIMESTAMPTZ NOT NULL, measure text NOT NULL, value text, metadata jsonb default '{}');
CREATE view mother AS select '' as table_name, ''as id, null::timestamptz as timestamp, ''::text as measure, ''::text as value, null::jsonb as metadata;
CREATE OR REPLACE FUNCTION feed_child_table()
RETURNS trigger AS
$BODY$
DECLARE
table_exists boolean;
create_table text;
next_command text;
create_hypertable text;
insert_data text;
BEGIN
insert_data := 'INSERT INTO ' || NEW.table_name || ' (id, timestamp, measure, value, metadata) VALUES ($1, $2, $3, $4, $5)';
BEGIN
EXECUTE insert_data USING NEW.id, NEW.timestamp, NEW.measure, NEW.value, NEW.metadata;
EXCEPTION WHEN undefined_table then
-- CREATE TABLE
create_table := 'CREATE TABLE IF NOT EXISTS ' || NEW.table_name || '( like model )';
create_hypertable := 'SELECT create_hypertable('''|| NEW.table_name ||''',''timestamp'')';
EXECUTE create_table;
EXECUTE create_hypertable;
-- CREATE COMPRESSION POLICY
next_command := 'ALTER TABLE ' || NEW.table_name || ' SET (
timescaledb.compress,
timescaledb.compress_segmentby = ''id,measure''
)';
EXECUTE next_command;
next_command := 'SELECT add_compression_policy('''|| NEW.table_name ||''', INTERVAL ''7 days'')';
EXECUTE next_command;
-- RETRY INSERT
EXECUTE insert_data USING NEW.id, NEW.timestamp::timestamptz, NEW.measure, NEW.value, NEW.metadata;
END;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER feed_child_table_trigger
INSTEAD OF INSERT ON mother FOR EACH ROW
EXECUTE PROCEDURE feed_child_table();
INSERT INTO mother (table_name, id,timestamp, measure, value, metadata) VALUES
('w', '1', '2021-08-26 10:09:00.01'::timestamp, 'id1', '10.1',null),
('a', '1', '2021-08-26 10:09:00.01'::timestamp, 'id1', '10.1',null),
('a', '1', '2021-08-26 10:09:00.01'::timestamp, 'id1', '10.1',null),
('a', '1', '2021-08-26 10:09:00.01'::timestamp, 'id1', '10.1',null),
('r', '2', '2021-08-26 10:09:00.08'::timestamp, 'id2', '10.0',null),
('b', '2','2021-08-26 10:09:00.23'::timestamp, 'id3', '10.2',null),
('b', '2','2021-08-26 10:09:00.40'::timestamp, 'id4', '10.3',null);