From c1f04c65aaa8529e3d01586d1fb2a60fe71a749f Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:17:29 +0100 Subject: [PATCH 01/11] Count rows with `select()` in the tests `Session.query()` is the legacy API in SQLAlchemy 2.x. --- tests/console/test_gridify.py | 5 +++-- tests/db/replay/test_orders.py | 14 ++++++++++---- tests/db/test_addresses.py | 8 ++++++-- tests/db/test_addresses_addresses.py | 24 ++++++++++++------------ tests/db/test_addresses_pixels.py | 14 ++++++++++++-- tests/db/test_cities.py | 5 +++-- tests/db/test_couriers.py | 9 +++++++-- tests/db/test_customer.py | 9 +++++++-- tests/db/test_forecasts.py | 8 ++++++-- tests/db/test_grids.py | 4 ++-- tests/db/test_orders.py | 12 ++++++------ tests/db/test_pixels.py | 4 ++-- tests/db/test_restaurants.py | 10 ++++++++-- tests/forecasts/test_models.py | 13 ++++++++++--- 14 files changed, 94 insertions(+), 45 deletions(-) diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index f730951..8a7af2a 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -1,6 +1,7 @@ """Integration test for the `velofy.console.gridify` module.""" import pytest +import sqlalchemy as sa import velofy from velofy import db @@ -50,5 +51,5 @@ def test_two_pixels_with_two_addresses( assert result.exit_code == 0 - assert db_session.query(db.Grid).count() == 1 - assert db_session.query(db.Pixel).count() == 2 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Grid)) == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Pixel)) == 2 diff --git a/tests/db/replay/test_orders.py b/tests/db/replay/test_orders.py index 967ae0b..55beb6c 100644 --- a/tests/db/replay/test_orders.py +++ b/tests/db/replay/test_orders.py @@ -31,12 +31,18 @@ class TestConstraints: def test_insert_into_into_database(self, db_session, replayed_order): """Insert an instance into the (empty) database.""" - assert db_session.query(db.ReplayedOrder).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.ReplayedOrder)) + == 0 + ) db_session.add(replayed_order) db_session.commit() - assert db_session.query(db.ReplayedOrder).count() == 1 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.ReplayedOrder)) + == 1 + ) def test_delete_a_referenced_simulation(self, db_session, replayed_order): """Remove a record that is referenced with a FK.""" @@ -202,12 +208,12 @@ class TestConstraints: dispatch_at=scheduled_delivery_at + dt.timedelta(hours=1), ) - assert db_session.query(db.Order).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 0 db_session.add(replay_pre_order) db_session.commit() - assert db_session.query(db.Order).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 1 def test_scheduled_order_too_late(self, db_session, make_replay_order): """Insert an instance with invalid data.""" diff --git a/tests/db/test_addresses.py b/tests/db/test_addresses.py index 9057657..759d39e 100644 --- a/tests/db/test_addresses.py +++ b/tests/db/test_addresses.py @@ -29,12 +29,16 @@ class TestConstraints: def test_insert_into_database(self, db_session, address): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Address).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Address)) == 0 + ) db_session.add(address) db_session.commit() - assert db_session.query(db.Address).count() == 1 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Address)) == 1 + ) def test_delete_a_referenced_address(self, db_session, address, make_address): """Remove a record that is referenced with a FK.""" diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index a9a0dbf..267554f 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -60,12 +60,12 @@ class TestConstraints: def test_insert_into_database(self, db_session, path): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Path).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0 db_session.add(path) db_session.commit() - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 def test_delete_a_referenced_first_address(self, db_session, path): """Remove a record that is referenced with a FK.""" @@ -222,11 +222,11 @@ class TestFromAddresses: another_address, ): """Test instantiation of a new `Path` instance.""" - assert db_session.query(db.Path).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0 db.Path.from_addresses(address, another_address) - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 def test_make_the_same_path_instance_twice( self, @@ -235,15 +235,15 @@ class TestFromAddresses: another_address, ): """Test instantiation of a new `Path` instance.""" - assert db_session.query(db.Path).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0 db.Path.from_addresses(address, another_address) - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 db.Path.from_addresses(another_address, address) - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 def test_structure_of_return_value(self, address, another_address): """Test instantiation of a new `Path` instance.""" @@ -323,11 +323,11 @@ class TestFromAddresses: order, ): """Test instantiation of a new `Path` instance.""" - assert db_session.query(db.Path).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0 db.Path.from_order(order) - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 def test_make_the_same_path_instance_from_order_twice( self, @@ -335,15 +335,15 @@ class TestFromAddresses: order, ): """Test instantiation of a new `Path` instance.""" - assert db_session.query(db.Path).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0 db.Path.from_order(order) - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 db.Path.from_order(order) - assert db_session.query(db.Path).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1 def test_structure_of_return_value_from_order(self, order): """Test instantiation of a new `Path` instance.""" diff --git a/tests/db/test_addresses_pixels.py b/tests/db/test_addresses_pixels.py index 6fa46d9..90af9ed 100644 --- a/tests/db/test_addresses_pixels.py +++ b/tests/db/test_addresses_pixels.py @@ -43,12 +43,22 @@ class TestConstraints: def test_insert_into_database(self, db_session, assoc): """Insert an instance into the (empty) database.""" - assert db_session.query(db.AddressPixelAssociation).count() == 0 + assert ( + db_session.scalar( + sa.select(sa.func.count()).select_from(db.AddressPixelAssociation), + ) + == 0 + ) db_session.add(assoc) db_session.commit() - assert db_session.query(db.AddressPixelAssociation).count() == 1 + assert ( + db_session.scalar( + sa.select(sa.func.count()).select_from(db.AddressPixelAssociation), + ) + == 1 + ) def test_delete_a_referenced_address(self, db_session, assoc): """Remove a record that is referenced with a FK.""" diff --git a/tests/db/test_cities.py b/tests/db/test_cities.py index 85a2a99..cc7df6a 100644 --- a/tests/db/test_cities.py +++ b/tests/db/test_cities.py @@ -1,6 +1,7 @@ """Test the ORM's `City` model.""" import pytest +import sqlalchemy as sa from velofy import db from velofy.db import utils @@ -27,12 +28,12 @@ class TestConstraints: def test_insert_into_database(self, db_session, city): """Insert an instance into the (empty) database.""" - assert db_session.query(db.City).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.City)) == 0 db_session.add(city) db_session.commit() - assert db_session.query(db.City).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.City)) == 1 class TestProperties: diff --git a/tests/db/test_couriers.py b/tests/db/test_couriers.py index 531750d..d66a5fe 100644 --- a/tests/db/test_couriers.py +++ b/tests/db/test_couriers.py @@ -1,6 +1,7 @@ """Test the ORM's `Courier` model.""" import pytest +import sqlalchemy as sa from sqlalchemy import exc as sa_exc from velofy import db @@ -27,12 +28,16 @@ class TestConstraints: def test_insert_into_database(self, db_session, courier): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Courier).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Courier)) == 0 + ) db_session.add(courier) db_session.commit() - assert db_session.query(db.Courier).count() == 1 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Courier)) == 1 + ) def test_invalid_vehicle(self, db_session, courier): """Insert an instance with invalid data.""" diff --git a/tests/db/test_customer.py b/tests/db/test_customer.py index 761ed31..ec2ba2c 100644 --- a/tests/db/test_customer.py +++ b/tests/db/test_customer.py @@ -1,6 +1,7 @@ """Test the ORM's `Customer` model.""" import pytest +import sqlalchemy as sa from velofy import db @@ -26,9 +27,13 @@ class TestConstraints: def test_insert_into_database(self, db_session, customer): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Customer).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Customer)) == 0 + ) db_session.add(customer) db_session.commit() - assert db_session.query(db.Customer).count() == 1 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Customer)) == 1 + ) diff --git a/tests/db/test_forecasts.py b/tests/db/test_forecasts.py index 7bf7abf..4720870 100644 --- a/tests/db/test_forecasts.py +++ b/tests/db/test_forecasts.py @@ -63,12 +63,16 @@ class TestConstraints: def test_insert_into_database(self, db_session, forecast): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Forecast).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Forecast)) == 0 + ) db_session.add(forecast) db_session.commit() - assert db_session.query(db.Forecast).count() == 1 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Forecast)) == 1 + ) def test_delete_a_referenced_pixel(self, db_session, forecast): """Remove a record that is referenced with a FK.""" diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index a8bf845..c797e2e 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -28,12 +28,12 @@ class TestConstraints: def test_insert_into_database(self, db_session, grid): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Grid).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Grid)) == 0 db_session.add(grid) db_session.commit() - assert db_session.query(db.Grid).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Grid)) == 1 def test_delete_a_referenced_city(self, db_session, grid): """Remove a record that is referenced with a FK.""" diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index 3691cdd..f350057 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -34,23 +34,23 @@ class TestConstraints: """Insert an instance into the (empty) database.""" assert order.ad_hoc is True - assert db_session.query(db.Order).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 0 db_session.add(order) db_session.commit() - assert db_session.query(db.Order).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 1 def test_insert_scheduled_order_into_into_database(self, db_session, pre_order): """Insert an instance into the (empty) database.""" assert pre_order.ad_hoc is False - assert db_session.query(db.Order).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 0 db_session.add(pre_order) db_session.commit() - assert db_session.query(db.Order).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 1 def test_delete_a_referenced_customer(self, db_session, order): """Remove a record that is referenced with a FK.""" @@ -211,12 +211,12 @@ class TestConstraints: scheduled_delivery_at=dt.datetime(*test_config.DATE, 11, 45), ) - assert db_session.query(db.Order).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 0 db_session.add(pre_order) db_session.commit() - assert db_session.query(db.Order).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 1 def test_scheduled_order_too_late(self, db_session, make_order): """Insert an instance with invalid data.""" diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index 636328b..9231836 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -28,12 +28,12 @@ class TestConstraints: def test_insert_into_database(self, db_session, pixel): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Pixel).count() == 0 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Pixel)) == 0 db_session.add(pixel) db_session.commit() - assert db_session.query(db.Pixel).count() == 1 + assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Pixel)) == 1 def test_delete_a_referenced_grid(self, db_session, pixel): """Remove a record that is referenced with a FK.""" diff --git a/tests/db/test_restaurants.py b/tests/db/test_restaurants.py index a2d6b03..8737dac 100644 --- a/tests/db/test_restaurants.py +++ b/tests/db/test_restaurants.py @@ -28,12 +28,18 @@ class TestConstraints: def test_insert_into_database(self, db_session, restaurant): """Insert an instance into the (empty) database.""" - assert db_session.query(db.Restaurant).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Restaurant)) + == 0 + ) db_session.add(restaurant) db_session.commit() - assert db_session.query(db.Restaurant).count() == 1 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Restaurant)) + == 1 + ) def test_delete_a_referenced_address(self, db_session, restaurant): """Remove a record that is referenced with a FK.""" diff --git a/tests/forecasts/test_models.py b/tests/forecasts/test_models.py index 48de8c1..6d68e72 100644 --- a/tests/forecasts/test_models.py +++ b/tests/forecasts/test_models.py @@ -4,6 +4,7 @@ import typing as t import pandas as pd import pytest +import sqlalchemy as sa from tests import config as test_config from velofy import db @@ -173,7 +174,9 @@ class TestGenericForecastingModelProperties: """`*Model.make_forecast()` caches the `Forecast` object.""" model = model_cls(order_history=order_history) - assert db_session.query(db.Forecast).count() == 0 + assert ( + db_session.scalar(sa.select(sa.func.count()).select_from(db.Forecast)) == 0 + ) result1 = model.make_forecast( pixel=pixel, @@ -181,7 +184,9 @@ class TestGenericForecastingModelProperties: train_horizon=test_config.LONG_TRAIN_HORIZON, ) - n_cached_forecasts = db_session.query(db.Forecast).count() + n_cached_forecasts = db_session.scalar( + sa.select(sa.func.count()).select_from(db.Forecast), + ) assert n_cached_forecasts >= 1 result2 = model.make_forecast( @@ -190,6 +195,8 @@ class TestGenericForecastingModelProperties: train_horizon=test_config.LONG_TRAIN_HORIZON, ) - assert n_cached_forecasts == db_session.query(db.Forecast).count() + assert n_cached_forecasts == db_session.scalar( + sa.select(sa.func.count()).select_from(db.Forecast), + ) assert result1 == result2 -- 2.47.3 From 1f5a39f83ae1fdfb559950101b98e3b48318f74b Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:20:44 +0100 Subject: [PATCH 02/11] Query with `select()` in `velofy.console` `Session.query()` is the legacy API in SQLAlchemy 2.x. --- src/velofy/console/forecasts.py | 17 +++++++++-------- src/velofy/console/gridify.py | 11 ++++++----- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index c4d635f..9327635 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -68,7 +68,9 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 # Input validation. try: - city_obj = db.session.query(db.City).filter_by(name=city.title()).one() + city_obj = db.session.scalars( + sa.select(db.City).filter_by(name=city.title()), + ).one() except sa_exc.NoResultFound: click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"') sys.exit(1) @@ -104,15 +106,14 @@ def tactical_heuristic( # noqa:C901,D417,DOC001 # Important: this check may need to be adapted once further # commands are added the make `Forecast`s without the heuristic! # Continue with forecasting on the day the last prediction was made ... - last_predict_at = ( - db.session.query(sa.func.max(db.Forecast.start_at)) + last_predict_at = db.session.scalar( + sa.select(sa.func.max(db.Forecast.start_at)) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id) - .filter(db.Forecast.pixel == pixel) - .filter(db.Grid.side_length == side_length) - .filter(db.Forecast.time_step == time_step) - .filter(db.Forecast.train_horizon == train_horizon) - .scalar() + .where(db.Forecast.pixel == pixel) + .where(db.Grid.side_length == side_length) + .where(db.Forecast.time_step == time_step) + .where(db.Forecast.train_horizon == train_horizon), ) # ... or start `train_horizon` weeks after the first `Order` # if no `Forecast`s are in the database yet. diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index 9da5e5d..64f5311 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -1,6 +1,7 @@ """CLI script to create pixel grids.""" import click +import sqlalchemy as sa from velofy import config as pkg_config from velofy import db @@ -20,7 +21,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 All data are persisted to the database. """ - cities = db.session.query(db.City).all() + cities = db.session.scalars(sa.select(db.City)).all() click.echo(f"{len(cities)} cities retrieved from the database") for city in cities: @@ -37,10 +38,10 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 # Because the number of assigned addresses is the same across # different `side_length`s, we can take the last `grid` from the `city`. last_grid_id = grid.id # type: ignore[possibly-undefined] - n_assigned = ( - db.session.query(db.AddressPixelAssociation) - .filter(db.AddressPixelAssociation.grid_id == last_grid_id) - .count() + n_assigned = db.session.scalar( + sa.select(sa.func.count()) + .select_from(db.AddressPixelAssociation) + .where(db.AddressPixelAssociation.grid_id == last_grid_id), ) click.echo( f"=> Assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501 -- 2.47.3 From 53e1859ee8dfd3849312a2a8d52be7becd5c6587 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:29:18 +0100 Subject: [PATCH 03/11] Query with `select()` in `Grid` and `Path` `Session.query()` is the legacy API in SQLAlchemy 2.x. Unlike `Query`, `select()` does not deduplicate single entities from a `JOIN`; so, `Grid.gridify()` calls `.unique()` explicitly. The `addresses_mock` fixtures mock the new call chain. --- src/velofy/db/addresses_addresses.py | 11 +++++------ src/velofy/db/grids.py | 10 +++++++--- tests/db/test_grids.py | 2 +- tests/forecasts/timify/test_aggregate_orders.py | 4 ++-- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index cfb1fd0..57783f6 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -151,12 +151,11 @@ class Path(meta.Base): first, second = sorted(pair, key=lambda address: address.id) # If there is no `Path` object in the database ... - path = ( - db.session.query(cls) - .filter(cls.first_address == first) - .filter(cls.second_address == second) - .first() - ) + path = db.session.scalars( + sa.select(cls) + .where(cls.first_address == first) + .where(cls.second_address == second), + ).first() # ... create a new one. if path is None: air_distance = geo_distance.great_circle( diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index b6a3256..f711473 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -91,10 +91,14 @@ class Grid(meta.Base): # `Pixel`s grouped by `.n_x`-`.n_y` coordinates. pixels = {} + # `.unique()` because the `JOIN` yields an `Address` once per `Order`. pickup_addresses = ( - db.session.query(db.Address) - .join(db.Order, db.Address.id == db.Order.pickup_address_id) - .filter(db.Address.city == city) + db.session.scalars( + sa.select(db.Address) + .join(db.Order, db.Address.id == db.Order.pickup_address_id) + .where(db.Address.city == city), + ) + .unique() .all() ) diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index c797e2e..8116720 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -102,7 +102,7 @@ class TestGridification: all considered `Order.pickup_address` attributes for some orders. """ mock = mocker.Mock() - query = mock.query.return_value.join.return_value.filter.return_value.all + query = mock.scalars.return_value.unique.return_value.all monkeypatch.setattr(db, "session", mock) return query diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 9b625bf..91d66d7 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -26,8 +26,8 @@ class TestAggregateOrders: Note: This fixture also exists in `tests.db.test_grids`. """ mock = mocker.Mock() - query = mock.query.return_value.join.return_value.filter.return_value.all - monkeypatch.setattr(db_session, "query", mock.query) + query = mock.scalars.return_value.unique.return_value.all + monkeypatch.setattr(db_session, "scalars", mock.scalars) return query -- 2.47.3 From 9d2a4139b72a480108be77a6f723f17087756eb2 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:34:52 +0100 Subject: [PATCH 04/11] Query with `select()` in `City` `Session.query()` is the legacy API in SQLAlchemy 2.x. The addresses with restaurants are now selected with a subquery in one statement. --- src/velofy/db/cities.py | 35 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 879742c..94cc1aa 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -163,29 +163,25 @@ class City(meta.Base): `.map` for convenience in interactive usage """ # Obtain all primary `Address`es in the city that host `Restaurant`s. - addresses = ( - db.session.query(db.Address) - .filter( + addresses = db.session.scalars( + sa.select(db.Address).where( db.Address.id.in_( - db.session.query(db.Address.primary_id) + sa.select(db.Address.primary_id) .join(db.Restaurant, db.Address.id == db.Restaurant.address_id) - .filter(db.Address.city == self) - .distinct() - .all(), + .where(db.Address.city == self) + .distinct(), ), - ) - .all() - ) + ), + ).all() for address in addresses: # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. - restaurants = ( - db.session.query(db.Restaurant) + restaurants = db.session.scalars( + sa.select(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) - .all() - ) + .where(db.Address.primary_id == address.id), + ).all() if len(restaurants) == 1: tooltip = f"{restaurants[0].name} (#{restaurants[0].id})" else: @@ -195,12 +191,11 @@ class City(meta.Base): if order_counts: # Calculate the number of orders for ALL restaurants ... - n_orders = ( - db.session.query(db.Order.id) + n_orders = db.session.execute( + sa.select(sa.func.count(db.Order.id)) .join(db.Address, db.Order.pickup_address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) - .count() - ) + .where(db.Address.primary_id == address.id), + ).scalar_one() # ... and adjust the size of the red dot on the `.map`. if n_orders >= 1000: radius = 20 -- 2.47.3 From 54e21109e7605240c3f151c01238726d523e0555 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:37:43 +0100 Subject: [PATCH 05/11] Query with `select()` in `Restaurant` `Session.query()` is the legacy API in SQLAlchemy 2.x. The delivery addresses are now selected with a subquery in one statement. --- src/velofy/db/restaurants.py | 43 +++++++++++++++++------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 7936b60..34f9233 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -112,35 +112,32 @@ class Restaurant(meta.Base): if customers: # Obtain all primary `Address`es in the city that # received at least one delivery from `self`. - delivery_addresses = ( - db.session.query(db.Address) - .filter( + delivery_addresses = db.session.scalars( + sa.select(db.Address).where( db.Address.id.in_( - row.primary_id - for row in ( - db.session.query(db.Address.primary_id) - .join( - db.Order, - db.Address.id == db.Order.delivery_address_id, - ) - .filter(db.Order.restaurant_id == self.id) - .distinct() - .all() + sa.select(db.Address.primary_id) + .join( + db.Order, + db.Address.id == db.Order.delivery_address_id, ) + .where(db.Order.restaurant_id == self.id) + .distinct(), ), - ) - .all() - ) + ), + ).all() for address in delivery_addresses: if order_counts: - n_orders = ( - db.session.query(db.Order) - .join(db.Address, db.Order.delivery_address_id == db.Address.id) - .filter(db.Order.restaurant_id == self.id) - .filter(db.Address.primary_id == address.id) - .count() - ) + n_orders = db.session.execute( + sa.select(sa.func.count()) + .select_from(db.Order) + .join( + db.Address, + db.Order.delivery_address_id == db.Address.id, + ) + .where(db.Order.restaurant_id == self.id) + .where(db.Address.primary_id == address.id), + ).scalar_one() if n_orders >= 25: radius = 20 elif n_orders >= 10: -- 2.47.3 From 0dc3e11a63f2242747a06cc11eb24bdb1fb8789d Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:39:31 +0100 Subject: [PATCH 06/11] Query with `select()` in `Customer` `Session.query()` is the legacy API in SQLAlchemy 2.x. The delivery and pickup addresses are now selected with subqueries in one statement each. --- src/velofy/db/customers.py | 72 ++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 41 deletions(-) diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 7a9e4b1..f25b519 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -71,32 +71,26 @@ class Customer(meta.Base): # Obtain all primary `Address`es where # at least one delivery was made to `self`. - delivery_addresses = ( - db.session.query(db.Address) - .filter( + delivery_addresses = db.session.scalars( + sa.select(db.Address).where( db.Address.id.in_( - row.primary_id - for row in ( - db.session.query(db.Address.primary_id) - .join(db.Order, db.Address.id == db.Order.delivery_address_id) - .filter(db.Order.customer_id == self.id) - .distinct() - .all() - ) + sa.select(db.Address.primary_id) + .join(db.Order, db.Address.id == db.Order.delivery_address_id) + .where(db.Order.customer_id == self.id) + .distinct(), ), - ) - .all() - ) + ), + ).all() for address in delivery_addresses: if order_counts: - n_orders = ( - db.session.query(db.Order) + n_orders = db.session.execute( + sa.select(sa.func.count()) + .select_from(db.Order) .join(db.Address, db.Order.delivery_address_id == db.Address.id) - .filter(db.Order.customer_id == self.id) - .filter(db.Address.primary_id == address.id) - .count() - ) + .where(db.Order.customer_id == self.id) + .where(db.Address.primary_id == address.id), + ).scalar_one() if n_orders >= 25: radius = 20 elif n_orders >= 10: @@ -123,30 +117,26 @@ class Customer(meta.Base): ) if restaurants: - pickup_addresses = ( - db.session.query(db.Address) - .filter( + pickup_addresses = db.session.scalars( + sa.select(db.Address).where( db.Address.id.in_( - db.session.query(db.Address.primary_id) + sa.select(db.Address.primary_id) .join(db.Order, db.Address.id == db.Order.pickup_address_id) - .filter(db.Order.customer_id == self.id) - .distinct() - .all(), + .where(db.Order.customer_id == self.id) + .distinct(), ), - ) - .all() - ) + ), + ).all() for address in pickup_addresses: # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. # We cannot show the `Order.restaurant.name` due to the aggregation. - restaurants_at_address = ( - db.session.query(db.Restaurant) + restaurants_at_address = db.session.scalars( + sa.select(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) - .all() - ) + .where(db.Address.primary_id == address.id), + ).all() if len(restaurants_at_address) == 1: restaurant = restaurants_at_address[0] tooltip = f"{restaurant.name} (#{restaurant.id})" @@ -155,13 +145,13 @@ class Customer(meta.Base): tooltip = f"Restaurants {ids}" if order_counts: - n_orders = ( - db.session.query(db.Order) + n_orders = db.session.execute( + sa.select(sa.func.count()) + .select_from(db.Order) .join(db.Address, db.Order.pickup_address_id == db.Address.id) - .filter(db.Order.customer_id == self.id) - .filter(db.Address.primary_id == address.id) - .count() - ) + .where(db.Order.customer_id == self.id) + .where(db.Address.primary_id == address.id), + ).scalar_one() if n_orders >= 25: radius = 20 elif n_orders >= 10: -- 2.47.3 From 2eb6b5769f73159cd12a408c7cfc75861b3e0474 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:42:29 +0100 Subject: [PATCH 07/11] Query with `select()` in `Pixel` `Session.query()` is the legacy API in SQLAlchemy 2.x. The addresses with restaurants are now selected with a subquery in one statement. The `_restaurants_mock` fixture mocks the new call chain. --- src/velofy/db/pixels.py | 68 +++++++++++++++++++---------------------- tests/db/test_pixels.py | 2 +- 2 files changed, 32 insertions(+), 38 deletions(-) diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 001ef3c..321f5fc 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -140,14 +140,15 @@ class Pixel(meta.Base): @functools.cached_property def restaurants(self) -> list["db.Restaurant"]: # pragma: no cover """Obtain all `Restaurant`s in `self`.""" - return ( - db.session.query(db.Restaurant) - .join( - db.AddressPixelAssociation, - db.Restaurant.address_id == db.AddressPixelAssociation.address_id, - ) - .filter(db.AddressPixelAssociation.pixel_id == self.id) - .all() + return list( + db.session.scalars( + sa.select(db.Restaurant) + .join( + db.AddressPixelAssociation, + db.Restaurant.address_id == db.AddressPixelAssociation.address_id, + ) + .where(db.AddressPixelAssociation.pixel_id == self.id), + ).all(), ) def clear_map(self) -> t.Self: # pragma: no cover @@ -203,38 +204,32 @@ class Pixel(meta.Base): if restaurants: # Obtain all primary `Address`es in the city that host `Restaurant`s # and are in the `self` `Pixel`. - addresses = ( - db.session.query(db.Address) - .filter( + addresses = db.session.scalars( + sa.select(db.Address).where( db.Address.id.in_( - ( - db.session.query(db.Address.primary_id) - .join( - db.Restaurant, - db.Address.id == db.Restaurant.address_id, - ) - .join( - db.AddressPixelAssociation, - db.Address.id == db.AddressPixelAssociation.address_id, - ) - .filter(db.AddressPixelAssociation.pixel_id == self.id) + sa.select(db.Address.primary_id) + .join( + db.Restaurant, + db.Address.id == db.Restaurant.address_id, ) - .distinct() - .all(), + .join( + db.AddressPixelAssociation, + db.Address.id == db.AddressPixelAssociation.address_id, + ) + .where(db.AddressPixelAssociation.pixel_id == self.id) + .distinct(), ), - ) - .all() - ) + ), + ).all() for address in addresses: # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. - restaurants_at_address = ( - db.session.query(db.Restaurant) + restaurants_at_address = db.session.scalars( + sa.select(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) - .all() - ) + .where(db.Address.primary_id == address.id), + ).all() if len(restaurants_at_address) == 1: restaurant = restaurants_at_address[0] tooltip = f"{restaurant.name} (#{restaurant.id})" @@ -244,12 +239,11 @@ class Pixel(meta.Base): if order_counts: # Calculate the number of orders for ALL restaurants ... - n_orders = ( - db.session.query(db.Order.id) + n_orders = db.session.execute( + sa.select(sa.func.count(db.Order.id)) .join(db.Address, db.Order.pickup_address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) - .count() - ) + .where(db.Address.primary_id == address.id), + ).scalar_one() # ... and adjust the size of the red dot on the `.map`. if n_orders >= 1000: radius = 20 diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index 9231836..8da49e0 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -121,7 +121,7 @@ class TestProperties: def _restaurants_mock(self, mocker, monkeypatch, restaurant): """A `Mock` whose `.return_value` is `[restaurant]`.""" mock = mocker.Mock() - query = mock.query.return_value.join.return_value.filter.return_value.all + query = mock.scalars.return_value.all query.return_value = [restaurant] monkeypatch.setattr(db, "session", mock) -- 2.47.3 From 185a37f7d492f21608ce9c64ab8779ae47d93d70 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:48:22 +0100 Subject: [PATCH 08/11] Query with `select()` in the forecasting models `Session.query()` is the legacy API in SQLAlchemy 2.x. `.one_or_none()` expresses that the unique constraint on the five filtered columns allows at most one cached `Forecast`. --- src/velofy/forecasts/models/base.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index c8bc6d7..2cc5671 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -5,6 +5,7 @@ import datetime as dt import typing as t import pandas as pd +import sqlalchemy as sa from velofy import db from velofy.forecasts import timify @@ -80,15 +81,15 @@ class ForecastingModelABC(abc.ABC): Raises: RuntimeError: `*Model.predict()` misses the prediction for `predict_at` """ - if ( - cached_forecast := db.session.query(db.Forecast) - .filter_by(pixel=pixel) - .filter_by(start_at=predict_at) - .filter_by(time_step=self._order_history.time_step) - .filter_by(train_horizon=train_horizon) - .filter_by(model=self.name) - .first() - ): + if cached_forecast := db.session.scalars( + sa.select(db.Forecast).filter_by( + pixel=pixel, + start_at=predict_at, + time_step=self._order_history.time_step, + train_horizon=train_horizon, + model=self.name, + ), + ).one_or_none(): return cached_forecast # Horizontal and real-time `*Model`s return a `pd.DataFrame` with one -- 2.47.3 From bc2e3f439d8c7c185bb6972f735c251f16d0b8e4 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 23:50:44 +0100 Subject: [PATCH 09/11] Count with `.scalar_one()` in `velofy.console.gridify` A `COUNT` always returns exactly one row; `.scalar_one()` is typed as `int` and is used for all other counts as well. --- src/velofy/console/gridify.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index 64f5311..56f993e 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -38,11 +38,11 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 # Because the number of assigned addresses is the same across # different `side_length`s, we can take the last `grid` from the `city`. last_grid_id = grid.id # type: ignore[possibly-undefined] - n_assigned = db.session.scalar( + n_assigned = db.session.execute( sa.select(sa.func.count()) .select_from(db.AddressPixelAssociation) .where(db.AddressPixelAssociation.grid_id == last_grid_id), - ) + ).scalar_one() click.echo( f"=> Assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501 ) -- 2.47.3 From 9d98021b117f7a7bc9623b479b134ee0082761e0 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Wed, 2 Dec 2026 00:19:03 +0100 Subject: [PATCH 10/11] Request the `db_session` fixture The test queries the database but relied on the global `db.session` that the previous test had left behind. --- tests/db/test_pixels.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index 8da49e0..6284fa7 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -141,6 +141,7 @@ class TestProperties: assert result1 is result2 @pytest.mark.db + @pytest.mark.usefixtures("db_session") def test_restaurants_with_db(self, pixel): """Test `Pixel.restaurants` property. -- 2.47.3 From fc185fa3c0c1229d50c0f2b1ec1636231f4c51f3 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Wed, 2 Dec 2026 00:19:19 +0100 Subject: [PATCH 11/11] Create the engine and the session on first use The global `db.session` is now a `scoped_session`, like, for example, in Flask-SQLAlchemy. Importing the package no longer creates an engine; so, the placeholder for the tests is obsolete. The `db_session` fixture replaces `db.session` with `monkeypatch` such that it is reset after each test. Tests without the fixture get a placeholder that fails loudly instead of opening a real session, which would block the `DROP SCHEMA` at the end of the test run. --- src/velofy/db/connection.py | 31 +++++++++++++++++++------------ tests/conftest.py | 23 +++++++++++++++++++++-- tests/db/test_connection.py | 23 +++++++++++++++++++++++ 3 files changed, 63 insertions(+), 14 deletions(-) create mode 100644 tests/db/test_connection.py diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index 1e29d81..0e4a8cf 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -1,13 +1,12 @@ """Provide connection utils for the ORM layer. -This module defines a fully configured `session` object -to be used as a global within the `velofy` package. - -If a database is not guaranteed to be available, it is set to `None`. -That is the case on the CI server. +The `session` object is used as a global within the `velofy` package, +like `db.session` in Flask-SQLAlchemy: It is a proxy to one session per thread. +The engine and the session are only created on first use; +so, importing the package does not require a database. """ -import os +import functools import typing as t import sqlalchemy as sa @@ -16,10 +15,18 @@ from sqlalchemy import orm import velofy -if os.getenv("TESTING"): - # Placeholder that the test fixtures replace - session: orm.Session = None # type: ignore[assignment] +@functools.cache +def get_engine() -> sa.Engine: + """The engine for the configured `DATABASE_URI`, created on first use.""" + return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI)) -else: # pragma: no cover - engine = sa.create_engine(t.cast(str, velofy.config.DATABASE_URI)) - session = orm.Session(bind=engine) + +# `scoped_session()` accepts any callable creating sessions +# while its type stubs expect a `sessionmaker` +# => The lambda defers creating the engine to first use. +session: orm.scoped_session[orm.Session] = orm.scoped_session( + t.cast( + "orm.sessionmaker[orm.Session]", + lambda: orm.Session(bind=get_engine()), + ), +) diff --git a/tests/conftest.py b/tests/conftest.py index 754f515..31f8442 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,6 +6,7 @@ in the CLI layer need access to the database. import os import random +import typing as t import pytest import sqlalchemy as sa @@ -91,7 +92,7 @@ def db_connection(request): @pytest.fixture -def db_session(db_connection): +def db_session(db_connection, monkeypatch): """A SQLAlchemy session that rolls back everything after a test case.""" # Begin the outermost transaction # that is rolled back at the end of each test case. @@ -104,7 +105,7 @@ def db_session(db_connection): # Monkey patch the package's global `session` object, # which is used heavily in the code base. - db.session = session + monkeypatch.setattr(db, "session", session) try: yield session @@ -115,6 +116,24 @@ def db_session(db_connection): transaction.rollback() +class _NoSession: + """Placeholder for `db.session` in tests without the `db_session` fixture.""" + + def __getattr__(self, _name: str) -> t.NoReturn: + msg = "Use the `db_session` fixture to access the database" + raise RuntimeError(msg) + + +@pytest.fixture(autouse=True) +def _no_global_session(monkeypatch): + """Prevent tests from opening real sessions via `db.session`. + + Such a session would hold locks in the test schema + and block the `DROP SCHEMA` at the end of the test run. + """ + monkeypatch.setattr(db, "session", _NoSession()) + + @pytest.fixture(autouse=True) def _seed_random() -> None: """Make the fake data reproducible across test runs.""" diff --git a/tests/db/test_connection.py b/tests/db/test_connection.py new file mode 100644 index 0000000..73275a0 --- /dev/null +++ b/tests/db/test_connection.py @@ -0,0 +1,23 @@ +"""Test the connection utils in `velofy.db.connection`.""" + +import sqlalchemy as sa + +from velofy import config as pkg_config +from velofy.db import connection + + +def test_engine_uses_the_configured_database(): + """`get_engine()` connects to the `DATABASE_URI`.""" + result = connection.get_engine() + + assert result.url == sa.make_url(pkg_config.DATABASE_URI) + + +def test_session_is_bound_to_the_engine(): + """The `session` proxy creates sessions bound to `get_engine()`.""" + session = connection.session() + + try: + assert session.get_bind() is connection.get_engine() + finally: + connection.session.remove() -- 2.47.3