fleet-platform/db/migrations/20260601000004_state_live.sql

50 lines
1.7 KiB
SQL

-- migrate:up
CREATE TABLE state.live_positions (
imei text PRIMARY KEY REFERENCES domain.devices(imei),
vehicle_id bigint NOT NULL REFERENCES domain.vehicles(vehicle_id),
occurred_at timestamptz NOT NULL,
geom geometry(Point, 4326) NOT NULL,
speed_kmh numeric,
direction_deg numeric,
acc_state int,
source text NOT NULL,
parser_version int NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX live_positions_vehicle_idx ON state.live_positions (vehicle_id);
CREATE INDEX live_positions_occurred_idx ON state.live_positions (occurred_at DESC);
CREATE TABLE state.position_history (
history_id bigserial,
vehicle_id bigint NOT NULL REFERENCES domain.vehicles(vehicle_id),
imei text NOT NULL,
occurred_at timestamptz NOT NULL,
geom geometry(Point, 4326) NOT NULL,
speed_kmh numeric,
direction_deg numeric,
acc_state int,
altitude_m numeric,
satellites int,
source text NOT NULL,
parser_version int NOT NULL,
inserted_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (history_id, occurred_at)
);
SELECT create_hypertable('state.position_history', 'occurred_at', chunk_time_interval => INTERVAL '7 days');
CREATE INDEX position_history_vehicle_time_idx
ON state.position_history (vehicle_id, occurred_at DESC);
CREATE INDEX position_history_imei_time_idx
ON state.position_history (imei, occurred_at DESC);
CREATE INDEX position_history_geom_idx
ON state.position_history USING GIST (geom);
-- migrate:down
DROP TABLE IF EXISTS state.position_history;
DROP TABLE IF EXISTS state.live_positions;