46 lines
927 B
Python
46 lines
927 B
Python
from collections.abc import Generator
|
|
|
|
from sqlalchemy import create_engine, text
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
try:
|
|
# For module mode: `uvicorn app.main:app`
|
|
from app.settings import settings
|
|
except ModuleNotFoundError:
|
|
# For script mode: `python app/main.py` or VS Code "Run Python File"
|
|
from settings import settings
|
|
|
|
|
|
engine = create_engine(
|
|
settings.mysql_dsn,
|
|
pool_size=5,
|
|
max_overflow=10,
|
|
pool_pre_ping=True,
|
|
pool_recycle=1800,
|
|
future=True,
|
|
)
|
|
|
|
SessionLocal = sessionmaker(
|
|
bind=engine,
|
|
autocommit=False,
|
|
autoflush=False,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def check_db_connection() -> None:
|
|
with engine.connect() as conn:
|
|
conn.execute(text("SELECT 1"))
|
|
|
|
|
|
def close_db_engine() -> None:
|
|
engine.dispose()
|