Query with select() in velofy.console

`Session.query()` is the legacy API in SQLAlchemy 2.x.
This commit is contained in:
Alexander Hess 2026-12-01 23:20:44 +01:00
commit 1f5a39f83a
Signed by: alexander
GPG key ID: B46EDB4DFC26805D
2 changed files with 15 additions and 13 deletions

View file

@ -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.

View file

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