Initial commit: migrate badge-admin from /tmp to /home/gpsystem
via HAPI (https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run>
This commit is contained in:
49
app/database.py
Normal file
49
app/database.py
Normal file
@@ -0,0 +1,49 @@
|
||||
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},
|
||||
)
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user