"""Online migrations scope bookkeeping and validate relation ownership before writes.""" from alembic import context from sqlalchemy import create_engine, pool, text from app.infrastructure.database import assert_foundation_scope, check_compatibility from app.modules.documents.settings import IngestionSettings def migrate(connection, settings): schema = context.config.attributes.get("application_schema") if schema is None: schema = connection.execute(text("SELECT current_schema()")).scalar_one() if not schema: raise RuntimeError("An existing application schema is required") # Historical SQL stays unchanged; check its name resolution before downgrade. assert_foundation_scope(connection, schema, require_all=False) if connection.dialect.has_table(connection, "alembic_version", schema=schema): quoted = connection.dialect.identifier_preparer.quote_schema(schema) revision = connection.execute(text( f"SELECT version_num FROM {quoted}.alembic_version" )).scalar_one_or_none() if revision is not None: assert_foundation_scope(connection, schema) if context.config.attributes.get("connection") is None: # Preflight reads must not keep the standalone CLI transaction open. connection.commit() context.configure(connection=connection, version_table_schema=schema) with context.begin_transaction(): context.run_migrations(settings=settings) assert_foundation_scope(connection, schema, require_all=False) if connection.dialect.has_table(connection, "document_chunks", schema=schema): check_compatibility(connection, settings.embedding_profile) def run_migrations(): if context.is_offline_mode(): raise RuntimeError("Use online migration so the pinned profile can be verified") settings = context.config.attributes.get("ingestion_settings") or IngestionSettings() supplied = context.config.attributes.get("connection") if supplied is not None: migrate(supplied, settings) return engine = create_engine( settings.database_url.get_secret_value(), poolclass=pool.NullPool, hide_parameters=True, ) try: with engine.connect() as connection: migrate(connection, settings) finally: engine.dispose() run_migrations()