From 731299bb6e22be4e3bf8ae3c117fe4c1f318af22 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 21:46:38 +0100 Subject: [PATCH 01/10] Add `nox` session "verify-db-objects" The new "verify-db-objects" session creates the ORM objects with `.create_all()` in a temporary database and compares them with the `CLEAN_SCHEMA` of a "live" database using `sqlalchemy-diff` --- noxfile.py | 112 +++++++++++++++++++++++++++++ pyproject.toml | 4 ++ scripts/verify_database_objects.py | 60 ++++++++++++++++ uv.lock | 16 +++++ 4 files changed, 192 insertions(+) create mode 100644 scripts/verify_database_objects.py diff --git a/noxfile.py b/noxfile.py index f4b38a4..0e3edfa 100644 --- a/noxfile.py +++ b/noxfile.py @@ -18,6 +18,7 @@ Further sessions run on demand with `uv run nox -s `: - "deps-upgrade-check": Show newer versions and the age of all pinned releases - "init-project": Install the `pre-commit` hooks and configure `git blame` - "clean-cwd": Run approx. `git clean -X` with minor exceptions +- "verify-db-objects": Compare a live database with the ORM models Most sessions accept extra arguments after the "--", e.g., `uv run nox -s test -- tests/test_config.py`. @@ -25,11 +26,16 @@ e.g., `uv run nox -s test -- tests/test_config.py`. import collections import collections.abc as cabc +import contextlib import itertools import os import pathlib +import random +import shutil +import subprocess # noqa: S404 import tempfile import typing as t +import urllib.parse import nox from packaging import version as pkg_version @@ -254,6 +260,7 @@ def lint_code(session: nox.Session) -> None: "pydoclint[flake8]", "pyright[nodejs]", "ruff", + "sqlalchemy-diff", "tryceratops", ) @@ -597,6 +604,111 @@ def _expand(*patterns: str) -> cabc.Generator[pathlib.Path]: yield path.resolve() +@nox.session(name="verify-db-objects", python=MAIN_PYTHON) +def verify_database_objects(session: nox.Session) -> None: + """Verify a "live" database aligns with the ORM models in `velofy.db`. + + Compare all objects in the `CLEAN_SCHEMA` of a "live" database to + all objects in a temporary database created with `.create_all()`. + + The result shows if the "live" database differs from what it + should be, possibly after applying some `alembic` migrations. + + The "live" database is specified either with the environment + variable "DATABASE_URI" or as the only positional argument: + `uv run nox -s verify-db-objects -- DATABASE_URI` + """ + start(session) + + live_db_uri, *further_args = session.posargs or (os.getenv("DATABASE_URI"),) + + if not live_db_uri or further_args: + session.error("Must provide `DATABASE_URI` and nothing else") + + install_pinned(session, ".", "sqlalchemy-diff") + + with _random_database(session, db_uri=live_db_uri) as orm_db_uri: + session.run( + "python", + "scripts/verify_database_objects.py", + env={ + "DATABASE_URI": live_db_uri, + "_ORM_DATABASE_URI": orm_db_uri, + }, + ) + + +@contextlib.contextmanager +def _random_database(session: nox.Session, *, db_uri: str) -> cabc.Generator[str]: + """Create a temporary database on the `postgres` server at `db_uri`. + + The new database's name is the part in the given `db_uri` + with the current `git` commit hash and a random number appended. + The database is ensured to be dropped again after usage. + """ + parsed = urllib.parse.urlparse(db_uri) + + if not (orig_db_name := parsed.path.lstrip("/")): + session.error("`db_uri` has no ") + + # Credentials go via the `env`ironment to not expose them on the CLI + netloc = f"{parsed.hostname}:{parsed.port}" if parsed.port else f"{parsed.hostname}" + admin_uri = f"{parsed.scheme}://{netloc}/{orig_db_name}" + + env = { + key: value + for key, value in ( + ("PGUSER", parsed.username), + ("PGPASSWORD", parsed.password), + ) + if value + } + + db_name = orig_db_name + + if commit := _get_commit(): + db_name += f"_commit_{commit}" + + db_name += f"_randint_{random.randint(100_000_000, 999_999_999)}" # noqa: S311 + + session.run( + "createdb", + f"--maintenance-db={admin_uri}", + db_name, + env=env, + external=True, + ) + + try: + yield parsed._replace(path=f"/{db_name}").geturl() + + finally: + session.run( + "dropdb", + f"--maintenance-db={admin_uri}", + db_name, + env=env, + external=True, + ) + + +def _get_commit() -> str | None: + """Try to obtain the current `git` commit's hash.""" + if not (git := shutil.which("git")): + return None + + try: + output = subprocess.check_output( # noqa: S603 + [git, "rev-parse", "HEAD"], + stderr=subprocess.STDOUT, + ) + + except subprocess.CalledProcessError: + return None + + return output.decode().strip()[:9] + + def do_not_accept_arguments(session: nox.Session, *, raise_error: bool = True) -> None: """Do not accept any `session.posargs`.""" if session.posargs: diff --git a/pyproject.toml b/pyproject.toml index 09349c4..63994f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -145,6 +145,9 @@ docs = [ "sphinx-autodoc-typehints (>=3.17.7,<4.0.0)", ] +verify-db = [ + "sqlalchemy-diff (>=1.2.0,<2.0.0)", +] [tool.autoflake] @@ -519,6 +522,7 @@ module = [ "geopy.*", "googlemaps.*", "rpy2.*", + "sqlalchemydiff.*", "statsmodels.*", "utm.*", ] diff --git a/scripts/verify_database_objects.py b/scripts/verify_database_objects.py new file mode 100644 index 0000000..9fb40c6 --- /dev/null +++ b/scripts/verify_database_objects.py @@ -0,0 +1,60 @@ +"""Compare the objects in a "live" database with the ORM models. + +To be run with `uv run nox -s verify-db-objects`. + +The comparison is limited to the `CLEAN_SCHEMA`: both engines connect +with it as their `search_path`; so, the original data in the +`ORIGINAL_SCHEMA` and the `alembic_version` table are not compared. +""" + +import os +import sys + +import sqlalchemy as sa +from sqlalchemydiff import comparer + +import velofy +from velofy import db + + +def main() -> int: + """Create the ORM objects in a temporary database and compare.""" + try: + live_db_uri = os.environ["DATABASE_URI"] + orm_db_uri = os.environ["_ORM_DATABASE_URI"] + except KeyError: + print("Run this script with `uv run nox -s verify-db-objects`") + return 1 + + schema = velofy.config.CLEAN_SCHEMA + connect_args = {"options": f"-csearch_path={schema}"} + + live_engine = sa.create_engine(live_db_uri, connect_args=connect_args) + orm_engine = sa.create_engine(orm_db_uri, connect_args=connect_args) + + print('Live DB ("live"):', live_engine.url) # `URL`s hide the password + print('Temp DB ("orm"):', orm_engine.url) + + print(f'Creating the objects in schema {schema!r} in the "orm" database') + with orm_engine.begin() as conn: + conn.execute(sa.schema.CreateSchema(schema)) + db.Base.metadata.create_all(bind=orm_engine) + + print('Comparing the "orm" with the "live" database') + result = comparer.Comparer(orm_engine, live_engine).compare( + one_alias="orm", + two_alias="live", + ) + + if result.is_match: + print("Both databases consist of the exact same objects") + return 0 + + print('`diff` from "orm" to "live":') + print(result.errors) + result.dump_errors(".cache/sqlalchemy_diff.json") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/uv.lock b/uv.lock index b2c5c49..a9e4ec7 100644 --- a/uv.lock +++ b/uv.lock @@ -3724,6 +3724,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7a/ee/9926603a1f7e88b41bc0d1e068e889fc84981553fb4e6037426d6b174da3/sqlalchemy-2.1.9-py3-none-any.whl", hash = "sha256:449fed5c2caa3b278cc57499d09db001fb3f28dc7f18affc48142aee4dcc0cdf", size = 2071860, upload-time = "2026-11-16T21:16:28.413Z" }, ] +[[package]] +name = "sqlalchemy-diff" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sqlalchemy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bb/ec/657d1a5e53204daa31f60d78cec3e7dbd7d3c279f5d7c025da96bd03f3dc/sqlalchemy_diff-1.2.0.tar.gz", hash = "sha256:8d3b31c6d56907fb94faae173236440f2c8e367dad6685548cd11856b7a6479e", size = 17058, upload-time = "2026-11-18T16:37:38.945Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5f/00/f5e1699c7db36a3122de3f6776c3a6cafddaae06cbc1e8c9ab837f9d7ef4/sqlalchemy_diff-1.2.0-py3-none-any.whl", hash = "sha256:d456eea49135da86c6b654f046dae4d00c023ce7f05762949aedebed99125da4", size = 17531, upload-time = "2026-11-18T16:37:37.904Z" }, +] + [[package]] name = "stack-data" version = "0.6.3" @@ -4055,6 +4067,9 @@ test = [ { name = "typeguard" }, { name = "xdoctest", extra = ["colors"] }, ] +verify-db = [ + { name = "sqlalchemy-diff" }, +] [package.metadata] requires-dist = [ @@ -4138,6 +4153,7 @@ test = [ { name = "typeguard", specifier = ">=4.6.1,<5.0.0" }, { name = "xdoctest", extras = ["colors"], specifier = ">=1.3.2,<2.0.0" }, ] +verify-db = [{ name = "sqlalchemy-diff", specifier = ">=1.2.0,<2.0.0" }] [[package]] name = "virtualenv" -- 2.47.3 From b36a3d1cd638ae9ff97691a86295c881dfbc190a Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 21:58:14 +0100 Subject: [PATCH 02/10] Allow the same `Grid.side_length` across cities The `unique=True` on `Grid.side_length` made the side length unique across all cities. The intended rule is the `UniqueConstraint("city_id", "side_length")`, which the migrations already implement; so, no migration is needed. --- src/velofy/db/grids.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index 365f7c0..b6a3256 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -32,7 +32,6 @@ class Grid(meta.Base): side_length: orm.Mapped[int] = orm.mapped_column( sa.SmallInteger, nullable=False, - unique=True, ) # Constraints -- 2.47.3 From f532aae5882fc3383f49cf0563125e6b2691265c Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:18:52 +0100 Subject: [PATCH 03/10] Test grids with the same side length in different cities Regression test for the removed `unique=True` on `Grid.side_length`. --- tests/db/test_grids.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index 9561d43..a8bf845 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -61,6 +61,25 @@ class TestConstraints: with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): db_session.commit() + def test_two_grids_with_identical_side_length_in_different_cities( + self, + db_session, + grid, + city_data, + ): + """Insert two `Grid`s with the same `.side_length` in different `.city`s.""" + db_session.add(grid) + db_session.commit() + + # Create a `Grid` with the same `.side_length` in another `.city`. + another_city = db.City(**(city_data | {"id": 2, "name": "Lyon"})) + another_grid = db.Grid(city=another_city, side_length=grid.side_length) + db_session.add(another_grid) + + db_session.commit() # no `IntegrityError` + + assert another_grid.id is not None + class TestProperties: """Test properties in `Grid`.""" -- 2.47.3 From db2e00216d77caba4267914386e3ad106fc105ac Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:11:19 +0100 Subject: [PATCH 04/10] Simplify the docstrings of the migrations The "Revision" and "Revises" lines and the revision hashes in `upgrade()` and `downgrade()` repeated the `revision` and `down_revision` variables; the creation date is in the file name. --- migrations/script.py.mako | 13 +++++-------- ..._20200806_23_f11cd76d2f45_create_the_database.py | 9 +++------ .../rev_20210102_18_888e352d7526_add_pixel_grid.py | 10 +++------- ...210106_19_e40623e10405_add_demand_forecasting.py | 10 +++------- ...cd3f9b9_add_confidence_intervals_to_forecasts.py | 10 +++------- 5 files changed, 17 insertions(+), 35 deletions(-) diff --git a/migrations/script.py.mako b/migrations/script.py.mako index cafc97d..753e7df 100644 --- a/migrations/script.py.mako +++ b/migrations/script.py.mako @@ -1,8 +1,4 @@ -"""${message}. - -Revision: # ${up_revision} at ${create_date} -Revises: # ${down_revision | comma,n} -""" +"""${message}.""" import os @@ -12,20 +8,21 @@ ${imports if imports else ""} from velofy import configuration + revision = ${repr(up_revision)} down_revision = ${repr(down_revision)} branch_labels = ${repr(branch_labels)} depends_on = ${repr(depends_on)} -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): - """Upgrade to revision ${up_revision}.""" + """Upgrade to the next revision.""" ${upgrades if upgrades else "pass"} def downgrade(): - """Downgrade to revision ${down_revision}.""" + """Downgrade to the previous revision.""" ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py index 1e4cf9c..679ee30 100644 --- a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py +++ b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py @@ -1,7 +1,4 @@ -"""Create the database from scratch. - -Revision: #f11cd76d2f45 at 2020-08-06 23:24:32 -""" +"""Create the database from scratch.""" import os @@ -22,7 +19,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ def upgrade(): - """Upgrade to revision f11cd76d2f45.""" + """Upgrade to the next revision.""" op.execute(f"CREATE SCHEMA {config.CLEAN_SCHEMA};") op.create_table( "cities", @@ -806,5 +803,5 @@ def upgrade(): def downgrade(): - """Downgrade to revision None.""" + """Downgrade to the previous revision.""" op.execute(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;") diff --git a/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py b/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py index b0fa779..cba80c2 100644 --- a/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py +++ b/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py @@ -1,8 +1,4 @@ -"""Add pixel grid. - -Revision: #888e352d7526 at 2021-01-02 18:11:02 -Revises: #f11cd76d2f45 -""" +"""Add pixel grid.""" import os @@ -22,7 +18,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ def upgrade(): - """Upgrade to revision 888e352d7526.""" + """Upgrade to the next revision.""" op.create_table( "grids", sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False), @@ -153,7 +149,7 @@ def upgrade(): def downgrade(): - """Downgrade to revision f11cd76d2f45.""" + """Downgrade to the previous revision.""" op.drop_table("addresses_pixels", schema=config.CLEAN_SCHEMA) op.drop_constraint( "uq_addresses_on_id_city_id", diff --git a/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py b/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py index a5d0dfe..2fd5bf7 100644 --- a/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py +++ b/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py @@ -1,8 +1,4 @@ -"""Add demand forecasting. - -Revision: #e40623e10405 at 2021-01-06 19:55:56 -Revises: #888e352d7526 -""" +"""Add demand forecasting.""" import os @@ -23,7 +19,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ def upgrade(): - """Upgrade to revision e40623e10405.""" + """Upgrade to the next revision.""" op.create_table( "forecasts", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), @@ -93,5 +89,5 @@ def upgrade(): def downgrade(): - """Downgrade to revision 888e352d7526.""" + """Downgrade to the previous revision.""" op.drop_table("forecasts", schema=config.CLEAN_SCHEMA) diff --git a/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py b/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py index c134474..2dd3db5 100644 --- a/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py +++ b/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py @@ -1,8 +1,4 @@ -"""Add confidence intervals to forecasts. - -Revision: #26711cd3f9b9 at 2021-01-20 16:08:21 -Revises: #e40623e10405 -""" +"""Add confidence intervals to forecasts.""" import os @@ -23,7 +19,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ def upgrade(): - """Upgrade to revision 26711cd3f9b9.""" + """Upgrade to the next revision.""" op.alter_column( "forecasts", "method", @@ -109,7 +105,7 @@ def upgrade(): def downgrade(): - """Downgrade to revision e40623e10405.""" + """Downgrade to the previous revision.""" op.alter_column( "forecasts", "model", -- 2.47.3 From 2a627072d87c2707379fc59c43d5c262d5989f69 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:02:29 +0100 Subject: [PATCH 05/10] Make `grids.side_length` not nullable The ORM always defined `Grid.side_length` with `nullable=False`, but the migration that created the "grids" table did not; the live database contains no `NULL`s. --- ...132_make_grids_side_length_not_nullable.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 migrations/versions/rev_20261201_21_6cb552f31132_make_grids_side_length_not_nullable.py diff --git a/migrations/versions/rev_20261201_21_6cb552f31132_make_grids_side_length_not_nullable.py b/migrations/versions/rev_20261201_21_6cb552f31132_make_grids_side_length_not_nullable.py new file mode 100644 index 0000000..e5fb223 --- /dev/null +++ b/migrations/versions/rev_20261201_21_6cb552f31132_make_grids_side_length_not_nullable.py @@ -0,0 +1,39 @@ +"""Make `grids.side_length` not nullable.""" + +import os + +import sqlalchemy as sa +from alembic import op + +from velofy import configuration + + +revision = "6cb552f31132" +down_revision = "81aa304d7a6e" +branch_labels = None +depends_on = None + + +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") + + +def upgrade(): + """Upgrade to the next revision.""" + op.alter_column( + "grids", + "side_length", + existing_type=sa.SmallInteger(), + nullable=False, + schema=config.CLEAN_SCHEMA, + ) + + +def downgrade(): + """Downgrade to the previous revision.""" + op.alter_column( + "grids", + "side_length", + existing_type=sa.SmallInteger(), + nullable=True, + schema=config.CLEAN_SCHEMA, + ) -- 2.47.3 From 1f9d0effae84bc3582556db879797c114041767b Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:27:07 +0100 Subject: [PATCH 06/10] Cache `City.map` with `functools.cached_property` This replaces the manual caching in the uninitialized `._map` attribute with a `hasattr()` check. `.clear_map()` now only discards the cached map. --- src/velofy/db/cities.py | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 570baa6..879742c 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -79,7 +79,6 @@ class City(meta.Base): ) # We do not implement a `.__init__()` method and use SQLAlchemy's default. - # The uninitialized attribute `._map` is computed on the fly. note:d334120ei def __repr__(self) -> str: """Non-literal text representation.""" @@ -129,31 +128,26 @@ class City(meta.Base): return self.northeast.northing - self.southwest.northing def clear_map(self) -> t.Self: # pragma: no cover - """Create a new `folium.Map` object aligned with the city's viewport. - - The map is available via the `.map` property. Note that it is mutable - and changed from various locations in the code base. + """Discard the `.map` such that the next access creates a new one. Returns: self: enabling method chaining - """ # note:d334120e - self._map = folium.Map( - location=[self.center_latitude, self.center_longitude], - zoom_start=self.initial_zoom, - ) + """ + vars(self).pop("map", None) return self - @property # pragma: no cover + @functools.cached_property # pragma: no cover def map(self) -> folium.Map: """A `folium.Map` object aligned with the city's viewport. - See docstring for `.clear_map()` for further info. + The map is mutable and changed from various locations in the code base. + Use `.clear_map()` to start over with an empty map. """ - if not hasattr(self, "_map"): # note:d334120e - self.clear_map() - - return self._map + return folium.Map( + location=[self.center_latitude, self.center_longitude], + zoom_start=self.initial_zoom, + ) def draw_restaurants( self, -- 2.47.3 From 7d53abc0571cbe9947a519093d25cf611f217518 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:34:16 +0100 Subject: [PATCH 07/10] Avoid lazy loads in `.__repr__()` `ReplaySimulation`, `ReplayedOrder`, and `Forecast` accessed relationships in their `.__repr__()`, which emits queries or fails for detached instances. They now use the foreign key columns. --- src/velofy/db/forecasts.py | 5 +++-- src/velofy/db/replay/orders.py | 2 +- src/velofy/db/replay/simulations.py | 2 +- tests/db/replay/test_orders.py | 2 +- tests/db/replay/test_simulations.py | 2 +- tests/db/test_forecasts.py | 2 +- 6 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index a7246ef..6981aae 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -184,8 +184,9 @@ class Forecast(meta.Base): def __repr__(self) -> str: """Non-literal text representation.""" cls = self.__class__.__name__ - pixel = f"({self.pixel.n_x}|{self.pixel.n_y})" - return f"<{cls}: {self.prediction} for pixel {pixel} at {self.start_at}>" + return ( + f"<{cls}: {self.prediction} for pixel #{self.pixel_id} at {self.start_at}>" + ) @classmethod def from_dataframe( diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index b59d706..708f3e9 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -411,7 +411,7 @@ class ReplayedOrder(meta.Base): def __repr__(self) -> str: """Non-literal text representation.""" - return f"<{self.__class__.__name__}(#{self.actual.id})>" + return f"<{self.__class__.__name__}(#{self.actual_order_id})>" # Convenience properties diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index 883e8a6..50b93c3 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -63,4 +63,4 @@ class ReplaySimulation(meta.Base): def __repr__(self) -> str: """Non-literal text representation.""" cls = self.__class__.__name__ - return f"<{cls}({self.strategy} #{self.run} in {self.city.name})>" + return f"<{cls}({self.strategy} #{self.run} in city #{self.city_id})>" diff --git a/tests/db/replay/test_orders.py b/tests/db/replay/test_orders.py index 8d347f2..967ae0b 100644 --- a/tests/db/replay/test_orders.py +++ b/tests/db/replay/test_orders.py @@ -21,7 +21,7 @@ class TestSpecialMethods: """`ReplayedOrder` has a non-literal text representation.""" result = repr(replayed_order) - assert result == f"" + assert result == f"" @pytest.mark.db diff --git a/tests/db/replay/test_simulations.py b/tests/db/replay/test_simulations.py index ee97549..f03296f 100644 --- a/tests/db/replay/test_simulations.py +++ b/tests/db/replay/test_simulations.py @@ -13,5 +13,5 @@ class TestSpecialMethods: result = repr(simulation) assert result.startswith("" # noqa:E501 + == f"" # noqa:E501 ) -- 2.47.3 From 69d3be4a532563597e1b8059d7bda130a51e4c7b Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:49:18 +0100 Subject: [PATCH 08/10] Rename constraints to follow the naming convention Earlier migrations named some constraints without `op.f()`, a column rename did not rename the unique constraint containing the column, and the "ordered_timestamps_N" checks in "orders" were shifted by one compared to the ORM. See the docstring of the migration for details. --- ...ename_constraints_to_follow_the_naming_.py | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py diff --git a/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py b/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py new file mode 100644 index 0000000..9d7809d --- /dev/null +++ b/migrations/versions/rev_20261201_22_87412e235878_rename_constraints_to_follow_the_naming_.py @@ -0,0 +1,161 @@ +"""Rename constraints to follow the naming convention. + +The live database diverged from the ORM models in `velofy.db`: + +- Earlier migrations created some constraints with hand-written names + without `op.f()`; so, the naming convention was not applied to them. +- Revision 8bfb928a31f8 renamed the column "training_horizon" into + "train_horizon" but not the unique constraint that contains it. +- The "ordered_timestamps_N" checks in "orders" are numbered by their + position in a list in the ORM. A check that was later inserted into + that list shifted the numbers, while the corresponding migration + added the check under a separate name. +""" + +import os + +from alembic import op + +from velofy import configuration + + +revision = "87412e235878" +down_revision = "6cb552f31132" +branch_labels = None +depends_on = None + + +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") + + +# The order matters: the "ordered_timestamps_N" constraints are shifted +# by one from the top down such that every new name is free. +RENAMES = ( + ( + "forecasts", + "uq_forecasts_on_pixel_id_start_at_time_step_training_ho_ec47", + "uq_forecasts_on_pixel_id_start_at_time_step_train_horizon_model", + ), + ( + "forecasts", + "ci95_must_be_wider_than_ci80", + "ck_forecasts_on_ci95_must_be_wider_than_ci80", + ), + ( + "forecasts", + "ci_upper_bound_greater_than_lower_bound", + "ck_forecasts_on_ci_upper_bound_greater_than_lower_bound", + ), + ( + "forecasts", + "prediction_must_be_within_ci", + "ck_forecasts_on_prediction_must_be_within_ci", + ), + ( + "orders", + "courier_waited_at_delivery_only_if_delivery", + "ck_orders_on_courier_waited_at_delivery_only_if_delivery", + ), + ( + "orders", + "delivery_not_confirmed_only_if_delivery", + "ck_orders_on_delivery_not_confirmed_only_if_delivery", + ), + ( + "orders", + "pickup_not_confirmed_only_if_pickup", + "ck_orders_on_pickup_not_confirmed_only_if_pickup", + ), + ( + "orders", + "check_orders_on_scheduled_orders_must_be_at_quarters_of_an_hour", + "ck_orders_on_scheduled_orders_must_be_at_quarters_of_an_hour", + ), + *( + ( + "orders", + f"ck_orders_on_ordered_timestamps_{n}", + f"ck_orders_on_ordered_timestamps_{n + 1}", + ) + for n in range(20, 8, -1) + ), + ( + "orders", + "check_orders_on_ordered_timestamps_placed_at_before_pickup_at", + "ck_orders_on_ordered_timestamps_9", + ), + ("replay_simulations", "run_is_a_count", "ck_replay_simulations_on_run_is_a_count"), + ( + "replayed_orders", + "ad_hoc_orders_within_business_hours", + "ck_replayed_orders_on_ad_hoc_orders_within_business_hours", + ), + ( + "replayed_orders", + "cancellations_may_only_occur_before_pickup", + "ck_replayed_orders_on_cancellations_may_only_occur_befo_e482", + ), + ( + "replayed_orders", + "either_ad_hoc_or_scheduled_order", + "ck_replayed_orders_on_either_ad_hoc_or_scheduled_order", + ), + ( + "replayed_orders", + "estimated_prep_duration_between_0_and_3600", + "ck_replayed_orders_on_estimated_prep_duration_between_0_d15f", + ), + ( + "replayed_orders", + "estimated_prep_duration_must_be_whole_minutes", + "ck_replayed_orders_on_estimated_prep_duration_must_be_w_7021", + ), + ( + "replayed_orders", + "orders_dispatched_in_business_hours", + "ck_replayed_orders_on_orders_dispatched_in_business_hours", + ), + ( + "replayed_orders", + "orders_must_be_either_cancelled_or_fully_simulated", + "ck_replayed_orders_on_orders_must_be_either_cancelled_o_360b", + ), + ( + "replayed_orders", + "scheduled_orders_must_be_at_quarters_of_an_hour", + "ck_replayed_orders_on_scheduled_orders_must_be_at_quart_c770", + ), + ( + "replayed_orders", + "scheduled_orders_not_within_30_minutes", + "ck_replayed_orders_on_scheduled_orders_not_within_30_minutes", + ), + ( + "replayed_orders", + "scheduled_orders_within_business_hours", + "ck_replayed_orders_on_scheduled_orders_within_business_hours", + ), + ( + "replayed_orders", + "utilization_between_0_and_100", + "ck_replayed_orders_on_utilization_between_0_and_100", + ), +) + + +def upgrade(): + """Upgrade to the next revision.""" + for table, old_name, new_name in RENAMES: + op.execute( + f"ALTER TABLE {config.CLEAN_SCHEMA}.{table}" + f" RENAME CONSTRAINT {old_name} TO {new_name};", + ) + + +def downgrade(): + """Downgrade to the previous revision.""" + for table, old_name, new_name in reversed(RENAMES): + op.execute( + f"ALTER TABLE {config.CLEAN_SCHEMA}.{table}" + f" RENAME CONSTRAINT {new_name} TO {old_name};", + ) -- 2.47.3 From 25ed8c744b30f13332547bdf380c82adf9bdcab1 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:55:47 +0100 Subject: [PATCH 09/10] Recreate checks stored by an old PostgreSQL version Before version 14, PostgreSQL stored `EXTRACT(...)` as `date_part(...)`, and the rendering of `IN (...)` changed as well. The checks created in 2021 express the same rules as the ORM models but render differently. See the docstring of the migration for details. --- ...2dda4_recreate_checks_stored_by_an_old_.py | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 migrations/versions/rev_20261201_22_09c70662dda4_recreate_checks_stored_by_an_old_.py diff --git a/migrations/versions/rev_20261201_22_09c70662dda4_recreate_checks_stored_by_an_old_.py b/migrations/versions/rev_20261201_22_09c70662dda4_recreate_checks_stored_by_an_old_.py new file mode 100644 index 0000000..ead79a9 --- /dev/null +++ b/migrations/versions/rev_20261201_22_09c70662dda4_recreate_checks_stored_by_an_old_.py @@ -0,0 +1,139 @@ +"""Recreate checks stored by an old PostgreSQL version. + +PostgreSQL stores a check constraint as an expression tree and prints it +in the style of the running version. Before version 14, `EXTRACT(...)` +was stored as `date_part(...)` returning a `double precision`; newer +versions keep `EXTRACT(...)` returning a `numeric`. The rendering of the +`IN (...)` check in "couriers" changed as well. + +The checks below were created in 2021 and still carry the old form. +They express the same rules as the ORM models, but a comparison with a +new database created from the ORM cannot tell. So, they are recreated. +""" + +import os + +from alembic import op + +from velofy import configuration + + +revision = "09c70662dda4" +down_revision = "87412e235878" +branch_labels = None +depends_on = None + + +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") + + +# (table, constraint, new expression, old expression) +CHECKS = ( + ( + "couriers", + "ck_couriers_on_available_vehicle_types", + "vehicle IN ('bicycle', 'motorcycle')", + ( + "vehicle::text = ANY (ARRAY['bicycle'::character varying::text," + " 'motorcycle'::character varying::text])" + ), + ), + ( + "forecasts", + "ck_forecasts_on_start_at_allows_no_microseconds", + "(EXTRACT(microseconds FROM start_at)::integer % 1000000) = 0", + "(date_part('microseconds'::text, start_at)::integer % 1000000) = 0", + ), + ( + "forecasts", + "ck_forecasts_on_start_at_allows_no_seconds", + "EXTRACT(seconds FROM start_at) = 0::numeric", + "date_part('seconds'::text, start_at) = 0::double precision", + ), + ( + "forecasts", + "ck_forecasts_on_start_at_minutes_must_be_quarters_of_the_hour", + "(EXTRACT(minutes FROM start_at)::integer % 15) = 0", + "(date_part('minutes'::text, start_at)::integer % 15) = 0", + ), + ( + "forecasts", + "ck_forecasts_on_start_at_must_be_within_operating_hours", + ( + "NOT (EXTRACT(hour FROM start_at) < 11::numeric" + " OR EXTRACT(hour FROM start_at) > 22::numeric)" + ), + ( + "NOT (date_part('hour'::text, start_at) < 11::double precision" + " OR date_part('hour'::text, start_at) > 22::double precision)" + ), + ), + ( + "orders", + "ck_orders_on_ad_hoc_orders_within_business_hours", + ( + "NOT (ad_hoc IS TRUE AND (EXTRACT(hour FROM placed_at) < 11::numeric" + " OR EXTRACT(hour FROM placed_at) > 22::numeric))" + ), + """ + NOT (ad_hoc IS TRUE AND ( + date_part('hour'::text, placed_at) < 11::double precision + OR date_part('hour'::text, placed_at) > 22::double precision + )) + """, + ), + ( + "orders", + "ck_orders_on_scheduled_orders_not_within_30_minutes", + "NOT EXTRACT(epoch FROM scheduled_delivery_at - placed_at) < 1800::numeric", + ( + "NOT date_part('epoch'::text, scheduled_delivery_at - placed_at)" + " < 1800::double precision" + ), + ), + ( + "orders", + "ck_orders_on_scheduled_orders_within_business_hours", + """ + NOT (ad_hoc IS FALSE AND ( + EXTRACT(hour FROM scheduled_delivery_at) <= 11::numeric + AND NOT ( + EXTRACT(hour FROM scheduled_delivery_at) = 11::numeric + AND EXTRACT(minute FROM scheduled_delivery_at) = 45::numeric + ) + OR EXTRACT(hour FROM scheduled_delivery_at) > 22::numeric + )) + """, + """ + NOT (ad_hoc IS FALSE AND ( + date_part('hour'::text, scheduled_delivery_at) <= 11::double precision + AND NOT ( + date_part('hour'::text, scheduled_delivery_at) = 11::double precision + AND date_part('minute'::text, scheduled_delivery_at) = 45::double precision + ) + OR date_part('hour'::text, scheduled_delivery_at) > 22::double precision + )) + """, + ), +) + + +def _recreate(table: str, name: str, sqltext: str) -> None: + """Replace the check `name` on `table` with one for `sqltext`.""" + op.execute( + f"ALTER TABLE {config.CLEAN_SCHEMA}.{table}" + f" DROP CONSTRAINT {name}," + f" ADD CONSTRAINT {name} CHECK ({sqltext});", + ) + + +def upgrade(): + """Upgrade to the next revision.""" + for table, name, new_sqltext, _old_sqltext in CHECKS: + _recreate(table, name, new_sqltext) + + +def downgrade(): + """Downgrade to the previous revision.""" + for table, name, _new_sqltext, old_sqltext in CHECKS: + _recreate(table, name, old_sqltext) -- 2.47.3 From 248c1ae60032ea65e22a65c40b82d5a6c81d18c3 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Tue, 1 Dec 2026 22:57:47 +0100 Subject: [PATCH 10/10] Ignore the foreign keys into the original data The migrations create foreign keys from the `CLEAN_SCHEMA` into the `ORIGINAL_SCHEMA` to ensure the cleaned data still refer to the original data. The ORM models do not know the original tables. Also, print the `diff` as indented JSON. --- scripts/verify_database_objects.py | 33 +++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/scripts/verify_database_objects.py b/scripts/verify_database_objects.py index 9fb40c6..87b3a2d 100644 --- a/scripts/verify_database_objects.py +++ b/scripts/verify_database_objects.py @@ -7,8 +7,11 @@ with it as their `search_path`; so, the original data in the `ORIGINAL_SCHEMA` and the `alembic_version` table are not compared. """ +import json import os +import pathlib import sys +import typing as t import sqlalchemy as sa from sqlalchemydiff import comparer @@ -17,6 +20,28 @@ import velofy from velofy import db +def _without_sanity_checks(errors: dict[str, t.Any]) -> dict[str, t.Any]: + """Drop the foreign keys from the `CLEAN_SCHEMA` into the `ORIGINAL_SCHEMA`. + + The migrations create them to ensure the cleaned data still refer to + the original data. The ORM models do not know the original tables. + """ + foreign_keys = {} + for table, entry in errors.get("foreign_keys", {}).items(): + live_only = [ + fk + for fk in entry.get("live_only", []) + if fk["referred_schema"] != velofy.config.ORIGINAL_SCHEMA + ] + rest = {key: value for key, value in entry.items() if key != "live_only"} + if live_only: + rest["live_only"] = live_only + if rest: + foreign_keys[table] = rest + + return {**errors, "foreign_keys": foreign_keys} + + def main() -> int: """Create the ORM objects in a temporary database and compare.""" try: @@ -46,13 +71,15 @@ def main() -> int: two_alias="live", ) - if result.is_match: + errors = _without_sanity_checks(result.errors) + + if not any(errors.values()): print("Both databases consist of the exact same objects") return 0 print('`diff` from "orm" to "live":') - print(result.errors) - result.dump_errors(".cache/sqlalchemy_diff.json") + print(json.dumps(errors, indent=2)) + pathlib.Path(".cache/sqlalchemy_diff.json").write_text(json.dumps(errors, indent=2)) return 1 -- 2.47.3