refactor: establish database migration foundation
This commit is contained in:
+5
-15
@@ -6,6 +6,8 @@ from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from backend.database import MIGRATIONS, MigrationRunner, SQLiteConnectionFactory
|
||||
|
||||
|
||||
def _optional_float(value: Any) -> float | None:
|
||||
if value in (None, ""):
|
||||
@@ -16,28 +18,15 @@ def _optional_float(value: Any) -> float | None:
|
||||
return None
|
||||
|
||||
|
||||
class ManagedConnection(sqlite3.Connection):
|
||||
"""Commit or roll back, then release the SQLite file handle on context exit."""
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
try:
|
||||
return super().__exit__(exc_type, exc_value, traceback)
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
|
||||
class ReviewDatabase:
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.connection_factory = SQLiteConnectionFactory(self.path)
|
||||
self._initialize()
|
||||
|
||||
def connect(self) -> sqlite3.Connection:
|
||||
connection = sqlite3.connect(self.path, timeout=20, factory=ManagedConnection)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
connection.execute("PRAGMA foreign_keys=ON")
|
||||
return connection
|
||||
return self.connection_factory.connect()
|
||||
|
||||
def _initialize(self) -> None:
|
||||
with self.connect() as connection:
|
||||
@@ -656,6 +645,7 @@ class ReviewDatabase:
|
||||
ON screener_runs(user_id, mode, trade_date DESC, id DESC)
|
||||
"""
|
||||
)
|
||||
MigrationRunner().apply(connection, MIGRATIONS)
|
||||
|
||||
def count_users(self) -> int:
|
||||
with self.connect() as connection:
|
||||
|
||||
Reference in New Issue
Block a user