import asyncio import hashlib from importlib import resources import asyncpg from messenger.shared.config import PlatformSettings from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger LOCK_KEY = 20_260_002 JOURNAL = """ CREATE TABLE IF NOT EXISTS schema_migrations ( version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now() ) """ class MigrationChangedError(Exception): pass def migrations() -> list[tuple[str, str]]: folder = resources.files("messenger") / "migrations" found = (item for item in folder.iterdir() if item.name.endswith(".sql")) return sorted((item.name.removesuffix(".sql"), item.read_text()) for item in found) async def migrate(dsn: str) -> list[str]: connection = await asyncpg.connect(dsn, timeout=10) try: await connection.execute("SELECT pg_advisory_lock($1)", LOCK_KEY) await connection.execute(JOURNAL) applied = dict(await connection.fetch("SELECT version, checksum FROM schema_migrations")) done: list[str] = [] for version, sql in migrations(): checksum = hashlib.sha256(sql.encode()).hexdigest() if version in applied: if applied[version] != checksum: raise MigrationChangedError(version) continue async with connection.transaction(): await connection.execute(sql) await connection.execute( "INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)", version, checksum, ) done.append(version) return done finally: await connection.close() def main() -> None: settings = PlatformSettings() logger = StructlogLogger(level=settings.log_level, allowed_fields=PLATFORM_FIELDS | {"version"}) try: done = asyncio.run(migrate(settings.database_url.get_secret_value())) except MigrationChangedError as error: logger.error("migration.changed", version=str(error)) raise SystemExit(1) from None for version in done: logger.info("migration.applied", version=version) logger.info("migration.completed", reason="up to date" if not done else "applied") if __name__ == "__main__": main()