Review the ORM models and align the live database with them #16

Merged
alexander merged 10 commits from orm-review into develop 2026-12-01 23:06:04 +01:00
4 changed files with 192 additions and 0 deletions
Showing only changes of commit 731299bb6e - Show all commits

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`
Alexander Hess 2026-12-01 21:46:38 +01:00
Signed by: alexander
GPG key ID: B46EDB4DFC26805D

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
- "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 <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:
"""Do not accept any `session.posargs`."""
if session.posargs:

View file

@ -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.*",
]

View file

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

16
uv.lock generated
View file

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