35 lines
1001 B
Python
35 lines
1001 B
Python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from sqlalchemy.orm import declarative_base
|
|
from app.core.config import settings
|
|
|
|
# Configure async engine
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=False,
|
|
future=True,
|
|
# SQLite-specific optimization if running SQLite
|
|
connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {}
|
|
)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autoflush=False
|
|
)
|
|
|
|
Base = declarative_base()
|
|
|
|
async def get_db():
|
|
"""FastAPI dependency for obtaining async database sessions."""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
finally:
|
|
await session.close()
|
|
|
|
async def init_db():
|
|
"""Initializes database tables if they do not already exist."""
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|