I am trying to implement dynamic partitioning on a table by using triggers on insert of data.
Table: property(record_uuid uuid NOT NULL, change timestamp NOT NULL, value VARCHAR(50), PRIMARY KEY(property_id, record_uuid, change)) PARTITION BY RANGE(change) Default partition table: property_default PARTITION OF property DEFAULT Trigger: TRIGGER property_trigger BEFORE INSERT ON property FOR EACH ROW EXECUTE PROCEDURE public.property_insert_function(); Function:
CREATE OR REPLACE FUNCTION property_insert_function()
RETURNS TRIGGER AS '
DECLARE
partition_date TEXT;
partition_name TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
BEGIN
partition_date := to_char(NEW.change,''YYYY-MM'');
partition_name := ''property_'' || partition_date;
start_of_month := to_char((NEW.change),''YYYY-MM'') || ''-01'';
end_of_next_month := to_char((NEW.change + interval ''1 month''),''YYYY-MM'') || ''-01'';
IF NOT EXISTS
(SELECT 1
FROM information_schema.tables
WHERE table_name = partition_name)
THEN
RAISE NOTICE ''A partition has been created %'', partition_name;
EXECUTE format(E''CREATE TABLE %I PARTITION OF property FOR VALUES FROM (%L) TO (%L)'', partition_name, start_of_month,end_of_next_month);
END IF;
EXECUTE format(''INSERT INTO %I (record_uuid, change, value) VALUES($1,$2,$3)'', partition_name) using NEW.record_uuid, NEW.change, NEW.value;
END;
'
LANGUAGE plpgsql;
Problem:
When it tries to create the partitioned table property_*, it fails with the error:
ERROR --- [ntainer#0-0-C-1] o.h.e.j.s.SqlExceptionHelper : **ERROR: cannot CREATE TABLE .. PARTITION OF "property" because it is being used by active queries in this session Where: SQL statement "CREATE TABLE "property_2023-06" PARTITION OF property FOR VALUES FROM ('2023-06-01') TO ('2023-07-01')" PL/pgSQL function property_insert_function() line 18 at EXECUTE**
Default partition table already exists, I am not sure how I can achieve dynamic partitioning at the time of data insertion.