50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import sessionmaker, with_loader_criteria
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
from typing import Annotated
|
|
from fastapi import Depends
|
|
from sqlalchemy.orm import Session
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
load_dotenv()
|
|
|
|
engine = create_engine(os.getenv("DATABASE_URL", ""))
|
|
SessionLocal = sessionmaker(autoflush=False, bind=engine)
|
|
|
|
def safe_commit(db : Session):
|
|
try:
|
|
db.commit()
|
|
except SQLAlchemyError:
|
|
db.rollback()
|
|
raise
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
except Exception:
|
|
db.rollback()
|
|
raise
|
|
finally:
|
|
db.close()
|
|
|
|
@event.listens_for(SessionLocal, "do_orm_execute")
|
|
def _add_filtering_criterial(execute_state):
|
|
skip_filter = execute_state.execution_options.get("skip_filter", False)
|
|
|
|
if execute_state.is_select and not skip_filter:
|
|
|
|
from ..models.models import AuditMixin
|
|
|
|
execute_state.statement = execute_state.statement.options(
|
|
with_loader_criteria(
|
|
AuditMixin,
|
|
lambda cls: cls.is_archived.is_(False),
|
|
include_aliases = True,
|
|
)
|
|
)
|
|
|
|
db_dependency = Annotated[Session, Depends(get_db)]
|