Merge branch 'orm-review' into develop
All checks were successful
CI / Checks (Python 3.13) (push) Successful in 2m46s

Reviewed-on: #16
This commit is contained in:
Alexander Hess 2026-12-01 23:06:03 +01:00 • committed by webartifex Forge
commit 455af6dfdb
Signed by: webartifex Forge
GPG key ID: FC460CAFCF91C88A
21 changed files with 612 additions and 59 deletions

View file

@ -1,8 +1,4 @@
"""${message}. """${message}."""
Revision: # ${up_revision} at ${create_date}
Revises: # ${down_revision | comma,n}
"""
import os import os
@ -12,20 +8,21 @@ ${imports if imports else ""}
from velofy import configuration from velofy import configuration
revision = ${repr(up_revision)} revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)} down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)} branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)} 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(): def upgrade():
"""Upgrade to revision ${up_revision}.""" """Upgrade to the next revision."""
${upgrades if upgrades else "pass"} ${upgrades if upgrades else "pass"}
def downgrade(): def downgrade():
"""Downgrade to revision ${down_revision}.""" """Downgrade to the previous revision."""
${downgrades if downgrades else "pass"} ${downgrades if downgrades else "pass"}

View file

@ -1,7 +1,4 @@
"""Create the database from scratch. """Create the database from scratch."""
Revision: #f11cd76d2f45 at 2020-08-06 23:24:32
"""
import os import os
@ -22,7 +19,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ
def upgrade(): def upgrade():
"""Upgrade to revision f11cd76d2f45.""" """Upgrade to the next revision."""
op.execute(f"CREATE SCHEMA {config.CLEAN_SCHEMA};") op.execute(f"CREATE SCHEMA {config.CLEAN_SCHEMA};")
op.create_table( op.create_table(
"cities", "cities",
@ -806,5 +803,5 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision None.""" """Downgrade to the previous revision."""
op.execute(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;") op.execute(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;")

View file

@ -1,8 +1,4 @@
"""Add pixel grid. """Add pixel grid."""
Revision: #888e352d7526 at 2021-01-02 18:11:02
Revises: #f11cd76d2f45
"""
import os import os
@ -22,7 +18,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ
def upgrade(): def upgrade():
"""Upgrade to revision 888e352d7526.""" """Upgrade to the next revision."""
op.create_table( op.create_table(
"grids", "grids",
sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False), sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False),
@ -153,7 +149,7 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision f11cd76d2f45.""" """Downgrade to the previous revision."""
op.drop_table("addresses_pixels", schema=config.CLEAN_SCHEMA) op.drop_table("addresses_pixels", schema=config.CLEAN_SCHEMA)
op.drop_constraint( op.drop_constraint(
"uq_addresses_on_id_city_id", "uq_addresses_on_id_city_id",

View file

@ -1,8 +1,4 @@
"""Add demand forecasting. """Add demand forecasting."""
Revision: #e40623e10405 at 2021-01-06 19:55:56
Revises: #888e352d7526
"""
import os import os
@ -23,7 +19,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ
def upgrade(): def upgrade():
"""Upgrade to revision e40623e10405.""" """Upgrade to the next revision."""
op.create_table( op.create_table(
"forecasts", "forecasts",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
@ -93,5 +89,5 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision 888e352d7526.""" """Downgrade to the previous revision."""
op.drop_table("forecasts", schema=config.CLEAN_SCHEMA) op.drop_table("forecasts", schema=config.CLEAN_SCHEMA)

View file

@ -1,8 +1,4 @@
"""Add confidence intervals to forecasts. """Add confidence intervals to forecasts."""
Revision: #26711cd3f9b9 at 2021-01-20 16:08:21
Revises: #e40623e10405
"""
import os import os
@ -23,7 +19,7 @@ config = configuration.make_config("testing" if os.getenv("TESTING") else "produ
def upgrade(): def upgrade():
"""Upgrade to revision 26711cd3f9b9.""" """Upgrade to the next revision."""
op.alter_column( op.alter_column(
"forecasts", "forecasts",
"method", "method",
@ -109,7 +105,7 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision e40623e10405.""" """Downgrade to the previous revision."""
op.alter_column( op.alter_column(
"forecasts", "forecasts",
"model", "model",

View file

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

View file

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

View file

@ -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};",
)

View file

@ -18,6 +18,7 @@ Further sessions run on demand with `uv run nox -s <session>`:
- "deps-upgrade-check": Show newer versions and the age of all pinned releases - "deps-upgrade-check": Show newer versions and the age of all pinned releases
- "init-project": Install the `pre-commit` hooks and configure `git blame` - "init-project": Install the `pre-commit` hooks and configure `git blame`
- "clean-cwd": Run approx. `git clean -X` with minor exceptions - "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 "--", Most sessions accept extra arguments after the "--",
e.g., `uv run nox -s test -- tests/test_config.py`. 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
import collections.abc as cabc import collections.abc as cabc
import contextlib
import itertools import itertools
import os import os
import pathlib import pathlib
import random
import shutil
import subprocess # noqa: S404
import tempfile import tempfile
import typing as t import typing as t
import urllib.parse
import nox import nox
from packaging import version as pkg_version from packaging import version as pkg_version
@ -254,6 +260,7 @@ def lint_code(session: nox.Session) -> None:
"pydoclint[flake8]", "pydoclint[flake8]",
"pyright[nodejs]", "pyright[nodejs]",
"ruff", "ruff",
"sqlalchemy-diff",
"tryceratops", "tryceratops",
) )
@ -597,6 +604,111 @@ def _expand(*patterns: str) -> cabc.Generator[pathlib.Path]:
yield path.resolve() 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 <db_name> 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 <db_name>")
# 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: def do_not_accept_arguments(session: nox.Session, *, raise_error: bool = True) -> None:
"""Do not accept any `session.posargs`.""" """Do not accept any `session.posargs`."""
if session.posargs: if session.posargs:

View file

@ -145,6 +145,9 @@ docs = [
"sphinx-autodoc-typehints (>=3.17.7,<4.0.0)", "sphinx-autodoc-typehints (>=3.17.7,<4.0.0)",
] ]
verify-db = [
"sqlalchemy-diff (>=1.2.0,<2.0.0)",
]
[tool.autoflake] [tool.autoflake]
@ -519,6 +522,7 @@ module = [
"geopy.*", "geopy.*",
"googlemaps.*", "googlemaps.*",
"rpy2.*", "rpy2.*",
"sqlalchemydiff.*",
"statsmodels.*", "statsmodels.*",
"utm.*", "utm.*",
] ]

View file

@ -0,0 +1,87 @@
"""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 json
import os
import pathlib
import sys
import typing as t
import sqlalchemy as sa
from sqlalchemydiff import comparer
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:
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",
)
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(json.dumps(errors, indent=2))
pathlib.Path(".cache/sqlalchemy_diff.json").write_text(json.dumps(errors, indent=2))
return 1
if __name__ == "__main__":
sys.exit(main())

View file

@ -79,7 +79,6 @@ class City(meta.Base):
) )
# We do not implement a `.__init__()` method and use SQLAlchemy's default. # 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: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
@ -129,31 +128,26 @@ class City(meta.Base):
return self.northeast.northing - self.southwest.northing return self.northeast.northing - self.southwest.northing
def clear_map(self) -> t.Self: # pragma: no cover def clear_map(self) -> t.Self: # pragma: no cover
"""Create a new `folium.Map` object aligned with the city's viewport. """Discard the `.map` such that the next access creates a new one.
The map is available via the `.map` property. Note that it is mutable
and changed from various locations in the code base.
Returns: Returns:
self: enabling method chaining self: enabling method chaining
""" # note:d334120e """
self._map = folium.Map( vars(self).pop("map", None)
location=[self.center_latitude, self.center_longitude],
zoom_start=self.initial_zoom,
)
return self return self
@property # pragma: no cover @functools.cached_property # pragma: no cover
def map(self) -> folium.Map: def map(self) -> folium.Map:
"""A `folium.Map` object aligned with the city's viewport. """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 return folium.Map(
self.clear_map() location=[self.center_latitude, self.center_longitude],
zoom_start=self.initial_zoom,
return self._map )
def draw_restaurants( def draw_restaurants(
self, self,

View file

@ -184,8 +184,9 @@ class Forecast(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
cls = self.__class__.__name__ cls = self.__class__.__name__
pixel = f"({self.pixel.n_x}|{self.pixel.n_y})" return (
return f"<{cls}: {self.prediction} for pixel {pixel} at {self.start_at}>" f"<{cls}: {self.prediction} for pixel #{self.pixel_id} at {self.start_at}>"
)
@classmethod @classmethod
def from_dataframe( def from_dataframe(

View file

@ -32,7 +32,6 @@ class Grid(meta.Base):
side_length: orm.Mapped[int] = orm.mapped_column( side_length: orm.Mapped[int] = orm.mapped_column(
sa.SmallInteger, sa.SmallInteger,
nullable=False, nullable=False,
unique=True,
) )
# Constraints # Constraints

View file

@ -411,7 +411,7 @@ class ReplayedOrder(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
return f"<{self.__class__.__name__}(#{self.actual.id})>" return f"<{self.__class__.__name__}(#{self.actual_order_id})>"
# Convenience properties # Convenience properties

View file

@ -63,4 +63,4 @@ class ReplaySimulation(meta.Base):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
cls = self.__class__.__name__ 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})>"

View file

@ -21,7 +21,7 @@ class TestSpecialMethods:
"""`ReplayedOrder` has a non-literal text representation.""" """`ReplayedOrder` has a non-literal text representation."""
result = repr(replayed_order) result = repr(replayed_order)
assert result == f"<ReplayedOrder(#{replayed_order.actual.id})>" assert result == f"<ReplayedOrder(#{replayed_order.actual_order_id})>"
@pytest.mark.db @pytest.mark.db

View file

@ -13,5 +13,5 @@ class TestSpecialMethods:
result = repr(simulation) result = repr(simulation)
assert result.startswith("<ReplaySimulation(") assert result.startswith("<ReplaySimulation(")
assert simulation.city.name in result assert f"city #{simulation.city_id}" in result
assert simulation.strategy in result assert simulation.strategy in result

View file

@ -52,7 +52,7 @@ class TestSpecialMethods:
assert ( assert (
result result
== f"<Forecast: {forecast.prediction} for pixel ({forecast.pixel.n_x}|{forecast.pixel.n_y}) at {forecast.start_at}>" # noqa:E501 == f"<Forecast: {forecast.prediction} for pixel #{forecast.pixel_id} at {forecast.start_at}>" # noqa:E501
) )

View file

@ -61,6 +61,25 @@ class TestConstraints:
with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"):
db_session.commit() 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: class TestProperties:
"""Test properties in `Grid`.""" """Test properties in `Grid`."""

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