FastSpine 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. fastspine/__init__.py +48 -0
  2. fastspine/abstract/owner_base.py +16 -0
  3. fastspine/alembic/__init__.py +4 -0
  4. fastspine/alembic/alembic.py +95 -0
  5. fastspine/alembic/config.py +40 -0
  6. fastspine/boostrap.py +78 -0
  7. fastspine/cache/cache_decorater.py +264 -0
  8. fastspine/cache/cache_encoder.py +87 -0
  9. fastspine/cache/cache_exception.py +4 -0
  10. fastspine/cache/cache_model.py +32 -0
  11. fastspine/cache/cache_service.py +144 -0
  12. fastspine/cache/key_builder.py +134 -0
  13. fastspine/cache/redis_cache.py +158 -0
  14. fastspine/celery/base_task.py +106 -0
  15. fastspine/celery/engine.py +52 -0
  16. fastspine/cli/scoped_typer.py +47 -0
  17. fastspine/ctx/ctx_pool.py +73 -0
  18. fastspine/database/engine.py +131 -0
  19. fastspine/decorators/contextualize_decorator.py +54 -0
  20. fastspine/decorators/retry_decorator.py +66 -0
  21. fastspine/decorators/upsert_decorator.py +107 -0
  22. fastspine/dependencies/database.py +193 -0
  23. fastspine/dependencies/profiler.py +37 -0
  24. fastspine/dependencies/repository_manager.py +202 -0
  25. fastspine/dependencies/services.py +140 -0
  26. fastspine/exception/access_exception.py +13 -0
  27. fastspine/exception/action_not_allowed_exception.py +13 -0
  28. fastspine/exception/base_app_exception.py +28 -0
  29. fastspine/exception/exception_handler.py +9 -0
  30. fastspine/exception/not_found_exception.py +13 -0
  31. fastspine/exception/security_exception.py +13 -0
  32. fastspine/exception/soft_delete_exception.py +13 -0
  33. fastspine/lib/__init__.py +4 -0
  34. fastspine/lib/contextualize.py +352 -0
  35. fastspine/lib/profiler.py +284 -0
  36. fastspine/mailer/mailer_service.py +44 -0
  37. fastspine/middleware/request_middleware.py +67 -0
  38. fastspine/middleware/session_middleware.py +38 -0
  39. fastspine/mixins/__init__.py +4 -0
  40. fastspine/mixins/representable.py +12 -0
  41. fastspine/mixins/soft_delete.py +41 -0
  42. fastspine/mixins/timestamps.py +35 -0
  43. fastspine/models/base.py +18 -0
  44. fastspine/redis/client.py +23 -0
  45. fastspine/repositories/abstract_repository.py +267 -0
  46. fastspine/repositories/base_repository.py +422 -0
  47. fastspine/repositories/external_base_repository.py +12 -0
  48. fastspine/repositories/repository_manager.py +101 -0
  49. fastspine/schemas/pagination_model.py +26 -0
  50. fastspine/services/api_service.py +292 -0
  51. fastspine/services/base_service.py +18 -0
  52. fastspine/settings/__init__.py +74 -0
  53. fastspine/settings/app_settings.py +5 -0
  54. fastspine/settings/cache_settings.py +32 -0
  55. fastspine/settings/celery_settings.py +10 -0
  56. fastspine/settings/mailer_settings.py +12 -0
  57. fastspine/settings/profiler_settings.py +10 -0
  58. fastspine/types/__init__.py +3 -0
  59. fastspine/types/types.py +6 -0
  60. fastspine/util/class_util.py +110 -0
  61. fastspine/util/conversion.py +37 -0
  62. fastspine/util/dataframe_util.py +30 -0
  63. fastspine/util/dates.py +34 -0
  64. fastspine/util/debug_util.py +29 -0
  65. fastspine/util/emails.py +14 -0
  66. fastspine/util/files.py +29 -0
  67. fastspine/util/math.py +3 -0
  68. fastspine-1.0.0.dist-info/METADATA +372 -0
  69. fastspine-1.0.0.dist-info/RECORD +71 -0
  70. fastspine-1.0.0.dist-info/WHEEL +4 -0
  71. fastspine-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,422 @@
1
+ from abc import ABC
2
+ from typing import final
3
+
4
+ from sqlalchemy import delete, func, select
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+ from sqlalchemy.sql.elements import BinaryExpression
7
+
8
+ from ..lib.profiler import Profiler
9
+ from ..mixins import SoftDeleteMixin
10
+ from ..models.base import Base as BaseModel
11
+ from ..repositories.abstract_repository import AbstractRepository
12
+ from ..types import DBSessions
13
+
14
+
15
+ class BaseRepository[T: BaseModel](AbstractRepository, ABC):
16
+ """Base repository class for database operations.
17
+
18
+ This class provides a common interface for all repository classes.
19
+ Use this class as a base for creating specific repositories.
20
+ Only for sqlalchemy ORM.
21
+
22
+ Attributes:
23
+ db (Session): The database session used for database operations.
24
+ profiler (Profiler): The profiler instance for performance tracking.
25
+ """
26
+
27
+ def __init__(self, db: DBSessions, profiler: Profiler):
28
+ """Initialize the repository with a database session and profiler.
29
+
30
+ Args:
31
+ db (Session): The database session used for database operations.
32
+ profiler (Profiler): The profiler instance for performance tracking.
33
+ """
34
+ super().__init__(db, profiler)
35
+ self.model = self.get_model()
36
+
37
+ @final
38
+ def get_model(self) -> type[T]:
39
+ """Get the model class associated with this repository.
40
+
41
+ Returns:
42
+ type[T]: The model class associated with this repository.
43
+
44
+ Raises:
45
+ ValueError: If the repository does not inherit with a model type parameter.
46
+ """
47
+ try:
48
+ if hasattr(self.__class__, "__orig_bases__"):
49
+ return self.__class__.__orig_bases__[0].__args__[0]
50
+
51
+ raise AttributeError("No __orig_bases__ found")
52
+ except (AttributeError, IndexError) as err:
53
+ raise ValueError("Repository {self.__class__} must inherit with model type parameter") from err
54
+
55
+ def sync_get_by_id(self, instance_id: int) -> T | None:
56
+ """Get an object by its ID.
57
+
58
+ Args:
59
+ instance_id (int): The ID of the object to retrieve.
60
+
61
+ Returns:
62
+ T: The object with the given ID, or None if it does not exist.
63
+ """
64
+ if issubclass(self.model, SoftDeleteMixin):
65
+ return (
66
+ self.db.query(self.model)
67
+ .filter(self.model.id == instance_id, self.model.deleted_at.is_(None)) # type: ignore[attr-defined]
68
+ .one_or_none()
69
+ )
70
+ return self.db.query(self.model).filter(self.model.id == instance_id).one_or_none()
71
+
72
+ def sync_get_instance(self, instance_id: int) -> T:
73
+ """Get an object by its ID.
74
+
75
+ Args:
76
+ instance_id (int): The ID of the object to retrieve.
77
+
78
+ Returns:
79
+ T: The object with the given ID, or None if it does not exist.
80
+ """
81
+ instance = self.sync_get_by_id(instance_id)
82
+ if instance is None:
83
+ raise ValueError(f"{self.model.__name__} with id {instance_id} does not exist.")
84
+ return instance
85
+
86
+ def sync_get(self, instance_id: int) -> T | None:
87
+ """Get an object by its ID.
88
+
89
+ Args:
90
+ instance_id (int): The ID of the object to retrieve.
91
+
92
+ Returns:
93
+ T: The object with the given ID, or None if it does not exist.
94
+ """
95
+ return self.db.get(self.model, instance_id)
96
+
97
+ def sync_read_commit(self) -> None:
98
+ """Check if there are some changed/deleted or new objects and it there are no perform commit."""
99
+ if self.db.new or self.db.dirty or self.db.deleted:
100
+ raise ValueError(
101
+ "There are some changes in the database session, please commit or rollback before read commit."
102
+ )
103
+ return self.db.commit()
104
+
105
+ def sync_commit(self):
106
+ """Commit the current transaction."""
107
+ self.db.commit()
108
+
109
+ def sync_soft_delete(self, instance: T, commit: bool = True) -> None:
110
+ """Soft delete an object by setting its deleted_at field to the current time.
111
+
112
+ Args:
113
+ instance (T): The object to soft delete.
114
+ commit (bool): Whether to commit the transaction after the operation.
115
+ """
116
+ if not isinstance(instance, SoftDeleteMixin):
117
+ raise TypeError(f"{instance.__class__.__name__} does not support soft deletion.")
118
+
119
+ instance.set_deleted()
120
+ self.db.add(instance)
121
+ if commit:
122
+ self.sync_commit()
123
+
124
+ def sync_delete(self, instance: T, commit: bool = True) -> None:
125
+ """Delete an object from the database.
126
+
127
+ Args:
128
+ instance (T): The object to delete.
129
+ """
130
+ self.db.delete(instance)
131
+ if commit:
132
+ self.sync_commit()
133
+
134
+ def sync_bulk_delete(self, ids: list[int], commit: bool = True) -> None:
135
+ """Bulk delete objects by their IDs."""
136
+ if issubclass(self.model, SoftDeleteMixin):
137
+ raise TypeError(f"{self.model.__name__} does not support bulk deletion use bulk soft delete instead.")
138
+ self.db.query(self.model).filter(self.model.id.in_(ids)).delete()
139
+
140
+ if commit:
141
+ self.sync_commit()
142
+
143
+ def sync_bulk_soft_delete(self, ids: list[int], commit: bool = True) -> None:
144
+ """Bulk soft delete objects by their IDs."""
145
+ if not issubclass(self.model, SoftDeleteMixin):
146
+ raise TypeError(f"{self.model.__name__} does not support bulk soft deletion.")
147
+
148
+ instances = self.db.query(self.model).filter(self.model.id.in_(ids)).all() # type: ignore[attr-defined]
149
+ for instance in instances:
150
+ instance.set_deleted()
151
+ self.db.add(instance)
152
+
153
+ if commit:
154
+ self.sync_commit()
155
+
156
+ def sync_count_by(self, *criterion: BinaryExpression | list[BinaryExpression]) -> int:
157
+ """Count objects by given criteria."""
158
+ filters = []
159
+ # If there's one argument and it's a list, unpack it
160
+ if len(criterion) == 1 and isinstance(criterion[0], list):
161
+ filters = criterion[0]
162
+ else:
163
+ filters = list(criterion)
164
+ if issubclass(self.model, SoftDeleteMixin):
165
+ filters.append(self.model.deleted_at.is_(None))
166
+
167
+ return self.db.query(self.model).filter(*filters).count()
168
+
169
+ def sync_filter_by(self, *criterion: BinaryExpression | list[BinaryExpression]) -> list[T]:
170
+ """Filter objects by given criteria."""
171
+ filters = []
172
+ # If there's one argument and it's a list, unpack it
173
+ if len(criterion) == 1 and isinstance(criterion[0], list):
174
+ filters = criterion[0]
175
+ else:
176
+ filters = list(criterion)
177
+
178
+ return self.db.query(self.model).filter(*filters).all()
179
+
180
+ def sync_filter_one_by(self, *criterion: BinaryExpression | list[BinaryExpression]) -> T | None:
181
+ """Filter objects by given criteria and return one result."""
182
+ filters = []
183
+ # If there's one argument and it's a list, unpack it
184
+ if len(criterion) == 1 and isinstance(criterion[0], list):
185
+ filters = criterion[0]
186
+ else:
187
+ filters = list(criterion)
188
+ if issubclass(self.model, SoftDeleteMixin):
189
+ filters.append(self.model.deleted_at.is_(None))
190
+
191
+ return self.db.query(self.model).filter(*filters).one_or_none()
192
+
193
+ def sync_filter_one(self, **kwargs) -> T | None:
194
+ """Filter objects by given criteria and return one result."""
195
+ if issubclass(self.model, SoftDeleteMixin):
196
+ kwargs["deleted_at"] = None
197
+ return self.db.query(self.model).filter_by(**kwargs).one_or_none()
198
+
199
+ def sync_create(self, instance: T, flush: bool = True, commit: bool = False) -> T:
200
+ """Create a new object in the database.
201
+
202
+ Args:
203
+ instance (T): The object to create.
204
+
205
+ Returns:
206
+ T: The created object.
207
+ """
208
+ self.db.add(instance)
209
+ if flush:
210
+ self.db.flush()
211
+ if commit:
212
+ self.sync_commit()
213
+
214
+ return instance
215
+
216
+ async def get(self, instance_id: int) -> T | None:
217
+ """Async get an object by its ID.
218
+
219
+ Args:
220
+ instance_id (int): The ID of the object to retrieve.
221
+
222
+ Returns:
223
+ T: The object with the given ID, or None if it does not exist.
224
+ """
225
+ if not isinstance(self.db, AsyncSession):
226
+ raise TypeError("aget async method requires AsyncSession")
227
+ return await self.db.get(self.model, instance_id)
228
+
229
+ async def commit(self):
230
+ """Async commit the current transaction."""
231
+ if not isinstance(self.db, AsyncSession):
232
+ raise TypeError("commit async method requires AsyncSession")
233
+ await self.db.commit()
234
+
235
+ async def read_commit(self) -> None:
236
+ """Async check if there are some changed/deleted or new objects and if there are none perform commit."""
237
+ if not isinstance(self.db, AsyncSession):
238
+ raise TypeError("aread_commit async method requires AsyncSession")
239
+ if self.db.new or self.db.dirty or self.db.deleted:
240
+ raise ValueError(
241
+ "There are some changes in the database session, please commit or rollback before read commit."
242
+ )
243
+ return await self.db.commit()
244
+
245
+ async def rollback(self):
246
+ """Async rollback the current transaction."""
247
+ if not isinstance(self.db, AsyncSession):
248
+ raise TypeError("rollback async method requires AsyncSession")
249
+ await self.db.rollback()
250
+
251
+ async def flush(self):
252
+ """Async flush the current transaction."""
253
+ if not isinstance(self.db, AsyncSession):
254
+ raise TypeError("flush async method requires AsyncSession")
255
+ await self.db.flush()
256
+
257
+ async def get_by_id(self, instance_id: int) -> T | None:
258
+ """Async get an object by its ID.
259
+
260
+ Args:
261
+ instance_id (int): The ID of the object to retrieve.
262
+
263
+ Returns:
264
+ T: The object with the given ID, or None if it does not exist.
265
+ """
266
+ if not isinstance(self.db, AsyncSession):
267
+ raise TypeError("aget_by_id async method requires AsyncSession")
268
+
269
+ if issubclass(self.model, SoftDeleteMixin):
270
+ result = await self.db.execute(
271
+ select(self.model).filter(self.model.id == instance_id, self.model.deleted_at.is_(None)) # type: ignore[attr-defined]
272
+ )
273
+ return result.scalar_one_or_none()
274
+
275
+ result = await self.db.execute(select(self.model).filter(self.model.id == instance_id))
276
+ return result.scalar_one_or_none()
277
+
278
+ async def get_instance(self, instance_id: int) -> T:
279
+ """Async get an object by its ID.
280
+
281
+ Args:
282
+ instance_id (int): The ID of the object to retrieve.
283
+
284
+ Returns:
285
+ T: The object with the given ID.
286
+
287
+ Raises:
288
+ ValueError: If the object does not exist.
289
+ """
290
+ instance = await self.get_by_id(instance_id)
291
+ if instance is None:
292
+ raise ValueError(f"{self.model.__name__} with id {instance_id} does not exist.")
293
+ return instance
294
+
295
+ async def soft_delete(self, instance: T, commit: bool = True) -> None:
296
+ """Async soft delete an object by setting its deleted_at field to the current time.
297
+
298
+ Args:
299
+ instance (T): The object to soft delete.
300
+ commit (bool): Whether to commit the transaction after the operation.
301
+ """
302
+ if not isinstance(self.db, AsyncSession):
303
+ raise TypeError("soft_delete async method requires AsyncSession")
304
+
305
+ if not isinstance(instance, SoftDeleteMixin):
306
+ raise TypeError(f"{instance.__class__.__name__} does not support soft deletion.")
307
+
308
+ instance.set_deleted()
309
+ self.db.add(instance)
310
+ if commit:
311
+ await self.commit()
312
+
313
+ async def bulk_soft_delete(self, ids: list[int], commit: bool = True) -> None:
314
+ """Async bulk soft delete objects by their IDs."""
315
+ if not isinstance(self.db, AsyncSession):
316
+ raise TypeError("bulk_soft_delete async method requires AsyncSession")
317
+
318
+ if not issubclass(self.model, SoftDeleteMixin):
319
+ raise TypeError(f"{self.model.__name__} does not support bulk soft deletion.")
320
+
321
+ result = await self.db.execute(select(self.model).filter(self.model.id.in_(ids))) # type: ignore[attr-defined]
322
+ instances = result.scalars().all()
323
+ for instance in instances:
324
+ instance.set_deleted()
325
+ self.db.add(instance)
326
+
327
+ if commit:
328
+ await self.commit()
329
+
330
+ async def count_by(self, *criterion: BinaryExpression | list[BinaryExpression]) -> int:
331
+ """Count objects by given criteria."""
332
+ filters = []
333
+ # If there's one argument and it's a list, unpack it
334
+ if len(criterion) == 1 and isinstance(criterion[0], list):
335
+ filters = criterion[0]
336
+ else:
337
+ filters = [c for c in criterion if isinstance(c, BinaryExpression)]
338
+
339
+ stmt = select(func.count()).select_from(self.model).where(*filters)
340
+ return (await self.db.execute(stmt)).scalar()
341
+
342
+ async def delete(self, instance: T, commit: bool = True) -> None:
343
+ """Async delete an object from the database.
344
+
345
+ Args:
346
+ instance (T): The object to delete.
347
+ commit (bool): Whether to commit the transaction after the operation.
348
+ """
349
+ if not isinstance(self.db, AsyncSession):
350
+ raise TypeError("adelete async method requires AsyncSession")
351
+
352
+ await self.db.delete(instance)
353
+ if commit:
354
+ await self.commit()
355
+
356
+ async def bulk_delete(self, ids: list[int], commit: bool = True) -> None:
357
+ """Async bulk delete objects by their IDs."""
358
+ if not isinstance(self.db, AsyncSession):
359
+ raise TypeError("bulk_delete async method requires AsyncSession")
360
+
361
+ if issubclass(self.model, SoftDeleteMixin):
362
+ raise TypeError(f"{self.model.__name__} does not support bulk deletion use bulk soft delete instead.")
363
+
364
+ await self.db.execute(delete(self.model).filter(self.model.id.in_(ids)))
365
+
366
+ if commit:
367
+ await self.commit()
368
+
369
+ async def filter_by(self, *criterion: BinaryExpression | list[BinaryExpression]) -> list[T]:
370
+ """Async filter objects by given criteria."""
371
+ if not isinstance(self.db, AsyncSession):
372
+ raise TypeError("filter_by async method requires AsyncSession")
373
+
374
+ filters = []
375
+ if len(criterion) == 1 and isinstance(criterion[0], list):
376
+ filters = criterion[0]
377
+ else:
378
+ filters = list(criterion)
379
+
380
+ result = await self.db.execute(select(self.model).filter(*filters))
381
+ return result.scalars().all()
382
+
383
+ async def filter_one_by(self, *criterion: BinaryExpression | list[BinaryExpression]) -> T | None:
384
+ """Filter objects by given criteria and return one result."""
385
+ filters = []
386
+ # If there's one argument and it's a list, unpack it
387
+ if len(criterion) == 1 and isinstance(criterion[0], list):
388
+ filters = criterion[0]
389
+ else:
390
+ filters = [c for c in criterion if isinstance(c, BinaryExpression)]
391
+
392
+ return (await self.db.execute(select(self.model).where(*filters))).scalar_one_or_none()
393
+
394
+ async def filter_one(self, **kwargs) -> T | None:
395
+ """Filter objects by given criteria and return one result."""
396
+ filters = []
397
+ for key, value in kwargs.items():
398
+ filters.append(getattr(self.model, key) == value)
399
+
400
+ return (await self.db.execute(select(self.model).where(*filters))).scalar_one_or_none()
401
+
402
+ async def create(self, instance: T, flush: bool = True, commit: bool = False) -> T:
403
+ """Async create a new object in the database.
404
+
405
+ Args:
406
+ instance (T): The object to create.
407
+ flush (bool): Whether to flush the session after adding.
408
+ commit (bool): Whether to commit the transaction after the operation.
409
+
410
+ Returns:
411
+ T: The created object.
412
+ """
413
+ if not isinstance(self.db, AsyncSession):
414
+ raise TypeError("acreate async method requires AsyncSession")
415
+
416
+ self.db.add(instance)
417
+ if flush:
418
+ await self.flush()
419
+ if commit:
420
+ await self.commit()
421
+
422
+ return instance
@@ -0,0 +1,12 @@
1
+ from abc import ABC
2
+
3
+ from ..repositories.abstract_repository import AbstractRepository
4
+
5
+
6
+ class ExternalBaseRepository(AbstractRepository, ABC): # noqa: B024
7
+ """Base repository class for external database operations.
8
+
9
+ This class provides a common interface for all repository classes for externale db.
10
+ """
11
+
12
+ pass
@@ -0,0 +1,101 @@
1
+ from typing import Any, cast
2
+
3
+ from sqlalchemy.ext.asyncio import AsyncSession
4
+ from sqlalchemy.orm import Session
5
+
6
+ from fastspine.lib.profiler import Profiler
7
+
8
+ from ..dependencies.profiler import load_profiler
9
+ from ..types import DBSessions
10
+ from ..util.class_util import get_annotations
11
+ from .abstract_repository import AbstractRepository
12
+
13
+
14
+ class RepositoryManager[SESSION_T: DBSessions]:
15
+ """Manages different repositories in the application."""
16
+
17
+ def __init__(self, db: SESSION_T):
18
+ self.db: SESSION_T = db
19
+ self._repositories: dict[type[AbstractRepository], AbstractRepository] = {}
20
+
21
+ def get[REPO_T: AbstractRepository](self, repository_class: type[REPO_T]) -> REPO_T:
22
+ """Get a repository instance, creating it if it doesn't exist."""
23
+ if repository_class not in self._repositories:
24
+ self._repositories[repository_class] = self._load_repository_instance(repository_class)
25
+ return cast(REPO_T, self._repositories[repository_class])
26
+
27
+ def sync_commit(self):
28
+ """Commit the current transaction."""
29
+ self.db.commit()
30
+
31
+ def sync_read_commit(self):
32
+ """Commit the current read-only transaction."""
33
+ if self.db.new or self.db.dirty or self.db.deleted:
34
+ raise ValueError(
35
+ "There are some changes in the database session, please commit or rollback before read commit."
36
+ )
37
+ return self.db.commit()
38
+
39
+ def sync_rollback(self):
40
+ """Rollback the current transaction."""
41
+ self.db.rollback()
42
+
43
+ def sync_flush(self):
44
+ """Flush the current transaction."""
45
+ self.db.flush()
46
+
47
+ async def commit(self):
48
+ """Async commit the current transaction."""
49
+ if not isinstance(self.db, AsyncSession):
50
+ raise TypeError("acommit async method requires AsyncSession")
51
+ await self.db.commit()
52
+
53
+ async def read_commit(self):
54
+ """Async commit the current read-only transaction."""
55
+ if not isinstance(self.db, AsyncSession):
56
+ raise TypeError("aread_commit async method requires AsyncSession")
57
+ if self.db.new or self.db.dirty or self.db.deleted:
58
+ raise ValueError(
59
+ "There are some changes in the database session, please commit or rollback before read commit."
60
+ )
61
+ return await self.db.commit()
62
+
63
+ async def rollback(self):
64
+ """Async rollback the current transaction."""
65
+ if not isinstance(self.db, AsyncSession):
66
+ raise TypeError("rollback async method requires AsyncSession")
67
+ await self.db.rollback()
68
+
69
+ async def flush(self):
70
+ """Async flush the current transaction."""
71
+ if not isinstance(self.db, AsyncSession):
72
+ raise TypeError("flush async method requires AsyncSession")
73
+ await self.db.flush()
74
+
75
+ def _load_repository_instance[REPO_T: AbstractRepository](self, repo_class: type[REPO_T]) -> REPO_T:
76
+ """Load repository.
77
+
78
+ load_repository is a utility function designed to create and return an instance of a repository class.
79
+ It is primarily used for dependency injection (DI) in contexts where FastAPI's Depends mechanism
80
+ is not available, such as background tasks or external services like Celery.
81
+ """
82
+ annotations = get_annotations(repo_class, mandatory_params=["db", "profiler"])
83
+ dependencies: dict[str, Any] = {}
84
+
85
+ for param_name, param_type in annotations.items():
86
+ if (isinstance(param_type, type) and issubclass(param_type, (Session, AsyncSession))) or (
87
+ hasattr(param_type, "__bound__")
88
+ and param_type.__bound__ in (Session, AsyncSession)
89
+ or (
90
+ hasattr(param_type, "__args__")
91
+ and any(
92
+ isinstance(arg, type) and issubclass(arg, (Session, AsyncSession))
93
+ for arg in param_type.__args__
94
+ )
95
+ )
96
+ ):
97
+ dependencies[param_name] = self.db
98
+ elif param_type is Profiler:
99
+ dependencies[param_name] = load_profiler()
100
+
101
+ return repo_class(**dependencies)
@@ -0,0 +1,26 @@
1
+ from pydantic import BaseModel, Field
2
+
3
+
4
+ class PaginationParams(BaseModel):
5
+ """Pagination parameters."""
6
+
7
+ limit: int = Field(default=10, ge=1, le=200)
8
+ offset: int = Field(default=0, ge=0)
9
+
10
+
11
+ class PaginatedData[T: BaseModel](BaseModel):
12
+ """Paginated data."""
13
+
14
+ count: int = Field(default=0, ge=0)
15
+ data: list[T] = Field(default_factory=list)
16
+
17
+
18
+ class PaginatedList:
19
+ """Paginated list."""
20
+
21
+ count: int = Field(default=0, ge=0)
22
+ rows: list = []
23
+
24
+ def __init__(self, count: int = 0, rows: list | None = None):
25
+ self.count = count
26
+ self.rows = rows if rows is not None else []