""" Database connection and initialization module. Manages SQLite database connection and table creation. """ import sqlite3 import os from contextlib import contextmanager from typing import Generator # Database file path DB_PATH = os.getenv("DATABASE_PATH", "annotation_platform.db") @contextmanager def get_db_connection() -> Generator[sqlite3.Connection, None, None]: """ Context manager for database connections. Ensures proper connection cleanup. """ conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row # Enable column access by name conn.execute("PRAGMA foreign_keys = ON") # Enable foreign key constraints try: yield conn conn.commit() except Exception: conn.rollback() raise finally: conn.close() def init_database() -> None: """ Initialize database and create tables if they don't exist. Creates projects, tasks, and annotations tables with proper relationships. """ with get_db_connection() as conn: cursor = conn.cursor() # Enable foreign key constraints cursor.execute("PRAGMA foreign_keys = ON") # Create projects table cursor.execute(""" CREATE TABLE IF NOT EXISTS projects ( id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, config TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # Create tasks table cursor.execute(""" CREATE TABLE IF NOT EXISTS tasks ( id TEXT PRIMARY KEY, project_id TEXT NOT NULL, name TEXT NOT NULL, data TEXT NOT NULL, status TEXT DEFAULT 'pending', assigned_to TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE ) """) # Create annotations table cursor.execute(""" CREATE TABLE IF NOT EXISTS annotations ( id TEXT PRIMARY KEY, task_id TEXT NOT NULL, user_id TEXT NOT NULL, result TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE ) """) conn.commit() def get_db() -> sqlite3.Connection: """ Get a database connection. Note: Caller is responsible for closing the connection. """ conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON") return conn