Files
you-music/backend/app/db/session.py
T
2025-11-07 12:28:28 +11:00

56 lines
1.7 KiB
Python

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from sqlalchemy.pool import NullPool
from sqlalchemy import text
from app.core.config import settings
# SQLite-specific connection arguments to handle concurrency
connect_args = {
"timeout": 30, # Wait up to 30 seconds for lock
"check_same_thread": False, # Allow usage across threads
}
engine = create_async_engine(
settings.DATABASE_URL,
echo=False,
future=True,
connect_args=connect_args,
poolclass=NullPool, # Disable connection pooling for SQLite to avoid locks
pool_pre_ping=True, # Verify connections before using
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
)
# Alias for compatibility
async_session_maker = AsyncSessionLocal
Base = declarative_base()
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def init_db():
"""Initialize database connection pool
Note: Table creation is handled by Alembic migrations.
This function just ensures the connection pool is ready and enables WAL mode.
"""
# Enable WAL mode for better concurrency with SQLite
async with engine.begin() as conn:
# Enable Write-Ahead Logging for better concurrent access
await conn.execute(text("PRAGMA journal_mode=WAL"))
# Set synchronous mode to NORMAL for better performance
await conn.execute(text("PRAGMA synchronous=NORMAL"))
# Increase busy timeout
await conn.execute(text("PRAGMA busy_timeout=30000"))