2026-03-31 09:41:09 +00:00
|
|
|
from sqlalchemy import event
|
2026-03-27 10:19:34 +00:00
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
|
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
|
|
|
|
|
|
|
|
from app.config import settings
|
|
|
|
|
|
|
|
|
|
engine = create_async_engine(
|
|
|
|
|
settings.DATABASE_URL,
|
|
|
|
|
echo=settings.DEBUG,
|
|
|
|
|
connect_args={"check_same_thread": False},
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-31 09:41:09 +00:00
|
|
|
# Enable WAL mode for concurrent read/write performance
|
|
|
|
|
@event.listens_for(engine.sync_engine, "connect")
|
|
|
|
|
def _set_sqlite_pragma(dbapi_conn, connection_record):
|
|
|
|
|
cursor = dbapi_conn.cursor()
|
|
|
|
|
cursor.execute("PRAGMA journal_mode=WAL")
|
|
|
|
|
cursor.execute("PRAGMA synchronous=NORMAL")
|
|
|
|
|
cursor.execute("PRAGMA cache_size=-64000") # 64MB cache
|
|
|
|
|
cursor.execute("PRAGMA busy_timeout=5000") # 5s wait on lock
|
|
|
|
|
cursor.execute("PRAGMA foreign_keys=ON")
|
|
|
|
|
cursor.close()
|
|
|
|
|
|
2026-03-27 10:19:34 +00:00
|
|
|
async_session = async_sessionmaker(
|
|
|
|
|
bind=engine,
|
|
|
|
|
class_=AsyncSession,
|
|
|
|
|
expire_on_commit=False,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def get_db() -> AsyncSession:
|
|
|
|
|
"""Dependency injection for async database sessions."""
|
|
|
|
|
async with async_session() as session:
|
|
|
|
|
try:
|
|
|
|
|
yield session
|
|
|
|
|
await session.commit()
|
|
|
|
|
except Exception:
|
|
|
|
|
await session.rollback()
|
|
|
|
|
raise
|
|
|
|
|
finally:
|
|
|
|
|
await session.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def init_db() -> None:
|
|
|
|
|
"""Create all database tables."""
|
|
|
|
|
async with engine.begin() as conn:
|
|
|
|
|
from app.models import ( # noqa: F401
|
|
|
|
|
AlarmRecord,
|
|
|
|
|
AttendanceRecord,
|
|
|
|
|
BluetoothRecord,
|
|
|
|
|
CommandLog,
|
|
|
|
|
Device,
|
|
|
|
|
HeartbeatRecord,
|
|
|
|
|
LocationRecord,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
await conn.run_sync(Base.metadata.create_all)
|