import asyncio from alembic import context from alembic.script import ScriptDirectory from legacy import adopt_legacy from sqlalchemy import Connection, func, make_url, pool, select from sqlalchemy.ext.asyncio import create_async_engine from messenger.attachments.infrastructure.postgres import ( AttachmentRow, JobEventRow, JobRow, OutboxRow, VariantRow, ) from messenger.identity.infrastructure.postgres import SessionRow, UserRow from messenger.messaging.infrastructure.postgres import ( ChatMemberRow, ChatRow, IdempotencyKeyRow, MessageAttachmentRow, MessageRow, ) from messenger.shared.config import PlatformSettings LOCK_KEY = 20_260_002 MODELS = ( UserRow, SessionRow, ChatRow, ChatMemberRow, MessageRow, IdempotencyKeyRow, AttachmentRow, JobRow, OutboxRow, JobEventRow, VariantRow, MessageAttachmentRow, ) target_metadata = UserRow.metadata config = context.config def include_object(_obj, name, _type, _reflected, _compare_to): return name != "schema_migrations" def run_migrations(connection: Connection) -> None: with connection.engine.connect() as lock: lock.execute(select(func.pg_advisory_lock(LOCK_KEY))) lock.commit() try: with connection.begin(): adopt_legacy(connection, ScriptDirectory.from_config(config)) context.configure( connection=connection, target_metadata=target_metadata, transaction_per_migration=True, compare_type=True, include_object=include_object, ) with context.begin_transaction(): context.run_migrations() finally: lock.execute(select(func.pg_advisory_unlock(LOCK_KEY))) lock.commit() async def run_async_migrations() -> None: dsn = config.attributes.get("database_url") if dsn is None: dsn = PlatformSettings().database_url.get_secret_value() engine = create_async_engine( make_url(dsn).set(drivername="postgresql+asyncpg"), poolclass=pool.NullPool, hide_parameters=True, connect_args={ "timeout": 10, "server_settings": {"lock_timeout": "10000", "statement_timeout": "60000"}, }, ) try: async with engine.connect() as connection: await connection.run_sync(run_migrations) finally: await engine.dispose() if context.is_offline_mode(): context.configure( dialect_name="postgresql", target_metadata=target_metadata, literal_binds=True, transaction_per_migration=True, ) with context.begin_transaction(): context.run_migrations() elif config.attributes.get("connection") is not None: run_migrations(config.attributes["connection"]) else: asyncio.run(run_async_migrations())