49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from sqlalchemy.orm import DeclarativeBase
|
|
from sqlalchemy import text
|
|
import structlog
|
|
|
|
from .config import settings
|
|
|
|
logger = structlog.get_logger()
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
engine = create_async_engine(
|
|
settings.database_url,
|
|
echo=settings.debug,
|
|
pool_pre_ping=True,
|
|
pool_recycle=300
|
|
)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False
|
|
)
|
|
|
|
async def get_db():
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
async def init_db():
|
|
try:
|
|
async with engine.begin() as conn:
|
|
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
|
|
logger.info("Database extensions initialized")
|
|
|
|
from ..models import user, application, job, document
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
logger.info("Database tables created")
|
|
|
|
except Exception as e:
|
|
logger.error("Database initialization failed", error=str(e))
|
|
raise |