|
| 1 | +import sqlite3 |
| 2 | +import json |
| 3 | +from contextlib import contextmanager |
| 4 | +from typing import Optional, List, Dict, Any |
| 5 | + |
| 6 | +@contextmanager |
| 7 | +def _db(db_path: str): |
| 8 | + conn = sqlite3.connect(db_path) |
| 9 | + conn.row_factory = sqlite3.Row |
| 10 | + try: |
| 11 | + yield conn |
| 12 | + conn.commit() |
| 13 | + finally: |
| 14 | + conn.close() |
| 15 | + |
| 16 | +def init_db(db_path: str): |
| 17 | + """Initialize the SQLite database with findings and risk_scores tables and unique indexes.""" |
| 18 | + with _db(db_path) as conn: |
| 19 | + cursor = conn.cursor() |
| 20 | + cursor.execute(""" |
| 21 | + CREATE TABLE IF NOT EXISTS findings ( |
| 22 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 23 | + run_id TEXT, |
| 24 | + timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, |
| 25 | + filepath TEXT, |
| 26 | + title TEXT, |
| 27 | + severity TEXT, |
| 28 | + description TEXT, |
| 29 | + line_numbers TEXT NOT NULL DEFAULT '[]', |
| 30 | + remediation TEXT, |
| 31 | + status TEXT NOT NULL DEFAULT 'reported', |
| 32 | + UNIQUE(filepath, title, description, line_numbers, run_id) |
| 33 | + ) |
| 34 | + """) |
| 35 | + cursor.execute(""" |
| 36 | + CREATE TABLE IF NOT EXISTS risk_scores ( |
| 37 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 38 | + run_id TEXT, |
| 39 | + timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, |
| 40 | + filepath TEXT, |
| 41 | + score INTEGER, |
| 42 | + reasoning TEXT, |
| 43 | + UNIQUE(filepath, run_id) |
| 44 | + ) |
| 45 | + """) |
| 46 | + |
| 47 | +def write_findings(db_path: str, filepath: str, findings: list, run_id: str = "", status: str = "reported"): |
| 48 | + """Write structured findings to the database contextually associated with real path.""" |
| 49 | + with _db(db_path) as conn: |
| 50 | + cursor = conn.cursor() |
| 51 | + for obj in findings: |
| 52 | + finding = obj.model_dump() if hasattr(obj, "model_dump") else (obj if isinstance(obj, dict) else dict(obj)) |
| 53 | + raw_lines = finding.get("line_numbers") |
| 54 | + if raw_lines and isinstance(raw_lines, (list, tuple, set)): |
| 55 | + try: |
| 56 | + line_numbers = json.dumps(sorted(list(raw_lines))) |
| 57 | + except Exception: |
| 58 | + line_numbers = json.dumps(list(raw_lines)) |
| 59 | + else: |
| 60 | + line_numbers = "[]" |
| 61 | + |
| 62 | + finding_status = finding.get("status") or status |
| 63 | + |
| 64 | + cursor.execute(""" |
| 65 | + INSERT OR REPLACE INTO findings (run_id, filepath, title, severity, description, line_numbers, remediation, status) |
| 66 | + VALUES (?, ?, ?, ?, ?, ?, ?, ?) |
| 67 | + """, ( |
| 68 | + run_id, |
| 69 | + filepath, |
| 70 | + finding.get("title"), |
| 71 | + finding.get("severity"), |
| 72 | + finding.get("description"), |
| 73 | + line_numbers, |
| 74 | + finding.get("remediation"), |
| 75 | + finding_status, |
| 76 | + )) |
| 77 | + |
| 78 | +def update_status(db_path: str, filepath: str, run_id: str, status: str): |
| 79 | + """Update status for all findings of a target file in a given run.""" |
| 80 | + with _db(db_path) as conn: |
| 81 | + cursor = conn.cursor() |
| 82 | + cursor.execute(""" |
| 83 | + UPDATE findings |
| 84 | + SET status = ? |
| 85 | + WHERE filepath = ? AND run_id = ? |
| 86 | + """, (status, filepath, run_id)) |
| 87 | + |
| 88 | + |
| 89 | +def read_findings( |
| 90 | + db_path: str, |
| 91 | + filepath: Optional[str] = None, |
| 92 | + run_id: Optional[str] = None, |
| 93 | + status: Optional[str] = None, |
| 94 | +) -> List[Dict[str, Any]]: |
| 95 | + """Read findings from the database, optionally filtered by filepath, run_id, or status.""" |
| 96 | + with _db(db_path) as conn: |
| 97 | + cursor = conn.cursor() |
| 98 | + query = "SELECT * FROM findings WHERE 1=1" |
| 99 | + params = [] |
| 100 | + if filepath: |
| 101 | + query += " AND filepath = ?" |
| 102 | + params.append(filepath) |
| 103 | + if run_id: |
| 104 | + query += " AND run_id = ?" |
| 105 | + params.append(run_id) |
| 106 | + if status: |
| 107 | + query += " AND status = ?" |
| 108 | + params.append(status) |
| 109 | + query += " ORDER BY id ASC" |
| 110 | + cursor.execute(query, params) |
| 111 | + rows = [] |
| 112 | + for r in cursor.fetchall(): |
| 113 | + row_dict = dict(r) |
| 114 | + if row_dict.get("line_numbers"): |
| 115 | + try: |
| 116 | + parsed = json.loads(row_dict["line_numbers"]) |
| 117 | + row_dict["line_numbers"] = parsed if parsed else None |
| 118 | + except Exception: |
| 119 | + row_dict["line_numbers"] = None |
| 120 | + else: |
| 121 | + row_dict["line_numbers"] = None |
| 122 | + rows.append(row_dict) |
| 123 | + return rows |
| 124 | + |
| 125 | +def record_calibration(db_path: str, filepath: str, score: int, reasoning: str, run_id: str = ""): |
| 126 | + """Record final risk calibration score into the database with idempotent overwrite on retry.""" |
| 127 | + with _db(db_path) as conn: |
| 128 | + cursor = conn.cursor() |
| 129 | + cursor.execute(""" |
| 130 | + INSERT OR REPLACE INTO risk_scores (run_id, filepath, score, reasoning) |
| 131 | + VALUES (?, ?, ?, ?) |
| 132 | + """, (run_id, filepath, score, reasoning)) |
| 133 | + |
| 134 | +def read_risk_scores(db_path: str, filepath: Optional[str] = None, run_id: Optional[str] = None) -> List[Dict[str, Any]]: |
| 135 | + """Read risk scores from the database, optionally filtered by filepath and run_id.""" |
| 136 | + with _db(db_path) as conn: |
| 137 | + cursor = conn.cursor() |
| 138 | + query = "SELECT * FROM risk_scores WHERE 1=1" |
| 139 | + params = [] |
| 140 | + if filepath: |
| 141 | + query += " AND filepath = ?" |
| 142 | + params.append(filepath) |
| 143 | + if run_id: |
| 144 | + query += " AND run_id = ?" |
| 145 | + params.append(run_id) |
| 146 | + query += " ORDER BY id ASC" |
| 147 | + cursor.execute(query, params) |
| 148 | + return [dict(r) for r in cursor.fetchall()] |
| 149 | + |
0 commit comments