Spaces:
Runtime error
Runtime error
Download src/db/database.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/db/database.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/db/database.py
-
curl -L -o database.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/db/database.py
17.1 kB
| """Database configuration and connection management.""" | |
| import os | |
| import tempfile | |
| from contextlib import contextmanager | |
| from pathlib import Path | |
| from typing import Any, Dict, Generator | |
| from uuid import uuid4 | |
| from sqlalchemy import create_engine, event, text | |
| from sqlalchemy.engine import Engine | |
| from sqlalchemy.orm import Session, declarative_base, sessionmaker | |
| from src.utils.env import env_bool, env_int | |
| def _resolve_data_dir() -> Path: | |
| """Resolve a writable data directory across desktop/server environments.""" | |
| candidates = [] | |
| env_dir = str(os.getenv("AI_TESTER_DATA_DIR", "") or "").strip() | |
| if env_dir: | |
| candidates.append(Path(env_dir).expanduser()) | |
| candidates.append(Path("./data")) | |
| candidates.append(Path.home() / ".ai-testing-platform" / "data") | |
| candidates.append(Path(tempfile.gettempdir()) / "ai-testing-platform-data") | |
| for directory in candidates: | |
| try: | |
| directory.mkdir(parents=True, exist_ok=True) | |
| return directory | |
| except Exception: | |
| continue | |
| # Last safety net (in-memory-ish temp location). | |
| fallback = Path(tempfile.mkdtemp(prefix="ai-tester-data-")) | |
| return fallback | |
| # Creazione directory data con fallback sicuro | |
| DATA_DIR = _resolve_data_dir() | |
| # Base per i modelli SQLAlchemy | |
| Base = declarative_base() | |
| class Database: | |
| """Gestione database con SQLAlchemy.""" | |
| def __init__(self, database_url: str = None): | |
| self.database_url = database_url or os.getenv( | |
| "DATABASE_URL", f"sqlite:///{DATA_DIR}/ai_tester.db" | |
| ) | |
| # Configurazione engine | |
| connect_args: Dict[str, Any] = {} | |
| engine_kwargs: Dict[str, Any] = { | |
| "echo": env_bool("DEBUG", False), | |
| "pool_pre_ping": env_bool("DB_POOL_PRE_PING", True), | |
| } | |
| if self.database_url.startswith("sqlite"): | |
| # SQLite uses a single-connection pool; the size kwargs would | |
| # conflict (NullPool by default for non-file URLs). Keep it simple. | |
| connect_args["check_same_thread"] = False | |
| else: | |
| # Postgres / MySQL / etc. — let the operator tune the pool from env. | |
| # Defaults are conservative for Render's free/starter tier where | |
| # connection limits on the upstream DB are tight. | |
| engine_kwargs.update( | |
| pool_size=env_int("DB_POOL_SIZE", 5), | |
| max_overflow=env_int("DB_MAX_OVERFLOW", 10), | |
| pool_recycle=env_int("DB_POOL_RECYCLE_SECONDS", 300), | |
| pool_timeout=env_int("DB_POOL_TIMEOUT_SECONDS", 30), | |
| ) | |
| self.engine = create_engine( | |
| self.database_url, | |
| connect_args=connect_args, | |
| **engine_kwargs, | |
| ) | |
| # Session factory | |
| self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine) | |
| # Setup per SQLite | |
| if self.database_url.startswith("sqlite"): | |
| self._setup_sqlite() | |
| def _setup_sqlite(self): | |
| """Setup specifico per SQLite (foreign keys, etc).""" | |
| def set_sqlite_pragma(dbapi_conn, connection_record): | |
| cursor = dbapi_conn.cursor() | |
| cursor.execute("PRAGMA foreign_keys=ON") | |
| cursor.close() | |
| def create_tables(self): | |
| """Crea tutte le tabelle.""" | |
| # Importa qui per evitare circular imports | |
| Base.metadata.create_all(bind=self.engine) | |
| self._apply_compatibility_migrations() | |
| def drop_tables(self): | |
| """Drop tutte le tabelle (attenzione!).""" | |
| Base.metadata.drop_all(bind=self.engine) | |
| def _apply_compatibility_migrations(self): | |
| """ | |
| Apply non-destructive schema compatibility migrations. | |
| DB engines do not auto-alter existing tables when SQLAlchemy models add | |
| new columns, so older schemas can break API queries at runtime. | |
| """ | |
| required_columns = { | |
| "bots": { | |
| "workspace_id": "VARCHAR(36)", | |
| "deterministic_fallbacks": "JSON", | |
| "knowledge_boundary_content": "TEXT", | |
| "knowledge_boundary_updated_at": "TIMESTAMP", | |
| }, | |
| "personas": { | |
| "workspace_id": "VARCHAR(36)", | |
| }, | |
| "scenarios": { | |
| "workspace_id": "VARCHAR(36)", | |
| "mode": "VARCHAR(32) DEFAULT 'deterministic'", | |
| "followup_policy": "VARCHAR(32) DEFAULT 'limited'", | |
| "followup_max_turns": "INTEGER DEFAULT 1", | |
| "seed_questions": "JSON", | |
| "supports_context": "BOOLEAN DEFAULT TRUE", | |
| }, | |
| "rag_documents": { | |
| "workspace_id": "VARCHAR(36)", | |
| }, | |
| "bot_versions": { | |
| "workspace_id": "VARCHAR(36)", | |
| }, | |
| "test_sessions": { | |
| "workspace_id": "VARCHAR(36)", | |
| "max_messages": "INTEGER", | |
| "max_turns": "INTEGER", | |
| "min_turns": "INTEGER DEFAULT 1", | |
| "critical_questions": "JSON", | |
| "termination_policy": "JSON", | |
| "messages_sent": "INTEGER DEFAULT 0", | |
| "knowledge_snapshot_id": "VARCHAR(36)", | |
| "memory_status": "JSON", | |
| }, | |
| "test_results": { | |
| "workspace_id": "VARCHAR(36)", | |
| "scenario_results": "JSON", | |
| "termination_reason": "VARCHAR(128)", | |
| }, | |
| "interactions": { | |
| "correctness_label": "VARCHAR(24)", | |
| "correctness_reasoning": "TEXT", | |
| "claims_json": "JSON", | |
| "evidence_pack_json": "JSON", | |
| "human_override_label": "VARCHAR(24)", | |
| "human_override_intent_label": "VARCHAR(24)", | |
| "human_override_reason": "TEXT", | |
| "human_override_reviewer_id": "VARCHAR(255)", | |
| "human_override_at": "TIMESTAMP", | |
| "retry_count": "INTEGER", | |
| }, | |
| "bug_tickets": { | |
| "turn_id": "VARCHAR(36)", | |
| "interaction_turn_number": "INTEGER", | |
| "expected_behavior": "TEXT", | |
| "external_parent_id": "VARCHAR(64)", | |
| "external_category_id": "VARCHAR(64)", | |
| "external_id": "VARCHAR(64)", | |
| "external_url": "VARCHAR(500)", | |
| "external_project_identifier": "VARCHAR(128)", | |
| "sync_status": "VARCHAR(16) DEFAULT 'pending'", | |
| "sync_error": "TEXT", | |
| "sync_attempts": "INTEGER DEFAULT 0", | |
| "synced_at": "TIMESTAMP", | |
| }, | |
| } | |
| # Extend test_sessions with verdict columns. | |
| required_columns["test_sessions"].update( | |
| { | |
| "verdict_label": "VARCHAR(24)", | |
| "verdict_p_hat": "FLOAT", | |
| "verdict_lower_bound": "FLOAT", | |
| "verdict_upper_bound": "FLOAT", | |
| "verdict_threshold": "FLOAT", | |
| "verdict_n": "INTEGER", | |
| } | |
| ) | |
| with self.engine.begin() as conn: | |
| if self.database_url.startswith("sqlite"): | |
| for table_name, columns in required_columns.items(): | |
| existing_tables = { | |
| row[0] | |
| for row in conn.execute( | |
| text("SELECT name FROM sqlite_master WHERE type='table'") | |
| ).fetchall() | |
| } | |
| if table_name not in existing_tables: | |
| continue | |
| existing = { | |
| row[1] | |
| for row in conn.execute(text(f"PRAGMA table_info({table_name})")).fetchall() | |
| } | |
| for column_name, column_def in columns.items(): | |
| if column_name in existing: | |
| continue | |
| conn.execute( | |
| text(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_def}") | |
| ) | |
| # Indexes added after initial schema (compat for existing DBs). | |
| try: | |
| conn.execute( | |
| text( | |
| "CREATE INDEX IF NOT EXISTS idx_bug_tickets_sync_status " | |
| "ON bug_tickets(sync_status)" | |
| ) | |
| ) | |
| except Exception: | |
| pass | |
| # Ensure one default workspace exists and backfill legacy rows. | |
| conn.execute( | |
| text( | |
| """ | |
| INSERT OR IGNORE INTO workspaces (id, name, description, is_active, created_at, updated_at, created_by) | |
| VALUES ('00000000-0000-0000-0000-000000000001', 'default-migrated', 'Auto-migrated default workspace', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'system') | |
| """ | |
| ) | |
| ) | |
| for table_name in ( | |
| "bots", | |
| "personas", | |
| "scenarios", | |
| "rag_documents", | |
| "bot_versions", | |
| "test_sessions", | |
| "test_results", | |
| ): | |
| try: | |
| conn.execute( | |
| text( | |
| f""" | |
| UPDATE {table_name} | |
| SET workspace_id = '00000000-0000-0000-0000-000000000001' | |
| WHERE workspace_id IS NULL OR workspace_id = '' | |
| """ | |
| ) | |
| ) | |
| except Exception: | |
| continue | |
| # Ensure max_turns mirrors legacy max_messages when needed. | |
| try: | |
| conn.execute( | |
| text( | |
| """ | |
| UPDATE test_sessions | |
| SET max_turns = max_messages | |
| WHERE max_turns IS NULL AND max_messages IS NOT NULL | |
| """ | |
| ) | |
| ) | |
| except Exception: | |
| pass | |
| # Backfill memberships from legacy created_by fields. | |
| legacy_users = set() | |
| for table_name in ("bots", "personas", "scenarios", "test_sessions"): | |
| try: | |
| rows = conn.execute( | |
| text( | |
| f""" | |
| SELECT DISTINCT created_by | |
| FROM {table_name} | |
| WHERE created_by IS NOT NULL | |
| AND TRIM(created_by) <> '' | |
| """ | |
| ) | |
| ).fetchall() | |
| for row in rows: | |
| if row and row[0]: | |
| legacy_users.add(str(row[0])) | |
| except Exception: | |
| continue | |
| for user_id in legacy_users: | |
| conn.execute( | |
| text( | |
| """ | |
| INSERT OR IGNORE INTO workspace_members (id, workspace_id, user_id, role, created_at, updated_at) | |
| VALUES (:id, '00000000-0000-0000-0000-000000000001', :user_id, 'workspace_owner', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) | |
| """ | |
| ), | |
| {"id": str(uuid4()), "user_id": user_id}, | |
| ) | |
| return | |
| # PostgreSQL / Supabase path | |
| for table_name, columns in required_columns.items(): | |
| existing = { | |
| row[0] | |
| for row in conn.execute( | |
| text( | |
| """ | |
| SELECT column_name | |
| FROM information_schema.columns | |
| WHERE table_name = :table_name | |
| AND table_schema = ANY(current_schemas(false)) | |
| """ | |
| ), | |
| {"table_name": table_name}, | |
| ).fetchall() | |
| } | |
| for column_name, column_def in columns.items(): | |
| if column_name in existing: | |
| continue | |
| conn.execute( | |
| text( | |
| f"ALTER TABLE {table_name} ADD COLUMN IF NOT EXISTS {column_name} {column_def}" | |
| ) | |
| ) | |
| # Indexes added after initial schema (compat for existing DBs). | |
| try: | |
| conn.execute( | |
| text( | |
| "CREATE INDEX IF NOT EXISTS idx_bug_tickets_sync_status " | |
| "ON bug_tickets(sync_status)" | |
| ) | |
| ) | |
| except Exception: | |
| pass | |
| conn.execute( | |
| text( | |
| """ | |
| INSERT INTO workspaces (id, name, description, is_active, created_at, updated_at, created_by) | |
| VALUES ('00000000-0000-0000-0000-000000000001', 'default-migrated', 'Auto-migrated default workspace', TRUE, NOW(), NOW(), 'system') | |
| ON CONFLICT (id) DO NOTHING | |
| """ | |
| ) | |
| ) | |
| for table_name in ( | |
| "bots", | |
| "personas", | |
| "scenarios", | |
| "rag_documents", | |
| "bot_versions", | |
| "test_sessions", | |
| "test_results", | |
| ): | |
| try: | |
| conn.execute( | |
| text( | |
| f""" | |
| UPDATE {table_name} | |
| SET workspace_id = '00000000-0000-0000-0000-000000000001' | |
| WHERE workspace_id IS NULL OR workspace_id = '' | |
| """ | |
| ) | |
| ) | |
| except Exception: | |
| continue | |
| try: | |
| conn.execute( | |
| text( | |
| """ | |
| UPDATE test_sessions | |
| SET max_turns = max_messages | |
| WHERE max_turns IS NULL AND max_messages IS NOT NULL | |
| """ | |
| ) | |
| ) | |
| except Exception: | |
| pass | |
| legacy_users = set() | |
| for table_name in ("bots", "personas", "scenarios", "test_sessions"): | |
| try: | |
| rows = conn.execute( | |
| text( | |
| f""" | |
| SELECT DISTINCT created_by | |
| FROM {table_name} | |
| WHERE created_by IS NOT NULL | |
| AND BTRIM(created_by) <> '' | |
| """ | |
| ) | |
| ).fetchall() | |
| for row in rows: | |
| if row and row[0]: | |
| legacy_users.add(str(row[0])) | |
| except Exception: | |
| continue | |
| for user_id in legacy_users: | |
| conn.execute( | |
| text( | |
| """ | |
| INSERT INTO workspace_members (id, workspace_id, user_id, role, created_at, updated_at) | |
| VALUES (:id, '00000000-0000-0000-0000-000000000001', :user_id, 'workspace_owner', NOW(), NOW()) | |
| ON CONFLICT (workspace_id, user_id) DO NOTHING | |
| """ | |
| ), | |
| {"id": str(uuid4()), "user_id": user_id}, | |
| ) | |
| def get_session(self) -> Generator[Session, None, None]: | |
| """Context manager per sessioni DB.""" | |
| session = self.SessionLocal() | |
| try: | |
| yield session | |
| session.commit() | |
| except Exception: | |
| session.rollback() | |
| raise | |
| finally: | |
| session.close() | |
| def close(self): | |
| """Chiude connessione.""" | |
| self.engine.dispose() | |
| # Singleton instance | |
| _db_instance: Database = None | |
| def get_db() -> Database: | |
| """Restituisce singleton instance del database.""" | |
| global _db_instance | |
| if _db_instance is None: | |
| _db_instance = Database() | |
| return _db_instance | |
| def init_db(): | |
| """Inizializza database (da chiamare all'avvio).""" | |
| db = get_db() | |
| db.create_tables() | |
| return db | |