""" Database utilities with hard separation enforcement. - Four isolated datasets: 2 worlds (lab vs literature) × 2 stages (hydrogels vs cells) - Identity tags prevent cross-contamination - Read-only mode enforcement - Connection validation """ from pathlib import Path import sqlite3 from typing import Optional # Valid database purposes (four-quadrant system) VALID_PURPOSES = { "lab_hydrogels", # Your experimental hydrogel data "lab_cellgrowth", # Your experimental cell culture data "lit_hydrogels", # Literature hydrogel data "lit_cellgrowth" # Literature cell culture data } def connect_checked(db_path: Path, expected_purpose: str, *, read_only: bool = False) -> sqlite3.Connection: """ Connect to a database with identity validation. Args: db_path: Path to SQLite database expected_purpose: Expected DB purpose (one of: lab_hydrogels, lab_cellgrowth, lit_hydrogels, lit_cellgrowth) read_only: If True, open in read-only mode Returns: sqlite3.Connection with validated identity Raises: RuntimeError: If DB purpose doesn't match expected ValueError: If expected_purpose is not valid """ if expected_purpose not in VALID_PURPOSES: raise ValueError(f"Invalid purpose '{expected_purpose}'. Must be one of: {VALID_PURPOSES}") if read_only: uri = f"file:{db_path.as_posix()}?mode=ro" con = sqlite3.connect(uri, uri=True) else: con = sqlite3.connect(str(db_path), isolation_level=None) con.execute("PRAGMA journal_mode=WAL;") con.row_factory = sqlite3.Row con.execute("PRAGMA foreign_keys=ON;") # Validate identity try: purpose_row = con.execute("SELECT purpose FROM db_identity LIMIT 1").fetchone() except sqlite3.OperationalError: # Table doesn't exist yet - will be created by init purpose_row = None if purpose_row and purpose_row["purpose"] != expected_purpose: con.close() raise RuntimeError( f"❌ WRONG DATABASE! Expected '{expected_purpose}', found '{purpose_row['purpose']}'. " f"Path: {db_path}" ) return con def ensure_db_identity(con: sqlite3.Connection, purpose: str): """ Create db_identity table and set purpose. Call once during database initialization. Args: con: Database connection purpose: One of: lab_hydrogels, lab_cellgrowth, lit_hydrogels, lit_cellgrowth Raises: ValueError: If purpose is not valid """ if purpose not in VALID_PURPOSES: raise ValueError(f"Invalid purpose '{purpose}'. Must be one of: {VALID_PURPOSES}") con.execute(""" CREATE TABLE IF NOT EXISTS db_identity( purpose TEXT PRIMARY KEY CHECK(purpose IN ('lab_hydrogels','lab_cellgrowth','lit_hydrogels','lit_cellgrowth')), created_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) con.execute("INSERT OR IGNORE INTO db_identity(purpose) VALUES(?)", (purpose,)) def get_db_purpose(db_path: Path) -> Optional[str]: """ Get the purpose tag from a database without validation. Args: db_path: Path to database Returns: Purpose string or None if not set """ try: con = sqlite3.connect(str(db_path)) row = con.execute("SELECT purpose FROM db_identity LIMIT 1").fetchone() con.close() return row[0] if row else None except Exception: return None def assert_write_allowed(con: sqlite3.Connection, expected_purpose: str): """ Assert that writes are allowed to this database. Call before any INSERT/UPDATE/DELETE. Args: con: Database connection expected_purpose: Expected DB purpose Raises: RuntimeError: If DB purpose doesn't match """ purpose = con.execute("SELECT purpose FROM db_identity").fetchone() if not purpose or purpose["purpose"] != expected_purpose: raise RuntimeError( f"❌ WRITE REFUSED: DB purpose is '{purpose and purpose['purpose']}', expected '{expected_purpose}'" )