apigateway / core /database.py
jebin2's picture
cors
178694a
"""
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)