1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Custom types for SQLAlchemy.
10 from typing import Callable, Any
12 import sqlalchemy as sa
13 import sqlalchemy.types as types
15 from nominatim.typing import SaColumn
17 class Geometry(types.UserDefinedType[Any]):
18 """ Simplified type decorator for PostGIS geometry. This type
19 only supports geometries in 4326 projection.
23 def __init__(self, subtype: str = 'Geometry'):
24 self.subtype = subtype
27 def get_col_spec(self) -> str:
28 return f'GEOMETRY({self.subtype}, 4326)'
31 def bind_processor(self, dialect: sa.Dialect) -> Callable[[Any], str]:
32 def process(value: Any) -> str:
33 assert isinstance(value, str)
38 def result_processor(self, dialect: sa.Dialect, coltype: object) -> Callable[[Any], str]:
39 def process(value: Any) -> str:
40 assert isinstance(value, str)
45 def bind_expression(self, bindvalue: sa.BindParameter[Any]) -> SaColumn:
46 return sa.func.ST_GeomFromText(bindvalue, type_=self)
49 class comparator_factory(types.UserDefinedType.Comparator):
51 def intersects(self, other: SaColumn) -> SaColumn:
52 return self.op('&&')(other)
54 def is_line_like(self) -> SaColumn:
55 return sa.func.ST_GeometryType(self, type_=sa.String).in_(('ST_LineString',
56 'ST_MultiLineString'))
58 def is_area(self) -> SaColumn:
59 return sa.func.ST_GeometryType(self, type_=sa.String).in_(('ST_Polygon',
63 def ST_DWithin(self, other: SaColumn, distance: SaColumn) -> SaColumn:
64 return sa.func.ST_DWithin(self, other, distance, type_=sa.Float)
67 def ST_Distance(self, other: SaColumn) -> SaColumn:
68 return sa.func.ST_Distance(self, other, type_=sa.Float)
71 def ST_Contains(self, other: SaColumn) -> SaColumn:
72 return sa.func.ST_Contains(self, other, type_=sa.Float)
75 def ST_ClosestPoint(self, other: SaColumn) -> SaColumn:
76 return sa.func.ST_ClosestPoint(self, other, type_=Geometry)
79 def ST_Buffer(self, other: SaColumn) -> SaColumn:
80 return sa.func.ST_Buffer(self, other, type_=Geometry)
83 def ST_Expand(self, other: SaColumn) -> SaColumn:
84 return sa.func.ST_Expand(self, other, type_=Geometry)
87 def ST_Centroid(self) -> SaColumn:
88 return sa.func.ST_Centroid(self, type_=Geometry)
91 def ST_LineInterpolatePoint(self, other: SaColumn) -> SaColumn:
92 return sa.func.ST_LineInterpolatePoint(self, other, type_=Geometry)
95 def ST_LineLocatePoint(self, other: SaColumn) -> SaColumn:
96 return sa.func.ST_LineLocatePoint(self, other, type_=sa.Float)