You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.3 KiB
Python
53 lines
1.3 KiB
Python
"""
|
|
Database configuration and session management
|
|
"""
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from sqlalchemy.pool import NullPool
|
|
from app.core.config import settings
|
|
|
|
# Conditional engine settings based on database type
|
|
_is_sqlite = settings.DATABASE_URL.startswith("sqlite")
|
|
|
|
if _is_sqlite:
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DATABASE_ECHO,
|
|
future=True,
|
|
poolclass=NullPool,
|
|
)
|
|
else:
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DATABASE_ECHO,
|
|
future=True,
|
|
pool_size=10,
|
|
max_overflow=20,
|
|
pool_timeout=30,
|
|
pool_pre_ping=True,
|
|
pool_recycle=3600,
|
|
connect_args={
|
|
"server_settings": {
|
|
"jit": "off"
|
|
}
|
|
}
|
|
)
|
|
|
|
# Create async session factory
|
|
AsyncSessionLocal = sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False
|
|
)
|
|
|
|
# Create base class for models
|
|
Base = declarative_base()
|
|
|
|
# Dependency to get DB session
|
|
async def get_db():
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
finally:
|
|
await session.close() |