Files
rag-technical-docs-assistant/app/infrastructure/database.py
T
amirhosein mazaheri baf58da562 feat(ingestion): add Phase 1 database and application foundation
Add the scoped PostgreSQL/pgvector schema, independent ingestion settings and ports, embedding profile checks, and trusted administrator bootstrap.

Include repository contracts and guidance, organized provider-free and PostgreSQL tests, deployment setup, and byte-preserving migration attributes.

Validation: 163 tests passed; all 48 PostgreSQL cases passed with pgvector Python 0.5.0 and 0.3.6. No production schema or historical metadata was changed.
2026-10-05 16:38:28 +03:30

105 lines
4.5 KiB
Python

"""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
SCHEMA_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) -> 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)
if connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one() != SCHEMA_REVISION:
raise CompatibilityError("Unexpected ingestion schema revision")
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()