refactor: migrate database to SQLModel and implement modular DB structure

This commit is contained in:
2026-04-09 16:43:30 -04:00
parent 1541b4b7e0
commit de84cc664f
16 changed files with 476 additions and 482 deletions

View File

@@ -0,0 +1,30 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy import create_engine
from sqlmodel import SQLModel
from pathlib import Path
# We need both sync and async engines for SQLite
# Sync for initialization (DDL) and async for standard queries
def get_async_engine(db_path: str):
# aiosqlite driver for async access
return create_async_engine(f"sqlite+aiosqlite:///{db_path}", echo=False, connect_args={"uri": True})
def get_sync_engine(db_path: str):
return create_engine(f"sqlite:///{db_path}", echo=False, connect_args={"uri": True})
def init_db(db_path: str):
"""Synchronously create all tables."""
engine = get_sync_engine(db_path)
# Ensure WAL mode is set
with engine.connect() as conn:
conn.exec_driver_sql("PRAGMA journal_mode=WAL")
conn.exec_driver_sql("PRAGMA synchronous=NORMAL")
SQLModel.metadata.create_all(engine)
async def get_session(engine) -> AsyncSession:
async_session = async_sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
async with async_session() as session:
yield session