31 lines
694 B
Python
31 lines
694 B
Python
|
|
"""
|
||
|
|
Database connections and init
|
||
|
|
|
||
|
|
Exports:
|
||
|
|
- db_dependency
|
||
|
|
- Base (sqlalchemy base model)
|
||
|
|
"""
|
||
|
|
from typing import Annotated
|
||
|
|
from sqlalchemy import create_engine
|
||
|
|
from sqlalchemy.orm import declarative_base, sessionmaker, Session
|
||
|
|
|
||
|
|
from fastapi import Depends
|
||
|
|
|
||
|
|
from src.config import SQLALCHEMY_DATABASE_URI
|
||
|
|
|
||
|
|
engine = create_engine(SQLALCHEMY_DATABASE_URI.get_secret_value())
|
||
|
|
|
||
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||
|
|
|
||
|
|
def get_db():
|
||
|
|
with SessionLocal.begin() as db:
|
||
|
|
try:
|
||
|
|
yield db
|
||
|
|
finally:
|
||
|
|
db.rollback() # Anything not explicitly commited is rolled back
|
||
|
|
db.close()
|
||
|
|
|
||
|
|
|
||
|
|
db_dependency = Annotated[Session, Depends(get_db)]
|
||
|
|
Base = declarative_base()
|