-- ============================================================ -- backfill-admin-coords.sql -- -- Prefer the admin-pinned coordinates over the user coordinates, and use the -- Mahabubnagar region centre ("vague" coords) only when neither is available. -- Mirrors the `__new_addresses` copy in -- packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql. -- -- Safe to re-run (every statement is idempotent). -- -- Local: -- wrangler d1 execute --local --file address_util/backfill-admin-coords.sql -- Remote: -- wrangler d1 execute --remote --config wrangler.prod.toml \ -- --file address_util/backfill-admin-coords.sql -- ============================================================ -- 1) Both admin coordinates present: admin wins, even when the user's -- latitude/longitude are also present. The row is no longer "vague". UPDATE addresses SET latitude = admin_latitude, longitude = admin_longitude, vague_backfilled_coords = 0 WHERE admin_latitude IS NOT NULL AND admin_longitude IS NOT NULL; -- 2) Only admin latitude present: take it. The longitude keeps whatever it had; -- vague is left untouched because that longitude may still be the fabricated -- region centre. (No such rows in the current DB.) UPDATE addresses SET latitude = admin_latitude WHERE admin_latitude IS NOT NULL AND admin_longitude IS NULL; -- 3) Only admin longitude present: take it. (No such rows in the current DB.) UPDATE addresses SET longitude = admin_longitude WHERE admin_longitude IS NOT NULL AND admin_latitude IS NULL; -- 4) No admin coordinates and a missing coordinate: backfill the Mahabubnagar -- region centre and mark the row vague. (No such rows in the current DB; -- kept so the rule is complete on other/future databases.) UPDATE addresses SET latitude = COALESCE(latitude, 16.750504), longitude = COALESCE(longitude, 77.993621), vague_backfilled_coords = 1 WHERE admin_latitude IS NULL AND admin_longitude IS NULL AND (latitude IS NULL OR longitude IS NULL); -- Verify: -- SELECT -- SUM(vague_backfilled_coords = 1) AS vague, -- SUM(admin_latitude IS NOT NULL AND admin_longitude IS NOT NULL) AS admin_rows, -- SUM(admin_latitude IS NOT NULL AND admin_longitude IS NOT NULL -- AND vague_backfilled_coords = 1) AS admin_still_vague -- FROM addresses; -- Expected after this file: admin_still_vague = 0.