"""Database models and initialization.""" import aiosqlite from pathlib import Path from .. import config async def init_db(): """Initialize the SQLite database.""" # Ensure data directory exists config.DATA_DIR.mkdir(parents=True, exist_ok=True) async with aiosqlite.connect(config.DATABASE_PATH) as db: # Sessions table await db.execute(""" CREATE TABLE IF NOT EXISTS sessions ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT UNIQUE NOT NULL, client_ip TEXT NOT NULL, user_agent TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP, is_active BOOLEAN DEFAULT 1 ) """) # Config table await db.execute(""" CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # Crash reports table await db.execute(""" CREATE TABLE IF NOT EXISTS crash_reports ( id INTEGER PRIMARY KEY AUTOINCREMENT, error_type TEXT NOT NULL, error_message TEXT NOT NULL, traceback TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # Command history table await db.execute(""" CREATE TABLE IF NOT EXISTS command_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, command TEXT NOT NULL, response TEXT, success BOOLEAN, executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (session_id) REFERENCES sessions(session_id) ) """) await db.commit() async def get_db(): """Get database connection.""" db = await aiosqlite.connect(config.DATABASE_PATH) db.row_factory = aiosqlite.Row try: yield db finally: await db.close()