"""Disposable PostgreSQL schemas with no public application-table fallback.""" from contextlib import contextmanager from pathlib import Path from uuid import uuid4 from alembic import command from alembic.config import Config from sqlalchemy import create_engine, event, text from sqlalchemy.engine import make_url from app.infrastructure.database import ( FOUNDATION_RELATIONS, CompatibilityError, assert_foundation_scope, ) ROOT = Path(__file__).resolve().parents[2] EXTENSION_SCHEMA = "test_vector" def validated_test_url(url): try: parsed = make_url(url) except Exception: raise ValueError("Invalid isolated test database configuration") from None if (parsed.drivername != "postgresql+psycopg" or not parsed.database or not parsed.database.endswith("_test")): raise ValueError("Use Psycopg and a dedicated database name ending in _test") return parsed def prepare_extension(connection): existing = connection.execute(text(""" SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid=e.extnamespace WHERE e.extname='vector' """)).scalar_one_or_none() if existing is None: connection.execute(text(f'CREATE SCHEMA IF NOT EXISTS "{EXTENSION_SCHEMA}"')) connection.execute(text(f'CREATE EXTENSION vector WITH SCHEMA "{EXTENSION_SCHEMA}"')) elif existing != EXTENSION_SCHEMA: raise RuntimeError("Test vector extension must be installed in test_vector; use a fresh dedicated test database") for name in FOUNDATION_RELATIONS: exists = connection.execute(text(""" SELECT EXISTS ( SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=:schema AND c.relname=:name ) """), {"schema": EXTENSION_SCHEMA, "name": name}).scalar_one() if exists: raise CompatibilityError("Extension namespace contains an application relation") def migration_config(settings, schema): config = Config(str(ROOT / "alembic.ini")) config.set_main_option("script_location", str(ROOT / "migrations")) config.attributes["ingestion_settings"] = settings config.attributes["application_schema"] = schema return config @contextmanager def disposable_database(url, settings): parsed = validated_test_url(url) schema = "test_" + uuid4().hex admin = create_engine(parsed, hide_parameters=True) engine = None created = False try: with admin.begin() as connection: prepare_extension(connection) connection.execute(text(f'CREATE SCHEMA "{schema}"')) created = True engine = create_engine( parsed, hide_parameters=True, connect_args={"options": f"-csearch_path={schema},{EXTENSION_SCHEMA}"}, ) config = migration_config(settings, schema) with engine.begin() as connection: config.attributes["connection"] = connection command.upgrade(config, "head") assert_foundation_scope(connection, schema) config.attributes.pop("connection") @event.listens_for(engine, "engine_connect") def verify_before_use(connection): # Validate every test connection before its first mutation. assert_foundation_scope(connection, schema) connection.rollback() yield engine, config finally: if engine is not None: engine.dispose() if created: with admin.begin() as connection: connection.execute(text(f'SET LOCAL search_path="{schema}",{EXTENSION_SCHEMA}')) assert_foundation_scope(connection, schema, require_all=False) connection.execute(text(f'DROP SCHEMA "{schema}" CASCADE')) admin.dispose() @contextmanager def fresh_test_database(url): """Public-schema regression gets its own DB; never modifies caller's public.""" parsed = validated_test_url(url) name = "foundation_" + uuid4().hex + "_test" admin = create_engine(parsed, isolation_level="AUTOCOMMIT", hide_parameters=True) created = False try: with admin.connect() as connection: connection.execute(text(f'CREATE DATABASE "{name}"')) created = True yield parsed.set(database=name) finally: if created: with admin.connect() as connection: connection.execute(text(f'DROP DATABASE "{name}" WITH (FORCE)')) admin.dispose()