|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +from typing import Any, Generic, Sequence, Type, TypeVar |
| 4 | + |
| 5 | +from pydantic import BaseModel |
| 6 | +from sqlalchemy import Row, RowMapping, select |
| 7 | +from sqlalchemy import delete as sa_delete |
| 8 | +from sqlalchemy import update as sa_update |
| 9 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 10 | + |
| 11 | +from sqlalchemy_crud_plus.errors import ModelColumnError |
| 12 | + |
| 13 | +_Model = TypeVar('_Model') |
| 14 | +_CreateSchema = TypeVar('_CreateSchema', bound=BaseModel) |
| 15 | +_UpdateSchema = TypeVar('_UpdateSchema', bound=BaseModel) |
| 16 | + |
| 17 | + |
| 18 | +class CRUDPlus(Generic[_Model]): |
| 19 | + def __init__(self, model: Type[_Model]): |
| 20 | + self.model = model |
| 21 | + |
| 22 | + async def create_model(self, session: AsyncSession, obj: _CreateSchema, **kwargs) -> None: |
| 23 | + """ |
| 24 | + Create a new instance of a model |
| 25 | +
|
| 26 | + :param session: |
| 27 | + :param obj: |
| 28 | + :param kwargs: |
| 29 | + :return: |
| 30 | + """ |
| 31 | + if kwargs: |
| 32 | + instance = self.model(**obj.model_dump(), **kwargs) |
| 33 | + else: |
| 34 | + instance = self.model(**obj.model_dump()) |
| 35 | + session.add(instance) |
| 36 | + |
| 37 | + async def select_model_by_id(self, session: AsyncSession, pk: int) -> _Model | None: |
| 38 | + """ |
| 39 | + Query by ID |
| 40 | +
|
| 41 | + :param session: |
| 42 | + :param pk: |
| 43 | + :return: |
| 44 | + """ |
| 45 | + query = await session.execute(select(self.model).where(self.model.id == pk)) |
| 46 | + return query.scalars().first() |
| 47 | + |
| 48 | + async def select_model_by_column(self, session: AsyncSession, column: str, column_value: Any) -> _Model | None: |
| 49 | + """ |
| 50 | + Query by column |
| 51 | +
|
| 52 | + :param session: |
| 53 | + :param column: |
| 54 | + :param column_value: |
| 55 | + :return: |
| 56 | + """ |
| 57 | + if hasattr(self.model, column): |
| 58 | + model_column = getattr(self.model, column) |
| 59 | + query = await session.execute(select(self.model).where(model_column == column_value)) # type: ignore |
| 60 | + return query.scalars().first() |
| 61 | + else: |
| 62 | + raise ModelColumnError('Model column not found') |
| 63 | + |
| 64 | + async def select_models(self, session: AsyncSession) -> Sequence[Row | RowMapping | Any] | None: |
| 65 | + """ |
| 66 | + Query all rows |
| 67 | +
|
| 68 | + :param session: |
| 69 | + :return: |
| 70 | + """ |
| 71 | + query = await session.execute(select(self.model)) |
| 72 | + return query.scalars().all() |
| 73 | + |
| 74 | + async def update_model(self, session: AsyncSession, pk: int, obj: _UpdateSchema | dict[str, Any], **kwargs) -> int: |
| 75 | + """ |
| 76 | + Update an instance of a model |
| 77 | +
|
| 78 | + :param session: |
| 79 | + :param pk: |
| 80 | + :param obj: |
| 81 | + :param kwargs: |
| 82 | + :return: |
| 83 | + """ |
| 84 | + if isinstance(obj, dict): |
| 85 | + instance_data = obj |
| 86 | + else: |
| 87 | + instance_data = obj.model_dump(exclude_unset=True) |
| 88 | + if kwargs: |
| 89 | + instance_data.update(kwargs) |
| 90 | + result = await session.execute(sa_update(self.model).where(self.model.id == pk).values(**instance_data)) |
| 91 | + return result.rowcount # type: ignore |
| 92 | + |
| 93 | + async def delete_model(self, session: AsyncSession, pk: int, **kwargs) -> int: |
| 94 | + """ |
| 95 | + Delete an instance of a model |
| 96 | +
|
| 97 | + :param session: |
| 98 | + :param pk: |
| 99 | + :param kwargs: |
| 100 | + :return: |
| 101 | + """ |
| 102 | + if not kwargs: |
| 103 | + result = await session.execute(sa_delete(self.model).where(self.model.id == pk)) |
| 104 | + else: |
| 105 | + result = await session.execute(sa_update(self.model).where(self.model.id == pk).values(**kwargs)) |
| 106 | + return result.rowcount # type: ignore |
0 commit comments