|
| 1 | +from typing import Any, Callable, List, Optional, Type, Union, Coroutine |
| 2 | + |
| 3 | +from fastapi import HTTPException |
| 4 | + |
| 5 | +from . import NOT_FOUND, CRUDGenerator, _utils |
| 6 | +from ._types import DEPENDENCIES, PAGINATION |
| 7 | +from ._types import PYDANTIC_SCHEMA as SCHEMA |
| 8 | + |
| 9 | +try: |
| 10 | + from asyncpg.exceptions import UniqueViolationError |
| 11 | + from gino import Gino |
| 12 | + from sqlalchemy.exc import IntegrityError |
| 13 | + from sqlalchemy.ext.declarative import DeclarativeMeta as Model |
| 14 | +except ImportError: |
| 15 | + Model: Any = None # type: ignore |
| 16 | + gino_installed = False |
| 17 | +else: |
| 18 | + gino_installed = True |
| 19 | + |
| 20 | +CALLABLE = Callable[..., Coroutine[Any, Any, Model]] |
| 21 | +CALLABLE_LIST = Callable[..., Coroutine[Any, Any, List[Model]]] |
| 22 | + |
| 23 | + |
| 24 | +class GinoCRUDRouter(CRUDGenerator[SCHEMA]): |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + schema: Type[SCHEMA], |
| 28 | + db_model: Model, |
| 29 | + db: "Gino", |
| 30 | + create_schema: Optional[Type[SCHEMA]] = None, |
| 31 | + update_schema: Optional[Type[SCHEMA]] = None, |
| 32 | + prefix: Optional[str] = None, |
| 33 | + tags: Optional[List[str]] = None, |
| 34 | + paginate: Optional[int] = None, |
| 35 | + get_all_route: Union[bool, DEPENDENCIES] = True, |
| 36 | + get_one_route: Union[bool, DEPENDENCIES] = True, |
| 37 | + create_route: Union[bool, DEPENDENCIES] = True, |
| 38 | + update_route: Union[bool, DEPENDENCIES] = True, |
| 39 | + delete_one_route: Union[bool, DEPENDENCIES] = True, |
| 40 | + delete_all_route: Union[bool, DEPENDENCIES] = True, |
| 41 | + **kwargs: Any |
| 42 | + ) -> None: |
| 43 | + assert gino_installed, "Gino must be installed to use the GinoCRUDRouter." |
| 44 | + |
| 45 | + self.db_model = db_model |
| 46 | + self.db = db |
| 47 | + self._pk: str = db_model.__table__.primary_key.columns.keys()[0] |
| 48 | + self._pk_type: type = _utils.get_pk_type(schema, self._pk) |
| 49 | + |
| 50 | + super().__init__( |
| 51 | + schema=schema, |
| 52 | + create_schema=create_schema, |
| 53 | + update_schema=update_schema, |
| 54 | + prefix=prefix or db_model.__tablename__, |
| 55 | + tags=tags, |
| 56 | + paginate=paginate, |
| 57 | + get_all_route=get_all_route, |
| 58 | + get_one_route=get_one_route, |
| 59 | + create_route=create_route, |
| 60 | + update_route=update_route, |
| 61 | + delete_one_route=delete_one_route, |
| 62 | + delete_all_route=delete_all_route, |
| 63 | + **kwargs |
| 64 | + ) |
| 65 | + |
| 66 | + def _get_all(self, *args: Any, **kwargs: Any) -> CALLABLE_LIST: |
| 67 | + async def route( |
| 68 | + pagination: PAGINATION = self.pagination, |
| 69 | + ) -> List[Model]: |
| 70 | + skip, limit = pagination.get("skip"), pagination.get("limit") |
| 71 | + |
| 72 | + db_models: List[Model] = ( |
| 73 | + await self.db_model.query.limit(limit).offset(skip).gino.all() |
| 74 | + ) |
| 75 | + return db_models |
| 76 | + |
| 77 | + return route |
| 78 | + |
| 79 | + def _get_one(self, *args: Any, **kwargs: Any) -> CALLABLE: |
| 80 | + async def route(item_id: self._pk_type) -> Model: # type: ignore |
| 81 | + model: Model = await self.db_model.get(item_id) |
| 82 | + |
| 83 | + if model: |
| 84 | + return model |
| 85 | + else: |
| 86 | + raise NOT_FOUND |
| 87 | + |
| 88 | + return route |
| 89 | + |
| 90 | + def _create(self, *args: Any, **kwargs: Any) -> CALLABLE: |
| 91 | + async def route( |
| 92 | + model: self.create_schema, # type: ignore |
| 93 | + ) -> Model: |
| 94 | + try: |
| 95 | + async with self.db.transaction(): |
| 96 | + db_model: Model = await self.db_model.create(**model.dict()) |
| 97 | + return db_model |
| 98 | + except (IntegrityError, UniqueViolationError): |
| 99 | + raise HTTPException(422, "Key already exists") |
| 100 | + |
| 101 | + return route |
| 102 | + |
| 103 | + def _update(self, *args: Any, **kwargs: Any) -> CALLABLE: |
| 104 | + async def route( |
| 105 | + item_id: self._pk_type, # type: ignore |
| 106 | + model: self.update_schema, # type: ignore |
| 107 | + ) -> Model: |
| 108 | + try: |
| 109 | + db_model: Model = await self._get_one()(item_id) |
| 110 | + async with self.db.transaction(): |
| 111 | + model = model.dict(exclude={self._pk}) |
| 112 | + await db_model.update(**model).apply() |
| 113 | + |
| 114 | + return db_model |
| 115 | + except (IntegrityError, UniqueViolationError) as e: |
| 116 | + raise HTTPException(422, ", ".join(e.args)) |
| 117 | + |
| 118 | + return route |
| 119 | + |
| 120 | + def _delete_all(self, *args: Any, **kwargs: Any) -> CALLABLE_LIST: |
| 121 | + async def route() -> List[Model]: |
| 122 | + await self.db_model.delete.gino.status() |
| 123 | + return await self._get_all()(pagination={"skip": 0, "limit": None}) |
| 124 | + |
| 125 | + return route |
| 126 | + |
| 127 | + def _delete_one(self, *args: Any, **kwargs: Any) -> CALLABLE: |
| 128 | + async def route(item_id: self._pk_type) -> Model: # type: ignore |
| 129 | + db_model: Model = await self._get_one()(item_id) |
| 130 | + await db_model.delete() |
| 131 | + |
| 132 | + return db_model |
| 133 | + |
| 134 | + return route |
0 commit comments