Skip to content
Skills Library
Programming · Learning & explanation

repository

/repository

Define a Protean repository, the persistence abstraction for aggregates in Domain-Driven Design. Repositories provide a collection-oriented interface to load and persist aggregates, hiding database details behind a clean domain API. Protean provides a default repository automatically for every aggregate; custom repositories add domain-specific queries or database-specific optimizations. Use when you need to persist an aggregate, load an aggregate, write a custom repository, add a custom query, override the default repository, connect to a specific database, or implement the repository pattern.

Repository
protean ↗
Licence
Apache-2.0
Last repository change
27.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
12
Scripts
6
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.

Licence

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

What to check before installing
  • 6 scripts in this package. Review them before installing, as Claude may execute them.

Scripts: assets/repository_counting_and_nulls.py, assets/repository_custom.py, assets/repository_default.py, assets/repository_with_children.py, assets/repository_with_database.py, assets/repository_with_uow.py

What it does and when to use it

Define a Protean repository, the persistence abstraction for aggregates in Domain-Driven Design. Repositories provide a collection-oriented interface to load and persist aggregates, hiding database details behind a clean domain API. Protean provides a default repository automatically for every aggregate; custom repositories add domain-specific queries or database-specific optimizations. Use when you need to persist an aggregate, load an aggregate, write a custom repository, add a custom query, override the default repository, connect to a specific database, or implement the repository pattern.

Original author description

Define a Protean repository, the persistence abstraction for aggregates in Domain-Driven Design. Repositories provide a collection-oriented interface to load and persist aggregates, hiding database details behind a clean domain API. Protean provides a default repository automatically for every aggregate; custom repositories add domain-specific queries or database-specific optimizations. Use when you need to persist an aggregate, load an aggregate, write a custom repository, add a custom query, override the default repository, connect to a specific database, or implement the repository pattern.

How it works

  1. Key concepts
  2. Basic structure: Default repository (no code needed)
  3. Basic structure: Custom repository
  4. Key rules
  5. Quick example: Custom repository with queries
  6. Counting and null-aware queries
  7. Common mistakes
  8. Detailed references
  9. Verify your work
Original SKILL.md headings · 202 lines, 961 words
SKILL.md preview
---
name: repository
description: Define a Protean repository, the persistence abstraction for aggregates in Domain-Driven Design. Repositories provide a collection-oriented interface to load and persist aggregates, hiding database details behind a clean domain API. Protean provides a default repository automatically for every aggregate; custom repositories add domain-specific queries or database-specific optimizations. Use when you need to persist an aggregate, load an aggregate, write a custom repository, add a custom query, override the default repository, connect to a specific database, or implement the repository pattern. Repositories always belong to an aggregate and respect Unit of Work transactional semantics.
license: Apache-2.0
compatibility: Requires Python 3.11+, protean framework
metadata:
  author: proteanhq
  version: "0.1"
  category: element
---

# Repository

## Key concepts

Repositories are the **gateway between your domain model and the persistence layer**. In DDD, repositories represent a collection of aggregates: you `add` to the collection and `get` from it, without exposing database internals to the domain.

**Protean provides a default repository for every aggregate automatically.** You only need a custom repository when you want to add custom query methods or database-specific optimizations.

## Basic structure: Default repository (no code needed)

The examples on this page use this aggregate and these commands. The custom
repositories below filter on `status`, `customer_id` and `assignee`, so the
aggregate declares an index led by each of them:

```python
@domain.aggregate(
    indexes=[Index("status"), Index("customer_id"), Index("assignee")]
)
class Order:
    order_id: Identifier(identifier=True)
    customer_id: Identifier()
    status: String(max_length=20, default="draft")
    assignee: String(max_length=80)
    items = HasMany("LineItem")

    def place(self):
        self.status = "placed"

    def cancel(self):
        self.status = "cancelled"


@domain.entity(part_of=Order)
class LineItem:
    product_id: String(required=True, max_length=50)
    quantity: Integer(default=1)


@domain.command(part_of=Order)
class PlaceOrder:
    order_id: Identifier(identifier=True)
    customer_id: Identifier(required=True)


@domain.command(part_of=Order)
class CancelOrder:
    order_id: Identifier(identifier=True)
```

No repository class is needed. Protean generates one, and you use it directly:

```python
domain.init(traverse=False)

with domain.domain_context():
    repo = domain.repository_for(Order)
    repo.add(Order(order_id="ORD-001", customer_id="CUST-1"))
    order = repo.get("ORD-001")
```

## Basic structure: Custom repository

```python
@domain.repository(part_of=Order)
class OrderRepository:
    def find_placed_orders(self):
        return self.query.filter(status="placed").all()

    def find_by_customer(self, customer_id):
        return self.query.filter(customer_id=customer_id).all()
```

## Key rules

1. **Repositories always belong to an aggregate**: Specify `part_of` with the aggregate class, `@domain.repository(part_of=Order)`, or with a string reference, `@domain.repository(part_of="Order")`. A string resolves at `init`, so the aggregate may be defined after the repository
2. **Default repository is automatic**: Every aggregate gets `add()` and `get()` for free; only write a custom repository when you need custom queries
3. **Persist at the aggregate level**: Repositories save the entire aggregate including enclosed entities and value objects; never persist entities separately
4. **Use `add()` for both create and update**: The repository's `add()` method handles both new and modified aggregates (collection semantics)
5. **Use `get()` to load by identifier**: Loads the aggregate with all its children from the persistence store
6. **Use the query helpers for custom queries**: Inside a custom repository, use `self.query` for filtering, sorting, and paging. `self.find_by()` loads one aggregate by its field values, `self.find()` runs a composable `Q` expression and returns one `ResultSet` page of matches, capped at the aggregate's `limit` (100 by default), with `total` carrying the full count. `self.exists()` returns a bool. Below these helpers sits a private data access object, kept for infrastructure work such as hard deletion and test teardown. [Custom Queries](references/custom-queries.md) names it and says when to use it
7. **Repositories respect Unit of Work**: When inside a UoW (e.g., command handlers), changes commit together at UoW commit, atomically on providers with transactions
8. **Database option controls provider binding**: Use `database` option to lock a repository to a specific database type (default is `"ALL"`)
9. **Children are synced automatically**: HasMany/HasOne child entities are persisted/removed automatically when the aggregate is added
10. **Custom repos inherit base methods**: Custom repositories still have `add()` and `get()` from `BaseRepository`; only add new methods

## Quick example: Custom repository with queries

Every field a query method filters on needs an index. The identifier field and
any field marked `unique=True` already have one. For any other field, add an
`Index`; without one, `check` reports `UNINDEXED_FILTER_PATH`. Index `String` fields, not `Text`: an index on
a `Text` field makes `check` report `UNBOUNDED_INDEXED_STRING`:

```python
@domain.aggregate(
    indexes=[Index("category"), Index("is_active"), Index("price")]
)
class Product:
    product_id: Identifier(identifier=True)
    name: String(required=True, max_length=200)
    category: String(max_length=50)
    price: Decimal(precision=19, scale=4)
    is_active: Boolean(default=True)

@domain.repository(part_of=Product)
class ProductRepository:
    def find_by_category(self, category):
        return self.query.filter(category=category).all()

    def find_active(self):
        return self.query.filter(is_active=True).all()

    def find_affordable(self, max_price):
        return self.query.filter(price__lte=max_price).all()
```

## Counting and null-aware queries

When you only need *how many* rows match, use `count()`. It issues a flat
`COUNT` without materializing entities, so it is cheaper than `len(query.all())`:

```python
@domain.repository(part_of=Order)
class OrderRepository:
    def open_count(self) -> int:
        return self.query.filter(status="open").count()
```

Filter on whether a field is set with the `isnull` lookup:

```python
# fragment
# Orders with no assignee (assignee IS NULL)
self.query.filter(assignee__isnull=True).all().items
# Orders that have an assignee (assignee IS NOT NULL)
self.query.filter(assignee__isnull=False).all().items
```

When you need the page of items but not the total match count, pass
`with_total=False` so the adapter can skip the separate count round-trip:

```python
# fragment
items = self.query.filter(status="open").all(with_total=False).items
```

## Common mistakes

### Persisting child entities separately

```python
# fragment
# Wrong! Never persist entities directly
@domain.repository(part_of=LineItem)  # LineItem is an entity, not an aggregate
class LineItemRepository:
    pass
```

Instead: Persist at the aggregate level; child entities are synced automatically (Key rule 9).

### Wrapping repository calls in manual UnitOfWork inside handlers

```python
# fragment
@handle(PlaceOrder)
def handle_place_order(self, command):
    with UnitOfWork():  # Unnecessary! Handler has implicit UoW
        order = Order(order_id=command.order_id, customer_id=command.customer_id)
        domain.repository_for(Order).add(order)
```

Instead: Let the handler's own Unit of Work do it. A Unit of Work started inside
another one joins it, so the inner `with UnitOfWork()` opens no transaction of its
own: its commit and rollback defer to the handler's.

## Detailed references

### Core Concepts
- [Default Repository](references/default-repository.md): How Protean auto-generates repositories
- [Custom Queries](references/custom-queries.md): Writing domain-specific query methods
- [Database-Specific Repositories](references/database-specific.md): Binding repositories to specific databases
- [Unit of Work Integration](references/unit-of-work.md): Transactional semantics and UoW
- [Anti-patterns](references/anti-patterns.md): Common mistakes and how to avoid them

### Complete Examples
- [Default Repository](assets/repository_default.py): Using the auto-generated repository
- [Custom Repository](assets/repository_custom.py): Custom repository with domain-specific queries
- [Repository with Children](assets/repository_with_children.py): Persisting aggregates with child entities
- [Database-Specific Repository](assets/repository_with_database.py): Per-database repository binding
- [Repository with Unit of Work](assets/repository_with_uow.py): Explicit UoW usage outside handlers
- [Counting and Null-Aware Queries](assets/repository_counting_and_nulls.py): `count()`, `all(with_total=False)`, and the `isnull` lookup

### Related Skills
- `aggregate`: Repositories persist aggregates
- `command-handler`: Command handlers use repositories to load and persist aggregates
- `event-handler`: Event handlers load and persist their own aggregate through its repository
- `entity`: Entities enclosed within aggregates are persisted automatically via repositories

## Verify your work

- [Verify with check](../../references/verify-with-check.md): run `check` and resolve what it reports
Files in this package (12)
  • SKILL.md 9 KB
  • assets/repository_counting_and_nulls.py 4 KB
  • assets/repository_custom.py 3 KB
  • assets/repository_default.py 2 KB
  • assets/repository_with_children.py 4 KB
  • assets/repository_with_database.py 4 KB
  • assets/repository_with_uow.py 4 KB
  • references/anti-patterns.md 6 KB
  • references/custom-queries.md 6 KB
  • references/database-specific.md 3 KB
  • references/default-repository.md 2 KB
  • references/unit-of-work.md 7 KB

Versions

The database has no other skills named repository.

Identical content appears in 1 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version 985b88c1ac20 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100command-handler
    Define a Protean command handler, a class responsible for receiving domain commands and orchestrating state changes in aggregates. Command handlers extract data from commands, load or create aggregates, invoke aggregate methods, and persist state changes. They are always…
  • 100domain-service
    Define a Protean domain service, a stateless orchestrator that encapsulates complex business logic spanning multiple aggregates. Domain services centralize cross-aggregate operations that don't naturally fit within any single aggregate, while keeping aggregates focused on their…
  • 90create-persistence-adapter
    Create or update the JPA persistence adapter for one domain aggregate: entity (for leasing applications the VanillaBP workflow aggregate), Spring Data repository, the @Component implementing the outbound Repository port, its Flyway migration and its @DataJpaTest. Use when the…
  • 100ddd-testing-strategist
    DDD testing strategy — domain model unit testing, aggregate root testing, repository testing with mocks, application service integration testing, adapter E2E testing, test pyramid for DDD layered/hexagonal/clean architectures, and Test-Driven Domain Design (TDDD). Use when user…
  • 100ddd
    Domain-Driven Design patterns. Bounded contexts, aggregates, entities, value objects, domain events, repositories, and application services. Strategic and tactical DDD for complex business domains. USE WHEN: user mentions "DDD", "Domain-Driven Design", "bounded context",…
  • 100ddd-best-practices
    Domain-Driven Design guidance for modeling complex domains. Use when designing Bounded Contexts or Subdomains, discovering Aggregate boundaries from invariants and transactions, defining Aggregate Roots, designing Domain Events, typed domain failures, or repository contracts,…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.