|
1 | 1 | import inspect |
2 | | -from typing import TYPE_CHECKING, Any |
| 2 | +from typing import TYPE_CHECKING, Any, Generic, TypeVar |
3 | 3 |
|
4 | 4 | from fastapi_startkit.masoniteorm.expressions.expressions import ( |
5 | 5 | JoinClause, |
|
19 | 19 |
|
20 | 20 | if TYPE_CHECKING: |
21 | 21 | from fastapi_startkit.masoniteorm.connections.connection import Connection |
| 22 | + from fastapi_startkit.masoniteorm.models.model import Model |
22 | 23 |
|
| 24 | +TModel = TypeVar("TModel", bound="Model") |
23 | 25 |
|
24 | | -class QueryBuilder(EagerLoadMixin, SupportMixin): |
| 26 | + |
| 27 | +class QueryBuilder(EagerLoadMixin, SupportMixin, Generic[TModel]): |
25 | 28 | def __init__(self, connection: "Connection", grammar, processor): |
26 | 29 | super().__init__() |
27 | 30 | self.connection = connection |
@@ -84,26 +87,31 @@ def limit(self, limit: int) -> "QueryBuilder": |
84 | 87 | self._limit = limit |
85 | 88 | return self |
86 | 89 |
|
87 | | - async def find(self, primary_key: str | int, columns=None): |
| 90 | + async def find(self, primary_key: str | int, columns=None) -> "TModel | None": |
88 | 91 | return await self.where(self._model.__primary_key__, primary_key).first(columns) |
89 | 92 |
|
90 | | - async def find_or_fail(self, primary_key: str | int, columns=None): |
| 93 | + async def find_or_fail(self, primary_key: str | int, columns=None) -> "TModel": |
| 94 | + """Return the record matching ``primary_key``. |
| 95 | +
|
| 96 | + Raises: |
| 97 | + ModelNotFoundException: If no record matches ``primary_key``. |
| 98 | + """ |
91 | 99 | from fastapi_startkit.masoniteorm.exceptions import ModelNotFoundException |
92 | 100 |
|
93 | 101 | result = await self.find(primary_key, columns) |
94 | 102 | if result is None: |
95 | 103 | raise ModelNotFoundException(f"{type(self._model).__name__} with primary key {primary_key!r} not found.") |
96 | 104 | return result |
97 | 105 |
|
98 | | - async def first_or_fail(self, columns=None): |
| 106 | + async def first_or_fail(self, columns=None) -> "TModel": |
99 | 107 | from fastapi_startkit.masoniteorm.exceptions import ModelNotFoundException |
100 | 108 |
|
101 | 109 | result = await self.first(columns) |
102 | 110 | if result is None: |
103 | 111 | raise ModelNotFoundException(f"{type(self._model).__name__} not found.") |
104 | 112 | return result |
105 | 113 |
|
106 | | - async def first(self, columns=None): |
| 114 | + async def first(self, columns=None) -> "TModel | None": |
107 | 115 | if not columns: |
108 | 116 | columns = [] |
109 | 117 |
|
|
0 commit comments