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`
This commit is contained in:
parent
69b9d53704
commit
731299bb6e
1 changed files with 192 additions and 0 deletions
112
noxfile.py
112
noxfile.py
|
|
@ -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:
|
||||
|
|
|
|||
Loading…
Reference in a new issue