Skip to content

BaseRepository

Base class for repositories, the persistence abstraction for aggregates. Repositories provide a collection-oriented interface (add, get, all) to load and persist aggregates. The interface hides database details from the domain code.

See Repositories guide for practical usage and Repositories concept for design rationale.

Bases: Element, OptionsMixin

Base class for repositories, which load and persist aggregates.

add(), get() and get_or_none() persist and load an aggregate together with its child entities, and take part in the active Unit of Work. A custom repository adds domain-named query methods built on query, find(), find_by() and exists(). A method that overrides add() or get() should call the parent method first.

A user-defined repository can only be part_of an aggregate. Repositories have no delete or remove method; see the Repositories concept page for the reason.

Source code in src/protean/core/repository.py
67
68
69
def __init__(self, domain: "Domain", provider: BaseDatabase) -> None:
    self._domain = domain
    self._provider = provider

query property

query: QuerySet

Return a QuerySet for fluent filtering on the aggregate's data store.

Use this inside custom repository methods instead of self._dao.query::

@domain.repository(part_of=Person)
class PersonRepository:
    def adults(self):
        return self.query.filter(age__gte=18).all().items

find_by

find_by(**kwargs: Any) -> Any

Find a single aggregate matching the given criteria.

Raises ObjectNotFoundError if no match is found. Raises TooManyObjectsError if multiple matches are found.

Example::

@domain.repository(part_of=Person)
class PersonRepository:
    def find_by_email(self, email: str) -> Person:
        return self.find_by(email=email)
Source code in src/protean/core/repository.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def find_by(self, **kwargs: Any) -> Any:
    """Find a single aggregate matching the given criteria.

    Raises ``ObjectNotFoundError`` if no match is found.
    Raises ``TooManyObjectsError`` if multiple matches are found.

    Example::

        @domain.repository(part_of=Person)
        class PersonRepository:
            def find_by_email(self, email: str) -> Person:
                return self.find_by(email=email)
    """
    item = self._dao.find_by(**kwargs)
    self._prewarm_associations(item)
    return item

find

find(criteria: Q) -> ResultSet

Find all aggregates matching a Q criteria expression.

Returns a ResultSet containing the matching aggregates. Accepts composable Q objects, making it easy to build reusable, domain-named query functions::

from protean.utils.query import Q

def overdue_orders() -> Q:
    return Q(status="pending", due_date__lt=datetime.now())

results = repo.find(overdue_orders())
results = repo.find(overdue_orders() & Q(total__gte=5000))
Source code in src/protean/core/repository.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def find(self, criteria: Q) -> "ResultSet":
    """Find all aggregates matching a Q criteria expression.

    Returns a `ResultSet` containing
    the matching aggregates. Accepts composable ``Q`` objects, making
    it easy to build reusable, domain-named query functions::

        from protean.utils.query import Q

        def overdue_orders() -> Q:
            return Q(status="pending", due_date__lt=datetime.now())

        results = repo.find(overdue_orders())
        results = repo.find(overdue_orders() & Q(total__gte=5000))
    """
    return self.query.filter(criteria).all()

exists

exists(criteria: Q) -> bool

Check if any aggregate matches the given Q criteria.

Returns True when at least one aggregate satisfies the criteria, False otherwise. It runs the same query as find and checks how many rows came back, so it reads the matching aggregates rather than asking the database for existence alone::

if repo.exists(Q(email="john@example.com")):
    raise ValueError("Email already taken")
Source code in src/protean/core/repository.py
171
172
173
174
175
176
177
178
179
180
181
182
def exists(self, criteria: Q) -> bool:
    """Check if any aggregate matches the given Q criteria.

    Returns ``True`` when at least one aggregate satisfies the
    criteria, ``False`` otherwise. It runs the same query as ``find``
    and checks how many rows came back, so it reads the matching
    aggregates rather than asking the database for existence alone::

        if repo.exists(Q(email="john@example.com")):
            raise ValueError("Email already taken")
    """
    return self.query.filter(criteria).all().total > 0

add

add(item: Any) -> Any

Persist a new or changed aggregate or projection, with its child entities.

Inside an active Unit of Work, the changes are written in its transaction and committed when it commits. Otherwise they are committed before add() returns.

RETURNS DESCRIPTION
Any

The item passed in.

Source code in src/protean/core/repository.py
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
def add(self, item: Any) -> Any:
    """Persist a new or changed aggregate or projection, with its child entities.

    Inside an active Unit of Work, the changes are written in its
    transaction and committed when it commits. Otherwise they are committed
    before ``add()`` returns.

    Returns:
        The item passed in.
    """
    # Increment access log repo save counter
    if has_domain_context():
        g._access_log_repo_saves = getattr(g, "_access_log_repo_saves", 0) + 1

    tracer = self._domain.tracer

    with tracer.start_as_current_span(
        "protean.repository.add",
        record_exception=False,
        set_status_on_exception=False,
    ) as span:
        span.set_attribute("protean.aggregate.type", item.__class__.__name__)
        span.set_attribute("protean.provider", self._provider.name)

        try:
            return self._do_add(item)
        except Exception as exc:  # marks the span as failed, then re-raises
            set_span_error(span, exc)
            raise

get

get(identifier: Any) -> Any

This is a utility method to fetch data from the persistence store by its key identifier. All child objects, including enclosed entities, are returned as part of this call.

Returns the fetched object.

All other data filtering capabilities can be implemented by using the query of the underlying DAO service.

Filter methods are typically implemented as domain-contextual queries, like find_adults(), find_residents_of_area(zipcode), etc. It is also possible to make use of more complicated, domain-friendly design patterns like the Specification pattern.

Source code in src/protean/core/repository.py
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
def get(self, identifier: Any) -> Any:
    """This is a utility method to fetch data from the persistence store by its key identifier. All child objects,
    including enclosed entities, are returned as part of this call.

    Returns the fetched object.

    All other data filtering capabilities can be implemented by using the
    ``query`` of the underlying ``DAO`` service.

    Filter methods are typically implemented as domain-contextual queries, like `find_adults()`,
    `find_residents_of_area(zipcode)`, etc. It is also possible to make use of more complicated,
    domain-friendly design patterns like the `Specification` pattern.
    """
    # Increment access log repo load counter
    if has_domain_context():
        g._access_log_repo_loads = getattr(g, "_access_log_repo_loads", 0) + 1

    tracer = self._domain.tracer

    with tracer.start_as_current_span(
        "protean.repository.get",
        record_exception=False,
        set_status_on_exception=False,
    ) as span:
        span.set_attribute("protean.aggregate.type", self.meta_.part_of.__name__)
        span.set_attribute("protean.provider", self._provider.name)

        try:
            item = self._dao.get(identifier)
            self._prewarm_associations(item)
            return item
        except Exception as exc:  # marks the span as failed, then re-raises
            set_span_error(span, exc)
            raise

get_or_none

get_or_none(identifier: Any) -> Any | None

Fetch data from the persistence store by its key identifier, same as get(), but return None instead of raising ObjectNotFoundError when nothing matches.

On a hit, the returned object has all child objects, including enclosed entities, pre-warmed exactly as get() does. On a miss, this method returns None and never raises ObjectNotFoundError. Any other error (for example TooManyObjectsError, or a provider/connection error) still propagates.

Use get() instead when a missing identifier should be treated as a hard failure.

Source code in src/protean/core/repository.py
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
def get_or_none(self, identifier: Any) -> Any | None:
    """Fetch data from the persistence store by its key identifier, same as `get()`,
    but return `None` instead of raising `ObjectNotFoundError` when nothing matches.

    On a hit, the returned object has all child objects, including enclosed entities,
    pre-warmed exactly as `get()` does. On a miss, this method returns `None` and never
    raises `ObjectNotFoundError`. Any other error (for example `TooManyObjectsError`, or
    a provider/connection error) still propagates.

    Use `get()` instead when a missing identifier should be treated as a hard failure.
    """
    # Increment access log repo load counter
    if has_domain_context():
        g._access_log_repo_loads = getattr(g, "_access_log_repo_loads", 0) + 1

    tracer = self._domain.tracer

    with tracer.start_as_current_span(
        "protean.repository.get_or_none",
        record_exception=False,
        set_status_on_exception=False,
    ) as span:
        span.set_attribute("protean.aggregate.type", self.meta_.part_of.__name__)
        span.set_attribute("protean.provider", self._provider.name)

        try:
            item = self._dao.get(identifier)
            self._prewarm_associations(item)
            return item
        except ObjectNotFoundError:
            return None
        except Exception as exc:  # marks the span as failed, then re-raises
            set_span_error(span, exc)
            raise