New ORM Declarative Mapping StyleΒΆ

SQLAlchemy>=2 introduced a new way to construct mappings using the sqlalchemy.orm.DeclarativeBase base class. This example shows how to use GeoAlchemy2 types in this context.

 9 import pytest
10 from pkg_resources import parse_version
11 from sqlalchemy import __version__ as SA_VERSION
12
13 try:
14     from sqlalchemy.orm import DeclarativeBase
15     from sqlalchemy.orm import Mapped
16     from sqlalchemy.orm import mapped_column
17 except ImportError:
18     pass
19
20 from geoalchemy2 import Geometry
21 from geoalchemy2 import WKBElement
22 from geoalchemy2 import shape
23
24
25 def check_wkb(wkb, x, y) -> None:
26     pt = shape.to_shape(wkb)
27     assert round(pt.x, 5) == x
28     assert round(pt.y, 5) == y
29
30
31 @pytest.mark.skipif(
32     parse_version(SA_VERSION) < parse_version("2"),
33     reason="New ORM mapping is only available for sqlalchemy>=2",
34 )
35 def test_ORM_mapping(session, conn, schema) -> None:
36     class Base(DeclarativeBase):
37         pass
38
39     class Lake(Base):
40         __tablename__ = "lake"
41         __table_args__ = {"schema": schema}
42         id: Mapped[int] = mapped_column(primary_key=True)
43         mapped_geom: Mapped[WKBElement] = mapped_column(Geometry(geometry_type="POINT", srid=4326))
44
45     Lake.__table__.drop(conn, checkfirst=True)  # type: ignore[attr-defined]
46     Lake.__table__.create(bind=conn)  # type: ignore[attr-defined]
47
48     # Create new point instance
49     p = Lake()
50     p.mapped_geom = "SRID=4326;POINT(5 45)"  # type: ignore[assignment]
51
52     # Insert point
53     session.add(p)
54     session.flush()
55     session.expire(p)
56
57     # Query the point and check the result
58     pt = session.query(Lake).one()
59     assert pt.id == 1
60     assert pt.mapped_geom.srid == 4326
61     check_wkb(pt.mapped_geom, 5, 45)

Gallery generated by Sphinx-Gallery