velofy/scripts/verify_database_objects.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

87 lines
2.7 KiB
Python
Raw Permalink Normal View History

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