pratikbackend / app /core /database.py
Antaram's picture
Upload 96 files
7647b38 verified
Raw
History Blame Contribute Delete
1.85 kB
"""
Database Configuration
Async SQLAlchemy engine with PostgreSQL support
Unicode support for Marathi text
"""
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy import MetaData
from .config import settings
# Naming convention for constraints
convention = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention=convention)
class Base(DeclarativeBase):
"""Base class for all models"""
metadata = metadata
# Create async engine with PostgreSQL support
engine = create_async_engine(
settings.DATABASE_URL,
echo=False, # Disable SQL logging
pool_size=5, # Number of connections to keep in pool
max_overflow=10, # Max additional connections beyond pool_size
pool_pre_ping=True, # Verify connections before using
pool_recycle=3600, # Recycle connections after 1 hour
)
# Async session factory
async_session = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False
)
async def get_db() -> AsyncSession:
"""Dependency to get database session"""
async with async_session() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def init_db():
"""Initialize database tables"""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def close_db():
"""Close database connections"""
await engine.dispose()