70 lines
2.4 KiB
Python
70 lines
2.4 KiB
Python
from sqlalchemy import and_
|
|
from sqlalchemy.orm import selectinload
|
|
|
|
from models import Module, Attribute, AttributeLabel, module_attribute
|
|
from repositories.mixins import *
|
|
from schemas.module import UpdateModuleCommonInfoSchema
|
|
|
|
|
|
class ModuleRepository(
|
|
BaseRepository,
|
|
RepGetAllMixin[Module],
|
|
RepGetByIdMixin[Module],
|
|
RepUpdateMixin[Module, UpdateModuleCommonInfoSchema],
|
|
RepDeleteMixin[Module]
|
|
):
|
|
entity_class = Module
|
|
|
|
def _process_get_by_id_stmt(self, stmt: Select) -> Select:
|
|
return stmt.options(selectinload(Module.attributes).joinedload(Attribute.type))
|
|
|
|
async def get_by_ids(self, ids: list[int]) -> list[Module]:
|
|
stmt = select(Module).where(Module.id.in_(ids))
|
|
modules = await self.session.scalars(stmt)
|
|
return modules.all()
|
|
|
|
@staticmethod
|
|
def _get_stmt_modules_with_tuples() -> Select:
|
|
return (
|
|
select(Module, Attribute, AttributeLabel)
|
|
.join(
|
|
module_attribute,
|
|
Module.id == module_attribute.c.module_id,
|
|
isouter=True,
|
|
)
|
|
.join(
|
|
Attribute, module_attribute.c.attribute_id == Attribute.id, isouter=True
|
|
)
|
|
.join(
|
|
AttributeLabel,
|
|
and_(
|
|
Module.id == AttributeLabel.module_id,
|
|
Attribute.id == AttributeLabel.attribute_id,
|
|
),
|
|
isouter=True,
|
|
)
|
|
.where(Module.is_deleted.is_(False), Attribute.is_deleted.is_(False))
|
|
.order_by(Attribute.id)
|
|
)
|
|
|
|
async def get_with_attributes_as_tuples(
|
|
self,
|
|
) -> list[tuple[Module, Attribute, AttributeLabel]]:
|
|
stmt = self._get_stmt_modules_with_tuples()
|
|
return (await self.session.execute(stmt)).unique().all()
|
|
|
|
async def get_with_attributes_as_tuple_by_id(
|
|
self, pk: int
|
|
) -> list[tuple[Module, Attribute, AttributeLabel]]:
|
|
stmt = self._get_stmt_modules_with_tuples()
|
|
stmt = stmt.where(Module.id == pk)
|
|
return (await self.session.execute(stmt)).unique().all()
|
|
|
|
async def add_attribute_to_module(self, module: Module, attribute: Attribute):
|
|
module.attributes.append(attribute)
|
|
await self.session.commit()
|
|
|
|
async def delete_attribute_from_module(self, module: Module, attribute: Attribute):
|
|
module.attributes.remove(attribute)
|
|
await self.session.commit()
|