Replace the legacy Session.query() API #17

Merged
alexander merged 11 commits from sqlalchemy-select into develop 2026-12-02 00:38:24 +01:00
27 changed files with 297 additions and 216 deletions

View file

@ -68,7 +68,9 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
# Input validation. # Input validation.
try: 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: except sa_exc.NoResultFound:
click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"') click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"')
sys.exit(1) sys.exit(1)
@ -104,15 +106,14 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
# Important: this check may need to be adapted once further # Important: this check may need to be adapted once further
# commands are added the make `Forecast`s without the heuristic! # commands are added the make `Forecast`s without the heuristic!
# Continue with forecasting on the day the last prediction was made ... # Continue with forecasting on the day the last prediction was made ...
last_predict_at = ( last_predict_at = db.session.scalar(
db.session.query(sa.func.max(db.Forecast.start_at)) sa.select(sa.func.max(db.Forecast.start_at))
.join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id)
.join(db.Grid, db.Pixel.grid_id == db.Grid.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id)
.filter(db.Forecast.pixel == pixel) .where(db.Forecast.pixel == pixel)
.filter(db.Grid.side_length == side_length) .where(db.Grid.side_length == side_length)
.filter(db.Forecast.time_step == time_step) .where(db.Forecast.time_step == time_step)
.filter(db.Forecast.train_horizon == train_horizon) .where(db.Forecast.train_horizon == train_horizon),
.scalar()
) )
# ... or start `train_horizon` weeks after the first `Order` # ... or start `train_horizon` weeks after the first `Order`
# if no `Forecast`s are in the database yet. # if no `Forecast`s are in the database yet.

View file

@ -1,6 +1,7 @@
"""CLI script to create pixel grids.""" """CLI script to create pixel grids."""
import click import click
import sqlalchemy as sa
from velofy import config as pkg_config from velofy import config as pkg_config
from velofy import db from velofy import db
@ -20,7 +21,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
All data are persisted to the database. 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") click.echo(f"{len(cities)} cities retrieved from the database")
for city in cities: for city in cities:
@ -37,11 +38,11 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
# Because the number of assigned addresses is the same across # Because the number of assigned addresses is the same across
# different `side_length`s, we can take the last `grid` from the `city`. # different `side_length`s, we can take the last `grid` from the `city`.
last_grid_id = grid.id # type: ignore[possibly-undefined] last_grid_id = grid.id # type: ignore[possibly-undefined]
n_assigned = ( n_assigned = db.session.execute(
db.session.query(db.AddressPixelAssociation) sa.select(sa.func.count())
.filter(db.AddressPixelAssociation.grid_id == last_grid_id) .select_from(db.AddressPixelAssociation)
.count() .where(db.AddressPixelAssociation.grid_id == last_grid_id),
) ).scalar_one()
click.echo( click.echo(
f"=> Assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501 f"=> Assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501
) )

View file

@ -151,12 +151,11 @@ class Path(meta.Base):
first, second = sorted(pair, key=lambda address: address.id) first, second = sorted(pair, key=lambda address: address.id)
# If there is no `Path` object in the database ... # If there is no `Path` object in the database ...
path = ( path = db.session.scalars(
db.session.query(cls) sa.select(cls)
.filter(cls.first_address == first) .where(cls.first_address == first)
.filter(cls.second_address == second) .where(cls.second_address == second),
.first() ).first()
)
# ... create a new one. # ... create a new one.
if path is None: if path is None:
air_distance = geo_distance.great_circle( air_distance = geo_distance.great_circle(

View file

@ -163,29 +163,25 @@ class City(meta.Base):
`.map` for convenience in interactive usage `.map` for convenience in interactive usage
""" """
# Obtain all primary `Address`es in the city that host `Restaurant`s. # Obtain all primary `Address`es in the city that host `Restaurant`s.
addresses = ( addresses = db.session.scalars(
db.session.query(db.Address) sa.select(db.Address).where(
.filter(
db.Address.id.in_( 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) .join(db.Restaurant, db.Address.id == db.Restaurant.address_id)
.filter(db.Address.city == self) .where(db.Address.city == self)
.distinct() .distinct(),
.all(),
), ),
) ),
.all() ).all()
)
for address in addresses: for address in addresses:
# Show the restaurant's name if there is only one. # Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's. # Otherwise, list all the restaurants' ID's.
restaurants = ( restaurants = db.session.scalars(
db.session.query(db.Restaurant) sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id) .join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.all() ).all()
)
if len(restaurants) == 1: if len(restaurants) == 1:
tooltip = f"{restaurants[0].name} (#{restaurants[0].id})" tooltip = f"{restaurants[0].name} (#{restaurants[0].id})"
else: else:
@ -195,12 +191,11 @@ class City(meta.Base):
if order_counts: if order_counts:
# Calculate the number of orders for ALL restaurants ... # Calculate the number of orders for ALL restaurants ...
n_orders = ( n_orders = db.session.execute(
db.session.query(db.Order.id) sa.select(sa.func.count(db.Order.id))
.join(db.Address, db.Order.pickup_address_id == db.Address.id) .join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.count() ).scalar_one()
)
# ... and adjust the size of the red dot on the `.map`. # ... and adjust the size of the red dot on the `.map`.
if n_orders >= 1000: if n_orders >= 1000:
radius = 20 radius = 20

View file

@ -1,13 +1,12 @@
"""Provide connection utils for the ORM layer. """Provide connection utils for the ORM layer.
This module defines a fully configured `session` object The `session` object is used as a global within the `velofy` package,
to be 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;
If a database is not guaranteed to be available, it is set to `None`. so, importing the package does not require a database.
That is the case on the CI server.
""" """
import os import functools
import typing as t import typing as t
import sqlalchemy as sa import sqlalchemy as sa
@ -16,10 +15,18 @@ from sqlalchemy import orm
import velofy import velofy
if os.getenv("TESTING"): @functools.cache
# Placeholder that the test fixtures replace def get_engine() -> sa.Engine:
session: orm.Session = None # type: ignore[assignment] """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)) # `scoped_session()` accepts any callable creating sessions
session = orm.Session(bind=engine) # 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()),
),
)

View file

@ -71,32 +71,26 @@ class Customer(meta.Base):
# Obtain all primary `Address`es where # Obtain all primary `Address`es where
# at least one delivery was made to `self`. # at least one delivery was made to `self`.
delivery_addresses = ( delivery_addresses = db.session.scalars(
db.session.query(db.Address) sa.select(db.Address).where(
.filter(
db.Address.id.in_( db.Address.id.in_(
row.primary_id sa.select(db.Address.primary_id)
for row in ( .join(db.Order, db.Address.id == db.Order.delivery_address_id)
db.session.query(db.Address.primary_id) .where(db.Order.customer_id == self.id)
.join(db.Order, db.Address.id == db.Order.delivery_address_id) .distinct(),
.filter(db.Order.customer_id == self.id)
.distinct()
.all()
)
), ),
) ),
.all() ).all()
)
for address in delivery_addresses: for address in delivery_addresses:
if order_counts: if order_counts:
n_orders = ( n_orders = db.session.execute(
db.session.query(db.Order) sa.select(sa.func.count())
.select_from(db.Order)
.join(db.Address, db.Order.delivery_address_id == db.Address.id) .join(db.Address, db.Order.delivery_address_id == db.Address.id)
.filter(db.Order.customer_id == self.id) .where(db.Order.customer_id == self.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.count() ).scalar_one()
)
if n_orders >= 25: if n_orders >= 25:
radius = 20 radius = 20
elif n_orders >= 10: elif n_orders >= 10:
@ -123,30 +117,26 @@ class Customer(meta.Base):
) )
if restaurants: if restaurants:
pickup_addresses = ( pickup_addresses = db.session.scalars(
db.session.query(db.Address) sa.select(db.Address).where(
.filter(
db.Address.id.in_( 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) .join(db.Order, db.Address.id == db.Order.pickup_address_id)
.filter(db.Order.customer_id == self.id) .where(db.Order.customer_id == self.id)
.distinct() .distinct(),
.all(),
), ),
) ),
.all() ).all()
)
for address in pickup_addresses: for address in pickup_addresses:
# Show the restaurant's name if there is only one. # Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's. # Otherwise, list all the restaurants' ID's.
# We cannot show the `Order.restaurant.name` due to the aggregation. # We cannot show the `Order.restaurant.name` due to the aggregation.
restaurants_at_address = ( restaurants_at_address = db.session.scalars(
db.session.query(db.Restaurant) sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id) .join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.all() ).all()
)
if len(restaurants_at_address) == 1: if len(restaurants_at_address) == 1:
restaurant = restaurants_at_address[0] restaurant = restaurants_at_address[0]
tooltip = f"{restaurant.name} (#{restaurant.id})" tooltip = f"{restaurant.name} (#{restaurant.id})"
@ -155,13 +145,13 @@ class Customer(meta.Base):
tooltip = f"Restaurants {ids}" tooltip = f"Restaurants {ids}"
if order_counts: if order_counts:
n_orders = ( n_orders = db.session.execute(
db.session.query(db.Order) sa.select(sa.func.count())
.select_from(db.Order)
.join(db.Address, db.Order.pickup_address_id == db.Address.id) .join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Order.customer_id == self.id) .where(db.Order.customer_id == self.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.count() ).scalar_one()
)
if n_orders >= 25: if n_orders >= 25:
radius = 20 radius = 20
elif n_orders >= 10: elif n_orders >= 10:

View file

@ -91,10 +91,14 @@ class Grid(meta.Base):
# `Pixel`s grouped by `.n_x`-`.n_y` coordinates. # `Pixel`s grouped by `.n_x`-`.n_y` coordinates.
pixels = {} pixels = {}
# `.unique()` because the `JOIN` yields an `Address` once per `Order`.
pickup_addresses = ( pickup_addresses = (
db.session.query(db.Address) db.session.scalars(
.join(db.Order, db.Address.id == db.Order.pickup_address_id) sa.select(db.Address)
.filter(db.Address.city == city) .join(db.Order, db.Address.id == db.Order.pickup_address_id)
.where(db.Address.city == city),
)
.unique()
.all() .all()
) )

View file

@ -140,14 +140,15 @@ class Pixel(meta.Base):
@functools.cached_property @functools.cached_property
def restaurants(self) -> list["db.Restaurant"]: # pragma: no cover def restaurants(self) -> list["db.Restaurant"]: # pragma: no cover
"""Obtain all `Restaurant`s in `self`.""" """Obtain all `Restaurant`s in `self`."""
return ( return list(
db.session.query(db.Restaurant) db.session.scalars(
.join( sa.select(db.Restaurant)
db.AddressPixelAssociation, .join(
db.Restaurant.address_id == db.AddressPixelAssociation.address_id, db.AddressPixelAssociation,
) db.Restaurant.address_id == db.AddressPixelAssociation.address_id,
.filter(db.AddressPixelAssociation.pixel_id == self.id) )
.all() .where(db.AddressPixelAssociation.pixel_id == self.id),
).all(),
) )
def clear_map(self) -> t.Self: # pragma: no cover def clear_map(self) -> t.Self: # pragma: no cover
@ -203,38 +204,32 @@ class Pixel(meta.Base):
if restaurants: if restaurants:
# Obtain all primary `Address`es in the city that host `Restaurant`s # Obtain all primary `Address`es in the city that host `Restaurant`s
# and are in the `self` `Pixel`. # and are in the `self` `Pixel`.
addresses = ( addresses = db.session.scalars(
db.session.query(db.Address) sa.select(db.Address).where(
.filter(
db.Address.id.in_( db.Address.id.in_(
( sa.select(db.Address.primary_id)
db.session.query(db.Address.primary_id) .join(
.join( db.Restaurant,
db.Restaurant, db.Address.id == db.Restaurant.address_id,
db.Address.id == db.Restaurant.address_id,
)
.join(
db.AddressPixelAssociation,
db.Address.id == db.AddressPixelAssociation.address_id,
)
.filter(db.AddressPixelAssociation.pixel_id == self.id)
) )
.distinct() .join(
.all(), db.AddressPixelAssociation,
db.Address.id == db.AddressPixelAssociation.address_id,
)
.where(db.AddressPixelAssociation.pixel_id == self.id)
.distinct(),
), ),
) ),
.all() ).all()
)
for address in addresses: for address in addresses:
# Show the restaurant's name if there is only one. # Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's. # Otherwise, list all the restaurants' ID's.
restaurants_at_address = ( restaurants_at_address = db.session.scalars(
db.session.query(db.Restaurant) sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id) .join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.all() ).all()
)
if len(restaurants_at_address) == 1: if len(restaurants_at_address) == 1:
restaurant = restaurants_at_address[0] restaurant = restaurants_at_address[0]
tooltip = f"{restaurant.name} (#{restaurant.id})" tooltip = f"{restaurant.name} (#{restaurant.id})"
@ -244,12 +239,11 @@ class Pixel(meta.Base):
if order_counts: if order_counts:
# Calculate the number of orders for ALL restaurants ... # Calculate the number of orders for ALL restaurants ...
n_orders = ( n_orders = db.session.execute(
db.session.query(db.Order.id) sa.select(sa.func.count(db.Order.id))
.join(db.Address, db.Order.pickup_address_id == db.Address.id) .join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Address.primary_id == address.id) .where(db.Address.primary_id == address.id),
.count() ).scalar_one()
)
# ... and adjust the size of the red dot on the `.map`. # ... and adjust the size of the red dot on the `.map`.
if n_orders >= 1000: if n_orders >= 1000:
radius = 20 radius = 20

View file

@ -112,35 +112,32 @@ class Restaurant(meta.Base):
if customers: if customers:
# Obtain all primary `Address`es in the city that # Obtain all primary `Address`es in the city that
# received at least one delivery from `self`. # received at least one delivery from `self`.
delivery_addresses = ( delivery_addresses = db.session.scalars(
db.session.query(db.Address) sa.select(db.Address).where(
.filter(
db.Address.id.in_( db.Address.id.in_(
row.primary_id sa.select(db.Address.primary_id)
for row in ( .join(
db.session.query(db.Address.primary_id) db.Order,
.join( db.Address.id == db.Order.delivery_address_id,
db.Order,
db.Address.id == db.Order.delivery_address_id,
)
.filter(db.Order.restaurant_id == self.id)
.distinct()
.all()
) )
.where(db.Order.restaurant_id == self.id)
.distinct(),
), ),
) ),
.all() ).all()
)
for address in delivery_addresses: for address in delivery_addresses:
if order_counts: if order_counts:
n_orders = ( n_orders = db.session.execute(
db.session.query(db.Order) sa.select(sa.func.count())
.join(db.Address, db.Order.delivery_address_id == db.Address.id) .select_from(db.Order)
.filter(db.Order.restaurant_id == self.id) .join(
.filter(db.Address.primary_id == address.id) db.Address,
.count() 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: if n_orders >= 25:
radius = 20 radius = 20
elif n_orders >= 10: elif n_orders >= 10:

View file

@ -5,6 +5,7 @@ import datetime as dt
import typing as t import typing as t
import pandas as pd import pandas as pd
import sqlalchemy as sa
from velofy import db from velofy import db
from velofy.forecasts import timify from velofy.forecasts import timify
@ -80,15 +81,15 @@ class ForecastingModelABC(abc.ABC):
Raises: Raises:
RuntimeError: `*Model.predict()` misses the prediction for `predict_at` RuntimeError: `*Model.predict()` misses the prediction for `predict_at`
""" """
if ( if cached_forecast := db.session.scalars(
cached_forecast := db.session.query(db.Forecast) sa.select(db.Forecast).filter_by(
.filter_by(pixel=pixel) pixel=pixel,
.filter_by(start_at=predict_at) start_at=predict_at,
.filter_by(time_step=self._order_history.time_step) time_step=self._order_history.time_step,
.filter_by(train_horizon=train_horizon) train_horizon=train_horizon,
.filter_by(model=self.name) model=self.name,
.first() ),
): ).one_or_none():
return cached_forecast return cached_forecast
# Horizontal and real-time `*Model`s return a `pd.DataFrame` with one # Horizontal and real-time `*Model`s return a `pd.DataFrame` with one

View file

@ -6,6 +6,7 @@ in the CLI layer need access to the database.
import os import os
import random import random
import typing as t
import pytest import pytest
import sqlalchemy as sa import sqlalchemy as sa
@ -91,7 +92,7 @@ def db_connection(request):
@pytest.fixture @pytest.fixture
def db_session(db_connection): def db_session(db_connection, monkeypatch):
"""A SQLAlchemy session that rolls back everything after a test case.""" """A SQLAlchemy session that rolls back everything after a test case."""
# Begin the outermost transaction # Begin the outermost transaction
# that is rolled back at the end of each test case. # 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, # Monkey patch the package's global `session` object,
# which is used heavily in the code base. # which is used heavily in the code base.
db.session = session monkeypatch.setattr(db, "session", session)
try: try:
yield session yield session
@ -115,6 +116,24 @@ def db_session(db_connection):
transaction.rollback() 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) @pytest.fixture(autouse=True)
def _seed_random() -> None: def _seed_random() -> None:
"""Make the fake data reproducible across test runs.""" """Make the fake data reproducible across test runs."""

View file

@ -1,6 +1,7 @@
"""Integration test for the `velofy.console.gridify` module.""" """Integration test for the `velofy.console.gridify` module."""
import pytest import pytest
import sqlalchemy as sa
import velofy import velofy
from velofy import db from velofy import db
@ -50,5 +51,5 @@ def test_two_pixels_with_two_addresses(
assert result.exit_code == 0 assert result.exit_code == 0
assert db_session.query(db.Grid).count() == 1 assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Grid)) == 1
assert db_session.query(db.Pixel).count() == 2 assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Pixel)) == 2

View file

@ -31,12 +31,18 @@ class TestConstraints:
def test_insert_into_into_database(self, db_session, replayed_order): def test_insert_into_into_database(self, db_session, replayed_order):
"""Insert an instance into the (empty) database.""" """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.add(replayed_order)
db_session.commit() 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): def test_delete_a_referenced_simulation(self, db_session, replayed_order):
"""Remove a record that is referenced with a FK.""" """Remove a record that is referenced with a FK."""
@ -202,12 +208,12 @@ class TestConstraints:
dispatch_at=scheduled_delivery_at + dt.timedelta(hours=1), 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.add(replay_pre_order)
db_session.commit() 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): def test_scheduled_order_too_late(self, db_session, make_replay_order):
"""Insert an instance with invalid data.""" """Insert an instance with invalid data."""

View file

@ -29,12 +29,16 @@ class TestConstraints:
def test_insert_into_database(self, db_session, address): def test_insert_into_database(self, db_session, address):
"""Insert an instance into the (empty) database.""" """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.add(address)
db_session.commit() 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): def test_delete_a_referenced_address(self, db_session, address, make_address):
"""Remove a record that is referenced with a FK.""" """Remove a record that is referenced with a FK."""

View file

@ -60,12 +60,12 @@ class TestConstraints:
def test_insert_into_database(self, db_session, path): def test_insert_into_database(self, db_session, path):
"""Insert an instance into the (empty) database.""" """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.add(path)
db_session.commit() 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): def test_delete_a_referenced_first_address(self, db_session, path):
"""Remove a record that is referenced with a FK.""" """Remove a record that is referenced with a FK."""
@ -222,11 +222,11 @@ class TestFromAddresses:
another_address, another_address,
): ):
"""Test instantiation of a new `Path` instance.""" """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) 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( def test_make_the_same_path_instance_twice(
self, self,
@ -235,15 +235,15 @@ class TestFromAddresses:
another_address, another_address,
): ):
"""Test instantiation of a new `Path` instance.""" """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) 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) 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): def test_structure_of_return_value(self, address, another_address):
"""Test instantiation of a new `Path` instance.""" """Test instantiation of a new `Path` instance."""
@ -323,11 +323,11 @@ class TestFromAddresses:
order, order,
): ):
"""Test instantiation of a new `Path` instance.""" """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) 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( def test_make_the_same_path_instance_from_order_twice(
self, self,
@ -335,15 +335,15 @@ class TestFromAddresses:
order, order,
): ):
"""Test instantiation of a new `Path` instance.""" """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) 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) 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): def test_structure_of_return_value_from_order(self, order):
"""Test instantiation of a new `Path` instance.""" """Test instantiation of a new `Path` instance."""

View file

@ -43,12 +43,22 @@ class TestConstraints:
def test_insert_into_database(self, db_session, assoc): def test_insert_into_database(self, db_session, assoc):
"""Insert an instance into the (empty) database.""" """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.add(assoc)
db_session.commit() 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): def test_delete_a_referenced_address(self, db_session, assoc):
"""Remove a record that is referenced with a FK.""" """Remove a record that is referenced with a FK."""

View file

@ -1,6 +1,7 @@
"""Test the ORM's `City` model.""" """Test the ORM's `City` model."""
import pytest import pytest
import sqlalchemy as sa
from velofy import db from velofy import db
from velofy.db import utils from velofy.db import utils
@ -27,12 +28,12 @@ class TestConstraints:
def test_insert_into_database(self, db_session, city): def test_insert_into_database(self, db_session, city):
"""Insert an instance into the (empty) database.""" """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.add(city)
db_session.commit() 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: class TestProperties:

View file

@ -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()

View file

@ -1,6 +1,7 @@
"""Test the ORM's `Courier` model.""" """Test the ORM's `Courier` model."""
import pytest import pytest
import sqlalchemy as sa
from sqlalchemy import exc as sa_exc from sqlalchemy import exc as sa_exc
from velofy import db from velofy import db
@ -27,12 +28,16 @@ class TestConstraints:
def test_insert_into_database(self, db_session, courier): def test_insert_into_database(self, db_session, courier):
"""Insert an instance into the (empty) database.""" """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.add(courier)
db_session.commit() 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): def test_invalid_vehicle(self, db_session, courier):
"""Insert an instance with invalid data.""" """Insert an instance with invalid data."""

View file

@ -1,6 +1,7 @@
"""Test the ORM's `Customer` model.""" """Test the ORM's `Customer` model."""
import pytest import pytest
import sqlalchemy as sa
from velofy import db from velofy import db
@ -26,9 +27,13 @@ class TestConstraints:
def test_insert_into_database(self, db_session, customer): def test_insert_into_database(self, db_session, customer):
"""Insert an instance into the (empty) database.""" """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.add(customer)
db_session.commit() 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
)

Some files were not shown because too many files have changed in this diff Show more