37 lines
826 B
Python
37 lines
826 B
Python
"""Database connection and session management."""
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from .config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
# Create engine with connection pooling
|
|
engine = create_engine(
|
|
settings.database_url,
|
|
pool_pre_ping=True,
|
|
pool_recycle=3600,
|
|
echo=False # Set to True for SQL debugging
|
|
)
|
|
|
|
# Session factory
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Base class for models
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""Dependency for getting database session."""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""Initialize database tables."""
|
|
from . import models # noqa: F401
|
|
Base.metadata.create_all(bind=engine)
|