feat: database setup with SQLAlchemy ORM models for Device and DeviceLog
- 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
This commit is contained in:
@@ -1,5 +1,33 @@
|
||||
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
|
||||
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
|
||||
Reference in New Issue
Block a user