diff --git a/geocode/scotland.py b/geocode/scotland.py index 27c50e3..f377c84 100644 --- a/geocode/scotland.py +++ b/geocode/scotland.py @@ -1,16 +1,17 @@ """Reverse geocode civil parishes in Scotland.""" -import psycopg2 -from flask import current_app +from sqlalchemy import func + +from geocode.database import session +from geocode.model import Scotland -def get_scotland_code(lat: str | float, lon: str | float) -> str | None: +def get_scotland_code(lat: float, lon: float) -> str | None: """Find civil parish in Scotland for given lat/lon.""" - conn = psycopg2.connect(**current_app.config["DB_PARAMS"]) - cur = conn.cursor() - - point = f"ST_Transform(ST_SetSRID(ST_MakePoint({lon}, {lat}), 4326), 27700)" - cur.execute(f"select code, name from scotland where st_contains(geom, {point});") - row = cur.fetchone() - conn.close() - return row[0] if row else None + point = func.ST_Transform(func.ST_SetSRID(func.ST_MakePoint(lon, lat), 4326), 27700) + result = ( + session.query(Scotland.code) + .filter(func.ST_Contains(Scotland.geom, point)) + .first() + ) + return result[0] if result else None