Use typed hybrids for the read-only columns

See commit 22286ddd0d just before
for how to solve the problem without a `hybrid`.

We choose `hybrid`s nevertheless
because they are the de-facto way of doing it.
This commit is contained in:
Alexander Hess 2026-12-06 09:02:30 +01:00
commit a36ed34b5e
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
2 changed files with 75 additions and 18 deletions

View file

@ -2,6 +2,7 @@
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext import hybrid as sa_hybrid
from velofy import db
from velofy.db import meta
@ -84,12 +85,22 @@ class AddressPixelAssociation(meta.Base):
back_populates="addresses",
)
# Read-only views of the private columns above
city_id: orm.Mapped[int] = orm.synonym(
"_city_id",
descriptor=property(lambda self: self._city_id),
)
grid_id: orm.Mapped[int] = orm.synonym(
"_grid_id",
descriptor=property(lambda self: self._grid_id),
)
@sa_hybrid.hybrid_property
def city_id(self) -> int:
"""The ID of the `.address`'s `City`."""
return self._city_id
@city_id.inplace.expression
@classmethod
def _city_id_expression(cls) -> orm.InstrumentedAttribute[int]:
return cls._city_id
@sa_hybrid.hybrid_property
def grid_id(self) -> int:
"""The ID of the `.pixel`'s `Grid`."""
return self._grid_id
@grid_id.inplace.expression
@classmethod
def _grid_id_expression(cls) -> orm.InstrumentedAttribute[int]:
return cls._grid_id

View file

@ -1,12 +1,8 @@
"""Test the ORM's `AddressPixelAssociation` model.
Implementation notes:
The test suite has 100% coverage without the test cases in this module.
That is so as the `AddressPixelAssociation` model is imported into the
`velofy.db` namespace so that the `Address` and `Pixel` models
can find it upon initialization. Yet, none of the other unit tests run any
code associated with it. Therefore, we test it here as non-e2e tests and do
not measure its coverage.
Only `TestHybrids` counts towards the coverage.
Importing `velofy.db` already runs the model's definition.
Its `hybrid`s are the only code that needs a test to run.
"""
import pytest
@ -82,7 +78,7 @@ class TestConstraints:
# Must insert without ORM as otherwise SQLAlchemy figures out
# that something is wrong before any query is sent to the database
stmt = sa.insert(db.AddressPixelAssociation).values(
stmt = sa.insert(db.AddressPixelAssociation.__table__).values(
address_id=address.id,
city_id=999,
grid_id=pixel.grid.id,
@ -103,7 +99,7 @@ class TestConstraints:
# Must insert without ORM as otherwise SQLAlchemy figures out
# that something is wrong before any query is sent to the database
stmt = sa.insert(db.AddressPixelAssociation).values(
stmt = sa.insert(db.AddressPixelAssociation.__table__).values(
address_id=address.id,
city_id=address.city.id,
grid_id=999,
@ -143,3 +139,53 @@ class TestConstraints:
with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"):
db_session.commit()
@pytest.mark.db
class TestHybrids:
"""Test the read-only `hybrid`s in the `AddressPixelAssociation`."""
def test_city_id_is_copied_from_the_address(self, db_session, assoc):
"""Read `.city_id` on an instance.
`sqlalchemy` copies it from the `.address` when flushing.
"""
db_session.add(assoc)
db_session.commit()
assert assoc.city_id == assoc.address.city.id
def test_grid_id_is_copied_from_the_pixel(self, db_session, assoc):
"""Read `.grid_id` on an instance.
`sqlalchemy` copies it from the `.pixel` when flushing.
"""
db_session.add(assoc)
db_session.commit()
assert assoc.grid_id == assoc.pixel.grid.id
@pytest.mark.parametrize("attribute", ["city_id", "grid_id"])
def test_cannot_be_set(self, assoc, attribute):
"""Set a `hybrid` on an instance.
Without a setter, this raises an `AttributeError`.
"""
with pytest.raises(AttributeError):
setattr(assoc, attribute, 1)
def test_filter_by_city_id(self, db_session, assoc):
"""Use `.city_id` in a query.
On the class, `._city_id_expression()` provides the column.
"""
db_session.add(assoc)
db_session.commit()
results = db_session.scalars(
sa.select(db.AddressPixelAssociation).where(
db.AddressPixelAssociation.city_id == assoc.address.city.id,
),
).all()
assert assoc in results