Read Models API Reference

Reference documentation for eventsource.ports.readmodels and its adapters, which together persist and query denormalized projection state: the ReadModel Pydantic base class, the Query/Filter specification objects, the ReadModelRepository protocol and its in-memory, PostgreSQL, and SQLite implementations, the ReadModelProjection bridge between events and stored rows, and the DDL generation helpers.

eventsource.readmodels -- the pre-slice-A import path for all sixteen names below -- no longer exists (ADR 0030). Importing it raises ModuleNotFoundError, with no deprecation shim. Update imports to the paths this page documents.

Public names covered here (everything the old eventsource.readmodels.__all__ listed, now split across eventsource.ports.readmodels and three adapter modules):

Name Kind Purpose
ReadModel class Pydantic base for read model definitions, with id, timestamps, version, and deleted_at
ReadModelRepository protocol Persistence contract: read, write, delete, and soft-delete operations
ReadModelProjection class Projection base that routes events to a repository-backed read model
Query / Filter classes Filter, ordering, and pagination specification passed to find(), find_one(), and count()
InMemoryReadModelRepository class In-process repository for tests and development
PostgreSQLReadModelRepository class Production repository over an asyncpg/SQLAlchemy async connection
SQLiteReadModelRepository class Embedded repository over an aiosqlite connection
generate_schema / generate_indexes / generate_full_schema functions DDL generation from a ReadModel subclass
generate_additive_migration / reconcile_read_model_schema functions Adding columns a model gained to a table that already exists
POSTGRESQL_TYPE_MAP / SQLITE_TYPE_MAP dicts Python-to-SQL column type mappings used by schema generation
ReadModelError / OptimisticLockError / ReadModelNotFoundError / ReadModelSchemaMismatchError exceptions Error hierarchy for read model operations

The pure ones import from the port; the backends from their adapter modules:


from eventsource.ports.readmodels import ReadModel, Query, Filter
from eventsource.adapters.memory.readmodels import InMemoryReadModelRepository

Overview

Read models are the query side of the library's CQRS split. Where an AggregateRoot is rebuilt from its event stream on every load, a ReadModel is a denormalized row that is written once by a projection and then read directly — no replay, no aggregation at query time.

The package divides into five concerns:

A few behaviors are worth internalizing before reading the per-symbol sections:

The three shipped implementations are interchangeable behind the protocol: InMemoryReadModelRepository for tests, PostgreSQLReadModelRepository for production, and SQLiteReadModelRepository for embedded or development use — with the SQLite type-fidelity caveats noted under Type Maps.

Import Surface

eventsource.ports.readmodels is a subpackage (ADR 0029) rather than a flat module, because it groups four genuinely distinct pure artifacts users import for four different reasons: a subclassable pydantic base, a query specification language, a 15-method repository Protocol, and an exception family. Its __all__ contains eight names; the three backend repositories and three schema-generation names live in their adapter modules instead:


__all__ = [
    "Filter",
    "OptimisticLockError",
    "Query",
    "ReadModel",
    "ReadModelError",
    "ReadModelNotFoundError",
    "ReadModelRepository",
]

Names by defining module

Exported name Defined in Kind
ReadModel eventsource.ports.readmodels.model Pydantic BaseModel subclass
ReadModelRepository eventsource.ports.readmodels.repository @runtime_checkable Protocol[TModel]
Query, Filter eventsource.ports.readmodels.query query specification classes
ReadModelError, OptimisticLockError, ReadModelNotFoundError eventsource.ports.readmodels.exceptions exceptions
ReadModelProjection eventsource.adapters.sql.readmodel_projection class (extends DatabaseProjection)
InMemoryReadModelRepository eventsource.adapters.memory.readmodels class InMemoryReadModelRepository[TModel: ReadModel]
PostgreSQLReadModelRepository eventsource.adapters.postgresql.readmodels class PostgreSQLReadModelRepository[TModel: ReadModel]
SQLiteReadModelRepository eventsource.adapters.sqlite.readmodels class SQLiteReadModelRepository[TModel: _BaseReadModel]
generate_schema, generate_indexes, generate_full_schema, generate_additive_migration eventsource.adapters.sql.readmodel_schema functions
reconcile_read_model_schema, read_table_columns eventsource.adapters.sql.readmodel_reconcile async functions
POSTGRESQL_TYPE_MAP, SQLITE_TYPE_MAP eventsource.adapters.sql.readmodel_schema dict constants

Import the pure names from the port package root — its submodule layout is an implementation detail — and the backend names from their adapter modules:


from eventsource.ports.readmodels import (
    Filter,
    OptimisticLockError,
    Query,
    ReadModel,
    ReadModelRepository,
)
from eventsource.adapters.memory.readmodels import InMemoryReadModelRepository
from eventsource.adapters.sql.readmodel_schema import generate_full_schema

Backend imports are per-adapter, not eager on one namespace

Unlike the pre-slice-A eventsource.readmodels package, which imported all three repository implementations eagerly at one package's import time, eventsource.ports.readmodels pulls in none of them — importing it costs no sqlalchemy and no aiosqlite. Each backend is its own adapter module, imported only when you need that backend:

So from eventsource.adapters.sqlite.readmodels import SQLiteReadModelRepository succeeds in a bare install; the missing-dependency error, if any, surfaces where you open the connection.

Relationship to the top-level `eventsource` namespace

Of these names, only ReadModelProjection is re-exported from the top-level eventsource package — unchanged by this move. Everything else must be imported from eventsource.ports.readmodels or the relevant adapter module:


from eventsource import ReadModelProjection               # available
from eventsource.ports.readmodels import ReadModel, Query  # required form

Name collision: two `OptimisticLockError` classes

The library defines two distinct exceptions with this name, and they are not related by inheritance. This collision predates the slice A structure work — it is not something the port split introduced — and is tracked in BACKLOG.md for resolution (proposed: rename the read-model one to ReadModelVersionConflictError with a deprecation alias):

Symbol Base Raised by
eventsource.OptimisticLockError (from eventsource.domain.exceptions) EventSourceError aggregate/event-store concurrency conflicts
eventsource.ports.readmodels.OptimisticLockError ReadModelError save_with_version_check() on a read model repository

An except eventsource.OptimisticLockError block will not catch a read model version conflict. When both are in scope, alias one at the import site:


from eventsource import OptimisticLockError
from eventsource.ports.readmodels import OptimisticLockError as ReadModelOptimisticLockError

See Exceptions for the attributes each carries.

ReadModel


class ReadModel(BaseModel)

Defined in eventsource.ports.readmodels.model. The Pydantic base class for every persisted projection row. Subclass it, add domain fields, and the repository and schema-generation helpers take care of the rest.


from decimal import Decimal
from uuid import uuid4

from eventsource.ports.readmodels import ReadModel


class OrderSummary(ReadModel):
    order_number: str
    customer_name: str
    status: str
    total_amount: Decimal
    item_count: int = 0


summary = OrderSummary(
    id=uuid4(),
    order_number="ORD-001",
    customer_name="Alice Smith",
    status="pending",
    total_amount=Decimal("99.99"),
)

id is the only required field — everything else on the base has a default.

Model configuration (mutable, `from_attributes`, `populate_by_name`)


model_config = ConfigDict(
    from_attributes=True,
    populate_by_name=True,
)
Setting Value Consequence
frozen not set (i.e. False) Instances are mutable. This is the deliberate contrast with DomainEvent, which is frozen — projection handlers mutate a loaded model and save it back.
from_attributes True Model.model_validate(obj) accepts any object with matching attributes, not just a mapping. Used to hydrate models from ORM rows and Row objects.
populate_by_name True Fields declared with an alias can be populated by either the alias or the Python field name.

Everything else is Pydantic v2 defaults: extra="ignore" (unknown keys are dropped rather than rejected) and validate_assignment=False (see the caveat below).

Mutability is what makes the read/modify/save cycle work:


model = await repo.get(order_id)
model.status = "shipped"      # no copy, no model_copy(update=...)
await repo.save(model)

from_attributes=True is what lets a model be hydrated from a database row or any other attribute-bearing object, not just a dict:


class SourceObject:
    def __init__(self) -> None:
        self.id = uuid4()
        self.name = "from_attrs"
        self.created_at = datetime.now(UTC)
        self.updated_at = datetime.now(UTC)
        self.version = 1
        self.deleted_at = None


class SimpleModel(ReadModel):
    name: str


model = SimpleModel.model_validate(SourceObject())
model.name    # 'from_attrs'

Validation still runs on construction and on model_validate — the field constraints on the base fields (notably version >= 1) are enforced there. Because validate_assignment is not enabled, those constraints are not re-checked on attribute assignment:


model = SimpleModel(id=uuid4(), name="x")
SimpleModel(id=uuid4(), name="x", version=0)   # ValidationError
model.version = 0                              # accepted silently

In practice this does not bite, because version and updated_at are repository-managed and overwritten on save() — but do not rely on assignment to catch a bad value in your own domain fields.

Base fields: `id`, `created_at`, `updated_at`, `version`, `deleted_at`

Field Type Default Notes
id UUID required Primary key. Usually the aggregate id the projection is tracking.
created_at datetime datetime.now(UTC) Set once when the model is first constructed; timezone-aware UTC.
updated_at datetime datetime.now(UTC) Refreshed by the repository on every write.
version int 1, constrained ge=1 Optimistic-locking counter. version=0 raises a Pydantic ValidationError.
deleted_at `datetime \ None` None Soft-delete marker. Non-None means the row is excluded from default reads.

Only id is required. A minimal construction therefore looks like:


model = SimpleModel(id=uuid4(), name="test")
model.version        # 1
model.deleted_at     # None
model.created_at     # timezone-aware datetime, tzinfo is not None

`id`

Declared id: UUID with no default, so it must be supplied explicitly — read models do not mint their own identity. In practice this is the id of the aggregate (or other natural key) the projection tracks, which is what makes get(aggregate_id) the normal lookup. It is the PRIMARY KEY in generated schemas and the conflict target for the upsert in save().

`created_at` and `updated_at`

Both use default_factory=lambda: datetime.now(UTC), so both are always timezone-aware UTC and both are set at construction time — a freshly built model has created_at == updated_at in effect, not None.

After the first write the two diverge, and the split is enforced by the repositories:

Assigning updated_at in a projection handler is therefore pointless: it is discarded on the next save.

`version`

version: int = Field(default=1, ge=1) — the optimistic-locking counter, and the only base field with a validation constraint. Construction with version=0 raises a Pydantic ValidationError; the counter starts at 1 for a newly-created model and is incremented by the repository, never by the caller: