README / fastapi-backend /app /database.py
TonyMoralist's picture
Upload 55 files
5c1ff2b verified
Raw History Blame Contribute Delete
1.02 kB
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from app.config import settings
import os
# Use SQLite for local testing without Docker
if settings.USE_SQLITE.lower() == "true":
# SQLite file path relative to the backend directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SQLITE_DB_PATH = os.path.join(BASE_DIR, "chatbot.db")
DATABASE_URL = f"sqlite+aiosqlite:///{SQLITE_DB_PATH}"
else:
DATABASE_URL = settings.DATABASE_URL
engine = create_async_engine(DATABASE_URL, echo=settings.DEBUG)
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
Base = declarative_base()
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()