Skip to content

Commit

Permalink
Refactored sqlalchemy-related parsing of geometry (#88)
Browse files Browse the repository at this point in the history
* Refactored sqlalchemy-related parsing of geometry

Geometry is now able to recognize custom CRS definitions

* Removed unnecessary import
  • Loading branch information
ricardogsilva authored Jan 8, 2024
1 parent f087964 commit 296e8b9
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
14 changes: 8 additions & 6 deletions pygeofilter/backends/sqlalchemy/filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import re
from datetime import timedelta
from functools import reduce
from inspect import signature
Expand All @@ -7,7 +6,6 @@
from pygeoif import shape
from sqlalchemy import and_, func, not_, or_


def parse_bbox(box, srid: int = None):
minx, miny, maxx, maxy = box
return func.ST_GeomFromEWKT(
Expand All @@ -18,11 +16,15 @@ def parse_bbox(box, srid: int = None):
)


def parse_geometry(geom):
def parse_geometry(geom: dict):
crs_identifier = geom.get(
"crs", {}
).get(
"properties", {}
).get("name", "urn:ogc:def:crs:EPSG::4326")
srid = crs_identifier.rpartition("::")[-1]
wkt = shape(geom).wkt
search = re.search(r"SRID=(\d+);", wkt)
sridtxt = "" if search else "SRID=4326;"
return func.ST_GeomFromEWKT(f"{sridtxt}{wkt}")
return func.ST_GeomFromEWKT(f"SRID={srid};{wkt}")


# ------------------------------------------------------------------------------
Expand Down
34 changes: 34 additions & 0 deletions tests/backends/sqlalchemy/test_filters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import cast
import pytest

from pygeofilter.backends.sqlalchemy import filters


@pytest.mark.parametrize("geom, expected", [
pytest.param(
{
"type": "Point",
"coordinates": [10, 12]
},
"ST_GeomFromEWKT('SRID=4326;POINT (10 12)')",
id="without-crs"
),
pytest.param(
{
"type": "Point",
"coordinates": [1, 2],
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:EPSG::3004"
}
}
},
"ST_GeomFromEWKT('SRID=3004;POINT (1 2)')",
id="with-crs"
),
])
def test_parse_geometry(geom, expected):
parsed = filters.parse_geometry(cast(dict, geom))
result = str(parsed.compile(compile_kwargs={"literal_binds": True}))
assert result == expected

0 comments on commit 296e8b9

Please sign in to comment.