Skip to content

Repositories

DDD CQRS ES

Repositories provide a collection-oriented interface to persist and retrieve aggregates. They hide the details of the underlying storage technology behind a clean, domain-focused API.

Protean automatically provides a default repository for every registered aggregate. You only need to define a custom repository when you want to add business-oriented query methods.

Default repository

Every aggregate gets a default repository. You access it with domain.repository_for():

from protean import Domain
from protean.fields import String

domain = Domain()


@domain.aggregate
class Person:
    name: String(required=True, max_length=50)
    email: String(required=True, max_length=254)
In [1]: repo = domain.repository_for(Person)

In [2]: repo
Out[2]: <protean.adapters.database.PersonRepository object at 0x104f3a1d0>

The default repository provides these methods:

  • add(aggregate): Persist or update an aggregate.
  • get(identifier): Retrieve an aggregate by its identity.
  • get_or_none(identifier): Like get(), but return None instead of raising when nothing matches.
  • find(criteria): Find all aggregates matching a Q expression.
  • find_by(**kwargs): find a single aggregate by field values.
  • exists(criteria): Check if any aggregate matches a Q expression.

For basic operations, the default repository is all you need.

Defining a custom repository

When you need domain-named query methods (such as finding all overdue orders or looking up customers by region) you define a custom repository:

from protean import Domain
from protean.fields import Integer, String

domain = Domain()


@domain.aggregate
class Person:
    name: String(required=True, max_length=50)
    email: String(required=True, max_length=254)
    age: Integer(default=21)


@domain.repository(part_of=Person)  # (1)
class CustomPersonRepository:
    def find_by_email(self, email: str) -> Person:
        return self.find_by(email=email)
  1. The repository is connected to Person aggregate through the part_of parameter.

Protean now returns the custom repository whenever you ask for Person's repository:

In [1]: repo = domain.repository_for(Person)

In [2]: repo
Out[2]: <__main__.CustomPersonRepository object at 0x1079af290>

In [3]: repo.add(Person(name="John Doe", email="john.doe@example.com"))
Out[3]: <Person: Person object (id: 9ba6a890-e783-455e-9a6b-a0a16c0514df)>

In [4]: repo.find_by_email("john.doe@example.com")
Out[4]: <Person: Person object (id: 9ba6a890-e783-455e-9a6b-a0a16c0514df)>

Multiple domain-named methods

A repository can contain as many query methods as needed. Name them after the domain concepts they represent:

from protean import Domain
from protean.fields import Integer, String

domain = Domain()


@domain.aggregate
class Person:
    name: String(required=True, max_length=50)
    email: String(required=True, max_length=254)
    age: Integer(default=21)
    country: String(max_length=2)


@domain.repository(part_of=Person)  # (1)!
class PersonRepository:
    def adults(self) -> list:  # (2)!
        """Find all adults."""
        return self.query.filter(age__gte=18).all().items

    def find_by_email(self, email: str) -> Person:
        """Find a person by email address."""
        return self.find_by(email=email)

    def by_country(self, country_code: str) -> list:
        """Find all people in a given country."""
        return self.query.filter(country=country_code).all().items
  1. The repository is connected to the Person aggregate through part_of.
  2. Custom methods use self.query and self.find_by to access the persistence layer.
In [1]: repo = domain.repository_for(Person)

In [2]: repo.adults()
Out[2]: [<Person: Person object (id: ...)>, ...]

In [3]: repo.by_country("CA")
Out[3]: [<Person: Person object (id: ...)>]

Note

Methods in the repository should be named for the business queries they perform. adults is a better name than filter_by_age_gte_18. The repository should speak the ubiquitous language of the domain.

Querying inside repositories

Every repository exposes these methods for building queries:

  • self.query: A QuerySet for building filtered, sorted, paginated queries.
  • self.find_by(**kwargs): find a single aggregate matching the given fields. Raises ObjectNotFoundError if no match is found, and TooManyObjectsError if multiple matches are found.
  • self.find(criteria): Find all aggregates matching a Q expression. Returns a ResultSet.
  • self.exists(criteria): Check if any aggregate matches a Q expression. Returns True or False.
from protean.utils.query import Q


@domain.repository(part_of=Person)
class PersonRepository:
    def adults_in_country(self, country_code: str) -> list:
        return self.find(Q(age__gte=18, country=country_code)).items

    def find_by_email(self, email: str) -> Person:
        return self.find_by(email=email)

    def has_adults(self) -> bool:
        return self.exists(Q(age__gte=18))

Internally, these delegate to the repository's Data Access Object (DAO), the layer that talks to the database.

Avoid direct _dao access

The underlying DAO is accessible as self._dao, but it is an internal API intended for framework use and infrastructure-level escape hatches (hard deletion, test teardown, GDPR compliance). For custom repository queries, always prefer self.query, self.find, self.find_by(), and self.exists().

Error handling in queries

get() and find_by() raise exceptions when the expected result is not found:

from protean.exceptions import ObjectNotFoundError, TooManyObjectsError


def get_person(person_id: str) -> Person | None:
    repo = domain.repository_for(Person)

    # Raises ObjectNotFoundError if no aggregate matches the identity
    try:
        return repo.get(person_id)
    except ObjectNotFoundError:
        return None


def find_person(email: str) -> Person | None:
    repo = domain.repository_for(Person)

    # Raises ObjectNotFoundError if no match, TooManyObjectsError if multiple
    try:
        return repo.find_by(email=email)
    except ObjectNotFoundError:
        return None
    except TooManyObjectsError as exc:
        raise ValueError(f"More than one person uses {email}") from exc

exists() never raises. It returns True or False:

def check_email_is_free(email: str) -> None:
    repo = domain.repository_for(Person)

    if repo.exists(Q(email=email)):
        raise ValueError("Email already taken")

Use get_or_none() when a miss is a normal outcome, such as resolving an optional reference by id (for example, an order's referred_by customer id that may not exist):

def referrer_name(referred_by: str) -> str:
    repo = domain.repository_for(Person)

    # Returns None instead of raising ObjectNotFoundError
    person = repo.get_or_none(referred_by)
    if person is None:
        return "nobody"
    return person.name

For a comprehensive guide on querying, see Retrieving Aggregates.

Connecting to a specific database

The database_type option ties a repository to one kind of database. Its value is a database type: memory, sqlite, postgresql, mysql, mssql, elasticsearch, or the database_type of a registered custom adapter. It is not the name of a configured provider. Protean returns the repository only when the aggregate is stored in a provider of that type.

The aggregate's database option picks which configured provider stores it. Here Person is stored in the reporting provider. That provider is a memory database, so domain.repository_for(Person) returns PersonReportingRepository:

from protean import Domain
from protean.fields import Boolean, String

domain = Domain(
    config={
        "databases": {
            "default": {"provider": "memory"},
            "reporting": {"provider": "memory"},
        }
    }
)


@domain.aggregate(database="reporting")
class Person:
    name: String(required=True, max_length=50)
    active: Boolean(default=True)


@domain.repository(part_of=Person, database_type="memory")
class PersonReportingRepository:
    def active_users_summary(self) -> list:
        return self.query.filter(active=True).all().items

When no database_type is specified, the default value is "ALL". With "ALL", Protean uses the repository for whichever provider the aggregate's database option assigns. The database option itself defaults to the "default" provider.

Note

Use database_type when an aggregate needs different query code on different databases, for example a raw SQL query that only PostgreSQL understands. If the aggregate's provider is a different type, Protean returns the generic repository instead.

domain.repository_for()

domain.repository_for(AggregateClass) is the sole entry point for obtaining a repository instance. It accepts an aggregate class (not a string) and returns the repository associated with that aggregate:

domain.init(traverse=False)

with domain.domain_context():
    repo = domain.repository_for(Person)
    repo.add(Person(id="42", name="John Doe"))

    person = repo.get("42")

How it works:

  • If the aggregate has event_sourced=True, repository_for() returns an event-sourced repository backed by the event store. The event-sourced repository reconstructs aggregate state by replaying events from the aggregate's stream. It does not read from a database table. When a BaseEventSourcedRepository subclass is registered for the aggregate, repository_for() returns an instance of it. A subclass registered with a string part_of is found only after domain.init(). When none is found, repository_for() returns a generated one. Registering a standard repository for an event-sourced aggregate raises IncorrectUsageError.

  • Otherwise, it returns the aggregate's database-backed repository (custom if one is registered, default if not).

This routing is transparent. You always call domain.repository_for() the same way, and Protean returns the correct repository based on the aggregate's configuration.

get_or_none() on an event-sourced repository

The event-sourced repository also has get_or_none(). It takes the same arguments as get(): the identifier, plus an optional at_version or as_of for a temporal query. Where get() raises ObjectNotFoundError, get_or_none() returns None. For example:

  • There is no event stream for the identifier.
  • at_version is past the last version in the stream.
  • as_of is earlier than the first event in the stream.

Every other error still raises. For example, passing both at_version and as_of raises IncorrectUsageError.

from datetime import datetime

def balance_or_zero(account_id: str) -> float:
    repo = domain.repository_for(Account)

    # Returns None when the account has no event stream
    account = repo.get_or_none(account_id)
    if account is None:
        return 0.0
    return account.balance


def balance_at_version(account_id: str, version: int) -> float | None:
    repo = domain.repository_for(Account)

    # Returns None when the stream has no event at that version
    account = repo.get_or_none(account_id, at_version=version)
    return None if account is None else account.balance


def balance_as_of(account_id: str, as_of: datetime) -> float | None:
    repo = domain.repository_for(Account)

    # Returns None when the stream has no events on or before as_of
    account = repo.get_or_none(account_id, as_of=as_of)
    return None if account is None else account.balance

Why there is no delete or remove

Repositories intentionally do not provide a delete() or remove() method.

In Domain-Driven Design, "deleting" a business entity is almost always a state transition, not a record erasure. An order is cancelled, a user is deactivated, a subscription is archived. These transitions are meaningful domain events. Model them explicitly with commands, aggregate methods, and events, and do not replace them with a database DELETE.

For infrastructure-level record removal (projection rebuilds, test teardown, GDPR right-to-erasure compliance), you can access the underlying DAO directly:

repo = domain.repository_for(Person)
repo._dao.delete(person)

This is an intentional escape hatch. Protean does not recommend it as a domain operation. Use it only when the domain model does not apply (e.g., cleaning up test data).

Transactions and Unit of Work

Every call to repository.add() participates in the enclosing Unit of Work. Inside a command handler or @use_case method, this happens automatically. Changes are committed when the handler completes, or rolled back if an exception is raised.

Outside a handler (e.g., in a shell session or script), add() creates a temporary UoW, commits immediately, and discards it.

When to define a custom repository

Define a custom repository when you need to:

  • Express domain queries: Methods like overdue_orders() or customers_in_region(region) that encapsulate business-oriented queries.
  • Compose complex queries: Queries involving Q objects, multiple filters, or specific ordering.
  • Use raw queries: Database-specific queries that cannot be expressed through the QuerySet API.

You do not need a custom repository for:

  • Basic add and get operations: the default repository already provides these.
  • One-off queries in command handlers or application services, consider adding a named method to a custom repository instead.

Note

Keep repositories thin. They should contain query logic, not business logic. If a retrieval method starts making decisions or enforcing rules, that logic belongs in the aggregate or a domain service.


See also

Concept overview: Repositories: The role of repositories in DDD and how Protean implements the pattern.

Related guides: