Spaces:
Sleeping
Sleeping
| """ | |
| Database configuration for SQLite with SQLAlchemy. | |
| """ | |
| from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker | |
| from sqlalchemy.orm import DeclarativeBase | |
| import os | |
| # Database URL - SQLite file in the same directory | |
| DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///./blink_data.db") | |
| # Create async engine | |
| engine = create_async_engine( | |
| DATABASE_URL, | |
| echo=False, # Set to True for SQL debugging | |
| future=True | |
| ) | |
| # Session factory | |
| async_session_maker = async_sessionmaker( | |
| engine, | |
| class_=AsyncSession, | |
| expire_on_commit=False | |
| ) | |
| class Base(DeclarativeBase): | |
| """Base class for SQLAlchemy models.""" | |
| pass | |
| async def get_db() -> AsyncSession: | |
| """ | |
| Dependency injection for database sessions. | |
| Yields a database session and ensures cleanup. | |
| """ | |
| async with async_session_maker() as session: | |
| try: | |
| yield session | |
| finally: | |
| await session.close() | |
| async def init_db(): | |
| """ | |
| Initialize the database by creating all tables. | |
| """ | |
| async with engine.begin() as conn: | |
| await conn.run_sync(Base.metadata.create_all) | |