- Replace minimal database.py with full SQLAlchemy async setup - Create Device and DeviceLog models with proper relationships - Add tests for model creation and relationship functionality - Fixed lazy loading issue in tests by avoiding .count() on dynamic relationships
33 lines
779 B
Python
33 lines
779 B
Python
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, async_session
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
from mqtt_home.config import get_settings
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
def get_engine():
|
|
settings = get_settings()
|
|
return create_async_engine(
|
|
settings.database_url,
|
|
echo=False,
|
|
)
|
|
|
|
|
|
def get_session_factory(engine=None):
|
|
_engine = engine or get_engine()
|
|
return async_sessionmaker(_engine, expire_on_commit=False)
|
|
|
|
|
|
async def init_db():
|
|
engine = get_engine()
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
await engine.dispose()
|
|
|
|
|
|
async def get_db():
|
|
factory = get_session_factory()
|
|
async with factory() as session:
|
|
yield session |