ALTER TABLE consumption_energy_measurements RENAME TO consumption_energy_measurements_old;
ALTER INDEX consumption_energy_measurements_pkey RENAME TO consumption_energy_measurements_pkey_old;
ALTER INDEX consumption_energy_measurements_measurement_category_idx RENAME TO consumption_energy_measurements_measurement_category_idx_old;
ALTER INDEX consumption_energy_measurements_source_idx RENAME TO consumption_energy_measurements_source_idx_old;

CREATE TABLE consumption_energy_measurements (
	"timestamp" timestamptz NOT NULL,
	value numeric(30, 15) NOT NULL,
	addr varchar(255) NOT NULL,
	var varchar(255) NOT NULL,
	"type" varchar(255) NULL,
	meter varchar(255) NOT NULL,
	"source" varchar(20) NULL,
	measurement_category varchar(50) NULL,
	create_batch_id int8 NULL,
	created_at timestamptz NULL,
	created_by varchar(150) NULL,
	update_batch_id int8 NULL,
	updated_at timestamptz NULL,
	updated_by varchar(150) NULL,

	CONSTRAINT consumption_energy_measurements_pkey PRIMARY KEY ("timestamp", addr, var, meter)
) PARTITION BY RANGE("timestamp");

CREATE INDEX consumption_energy_measurements_measurement_category_idx ON consumption_energy_measurements USING btree (measurement_category);
CREATE INDEX consumption_energy_measurements_source_idx ON consumption_energy_measurements USING btree (source);

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_min PARTITION OF consumption_energy_measurements
    FOR VALUES FROM (minvalue) TO ('2022-12-31T23:00:00.000Z');

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_2023 PARTITION OF consumption_energy_measurements
    FOR VALUES FROM ('2022-12-31T23:00:00.000Z') TO ('2023-12-31T23:00:00.000Z');

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_2024 PARTITION OF consumption_energy_measurements
    FOR VALUES FROM ('2023-12-31T23:00:00.000Z') TO ('2024-12-31T23:00:00.000Z');

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_2025 PARTITION OF consumption_energy_measurements
    FOR VALUES FROM ('2024-12-31T23:00:00.000Z') TO ('2025-12-31T23:00:00.000Z');

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_2026 PARTITION OF consumption_energy_measurements
    FOR VALUES FROM ('2025-12-31T23:00:00.000Z') TO ('2026-12-31T23:00:00.000Z');

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_2027 PARTITION OF consumption_energy_measurements
    FOR VALUES FROM ('2026-12-31T23:00:00.000Z') TO ('2027-12-31T23:00:00.000Z');

CREATE TABLE IF NOT EXISTS consumption_energy_measurements_max PARTITION OF consumption_energy_measurements
    FOR VALUES FROM ('2027-12-31T23:00:00.000Z') TO (maxvalue);
