import hashlib import json from pathlib import Path import sys import uuid ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from pipeline_support import compose, sql def database_command(program, database, *arguments, data=None): command = program + ' -U "$(cat /run/secrets/postgres_user)" "$@"' return compose("exec", "-T", "db", "sh", "-c", command, "sh", *arguments, database, data=data) def schema(database): dump = database_command( "pg_dump", database, "--schema-only", "--no-owner", "--no-privileges", "--exclude-table=public.flyway_schema_history", ) return "\n".join( line for line in dump.splitlines() if not line.startswith(("\\restrict ", "\\unrestrict ", "-- Dumped ")) ) def main(): files = sorted((ROOT / "src/main/resources/db/migration").glob("*.sql")) if [path.name for path in files] != ["V1__init.sql"]: raise AssertionError("Expected exactly V1__init.sql") database = "proof_v1_" + uuid.uuid4().hex current = sql("select current_database();") sql('create database "' + database + '";') try: database_command("psql", database, "-v", "ON_ERROR_STOP=1", data=files[0].read_text()) actual, expected = schema(database), schema(current) if actual != expected: raise AssertionError("Fresh V1 schema differs from existing migrated schema") result = { "migration": files[0].name, "migration_sha256": hashlib.sha256(files[0].read_bytes()).hexdigest(), "schema_sha256": hashlib.sha256(actual.encode()).hexdigest(), "equivalent_to_existing_schema": True, "excludes": "Flyway history and pg_dump random restriction tokens", "temporary_database_removed": True, } finally: sql('drop database "' + database + '" with (force);') (ROOT / "evidence/migration-check.json").write_text(json.dumps(result, indent=2)) print( "PASS one V1__init.sql; fresh PostgreSQL schema equals existing V1-V4 schema; temporary DB removed" ) if __name__ == "__main__": main()