Spaces:
Sleeping
Sleeping
File size: 1,311 Bytes
c05ab2d dbadc79 e4273eb 178694a dbadc79 c05ab2d dbadc79 c05ab2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
"""
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 configuration
DB_NAME = os.getenv("DB_NAME", "apigateway")
ENV = os.getenv("ENVIRONMENT", "production")
DB_FILENAME = f"{DB_NAME}_{ENV}.db"
# Database URL - SQLite file in the same directory
DATABASE_URL = os.getenv("DATABASE_URL", f"sqlite+aiosqlite:///./{DB_FILENAME}")
# 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)
|