"""Lazy SQLAlchemy/Psycopg access. No connections or settings are created on import.""" import json from dataclasses import asdict from uuid import UUID from sqlalchemy import create_engine, text from sqlalchemy.engine import Connection, Engine from sqlalchemy.orm import sessionmaker from app.modules.documents.types import EmbeddingProfile LIVE_REVISION = "0005_live_owner_chain" PREVIOUS_LIVE_REVISION = "0004_live_lifecycle" SCHEMA_REVISION = "0003_extraction_review" WORKER_REVISION = "0002_worker_artifact" FOUNDATION_REVISION = "0001_ingestion_foundation" FOUNDATION_TABLES = ( "organizations", "users", "organization_settings", "documents", "ingestion_jobs", "document_chunks", "audit_events", ) FOUNDATION_RELATIONS = (*FOUNDATION_TABLES, "alembic_version") def assert_foundation_scope(connection: Connection, schema: str, *, require_all=True) -> None: """Check actual name resolution before migrations or disposable-schema writes.""" if connection.execute(text("SELECT current_schema()")).scalar_one() != schema: raise CompatibilityError("Unexpected application schema") for name in FOUNDATION_RELATIONS: resolved = connection.execute(text(""" SELECT n.nspname, c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE c.oid=to_regclass(:name) """), {"name": name}).one_or_none() if resolved is None: if require_all: raise CompatibilityError("Missing scoped foundation relation") elif resolved[0] != schema or resolved[1] != "r": raise CompatibilityError("Foundation relation resolves outside application schema") class CompatibilityError(RuntimeError): pass def create_database(url: str) -> Engine: from sqlalchemy.engine import make_url if make_url(url).drivername != "postgresql+psycopg": raise ValueError("PostgreSQL with Psycopg is required") return create_engine(url, pool_pre_ping=True, hide_parameters=True) def register_vector_types(connection: Connection) -> None: """Register native vector adaptation on this connection after migration.""" from pgvector.psycopg import register_vector register_vector(connection.connection.driver_connection) def session_factory(engine: Engine): return sessionmaker(engine, expire_on_commit=False) def check_compatibility(connection: Connection, profile: EmbeddingProfile, *, require_worker=False) -> None: """Fail closed on schema, dimension or full embedding identity mismatch.""" schema = connection.execute(text("SELECT current_schema()")).scalar_one() assert_foundation_scope(connection, schema) revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one() allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION) if require_worker else ( FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION ) if revision not in allowed: raise CompatibilityError("Unexpected ingestion schema revision") if revision in (WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION): artifact_type = connection.execute(text(""" SELECT format_type(atttypid,atttypmod) FROM pg_attribute WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped """)).scalar_one_or_none() if artifact_type != "jsonb": raise CompatibilityError("Missing worker artifact attachment column") if revision in (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION): definitions = connection.execute(text(""" SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid=to_regclass(\'audit_events\') AND conname IN (\'audit_events_action_check\',\'audit_events_extraction_review_replay\') """)).scalars().all() if len(definitions) != 2 or not all("extraction_review" in d for d in definitions): raise CompatibilityError("Missing review audit/replay checks") row = connection.execute(text(""" SELECT format_type(a.atttypid,a.atttypmod) AS vector_type, col_description(a.attrelid,a.attnum) AS profile FROM pg_attribute a WHERE a.attrelid = to_regclass('document_chunks') AND a.attname = 'embedding' AND NOT a.attisdropped """)).mappings().one_or_none() if row is None or row["vector_type"] != f"vector({profile.dimensions})": raise CompatibilityError("Embedding dimension differs from migrated schema") try: pinned = json.loads(row["profile"]) except (TypeError, ValueError) as exc: raise CompatibilityError("Missing or invalid migrated embedding profile") from exc if pinned != asdict(profile): raise CompatibilityError("Embedding identity differs from migrated profile") incompatible = connection.execute(text(""" SELECT EXISTS ( SELECT 1 FROM documents WHERE processing_profile->'embedding' IS DISTINCT FROM CAST(:profile AS jsonb) ) """), {"profile": json.dumps(pinned)}).scalar_one() if incompatible: raise CompatibilityError("A document has an incompatible processing profile") class SqlDocumentRepository: """Read port bound to the caller's short-lived connection/transaction.""" def __init__(self, connection: Connection): self.connection = connection def get_document(self, organization_id: UUID, document_id: UUID): return self.connection.execute(text(""" SELECT * FROM documents WHERE organization_id=:org AND id=:id """), {"org": organization_id, "id": document_id}).mappings().one_or_none() def get_enabled_administrator(self, user_id: UUID): return self.connection.execute(text(""" SELECT id, organization_id, role FROM users WHERE id=:id AND role='admin' AND is_enabled """), {"id": user_id}).mappings().one_or_none()