feat: implement OrganizationRepository with CRUD operations

This commit is contained in:
Artem Kashaev 2025-11-27 15:04:13 +05:00
parent 1ce5843436
commit 845737abca
1 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,49 @@
"""Organization repository for database operations."""
from __future__ import annotations
from collections.abc import Sequence
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.organization import Organization, OrganizationCreate
from app.models.organization_member import OrganizationMember
class OrganizationRepository:
"""Provides CRUD helpers for Organization model."""
def __init__(self, session: AsyncSession) -> None:
self._session = session
@property
def session(self) -> AsyncSession:
return self._session
async def list(self) -> Sequence[Organization]:
result = await self._session.scalars(select(Organization))
return result.all()
async def get_by_id(self, organization_id: int) -> Organization | None:
return await self._session.get(Organization, organization_id)
async def get_by_name(self, name: str) -> Organization | None:
stmt = select(Organization).where(Organization.name == name)
result = await self._session.scalars(stmt)
return result.first()
async def list_for_user(self, user_id: int) -> Sequence[Organization]:
stmt = (
select(Organization)
.join(OrganizationMember, OrganizationMember.organization_id == Organization.id)
.where(OrganizationMember.user_id == user_id)
.order_by(Organization.id)
)
result = await self._session.scalars(stmt)
return result.unique().all()
async def create(self, data: OrganizationCreate) -> Organization:
organization = Organization(name=data.name)
self._session.add(organization)
await self._session.flush()
return organization