fleettickets/migrations/04_inc_latlng.sql
david kiania b323e8a1ac feat: populate inc latitude/longitude from geocoded geom (migration 04)
Feed coords are always empty; redefine the latitude/longitude generated columns to
COALESCE(feed, ST_Y/ST_X(geom)) so they carry the resolved/geocoded position for
every geocoded ticket (precision indicated by geo_source). STORED, recomputes when
geom changes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 23:26:39 +03:00

24 lines
1.7 KiB
SQL

-- 04_inc_latlng.sql — fleettickets · populate lat/lng from the resolved geom
-- ─────────────────────────────────────────────────────────────────────────────
-- The source feed never carries coordinates (latitude/longitude are always empty),
-- but geocoding resolves a position into `geom` (feed -> location -> cluster). This
-- redefines the latitude/longitude generated columns to fall back to that geom when
-- the feed is empty, so they are actually populated for every geocoded ticket.
--
-- Precision still varies by geo_source ('location' = street-level, 'cluster' =
-- cluster centroid). geom is a regular column (set by the geom trigger / resolve),
-- which a generated column may reference; ST_X/ST_Y are IMMUTABLE. STORED, so it
-- recomputes whenever geom changes (e.g. after a geocode pass). Idempotent.
-- ─────────────────────────────────────────────────────────────────────────────
SET search_path = tickets, public;
-- redefine (drop + re-add) the two generated columns added in migration 03
ALTER TABLE tickets.inc DROP COLUMN IF EXISTS latitude;
ALTER TABLE tickets.inc DROP COLUMN IF EXISTS longitude;
ALTER TABLE tickets.inc
ADD COLUMN IF NOT EXISTS latitude double precision GENERATED ALWAYS AS
(COALESCE(NULLIF(raw->>'latitude','')::double precision, ST_Y(geom))) STORED,
ADD COLUMN IF NOT EXISTS longitude double precision GENERATED ALWAYS AS
(COALESCE(NULLIF(raw->>'longitude','')::double precision, ST_X(geom))) STORED;