storage: create the SQLite schema once per file and always close connections
Browse files- backend/storage.py +20 -1
backend/storage.py
CHANGED
|
@@ -1,13 +1,20 @@
|
|
| 1 |
"""Local repository boundary. Cloud implementations must add per-user isolation."""
|
|
|
|
| 2 |
from typing import Protocol
|
| 3 |
from pathlib import Path
|
| 4 |
import sqlite3
|
| 5 |
import json
|
|
|
|
| 6 |
import uuid
|
| 7 |
from datetime import datetime, timezone
|
| 8 |
|
| 9 |
def now(): return datetime.now(timezone.utc).isoformat()
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
class InspectionRepository(Protocol):
|
| 12 |
def save(self, record:dict)->dict: ...
|
| 13 |
def get(self, identifier:str)->dict|None: ...
|
|
@@ -17,6 +24,12 @@ class SQLiteRepository:
|
|
| 17 |
def __init__(self,path:Path):
|
| 18 |
self.path=path
|
| 19 |
path.parent.mkdir(parents=True,exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
with self.connect() as db:
|
| 21 |
db.executescript('''
|
| 22 |
PRAGMA journal_mode=WAL;
|
|
@@ -28,10 +41,16 @@ class SQLiteRepository:
|
|
| 28 |
CREATE TABLE IF NOT EXISTS inspection_archives(id TEXT PRIMARY KEY,archived_at TEXT NOT NULL,archive_batch TEXT NOT NULL);
|
| 29 |
CREATE TABLE IF NOT EXISTS audit_events(id TEXT PRIMARY KEY,created_at TEXT NOT NULL,action TEXT NOT NULL,payload TEXT NOT NULL);
|
| 30 |
''')
|
|
|
|
| 31 |
def connect(self):
|
|
|
|
| 32 |
connection=sqlite3.connect(self.path,timeout=20)
|
| 33 |
connection.row_factory=sqlite3.Row
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def save(self,record):
|
| 36 |
with self.connect() as db:
|
| 37 |
db.execute('INSERT INTO inspections VALUES(?,?,?,?,?,?)',(record['id'],record['created_at'],record['category'],record['verdict'],record.get('batch',''),json.dumps(record)))
|
|
|
|
| 1 |
"""Local repository boundary. Cloud implementations must add per-user isolation."""
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
from typing import Protocol
|
| 4 |
from pathlib import Path
|
| 5 |
import sqlite3
|
| 6 |
import json
|
| 7 |
+
import threading
|
| 8 |
import uuid
|
| 9 |
from datetime import datetime, timezone
|
| 10 |
|
| 11 |
def now(): return datetime.now(timezone.utc).isoformat()
|
| 12 |
|
| 13 |
+
# Files whose schema this process already created. Rerunning the DDL on every request
|
| 14 |
+
# took a write lock and caused "database is locked" when batch requests overlapped.
|
| 15 |
+
_ready=set()
|
| 16 |
+
_ready_lock=threading.Lock()
|
| 17 |
+
|
| 18 |
class InspectionRepository(Protocol):
|
| 19 |
def save(self, record:dict)->dict: ...
|
| 20 |
def get(self, identifier:str)->dict|None: ...
|
|
|
|
| 24 |
def __init__(self,path:Path):
|
| 25 |
self.path=path
|
| 26 |
path.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
+
key=str(path.resolve())
|
| 28 |
+
with _ready_lock:
|
| 29 |
+
if key in _ready and path.exists():return
|
| 30 |
+
self._create_schema()
|
| 31 |
+
_ready.add(key)
|
| 32 |
+
def _create_schema(self):
|
| 33 |
with self.connect() as db:
|
| 34 |
db.executescript('''
|
| 35 |
PRAGMA journal_mode=WAL;
|
|
|
|
| 41 |
CREATE TABLE IF NOT EXISTS inspection_archives(id TEXT PRIMARY KEY,archived_at TEXT NOT NULL,archive_batch TEXT NOT NULL);
|
| 42 |
CREATE TABLE IF NOT EXISTS audit_events(id TEXT PRIMARY KEY,created_at TEXT NOT NULL,action TEXT NOT NULL,payload TEXT NOT NULL);
|
| 43 |
''')
|
| 44 |
+
@contextmanager
|
| 45 |
def connect(self):
|
| 46 |
+
# Commit on success, roll back on error, and always close the file.
|
| 47 |
connection=sqlite3.connect(self.path,timeout=20)
|
| 48 |
connection.row_factory=sqlite3.Row
|
| 49 |
+
try:
|
| 50 |
+
with connection:
|
| 51 |
+
yield connection
|
| 52 |
+
finally:
|
| 53 |
+
connection.close()
|
| 54 |
def save(self,record):
|
| 55 |
with self.connect() as db:
|
| 56 |
db.execute('INSERT INTO inspections VALUES(?,?,?,?,?,?)',(record['id'],record['created_at'],record['category'],record['verdict'],record.get('batch',''),json.dumps(record)))
|