3a97ca385a
Deploy / Deploy Staging (push) Failing after 1s
Deploy / Build Production Runtime Images (push) Has been skipped
Deploy / Deploy Production (push) Has been skipped
Deploy / Production Browser E2E (push) Has been skipped
CI/CD Pipeline / Validate Code Quality And Tests (push) Has been cancelled
CI/CD Pipeline / Validate Code Quality And Tests (pull_request) Failing after 1m0s
Tests / test (pull_request) Failing after 1m0s
Tests / lint (pull_request) Failing after 1m0s
50 lines
1.2 KiB
Python
50 lines
1.2 KiB
Python
"""Database session management and engine configuration.
|
|
|
|
统一使用 app.config 中的数据库配置,移除重复的 DatabaseSettings。
|
|
"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, Session
|
|
from contextlib import contextmanager
|
|
from typing import Generator
|
|
|
|
from app.config import settings
|
|
|
|
|
|
engine = create_engine(
|
|
settings.database_url,
|
|
pool_size=settings.DATABASE_POOL_SIZE,
|
|
max_overflow=settings.DATABASE_MAX_OVERFLOW,
|
|
pool_timeout=settings.DATABASE_POOL_TIMEOUT,
|
|
pool_recycle=settings.DATABASE_POOL_RECYCLE,
|
|
)
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
"""Dependency for getting database sessions."""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@contextmanager
|
|
def get_db_context() -> Generator[Session, None, None]:
|
|
"""Context manager for database sessions.
|
|
|
|
Usage:
|
|
with get_db_context() as db:
|
|
db.query(Model).all()
|
|
"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
db.commit()
|
|
except Exception:
|
|
db.rollback()
|
|
raise
|
|
finally:
|
|
db.close()
|