diff --git a/backend/migrations/003_normalize_room_layout_units.sql b/backend/migrations/003_normalize_room_layout_units.sql index 4c28a8f..296a1a2 100644 --- a/backend/migrations/003_normalize_room_layout_units.sql +++ b/backend/migrations/003_normalize_room_layout_units.sql @@ -1,30 +1,26 @@ -- Normalize room layout units: divide pixel-scale coordinates by 40. --- Applied per element with CASE WHEN so the transform is idempotent: --- coordinates already in grid units (≤50) are left untouched. --- PRECONDITION: assumes no pre-existing room has pixel-scale coords ≤50. --- Any element with pixel x/y/width/height ≤50 will be skipped (treated as --- already converted). Verify this holds before running on a production DB. +-- Only runs on rooms that contain at least one element with a coordinate > 50 +-- (i.e. still in pixel scale). Once identified, all elements are converted +-- unconditionally — no per-element heuristic needed. UPDATE rooms SET layout_json = ( SELECT json_group_array( json_object( 'id', json_extract(value, '$.id'), 'label', json_extract(value, '$.label'), - 'x', CASE WHEN CAST(json_extract(value, '$.x') AS REAL) > 50 - THEN ROUND(CAST(json_extract(value, '$.x') AS REAL) / 40.0, 2) - ELSE json_extract(value, '$.x') END, - 'y', CASE WHEN CAST(json_extract(value, '$.y') AS REAL) > 50 - THEN ROUND(CAST(json_extract(value, '$.y') AS REAL) / 40.0, 2) - ELSE json_extract(value, '$.y') END, - 'width', CASE WHEN CAST(json_extract(value, '$.width') AS REAL) > 50 - THEN ROUND(CAST(json_extract(value, '$.width') AS REAL) / 40.0, 2) - ELSE json_extract(value, '$.width') END, - 'height', CASE WHEN CAST(json_extract(value, '$.height') AS REAL) > 50 - THEN ROUND(CAST(json_extract(value, '$.height') AS REAL) / 40.0, 2) - ELSE json_extract(value, '$.height') END, + 'x', ROUND(CAST(json_extract(value, '$.x') AS REAL) / 40.0, 2), + 'y', ROUND(CAST(json_extract(value, '$.y') AS REAL) / 40.0, 2), + 'width', ROUND(CAST(json_extract(value, '$.width') AS REAL) / 40.0, 2), + 'height', ROUND(CAST(json_extract(value, '$.height') AS REAL) / 40.0, 2), 'type', json_extract(value, '$.type') ) ) FROM json_each(rooms.layout_json) ) -WHERE json_array_length(layout_json) > 0; +WHERE EXISTS ( + SELECT 1 FROM json_each(rooms.layout_json) + WHERE json_extract(value, '$.x') > 50 + OR json_extract(value, '$.y') > 50 + OR json_extract(value, '$.width') > 50 + OR json_extract(value, '$.height') > 50 +);