Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

1.9 KB
Raw Blame
"""Database utilities for metrics module with SQLAlchemy."""

from contextlib import contextmanager
from typing import Generator, Optional

from sqlalchemy.orm import Session

from ..database.session_context import get_user_db_session
from ..utilities.request_context import get_current_username  # noqa: F401


class MetricsDatabase:
    """Database manager for metrics using SQLAlchemy."""

    def __init__(
        self, username: Optional[str] = None, password: Optional[str] = None
    ):
        # Store credentials if provided (for testing/background tasks)
        self.username = username
        self.password = password

    @contextmanager
    def get_session(
        self, username: Optional[str] = None, password: Optional[str] = None
    ) -> Generator[Session, None, None]:
        """Get a database session with automatic cleanup.

        Args:
            username: Override username for this session
            password: Override password for this session (if needed for thread access)
        """
        # Use provided username or fall back to stored/session username
        user = username or self.username
        pwd = password or self.password

        # Try to get username from request context if still not available
        if not user:
            user = get_current_username()

        if not user:
            # No username available - can't access user database
            yield None
            return

        # If we have password, use thread-safe access
        if pwd:
            from ..database.thread_metrics import metrics_writer

            metrics_writer.set_user_password(user, pwd)
            with metrics_writer.get_session(user) as session:
                yield session
        else:
            # Use the per-user database session with proper context management
            with get_user_db_session(user) as session:
                yield session