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