Skip to content

Read Models

Projections are read-optimized views. Projectors maintain them by reacting to domain events. Together, projections and projectors form the read side of CQRS.

Guides: Projections


BaseProjection

BaseProjection(*args: Any, **kwargs: Any)

Bases: Element, BaseModel, OptionsMixin

Base class for projections: read-optimized views that projectors keep up to date from domain events.

Projections are mutable, and two projections are equal when their identifiers are equal. They accept basic field types and ValueObject fields. Reference, HasOne and HasMany fields are not allowed. Every projection must have at least one field marked identifier=True. Each attribute of a ValueObject field can be queried on its own. See the Projections guide for storage and querying.

Meta Options

Option Type Description
database str The [databases.*] entry that persists it (default: "default").
cache str Cache adapter name. When set, overrides database.
schema_name str The storage table/collection name.
order_by tuple Default ordering for queries.
limit int Default query result limit (default: 100).

Example::

@domain.projection
class OrderSummary(BaseProjection):
    order_id = Identifier(identifier=True)
    customer_name = String(max_length=100)
    total_amount = Float()
    status = String(max_length=20)
    shipping_address = ValueObject(Address)
Source code in src/protean/core/projection.py
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
def __init__(self, *args: Any, **kwargs: Any) -> None:
    # Check abstract before Pydantic validation to give a clear error
    # (abstract classes may lack fields, causing misleading Pydantic errors)
    if self.meta_.abstract is True:
        raise NotSupportedError(
            f"{self.__class__.__name__} class has been marked abstract"
            f" and cannot be instantiated"
        )

    # Pop VO descriptor kwargs and shadow field kwargs before Pydantic init.
    # Shadow fields (e.g. address_street, address_city) are dynamically
    # generated and must not reach Pydantic's __init__ (extra="forbid").
    projection_cls = type(self)
    values = _split_init_values(
        args,
        kwargs,
        _vo_shadow_field_names(projection_cls),
        lambda name: self._is_vo_descriptor(projection_cls, name),
    )

    # Push context onto thread-local stack for model_post_init to retrieve.
    # Pydantic clears __dict__ during super().__init__(), so we cannot
    # stash data on the instance.
    stack: list[dict[str, Any]] = getattr(_projection_init_context, "stack", [])
    depth_before_init = len(stack)
    stack.append(
        {
            "descriptor_kwargs": values.descriptor_kwargs,
            "shadow_kwargs": values.shadow_kwargs,
        }
    )
    _projection_init_context.stack = stack

    # Collect validation errors (Pydantic + required value objects)
    # before raising.
    collected_errors: dict[str, list[str]] = {}

    try:
        super().__init__(**values.kwargs)
    except PydanticValidationError as e:
        collected_errors.update(convert_pydantic_errors(e))
    finally:
        # ``model_post_init`` pops this call's entry on a successful init.
        # When Pydantic validation raises before it runs, the entry is left
        # behind. Truncate to the pre-push depth so this call's entry is
        # balanced, without popping a parent's entry or double-popping one
        # ``model_post_init`` already removed.
        del stack[depth_before_init:]

    _add_missing_required_errors(
        projection_cls,
        values.descriptor_kwargs,
        values.shadow_kwargs,
        collected_errors,
    )

    if collected_errors:
        raise ValidationError(collected_errors)

state_ property writable

state_: _EntityState

Access projection lifecycle state.

__validate_for_basic_field_types classmethod

__validate_for_basic_field_types() -> None

Reject Reference and Association descriptors.

ValueObject descriptors are allowed; they are handled via shadow fields for flat persistence storage.

Source code in src/protean/core/projection.py
190
191
192
193
194
195
196
197
198
199
200
201
202
@classmethod
def __validate_for_basic_field_types(cls) -> None:
    """Reject Reference and Association descriptors.

    ValueObject descriptors are allowed; they are handled via shadow
    fields for flat persistence storage.
    """
    for field_name, field_obj in vars(cls).items():
        if isinstance(field_obj, (Reference, Association)):
            raise IncorrectUsageError(
                f"Projections can only contain basic field types and ValueObjects. "
                f"Remove {field_name} ({field_obj.__class__.__name__}) from class {cls.__name__}"
            )

__track_id_field classmethod

__track_id_field() -> None

Find the field marked identifier=True and record its name.

Source code in src/protean/core/projection.py
227
228
229
230
231
232
233
234
235
236
237
238
239
@classmethod
def __track_id_field(cls) -> None:
    """Find the field marked ``identifier=True`` and record its name."""
    id_fld = next(
        (
            field
            for _, field in getattr(cls, _FIELDS, {}).items()
            if getattr(field, "identifier", False)
        ),
        None,
    )
    if id_fld is not None:
        setattr(cls, _ID_FIELD_NAME, id_fld.field_name)

defaults

defaults() -> None

Placeholder for defaults.

Override in subclass when an attribute's default depends on other attribute values.

Source code in src/protean/core/projection.py
327
328
329
330
331
332
def defaults(self) -> None:
    """Placeholder for defaults.

    Override in subclass when an attribute's default depends on other
    attribute values.
    """

to_dict

to_dict() -> dict[str, Any]

Return projection data as a dictionary.

ValueObject fields are serialized via the descriptor's as_dict() method.

Source code in src/protean/core/projection.py
387
388
389
390
391
392
393
394
395
396
397
def to_dict(self) -> dict[str, Any]:
    """Return projection data as a dictionary.

    ValueObject fields are serialized via the descriptor's
    ``as_dict()`` method.
    """
    result: dict[str, Any] = {}
    for fname, shim in getattr(self, _FIELDS, {}).items():
        value = getattr(self, fname, None)
        result[fname] = shim.as_dict(value)
    return result

BaseProjector

Bases: Element, HandlerMixin, OptionsMixin

Base class for projectors, which keep a projection up to date from domain events.

A projector names its projection with projector_for and can listen to events from several aggregates. The @handle decorator, or its alias @on, maps an event type to a handler method. A handler method receives the event as its only argument and creates, updates or deletes the projection record. See the Projectors guide for a walk-through.

Meta Options

Option Type Description
projector_for type The projection class this projector maintains. Required.
aggregates list Aggregate classes whose events this projector listens to.
stream_categories list Explicit stream categories to subscribe to. Overrides aggregates. A value without :: gets the domain prefix; $all stays as written.
retries int Max retry attempts on transient exceptions. Overrides server.transient_retry; None defers to it.
backoff str Retry delay strategy: "exponential", "linear", or "fixed".
retry_exceptions list Exception types (classes or dotted paths) treated as transient for retry.
sequential_by str Partition key field name for per-key sequential processing (ADR-0028).
subscription_type str "stream" or "event_store". None uses the domain default.
subscription_profile str Named subscription profile, such as "projection".
subscription_config dict Custom subscription settings that override the profile.
idempotent bool Record a delivery marker per event so a redelivered event is applied once.
suppress_checks tuple Diagnostic codes protean check should not report for this projector.

Example::

@domain.projector(projector_for=OrderSummary, aggregates=[Order])
class OrderSummaryProjector(BaseProjector):

    @on(OrderPlaced)
    def on_order_placed(self, event):
        repo = current_domain.repository_for(OrderSummary)
        repo.add(OrderSummary(
            order_id=event.order_id,
            status="placed",
        ))

    @on(OrderShipped)
    def on_order_shipped(self, event):
        repo = current_domain.repository_for(OrderSummary)
        summary = repo.get(event.order_id)
        summary.status = "shipped"
        repo.add(summary)