SqlAlchemyRepository

Bases: Generic[DomainModel]

SqlAlchemy repository implementation. Provides basic CRUD operations for domain models.

The repository uses a SqlAlchemy session to interact with the database. It requires a default domain model type to be specified which will be used for operations where no specific model type is provided. The following operations are supported: - add - add_all - count - get - get_all - get_one - get_one_or_none - get_by_id - patch - remove - remove_all - select - update - view

You can also extend this repository to add custom methods by inheriting from it and adding your own methods.

Example:

class CustomRepository(SqlAlchemyRepository[MyDomainModel]):
    def custom_method(self, param: str) -> list[MyDomainModel]:
        # Custom query logic here
        pass

Generic
A generic type variable used to specify the domain model type for the
repository.
Source code in src/alpha/repositories/sql_alchemy_repository.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
class SqlAlchemyRepository(Generic[DomainModel]):
    """SqlAlchemy repository implementation. Provides basic CRUD operations for
    domain models.

    The repository uses a SqlAlchemy session to interact with the database. It
    requires a default domain model type to be specified which will be used
    for operations where no specific model type is provided. The following
    operations are supported:
        - add
        - add_all
        - count
        - get
        - get_all
        - get_one
        - get_one_or_none
        - get_by_id
        - patch
        - remove
        - remove_all
        - select
        - update
        - view

    You can also extend this repository to add custom methods by inheriting
    from it and adding your own methods.

    Example:
    ```python
    class CustomRepository(SqlAlchemyRepository[MyDomainModel]):
        def custom_method(self, param: str) -> list[MyDomainModel]:
            # Custom query logic here
            pass
    ```

    Generic
    -------
        A generic type variable used to specify the domain model type for the
        repository.
    """

    def __init__(self, session: Session, default_model: DomainModel) -> None:
        """Initialize the SqlAlchemyRepository with a database session and a
        default domain model type. The session is used for all database
        interactions, and the default model is used for operations where no
        specific model type is provided.


        Parameters
        ----------
        session
            The SQLAlchemy session used for database interactions.
        default_model
            The default domain model type for the repository.
        """
        self.session = session
        self._default_model = default_model

    def add(
        self,
        obj: DomainModel,
        return_obj: bool = True,
        raise_if_exists: bool = False,
    ) -> DomainModel | None:
        """Add a domain model instance to the database session.

        Parameters
        ----------
        obj
            The domain model instance to add.
        return_obj
            Whether to return the added object, by default True
        raise_if_exists
            Whether to raise an exception if the object already exists, by
            default False

        Returns
        -------
        DomainModel | None
            The added domain model instance if return_obj is True, otherwise
            None.

        Raises
        ------
        exceptions.AlreadyExistsException
            If raise_if_exists is True and an IntegrityError occurs during the
            add operation, indicating that the object already exists in the
            database.
        """
        try:
            self.session.add(obj)
            self.session.flush()
            if return_obj:
                self.session.refresh(obj)
            if llc("debug"):
                logging.debug(
                    "added object to database session: %s",
                    json.dumps(obj, cls=JSONEncoder),
                )
                logging.debug("flushed pending transaction to session")
            if return_obj:
                if llc("debug"):
                    logging.debug(
                        "refreshed object: %s",
                        json.dumps(obj, cls=JSONEncoder),
                    )
                return obj
        except IntegrityError as exc:
            self.session.rollback()
            if llc("debug"):
                logging.debug("rolled back pending transaction from session")
            if raise_if_exists:
                raise exceptions.AlreadyExistsException(exc)
        return None

    def add_all(
        self,
        objs: list[DomainModel],
        return_obj: bool = False,
        raise_if_exists: bool = False,
    ) -> list[DomainModel] | None:
        """Add multiple domain model instances to the database session.

        Parameters
        ----------
        objs
            The list of domain model instances to add.
        return_obj
            Whether to return the added objects, by default False
        raise_if_exists
            Whether to raise an exception if any object already exists, by
            default False

        Returns
        -------
        list[DomainModel] | None
            The list of added domain model instances if return_obj is True,
            otherwise None.

        Raises
        ------
        exceptions.AlreadyExistsException
            If raise_if_exists is True and an IntegrityError occurs during the
            add operation, indicating that one or more objects already exist in
            the database.
        """
        if return_obj:
            objects: list[DomainModel] | None = []
            for obj in objs:
                object_ = self.add(
                    obj=obj,
                    return_obj=return_obj,
                    raise_if_exists=raise_if_exists,
                )
                objects.append(object_)  # type: ignore
            return objects
        try:
            self.session.bulk_save_objects(objs)
            if llc("debug"):
                logging.debug(
                    "bulk added objects to database session: %s",
                    json.dumps(objs, cls=JSONEncoder),
                )
            self.session.flush()
            if llc("debug"):
                logging.debug("flushed pending transactions to session")
        except IntegrityError as exc:
            self.session.rollback()
            if llc("debug"):
                logging.debug("rolled back pending transaction from session")
            if raise_if_exists:
                raise exceptions.AlreadyExistsException(exc)
            for obj in objs:
                self.add(obj)
        return None

    def count(
        self,
        model: DomainModel | None = None,
        **kwargs: Any,
    ) -> int:
        """Count the number of records in the database for a given model and
        optional filters.

        Parameters
        ----------
        model
            The domain model class to count records for, by default None

        Returns
        -------
        int
            The number of records in the database for the given model and
            filters.
        """
        return self._query(cursor_result="count", model=model, **kwargs)  # type: ignore

    def get(
        self,
        attr: str | InstrumentedAttribute[Any],
        value: str | int | float | Enum | UUID,
        cursor_result: str = "first",
        model: DomainModel | None = None,
        **kwargs: Any,
    ) -> DomainModel:
        """Retrieve a single domain model instance from the database based on a
        specified attribute and value.

        Parameters
        ----------
        attr
            The attribute to filter by.
        value
            The value to filter by.
        cursor_result
            The type of result to return, by default "first"
        model
            The domain model class to query, by default None

        Returns
        -------
        DomainModel
            The retrieved domain model instance.
        """
        if isinstance(attr, InstrumentedAttribute):
            attr = attr.key
        return self._query(
            cursor_result=cursor_result,
            filter_by={attr: value},
            model=model,
            **kwargs,  # type: ignore
        )

    def get_all(
        self,
        attr: str | InstrumentedAttribute[Any],
        value: str | int | float | Enum | UUID,
        cursor_result: str = "all",
        model: DomainModel | None = None,
        **kwargs: Any,
    ) -> list[DomainModel]:
        """Retrieve multiple domain model instances from the database based on
        a specified attribute and value.

        Parameters
        ----------
        attr
            The attribute to filter by.
        value
            The value to filter by.
        cursor_result
            The type of result to return, by default "all"
        model
            The domain model class to query, by default None

        Returns
        -------
        list[DomainModel]
            The list of retrieved domain model instances.
        """
        objs = self.get(
            attr=attr,
            value=value,
            cursor_result=cursor_result,
            model=model,
            **kwargs,
        )
        return objs  # type: ignore

    def get_one(
        self,
        attr: str | InstrumentedAttribute[Any],
        value: str | int | float | Enum | UUID,
        cursor_result: str = "one",
        model: DomainModel | None = None,
        **kwargs: Any,
    ) -> DomainModel:
        """Retrieve a single domain model instance from the database based on a
        specified attribute and value, expecting exactly one result.

        Parameters
        ----------
        attr
            The attribute to filter by.
        value
            The value to filter by.
        cursor_result
            The type of result to return, by default "one"
        model
            The domain model class to query, by default None

        Returns
        -------
        DomainModel
            The retrieved domain model instance.
        """
        return self.get(
            attr=attr,
            value=value,
            cursor_result=cursor_result,
            model=model,
            **kwargs,
        )

    def get_one_or_none(
        self,
        attr: str | InstrumentedAttribute[Any],
        value: str | int | float | Enum | UUID,
        cursor_result: str = "one_or_none",
        model: DomainModel | None = None,
        **kwargs: Any,
    ) -> DomainModel | None:
        """Retrieve a single domain model instance from the database based on a
        specified attribute and value, expecting zero or one result.

        Parameters
        ----------
        attr
            The attribute to filter by.
        value
            The value to filter by.
        cursor_result
            The type of result to return, by default "one_or_none"
        model
            The domain model class to query, by default None

        Returns
        -------
        DomainModel | None
            The retrieved domain model instance or None if not found.
        """
        return self.get(
            attr=attr,
            value=value,
            cursor_result=cursor_result,
            model=model,
            **kwargs,
        )

    def get_by_id(
        self,
        value: str | int | UUID,
        attr: str | InstrumentedAttribute[Any] = "id",
        cursor_result: str = "one_or_none",
        model: DomainModel | None = None,
        **kwargs: Any,
    ) -> DomainModel | None:
        """Retrieve a single domain model instance from the database based on
        its ID.

        Parameters
        ----------
        value
            The ID value to filter by.
        attr
            The attribute to filter by, by default "id"
        cursor_result
            The type of result to return, by default "one_or_none"
        model
            The domain model class to query, by default None

        Returns
        -------
        DomainModel | None
            The retrieved domain model instance or None if not found.
        """
        return self.get(
            attr=attr,
            value=value,
            cursor_result=cursor_result,
            model=model,
            **kwargs,
        )

    def patch(
        self, obj: Patchable[Any], patches: JsonPatch
    ) -> BaseDomainModel:
        """Patch a domain model object using a JSON patch object.

        Parameters
        ----------
        obj
            Patchable object to be patched.
        patches
            JSON patch object containing the changes to apply.

        Returns
        -------
        DomainModel
            Patched object.
        """
        if not hasattr(obj, "patch"):
            raise TypeError("Object does not support patch operation")
        patched = obj.patch(patches)  # type: ignore[attr-defined]
        self.session.flush()
        return cast(BaseDomainModel, patched)

    def remove(self, obj: DomainModel) -> None:
        """Remove a domain model instance from the database.

        Parameters
        ----------
        obj
            The domain model instance to remove.
        """
        self.session.delete(obj)
        self.session.flush()

    def remove_all(
        self,
        objs: list[DomainModel] | None = None,
        **kwargs: Any,
    ) -> None:
        """Remove multiple domain model instances from the database.

        Parameters
        ----------
        objs
            The list of domain model instances to remove, by default None
        """
        if not objs:
            objs = self.select(**kwargs)  # type: ignore
        for obj in objs:
            self.remove(obj)

    def select(
        self,
        model: DomainModel | None = None,
        cursor_result: str = "all",
        **kwargs: Any,
    ) -> list[DomainModel]:
        """Select domain model instances from the database based on optional
        filters.

        Parameters
        ----------
        model
            The domain model class to query, by default None
        cursor_result
            The type of result to return, by default "all"

        Returns
        -------
        list[DomainModel]
            The list of retrieved domain model instances.
        """
        return self._query(cursor_result=cursor_result, model=model, **kwargs)  # type: ignore

    def update(self, obj: Updatable, new: DomainModel) -> DomainModel:
        """Update a domain model instance with new data.

        Parameters
        ----------
        obj
            The domain model instance to update.
        new
            The new data to update the domain model instance with.

        Returns
        -------
        DomainModel
            The updated domain model instance.
        """
        obj = obj.update(new)
        self.session.flush()
        self.session.refresh(obj)
        return obj

    def view(
        self,
        model: DomainModel,
        cursor_result: str = "all",
        **kwargs: Any,
    ) -> list[DomainModel]:
        """View domain model instances from the database based on optional
        filters.

        Parameters
        ----------
        model
            The domain model class to query.
        cursor_result
            The type of result to return, by default "all"

        Returns
        -------
        list[DomainModel]
            The list of retrieved domain model instances.
        """
        return self._query(cursor_result=cursor_result, model=model, **kwargs)  # type: ignore

    def _query(
        self,
        cursor_result: str | None = None,
        model: DomainModel | None = None,
        filters: Iterable[SearchFilter | FilterOperator] | None = None,
        query: Query[Any] | None = None,
        order_by: list[
            InstrumentedAttribute[Any]
            | UnaryExpression[Any]
            | OrderBy
            | QueryClause
        ] = list(),
        **kwargs: Any,
    ) -> Any:
        """Select domain model instances from the database based on optional
        filters.

        cursor_result:
            all
            first
            one
            one_or_none
            count
            None

        **kwargs:
            limit=n
            order_by=User.id
            order_by=[User.username, User.birthday]
            distinct=User.username

        Parameters
        ----------
        cursor_result
            The type of result to return, by default None
        model
            The domain model class to query, by default None
        filters
            The list of filters to apply, by default list()
        query
            The query object to use, by default None
        order_by
            The list of order by clauses, by default list()

        Returns
        -------
        Any
            The result of the query.
        """
        if not model:
            model = self._default_model

        subquery: Query[Any]

        if query:
            subquery = query
        else:
            subquery = self.session.query(model)  # type: ignore

        normalized_filters = list(filters) if filters else []
        if normalized_filters:
            filter_statements = self._process_filters(
                filters=normalized_filters, model=model
            )
            subquery = subquery.filter(*filter_statements)  # type: ignore

        for k, value in kwargs.items():
            if not value:
                break

            if isinstance(value, QueryClause):
                subquery = self._query_clause(
                    clause=value,
                    query=subquery,
                    model=model,  # type: ignore
                )
            elif isinstance(value, dict):  # type: ignore
                subquery = getattr(subquery, k)(**value)  # type: ignore
            elif isinstance(value, list):
                for item in value:  # type: ignore
                    if isinstance(item, QueryClause):
                        subquery = self._query_clause(
                            clause=item,
                            query=subquery,
                            model=model,  # type: ignore
                        )
                    else:
                        subquery = getattr(subquery, k)(item)  # type: ignore
            else:
                subquery = getattr(subquery, k)(value)  # type: ignore

        for order in order_by:
            if isinstance(order, QueryClause):
                subquery = self._query_clause(
                    clause=order,
                    query=subquery,
                    model=model,  # type: ignore
                )
            elif isinstance(order, InstrumentedAttribute | UnaryExpression):  # type: ignore
                subquery = getattr(subquery, "order_by")(order)  # type: ignore

        # Process cursor_result parameter
        if cursor_result:
            return getattr(subquery, cursor_result)()  # type: ignore

        return subquery  # type: ignore

    def _query_clause(
        self,
        clause: QueryClause,
        query: Query[Any],
        model: DomainModel,
    ) -> Query[Any]:
        """Apply a QueryClause to a query object.

        Parameters
        ----------
        clause
            The QueryClause to apply.
        query
            The query object to apply the clause to.
        model
            The domain model class to query, used to set the `_domain_model`
            attribute of the QueryClause if it is not already set.

        Returns
        -------
        Query[Any]
            The query object with the QueryClause applied.
        """
        if not clause._domain_model:  # type: ignore
            clause.set_domain_model(model)
        return clause.query_clause(query)

    def _process_filters(
        self,
        filters: Iterable[SearchFilter | FilterOperator],
        model: BaseDomainModel,
    ) -> list[ColumnElement[Any] | BinaryExpression[Any] | ColumnOperators]:
        """Process query filters and apply them to the query object

        Parameters
        ----------
        filters
            Filters which can be SearchFilter or FilerOperator objects
        model
            The domain model which will be used to set the `_domain_model`
            attribute of SearchFilter objects

        Returns
        -------
            Query object to which the filters have been applied
        """
        filter_expressions = [
            self._process_filter_item(filter_=f, model=model) for f in filters
        ]
        return filter_expressions

    def _process_filter_item(
        self,
        filter_: SearchFilter | FilterOperator,
        model: BaseDomainModel,
    ) -> ColumnElement[Any] | BinaryExpression[Any] | ColumnOperators:
        """Process a filter item. When the item is a SeachFilter object
        the domain model will be set and the filter statement will be returned.
        When the item is a FilterOperator object, all the filters will be
        processed recursively by this method and they are supplied to the
        filter operator.

        Parameters
        ----------
        filter_
            A filter object
        model
            Domain model type

        Returns
        -------
            Returns a filter statement or a filter operator containing
            filter statements

        Raises
        ------
        TypeError
            When an unsupported filter type is being used
        """
        if isinstance(filter_, FilterOperator):
            filters = [
                self._process_filter_item(filter_=filter_item, model=model)
                for filter_item in filter_.search_filters
            ]
            return filter_.filter_operator(*filters)  # type: ignore
        elif isinstance(filter_, SearchFilter):  # type: ignore
            if not filter_._domain_model:  # type: ignore
                filter_.set_domain_model(model)  # type: ignore
            return filter_.filter_statement
        else:
            raise TypeError(
                "Only QueryClause and FilterOperator types are allowed "
                "as values for the 'filters' argument"
            )

Methods:

__init__

__init__(session, default_model)

Initialize the SqlAlchemyRepository with a database session and a default domain model type. The session is used for all database interactions, and the default model is used for operations where no specific model type is provided.

Parameters:
  • session (Session) –

    The SQLAlchemy session used for database interactions.

  • default_model (DomainModel) –

    The default domain model type for the repository.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def __init__(self, session: Session, default_model: DomainModel) -> None:
    """Initialize the SqlAlchemyRepository with a database session and a
    default domain model type. The session is used for all database
    interactions, and the default model is used for operations where no
    specific model type is provided.


    Parameters
    ----------
    session
        The SQLAlchemy session used for database interactions.
    default_model
        The default domain model type for the repository.
    """
    self.session = session
    self._default_model = default_model

add

add(obj, return_obj=True, raise_if_exists=False)

Add a domain model instance to the database session.

Parameters:
  • obj (DomainModel) –

    The domain model instance to add.

  • return_obj (bool, default: True ) –

    Whether to return the added object, by default True

  • raise_if_exists (bool, default: False ) –

    Whether to raise an exception if the object already exists, by default False

Returns:
  • DomainModel | None

    The added domain model instance if return_obj is True, otherwise None.

Raises:
  • AlreadyExistsException

    If raise_if_exists is True and an IntegrityError occurs during the add operation, indicating that the object already exists in the database.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def add(
    self,
    obj: DomainModel,
    return_obj: bool = True,
    raise_if_exists: bool = False,
) -> DomainModel | None:
    """Add a domain model instance to the database session.

    Parameters
    ----------
    obj
        The domain model instance to add.
    return_obj
        Whether to return the added object, by default True
    raise_if_exists
        Whether to raise an exception if the object already exists, by
        default False

    Returns
    -------
    DomainModel | None
        The added domain model instance if return_obj is True, otherwise
        None.

    Raises
    ------
    exceptions.AlreadyExistsException
        If raise_if_exists is True and an IntegrityError occurs during the
        add operation, indicating that the object already exists in the
        database.
    """
    try:
        self.session.add(obj)
        self.session.flush()
        if return_obj:
            self.session.refresh(obj)
        if llc("debug"):
            logging.debug(
                "added object to database session: %s",
                json.dumps(obj, cls=JSONEncoder),
            )
            logging.debug("flushed pending transaction to session")
        if return_obj:
            if llc("debug"):
                logging.debug(
                    "refreshed object: %s",
                    json.dumps(obj, cls=JSONEncoder),
                )
            return obj
    except IntegrityError as exc:
        self.session.rollback()
        if llc("debug"):
            logging.debug("rolled back pending transaction from session")
        if raise_if_exists:
            raise exceptions.AlreadyExistsException(exc)
    return None

add_all

add_all(objs, return_obj=False, raise_if_exists=False)

Add multiple domain model instances to the database session.

Parameters:
  • objs (list[DomainModel]) –

    The list of domain model instances to add.

  • return_obj (bool, default: False ) –

    Whether to return the added objects, by default False

  • raise_if_exists (bool, default: False ) –

    Whether to raise an exception if any object already exists, by default False

Returns:
  • list[DomainModel] | None

    The list of added domain model instances if return_obj is True, otherwise None.

Raises:
  • AlreadyExistsException

    If raise_if_exists is True and an IntegrityError occurs during the add operation, indicating that one or more objects already exist in the database.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def add_all(
    self,
    objs: list[DomainModel],
    return_obj: bool = False,
    raise_if_exists: bool = False,
) -> list[DomainModel] | None:
    """Add multiple domain model instances to the database session.

    Parameters
    ----------
    objs
        The list of domain model instances to add.
    return_obj
        Whether to return the added objects, by default False
    raise_if_exists
        Whether to raise an exception if any object already exists, by
        default False

    Returns
    -------
    list[DomainModel] | None
        The list of added domain model instances if return_obj is True,
        otherwise None.

    Raises
    ------
    exceptions.AlreadyExistsException
        If raise_if_exists is True and an IntegrityError occurs during the
        add operation, indicating that one or more objects already exist in
        the database.
    """
    if return_obj:
        objects: list[DomainModel] | None = []
        for obj in objs:
            object_ = self.add(
                obj=obj,
                return_obj=return_obj,
                raise_if_exists=raise_if_exists,
            )
            objects.append(object_)  # type: ignore
        return objects
    try:
        self.session.bulk_save_objects(objs)
        if llc("debug"):
            logging.debug(
                "bulk added objects to database session: %s",
                json.dumps(objs, cls=JSONEncoder),
            )
        self.session.flush()
        if llc("debug"):
            logging.debug("flushed pending transactions to session")
    except IntegrityError as exc:
        self.session.rollback()
        if llc("debug"):
            logging.debug("rolled back pending transaction from session")
        if raise_if_exists:
            raise exceptions.AlreadyExistsException(exc)
        for obj in objs:
            self.add(obj)
    return None

count

count(model=None, **kwargs)

Count the number of records in the database for a given model and optional filters.

Parameters:
  • model (DomainModel | None, default: None ) –

    The domain model class to count records for, by default None

Returns:
  • int

    The number of records in the database for the given model and filters.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def count(
    self,
    model: DomainModel | None = None,
    **kwargs: Any,
) -> int:
    """Count the number of records in the database for a given model and
    optional filters.

    Parameters
    ----------
    model
        The domain model class to count records for, by default None

    Returns
    -------
    int
        The number of records in the database for the given model and
        filters.
    """
    return self._query(cursor_result="count", model=model, **kwargs)  # type: ignore

get

get(attr, value, cursor_result='first', model=None, **kwargs)

Retrieve a single domain model instance from the database based on a specified attribute and value.

Parameters:
  • attr (str | InstrumentedAttribute[Any]) –

    The attribute to filter by.

  • value (str | int | float | Enum | UUID) –

    The value to filter by.

  • cursor_result (str, default: 'first' ) –

    The type of result to return, by default "first"

  • model (DomainModel | None, default: None ) –

    The domain model class to query, by default None

Returns:
  • DomainModel

    The retrieved domain model instance.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def get(
    self,
    attr: str | InstrumentedAttribute[Any],
    value: str | int | float | Enum | UUID,
    cursor_result: str = "first",
    model: DomainModel | None = None,
    **kwargs: Any,
) -> DomainModel:
    """Retrieve a single domain model instance from the database based on a
    specified attribute and value.

    Parameters
    ----------
    attr
        The attribute to filter by.
    value
        The value to filter by.
    cursor_result
        The type of result to return, by default "first"
    model
        The domain model class to query, by default None

    Returns
    -------
    DomainModel
        The retrieved domain model instance.
    """
    if isinstance(attr, InstrumentedAttribute):
        attr = attr.key
    return self._query(
        cursor_result=cursor_result,
        filter_by={attr: value},
        model=model,
        **kwargs,  # type: ignore
    )

get_all

get_all(attr, value, cursor_result='all', model=None, **kwargs)

Retrieve multiple domain model instances from the database based on a specified attribute and value.

Parameters:
  • attr (str | InstrumentedAttribute[Any]) –

    The attribute to filter by.

  • value (str | int | float | Enum | UUID) –

    The value to filter by.

  • cursor_result (str, default: 'all' ) –

    The type of result to return, by default "all"

  • model (DomainModel | None, default: None ) –

    The domain model class to query, by default None

Returns:
  • list[DomainModel]

    The list of retrieved domain model instances.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def get_all(
    self,
    attr: str | InstrumentedAttribute[Any],
    value: str | int | float | Enum | UUID,
    cursor_result: str = "all",
    model: DomainModel | None = None,
    **kwargs: Any,
) -> list[DomainModel]:
    """Retrieve multiple domain model instances from the database based on
    a specified attribute and value.

    Parameters
    ----------
    attr
        The attribute to filter by.
    value
        The value to filter by.
    cursor_result
        The type of result to return, by default "all"
    model
        The domain model class to query, by default None

    Returns
    -------
    list[DomainModel]
        The list of retrieved domain model instances.
    """
    objs = self.get(
        attr=attr,
        value=value,
        cursor_result=cursor_result,
        model=model,
        **kwargs,
    )
    return objs  # type: ignore

get_one

get_one(attr, value, cursor_result='one', model=None, **kwargs)

Retrieve a single domain model instance from the database based on a specified attribute and value, expecting exactly one result.

Parameters:
  • attr (str | InstrumentedAttribute[Any]) –

    The attribute to filter by.

  • value (str | int | float | Enum | UUID) –

    The value to filter by.

  • cursor_result (str, default: 'one' ) –

    The type of result to return, by default "one"

  • model (DomainModel | None, default: None ) –

    The domain model class to query, by default None

Returns:
  • DomainModel

    The retrieved domain model instance.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def get_one(
    self,
    attr: str | InstrumentedAttribute[Any],
    value: str | int | float | Enum | UUID,
    cursor_result: str = "one",
    model: DomainModel | None = None,
    **kwargs: Any,
) -> DomainModel:
    """Retrieve a single domain model instance from the database based on a
    specified attribute and value, expecting exactly one result.

    Parameters
    ----------
    attr
        The attribute to filter by.
    value
        The value to filter by.
    cursor_result
        The type of result to return, by default "one"
    model
        The domain model class to query, by default None

    Returns
    -------
    DomainModel
        The retrieved domain model instance.
    """
    return self.get(
        attr=attr,
        value=value,
        cursor_result=cursor_result,
        model=model,
        **kwargs,
    )

get_one_or_none

get_one_or_none(attr, value, cursor_result='one_or_none', model=None, **kwargs)

Retrieve a single domain model instance from the database based on a specified attribute and value, expecting zero or one result.

Parameters:
  • attr (str | InstrumentedAttribute[Any]) –

    The attribute to filter by.

  • value (str | int | float | Enum | UUID) –

    The value to filter by.

  • cursor_result (str, default: 'one_or_none' ) –

    The type of result to return, by default "one_or_none"

  • model (DomainModel | None, default: None ) –

    The domain model class to query, by default None

Returns:
  • DomainModel | None

    The retrieved domain model instance or None if not found.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def get_one_or_none(
    self,
    attr: str | InstrumentedAttribute[Any],
    value: str | int | float | Enum | UUID,
    cursor_result: str = "one_or_none",
    model: DomainModel | None = None,
    **kwargs: Any,
) -> DomainModel | None:
    """Retrieve a single domain model instance from the database based on a
    specified attribute and value, expecting zero or one result.

    Parameters
    ----------
    attr
        The attribute to filter by.
    value
        The value to filter by.
    cursor_result
        The type of result to return, by default "one_or_none"
    model
        The domain model class to query, by default None

    Returns
    -------
    DomainModel | None
        The retrieved domain model instance or None if not found.
    """
    return self.get(
        attr=attr,
        value=value,
        cursor_result=cursor_result,
        model=model,
        **kwargs,
    )

get_by_id

get_by_id(value, attr='id', cursor_result='one_or_none', model=None, **kwargs)

Retrieve a single domain model instance from the database based on its ID.

Parameters:
  • value (str | int | UUID) –

    The ID value to filter by.

  • attr (str | InstrumentedAttribute[Any], default: 'id' ) –

    The attribute to filter by, by default "id"

  • cursor_result (str, default: 'one_or_none' ) –

    The type of result to return, by default "one_or_none"

  • model (DomainModel | None, default: None ) –

    The domain model class to query, by default None

Returns:
  • DomainModel | None

    The retrieved domain model instance or None if not found.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def get_by_id(
    self,
    value: str | int | UUID,
    attr: str | InstrumentedAttribute[Any] = "id",
    cursor_result: str = "one_or_none",
    model: DomainModel | None = None,
    **kwargs: Any,
) -> DomainModel | None:
    """Retrieve a single domain model instance from the database based on
    its ID.

    Parameters
    ----------
    value
        The ID value to filter by.
    attr
        The attribute to filter by, by default "id"
    cursor_result
        The type of result to return, by default "one_or_none"
    model
        The domain model class to query, by default None

    Returns
    -------
    DomainModel | None
        The retrieved domain model instance or None if not found.
    """
    return self.get(
        attr=attr,
        value=value,
        cursor_result=cursor_result,
        model=model,
        **kwargs,
    )

patch

patch(obj, patches)

Patch a domain model object using a JSON patch object.

Parameters:
  • obj (Patchable[Any]) –

    Patchable object to be patched.

  • patches (JsonPatch) –

    JSON patch object containing the changes to apply.

Returns:
  • DomainModel

    Patched object.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def patch(
    self, obj: Patchable[Any], patches: JsonPatch
) -> BaseDomainModel:
    """Patch a domain model object using a JSON patch object.

    Parameters
    ----------
    obj
        Patchable object to be patched.
    patches
        JSON patch object containing the changes to apply.

    Returns
    -------
    DomainModel
        Patched object.
    """
    if not hasattr(obj, "patch"):
        raise TypeError("Object does not support patch operation")
    patched = obj.patch(patches)  # type: ignore[attr-defined]
    self.session.flush()
    return cast(BaseDomainModel, patched)

remove

remove(obj)

Remove a domain model instance from the database.

Parameters:
  • obj (DomainModel) –

    The domain model instance to remove.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def remove(self, obj: DomainModel) -> None:
    """Remove a domain model instance from the database.

    Parameters
    ----------
    obj
        The domain model instance to remove.
    """
    self.session.delete(obj)
    self.session.flush()

remove_all

remove_all(objs=None, **kwargs)

Remove multiple domain model instances from the database.

Parameters:
  • objs (list[DomainModel] | None, default: None ) –

    The list of domain model instances to remove, by default None

Source code in src/alpha/repositories/sql_alchemy_repository.py
def remove_all(
    self,
    objs: list[DomainModel] | None = None,
    **kwargs: Any,
) -> None:
    """Remove multiple domain model instances from the database.

    Parameters
    ----------
    objs
        The list of domain model instances to remove, by default None
    """
    if not objs:
        objs = self.select(**kwargs)  # type: ignore
    for obj in objs:
        self.remove(obj)

select

select(model=None, cursor_result='all', **kwargs)

Select domain model instances from the database based on optional filters.

Parameters:
  • model (DomainModel | None, default: None ) –

    The domain model class to query, by default None

  • cursor_result (str, default: 'all' ) –

    The type of result to return, by default "all"

Returns:
  • list[DomainModel]

    The list of retrieved domain model instances.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def select(
    self,
    model: DomainModel | None = None,
    cursor_result: str = "all",
    **kwargs: Any,
) -> list[DomainModel]:
    """Select domain model instances from the database based on optional
    filters.

    Parameters
    ----------
    model
        The domain model class to query, by default None
    cursor_result
        The type of result to return, by default "all"

    Returns
    -------
    list[DomainModel]
        The list of retrieved domain model instances.
    """
    return self._query(cursor_result=cursor_result, model=model, **kwargs)  # type: ignore

update

update(obj, new)

Update a domain model instance with new data.

Parameters:
  • obj (Updatable) –

    The domain model instance to update.

  • new (DomainModel) –

    The new data to update the domain model instance with.

Returns:
  • DomainModel

    The updated domain model instance.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def update(self, obj: Updatable, new: DomainModel) -> DomainModel:
    """Update a domain model instance with new data.

    Parameters
    ----------
    obj
        The domain model instance to update.
    new
        The new data to update the domain model instance with.

    Returns
    -------
    DomainModel
        The updated domain model instance.
    """
    obj = obj.update(new)
    self.session.flush()
    self.session.refresh(obj)
    return obj

view

view(model, cursor_result='all', **kwargs)

View domain model instances from the database based on optional filters.

Parameters:
  • model (DomainModel) –

    The domain model class to query.

  • cursor_result (str, default: 'all' ) –

    The type of result to return, by default "all"

Returns:
  • list[DomainModel]

    The list of retrieved domain model instances.

Source code in src/alpha/repositories/sql_alchemy_repository.py
def view(
    self,
    model: DomainModel,
    cursor_result: str = "all",
    **kwargs: Any,
) -> list[DomainModel]:
    """View domain model instances from the database based on optional
    filters.

    Parameters
    ----------
    model
        The domain model class to query.
    cursor_result
        The type of result to return, by default "all"

    Returns
    -------
    list[DomainModel]
        The list of retrieved domain model instances.
    """
    return self._query(cursor_result=cursor_result, model=model, **kwargs)  # type: ignore