|
| 1 | +from typing import List, Optional |
| 2 | +from uuid import UUID |
| 3 | + |
| 4 | +from app.core.exceptions import ApiException, NotFoundObjectMatchingUuid, create_error |
| 5 | +from app.db.database import get_db_session |
| 6 | +from app.models import Student |
| 7 | +from app.schemas import CreateStudentSchema, UpdateStudentSchema |
| 8 | +from sqlalchemy.orm import scoped_session |
| 9 | + |
| 10 | +from .base import BaseCRUD |
| 11 | + |
| 12 | +db_session = get_db_session() |
| 13 | + |
| 14 | + |
| 15 | +class StudentCRUD(BaseCRUD): |
| 16 | + def __init__(self, db_session: scoped_session): |
| 17 | + super().__init__(db_session, Student) |
| 18 | + |
| 19 | + def gets_by_student_sheet_uuid(self, student_sheet_uuid: UUID) -> List[Student]: |
| 20 | + return self.get_query().filter_by(student_sheet_uuid=student_sheet_uuid).all() |
| 21 | + |
| 22 | + def get_by_student_sheet_uuid_and_number( |
| 23 | + self, student_sheet_uuid: UUID, number: int |
| 24 | + ) -> Optional[Student]: |
| 25 | + return ( |
| 26 | + self.get_query() |
| 27 | + .filter_by(student_sheet_uuid=student_sheet_uuid, number=number) |
| 28 | + .first() |
| 29 | + ) |
| 30 | + |
| 31 | + def create(self, schema: CreateStudentSchema) -> Student: |
| 32 | + if ( |
| 33 | + self.get_by_student_sheet_uuid_and_number( |
| 34 | + schema.student_sheet_uuid, schema.number |
| 35 | + ) |
| 36 | + is not None |
| 37 | + ): |
| 38 | + raise ApiException( |
| 39 | + create_error( |
| 40 | + f"Student with number {schema.number} already exists in this student sheet." |
| 41 | + ) |
| 42 | + ) |
| 43 | + return super().create(schema.dict()) |
| 44 | + |
| 45 | + def update(self, uuid: UUID, schema: UpdateStudentSchema) -> Student: |
| 46 | + update_obj = self.get_by_uuid(uuid) |
| 47 | + if update_obj is None: |
| 48 | + raise ApiException(NotFoundObjectMatchingUuid(self.model, uuid)) |
| 49 | + |
| 50 | + new_data_obj = self.get_by_student_sheet_uuid_and_number( |
| 51 | + schema.student_sheet_uuid, schema.number |
| 52 | + ) |
| 53 | + if new_data_obj is not None and new_data_obj.uuid != update_obj.uuid: |
| 54 | + raise ApiException( |
| 55 | + create_error( |
| 56 | + f"Student with number {schema.number} already exists in this student sheet." |
| 57 | + ) |
| 58 | + ) |
| 59 | + return super().update(uuid, schema.dict()) |
0 commit comments