44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import Session
|
|
import logging
|
|
import os
|
|
from contextlib import contextmanager
|
|
|
|
|
|
# Configure logging
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Database configuration
|
|
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///database.db")
|
|
|
|
engine = create_engine(DATABASE_URL)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
Base = declarative_base()
|
|
|
|
def get_db():
|
|
"""Dependency to get a database session. Used for simple, single service operations."""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
@contextmanager
|
|
def transaction(db: Session):
|
|
"""Context manager to handle database transactions. Used for service operations that require multiple database operations."""
|
|
try:
|
|
yield
|
|
db.commit()
|
|
except Exception as e:
|
|
db.rollback()
|
|
# Reset the session state
|
|
db.expire_all()
|
|
raise e
|
|
|
|
def init_db():
|
|
Base.metadata.create_all(bind=engine)
|
|
|