Files
member-backend/app/repositories/member_organizations_repo.py

44 lines
1.6 KiB
Python

from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from app.models.member_organization import MemberOrganization
from app.models.organization import Organization
class MemberOrganizationsRepository:
def __init__(self, db: Session) -> None:
self.db = db
def list_organizations_by_member_id(self, member_id: str) -> list[Organization]:
stmt = (
select(Organization)
.join(MemberOrganization, MemberOrganization.organization_id == Organization.id)
.where(MemberOrganization.member_id == member_id)
.order_by(Organization.name.asc())
)
return list(self.db.scalars(stmt).all())
def add_if_not_exists(self, member_id: str, organization_id: str) -> MemberOrganization:
stmt = select(MemberOrganization).where(
MemberOrganization.member_id == member_id,
MemberOrganization.organization_id == organization_id,
)
existing = self.db.scalar(stmt)
if existing:
return existing
relation = MemberOrganization(member_id=member_id, organization_id=organization_id)
self.db.add(relation)
self.db.commit()
self.db.refresh(relation)
return relation
def remove(self, member_id: str, organization_id: str) -> int:
stmt = delete(MemberOrganization).where(
MemberOrganization.member_id == member_id,
MemberOrganization.organization_id == organization_id,
)
result = self.db.execute(stmt)
self.db.commit()
return int(result.rowcount or 0)