File size: 4,175 Bytes
266eda8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
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}'"
        )