BEGIN; -- Numbers target every direction in the city. Keep route_id for older clients. ALTER TABLE alerts ADD COLUMN IF NOT EXISTS route_numbers TEXT[] NOT NULL DEFAULT '{}'; UPDATE alerts a SET route_numbers = ARRAY[upper(regexp_replace(r.route_number, '[[:space:]№]', '', 'g'))] FROM routes r WHERE r.id=a.route_id AND cardinality(a.route_numbers)=0; CREATE INDEX IF NOT EXISTS idx_alerts_route_numbers ON alerts USING gin(route_numbers); -- Removing one direction must not remove a notification for the whole number. ALTER TABLE alerts DROP CONSTRAINT IF EXISTS alerts_route_id_fkey; ALTER TABLE alerts ADD CONSTRAINT alerts_route_id_fkey FOREIGN KEY(route_id) REFERENCES routes(id) ON DELETE SET NULL; -- One source publication creates one alert. A NULL alert_id preserves deletion. -- Legacy per-direction links stay intact until that publication is edited/reviewed. CREATE TABLE IF NOT EXISTS telegram_message_alerts ( message_id INTEGER PRIMARY KEY REFERENCES telegram_import_messages(id) ON DELETE CASCADE, alert_id INTEGER UNIQUE REFERENCES alerts(id) ON DELETE SET NULL ); COMMIT;