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
60
scripts/verify_database_objects.py
Normal file
60
scripts/verify_database_objects.py
Normal 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())
|
||||
Loading…
Reference in a new issue