性能: SQLite WAL模式、aiohttp Session复用、TCP连接锁+空闲超时、 device_id缓存、WebSocket并发广播、API Key认证缓存、围栏N+1查询 批量化、逆地理编码并行化、新增5个DB索引、日志降级DEBUG 功能: 广播指令API(broadcast)、exclude_type低精度后端过滤、 前端设备总览Tab+多设备轨迹叠加+高亮联动+搜索+专属颜色 via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run>
62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
from sqlalchemy import event
|
|
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},
|
|
)
|
|
|
|
# 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()
|
|
|
|
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)
|