Skip to content

DatabasePort

The database Ports are the contract a database adapter implements. Every database adapter implements DatabasePort. RawQueryDatabasePort adds raw(), and an adapter that declares DatabaseCapabilities.RAW_QUERIES implements it.

A database adapter class subclasses BaseDatabase first, then the Port it implements. BaseDatabase holds the lookup registry, the schema migrator and the managed flag.

See Database Adapters for concrete adapter configuration, and Custom Database Adapters to write one.

Bases: Protocol

The members every database provider implements.

An adapter subclasses this, or RawQueryDatabasePort, explicitly.

Source code in src/protean/port/database.py
219
220
221
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

database_type class-attribute

database_type: str

A short identifier for the database, such as "memory", "elasticsearch" or one of the SQLAlchemy dialect names.

capabilities abstractmethod property

capabilities: DatabaseCapabilities

The behaviours this provider supports.

get_session abstractmethod

get_session() -> SessionProtocol

The session the Unit of Work commits or rolls back.

A backend without transactions returns a session whose methods do nothing and whose is_active is True.

Source code in src/protean/port/database.py
228
229
230
231
232
233
234
@abstractmethod
def get_session(self) -> SessionProtocol:
    """The session the Unit of Work commits or rolls back.

    A backend without transactions returns a session whose methods do
    nothing and whose `is_active` is `True`.
    """

new_session abstractmethod

new_session() -> SessionProtocol

A new session, independent of any session a Unit of Work holds.

The DAO service runs a standalone operation in it, and ends it with commit or rollback and then close.

Source code in src/protean/port/database.py
236
237
238
239
240
241
242
@abstractmethod
def new_session(self) -> SessionProtocol:
    """A new session, independent of any session a Unit of Work holds.

    The `DAO` service runs a standalone operation in it, and ends it with
    `commit` or `rollback` and then `close`.
    """

commit abstractmethod

commit(session: SessionProtocol) -> None

Commit session.

RAISES DESCRIPTION
ExpectedVersionError

A version-checked write in the session found a newer stored version.

Source code in src/protean/port/database.py
244
245
246
247
248
249
250
251
@abstractmethod
def commit(self, session: SessionProtocol) -> None:
    """Commit `session`.

    Raises:
        ExpectedVersionError: A version-checked write in the session found
            a newer stored version.
    """

rollback abstractmethod

rollback(session: SessionProtocol) -> None

Roll back session.

Source code in src/protean/port/database.py
253
254
255
@abstractmethod
def rollback(self, session: SessionProtocol) -> None:
    """Roll back `session`."""

flush

flush(session: SessionProtocol) -> None

Run session's pending writes inside its transaction, without committing. Does nothing by default, for a session that writes at commit.

RAISES DESCRIPTION
ExpectedVersionError

A version-checked write in the session found a newer stored version.

Source code in src/protean/port/database.py
257
258
259
260
261
262
263
264
265
266
267
268
def flush(self, session: SessionProtocol) -> None:
    """Run `session`'s pending writes inside its transaction, without
    committing. Does nothing by default, for a session that writes at
    commit.

    Raises:
        ExpectedVersionError: A version-checked write in the session found
            a newer stored version.
    """
    # mypy treats a Protocol member whose body is only a docstring as
    # abstract; a provider whose session writes at commit inherits this no-op.
    return None  # noqa: RET501

get_connection abstractmethod

get_connection() -> object

The adapter's native handle, such as a SQLAlchemy session or an Elasticsearch client.

Source code in src/protean/port/database.py
270
271
272
273
@abstractmethod
def get_connection(self) -> object:
    """The adapter's native handle, such as a SQLAlchemy session or an
    Elasticsearch client."""

ping abstractmethod

ping() -> bool

Whether the database is reachable.

Source code in src/protean/port/database.py
275
276
277
@abstractmethod
def ping(self) -> bool:
    """Whether the database is reachable."""

health abstractmethod

health() -> DatabaseHealth

The provider's health record.

Source code in src/protean/port/database.py
279
280
281
@abstractmethod
def health(self) -> DatabaseHealth:
    """The provider's health record."""

close

close() -> None

Release the provider's connections and pools. Does nothing by default.

Source code in src/protean/port/database.py
283
284
285
286
287
288
def close(self) -> None:
    """Release the provider's connections and pools. Does nothing by
    default."""
    # mypy treats a Protocol member whose body is only a docstring as
    # abstract, which would make every adapter implement `close`.
    return None  # noqa: RET501

clear abstractmethod

clear() -> None

Remove every record from the provider's store.

Source code in src/protean/port/database.py
290
291
292
@abstractmethod
def clear(self) -> None:
    """Remove every record from the provider's store."""

create_schema

create_schema() -> None

Create the tables or indices the domain's elements need, leaving existing ones untouched. Does nothing by default.

Source code in src/protean/port/database.py
294
295
296
297
298
299
def create_schema(self) -> None:
    """Create the tables or indices the domain's elements need, leaving
    existing ones untouched. Does nothing by default."""
    # mypy treats a Protocol member whose body is only a docstring as
    # abstract; a provider without schema objects inherits this no-op.
    return None  # noqa: RET501

drop_schema

drop_schema() -> None

Drop the tables or indices the domain's elements own. Does nothing by default.

Source code in src/protean/port/database.py
301
302
303
304
305
306
def drop_schema(self) -> None:
    """Drop the tables or indices the domain's elements own. Does nothing
    by default."""
    # mypy treats a Protocol member whose body is only a docstring as
    # abstract; a provider without schema objects inherits this no-op.
    return None  # noqa: RET501

dao_for abstractmethod

dao_for(
    entity_cls: type[BaseEntity | BaseProjection],
    model_cls: type[DatabaseModelPort],
) -> DAOPort

The adapter DAO for entity_cls that stores it through model_cls.

Source code in src/protean/port/database.py
308
309
310
311
312
313
314
315
@abstractmethod
def dao_for(
    self,
    entity_cls: "type[BaseEntity | BaseProjection]",
    model_cls: "type[DatabaseModelPort]",
) -> "DAOPort":
    """The adapter DAO for `entity_cls` that stores it through
    `model_cls`."""

model_for abstractmethod

model_for(
    entity_cls: type[BaseEntity | BaseProjection],
    model_cls: type[BaseDatabaseModel] | None = None,
) -> type[DatabaseModelPort]

The database model class for entity_cls.

With model_cls, a user-defined model, it returns a subclass of that model with the adapter's internals added, or model_cls unchanged when it already subclasses the adapter's model class. Without it, it builds a model from the entity's fields. The adapter caches each class it builds or decorates per entity, and later calls for that entity return the cached class.

Source code in src/protean/port/database.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
@abstractmethod
def model_for(
    self,
    entity_cls: "type[BaseEntity | BaseProjection]",
    model_cls: "type[BaseDatabaseModel] | None" = None,
) -> "type[DatabaseModelPort]":
    """The database model class for `entity_cls`.

    With `model_cls`, a user-defined model, it returns a subclass of that
    model with the adapter's internals added, or `model_cls` unchanged when it
    already subclasses the adapter's model class. Without it, it builds a model
    from the entity's fields. The adapter caches each class it builds or
    decorates per entity, and later calls for that entity return the
    cached class.
    """

get_lookups abstractmethod classmethod

get_lookups() -> Mapping[str, type[LookupPort]]

Every lookup class the provider class registers, keyed by lookup name.

Source code in src/protean/port/database.py
333
334
335
336
337
@classmethod
@abstractmethod
def get_lookups(cls) -> "Mapping[str, type[LookupPort]]":
    """Every lookup class the provider class registers, keyed by lookup
    name."""

get_lookup abstractmethod

get_lookup(lookup_name: str) -> type[LookupPort]

The lookup class registered under lookup_name.

Raises NotImplementedError naming the lookup and the provider when no lookup is registered under lookup_name.

Source code in src/protean/port/database.py
339
340
341
342
343
344
345
@abstractmethod
def get_lookup(self, lookup_name: str) -> "type[LookupPort]":
    """The lookup class registered under `lookup_name`.

    Raises `NotImplementedError` naming the lookup and the provider when
    no lookup is registered under `lookup_name`.
    """

RawQueryDatabasePort

Bases: DatabasePort, Protocol

The raw-query member, unlocked by DatabaseCapabilities.RAW_QUERIES.

Source code in src/protean/port/database.py
219
220
221
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

raw abstractmethod

raw(query: Any, data: Any = None) -> Any

Run query on the provider's connection and return the database's result unchanged.

Source code in src/protean/port/database.py
351
352
353
354
@abstractmethod
def raw(self, query: Any, data: Any = None) -> Any:
    """Run `query` on the provider's connection and return the database's
    result unchanged."""

DatabaseHealth

What DatabasePort.health reports.

pool instance-attribute

pool: PoolStats | None

The provider's connection pool, or None for a provider without one or whose pool keeps no counters.

BaseDatabase

Bases: RegisterLookupMixin, DatabasePort

Framework logic shared by the built-in providers.

A provider subclasses this class first and then DatabasePort, or RawQueryDatabasePort when it declares DatabaseCapabilities.RAW_QUERIES. It sets database_type, implements the Port's abstract members, and registers every lookup in protean.port.dao.REQUIRED_LOOKUPS.

The Custom Database Adapters guide walks through building an adapter: the DAO, the database model, lookups, registration, and the call flow.

Source code in src/protean/port/database.py
381
382
383
384
385
def __init__(self, name: str, domain: "Domain", config: Mapping[str, Any]) -> None:
    self.name = name
    self.domain = domain
    self.config = config
    self.managed = config.get("managed", True)

__init_subclass__

__init_subclass__(**kwargs: Any) -> None

Raise TypeError when a subclass names RawQueryDatabasePort but defines no raw of its own.

Source code in src/protean/port/database.py
369
370
371
372
373
374
375
376
377
378
379
def __init_subclass__(cls, **kwargs: Any) -> None:
    """Raise `TypeError` when a subclass names `RawQueryDatabasePort` but
    defines no `raw` of its own."""
    super().__init_subclass__(**kwargs)
    # `BaseDatabase.raw` satisfies the Port's abstract `raw` in the MRO, so
    # without this check such a provider builds and fails at call time.
    if RawQueryDatabasePort in cls.__mro__ and cls.raw is BaseDatabase.raw:
        raise TypeError(
            f"{cls.__name__} subclasses RawQueryDatabasePort but does not "
            "implement raw"
        )

raw

raw(query: Any, data: Any = None) -> Any

Raise NotSupportedError naming the provider.

A provider that declares DatabaseCapabilities.RAW_QUERIES overrides this with its own raw.

Source code in src/protean/port/database.py
387
388
389
390
391
392
393
394
395
396
def raw(self, query: Any, data: Any = None) -> Any:
    """Raise `NotSupportedError` naming the provider.

    A provider that declares `DatabaseCapabilities.RAW_QUERIES` overrides
    this with its own `raw`.
    """
    raise NotSupportedError(
        f"Provider '{self.name}' ({self.__class__.__name__}) "
        "does not support raw queries"
    )

schema_migrator

schema_migrator(directory: Path) -> SchemaMigrator

Return the schema migrator that keeps its history in directory.

Raises NotSupportedError if the provider does not declare SCHEMA_MIGRATIONS.

Source code in src/protean/port/database.py
398
399
400
401
402
403
404
405
406
407
408
409
def schema_migrator(self, directory: pathlib.Path) -> SchemaMigrator:
    """Return the schema migrator that keeps its history in ``directory``.

    Raises NotSupportedError if the provider does not declare
    ``SCHEMA_MIGRATIONS``.
    """
    if DatabaseCapabilities.SCHEMA_MIGRATIONS not in self.capabilities:
        raise NotSupportedError(
            f"Provider '{self.name}' ({self.__class__.__name__}) "
            "does not support schema migrations"
        )
    return self._schema_migrator(directory)

owns

owns(element_cls: type[Any]) -> bool

Return whether this provider materializes a table/index for element_cls.

It returns False for:

  • Event-sourced aggregates: They persist to the event store, not a database table/index.
  • Entities of event-sourced aggregates (at any nesting depth): They follow their root aggregate into the event store.
  • Cache-backed elements (e.g. @domain.projection(cache=...)): They persist to a cache adapter and carry meta_.database is None.
  • Elements owned by a different provider: In multi-provider domains, each provider materializes only the elements configured to it.

Call it after domain.init(), which sets meta_.aggregate_cluster.

RAISES DESCRIPTION
ConfigurationError

element_cls names a provider that is not configured.

Source code in src/protean/port/database.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def owns(self, element_cls: type[Any]) -> bool:
    """Return whether this provider materializes a table/index for ``element_cls``.

    It returns ``False`` for:

    - **Event-sourced aggregates**: They persist to the event store, not a
      database table/index.
    - **Entities of event-sourced aggregates** (at any nesting depth): They
      follow their root aggregate into the event store.
    - **Cache-backed elements** (e.g. ``@domain.projection(cache=...)``):
      They persist to a cache adapter and carry ``meta_.database is None``.
    - **Elements owned by a different provider**: In multi-provider domains,
      each provider materializes only the elements configured to it.

    Call it after ``domain.init()``, which sets
    ``meta_.aggregate_cluster``.

    Raises:
        ConfigurationError: ``element_cls`` names a provider that is not
            configured.
    """
    meta = element_cls.meta_

    # Event-sourced aggregates (and entities anywhere in their cluster) live
    # in the event store, not a database. Entities inherit their root
    # aggregate via ``aggregate_cluster``; an aggregate is its own cluster.
    # Projections have no cluster, so fall back to the element itself.
    cluster = getattr(meta, "aggregate_cluster", None) or element_cls
    if getattr(cluster.meta_, "is_event_sourced", False):
        return False

    # Cache-backed elements have no database (``database is None``).
    provider_name = getattr(meta, "database", None)
    if provider_name is None:
        return False

    # A provider name that resolves to nothing is a misconfiguration —
    # surface it here rather than silently skipping the element.
    if provider_name not in self.domain.databases:
        raise ConfigurationError(
            f"{element_cls.__name__} references provider '{provider_name}', "
            f"but no provider is configured with that name"
        )

    # In multi-provider domains, only materialize elements owned by this
    # provider. Provider names are the unique keys of the provider registry,
    # so comparing names resolves ownership without indexing on ``None``.
    return bool(provider_name == self.name)

DatabaseModelPort

Bases: Protocol

The class methods the framework calls on an adapter's database model.

A DAO converts an entity to a record with from_entity on each single-entity write, and a query converts records back with to_entity or to_records. Protean calls each member on the model class.

BaseDatabaseModel, the class a user subclasses with @domain.database_model, satisfies this Protocol structurally.

from_entity abstractmethod classmethod

from_entity(entity: BaseEntity) -> Any

The storage record for entity, ready for the adapter to persist.

Source code in src/protean/port/database.py
188
189
190
191
@classmethod
@abstractmethod
def from_entity(cls, entity: "BaseEntity") -> Any:
    """The storage record for `entity`, ready for the adapter to persist."""

to_entity abstractmethod classmethod

to_entity(item: Any) -> BaseEntity

The entity or aggregate that the storage record item holds.

Source code in src/protean/port/database.py
193
194
195
196
@classmethod
@abstractmethod
def to_entity(cls, item: Any) -> "BaseEntity":
    """The entity or aggregate that the storage record `item` holds."""

to_records abstractmethod classmethod

to_records(
    items: list[Any], fields: list[str]
) -> list[Record]

One read-only Record per storage record in items, in order, holding only the attributes named in fields.

Source code in src/protean/port/database.py
198
199
200
201
202
@classmethod
@abstractmethod
def to_records(cls, items: list[Any], fields: list[str]) -> "list[Record]":
    """One read-only `Record` per storage record in `items`, in order,
    holding only the attributes named in `fields`."""

DAOPort

An adapter's DAO class implements DAOPort, and subclasses the optional DAO ports whose flags its database declares.

Bases: Protocol

The storage operations every database adapter's DAO implements.

Each operation that touches stored rows takes the session to run in as its first argument. The adapter runs the operation in that session and leaves it open and uncommitted: the caller owns the transaction.

The adapter DAO class sets the four attributes in its own constructor, which takes (provider, entity_cls, database_model_cls). The Protocol supplies no constructor body.

Source code in src/protean/port/dao.py
93
94
95
96
97
98
def __init__(
    self,
    provider: Any,
    entity_cls: type[BaseEntity],
    database_model_cls: type[DatabaseModelPort],
) -> None: ...

schema_name instance-attribute

schema_name: str

The table, index or store key the entity's rows live under.

filter abstractmethod

filter(
    session: SessionProtocol,
    criteria: Q,
    *,
    offset: int = 0,
    limit: int = 10,
    order_by: Sequence[str] = (),
    with_total: bool = True,
    fields: Sequence[str] | None = None,
) -> ResultSet

Return one page of the rows that match criteria.

PARAMETER DESCRIPTION
session

The session to read in.

TYPE: SessionProtocol

criteria

The filter conditions.

TYPE: Q

offset

The number of matching rows to skip.

TYPE: int DEFAULT: 0

limit

The most rows to return.

TYPE: int DEFAULT: 10

order_by

Keys to sort by, applied in turn. A - prefix sorts that key descending.

TYPE: Sequence[str] DEFAULT: ()

with_total

When False, the caller does not need the full match count. The adapter may skip computing it (for example, SQL's separate COUNT query) and set ResultSet.total to the size of the returned page.

TYPE: bool DEFAULT: True

fields

Column names to fetch, set by QuerySet.only(). The identifier is always among them. The adapter fetches only those columns. None fetches full rows.

TYPE: Sequence[str] | None DEFAULT: None

RETURNS DESCRIPTION
ResultSet

A ResultSet whose items are raw storage records.

Source code in src/protean/port/dao.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@abstractmethod
def filter(
    self,
    session: SessionProtocol,
    criteria: Q,
    *,
    offset: int = 0,
    limit: int = 10,
    order_by: Sequence[str] = (),
    with_total: bool = True,
    fields: Sequence[str] | None = None,
) -> ResultSet:
    """Return one page of the rows that match ``criteria``.

    Args:
        session: The session to read in.
        criteria: The filter conditions.
        offset: The number of matching rows to skip.
        limit: The most rows to return.
        order_by: Keys to sort by, applied in turn. A ``-`` prefix sorts
            that key descending.
        with_total: When ``False``, the caller does not need the full
            match count. The adapter may skip computing it (for example,
            SQL's separate ``COUNT`` query) and set ``ResultSet.total`` to
            the size of the returned page.
        fields: Column names to fetch, set by ``QuerySet.only()``. The
            identifier is always among them. The adapter fetches only those
            columns. ``None`` fetches full rows.

    Returns:
        A ``ResultSet`` whose ``items`` are raw storage records.
    """

count abstractmethod

count(session: SessionProtocol, criteria: Q) -> int

The number of rows that match criteria, read without fetching the rows.

Source code in src/protean/port/dao.py
133
134
135
136
@abstractmethod
def count(self, session: SessionProtocol, criteria: Q) -> int:
    """The number of rows that match ``criteria``, read without fetching
    the rows."""

insert abstractmethod

insert(session: SessionProtocol, model: Any) -> Any

Write model as a new row and return the model object.

RAISES DESCRIPTION
ValidationError

A unique field's value is already stored, on a store that checks unique fields itself.

Source code in src/protean/port/dao.py
138
139
140
141
142
143
144
145
@abstractmethod
def insert(self, session: SessionProtocol, model: Any) -> Any:
    """Write ``model`` as a new row and return the model object.

    Raises:
        ValidationError: A unique field's value is already stored, on a
            store that checks unique fields itself.
    """

update abstractmethod

update(
    session: SessionProtocol,
    model: Any,
    *,
    expected_version: int | None = None,
) -> Any

Write model over its stored row and return the model object.

When expected_version is not None, the adapter rejects the write when the stored version differs, including when another writer commits a new version between the check and the write. For example, the SQL adapter compares the version it loads, and the mapper's version column makes a late UPDATE fail at flush or commit.

RAISES DESCRIPTION
ObjectNotFoundError

No row is stored under the model's identifier.

ExpectedVersionError

The stored version is not expected_version.

Source code in src/protean/port/dao.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
@abstractmethod
def update(
    self,
    session: SessionProtocol,
    model: Any,
    *,
    expected_version: int | None = None,
) -> Any:
    """Write ``model`` over its stored row and return the model object.

    When ``expected_version`` is not ``None``, the adapter rejects the
    write when the stored version differs, including when another writer
    commits a new version between the check and the write. For example,
    the SQL adapter compares the version it loads, and the mapper's
    version column makes a late ``UPDATE`` fail at flush or commit.

    Raises:
        ObjectNotFoundError: No row is stored under the model's identifier.
        ExpectedVersionError: The stored version is not
            ``expected_version``.
    """

update_all abstractmethod

update_all(
    session: SessionProtocol,
    criteria: Q,
    values: Mapping[str, Any],
) -> int

Write values to every row that matches criteria.

RETURNS DESCRIPTION
int

The number of rows that matched criteria. An adapter may

int

return 0 without reading the store when values is empty,

int

as the Elasticsearch adapter does.

Source code in src/protean/port/dao.py
169
170
171
172
173
174
175
176
177
178
179
@abstractmethod
def update_all(
    self, session: SessionProtocol, criteria: Q, values: Mapping[str, Any]
) -> int:
    """Write ``values`` to every row that matches ``criteria``.

    Returns:
        The number of rows that matched ``criteria``. An adapter may
        return ``0`` without reading the store when ``values`` is empty,
        as the Elasticsearch adapter does.
    """

delete abstractmethod

delete(session: SessionProtocol, model: Any) -> Any

Delete the row stored under model's identifier and return the model object.

RAISES DESCRIPTION
ObjectNotFoundError

No row is stored under the identifier.

Source code in src/protean/port/dao.py
181
182
183
184
185
186
187
188
@abstractmethod
def delete(self, session: SessionProtocol, model: Any) -> Any:
    """Delete the row stored under ``model``'s identifier and return the
    model object.

    Raises:
        ObjectNotFoundError: No row is stored under the identifier.
    """

delete_all abstractmethod

delete_all(
    session: SessionProtocol, criteria: Q | None = None
) -> int

Delete every row that matches criteria.

PARAMETER DESCRIPTION
session

The session to delete in.

TYPE: SessionProtocol

criteria

The filter conditions. None deletes every row of the table or index.

TYPE: Q | None DEFAULT: None

RETURNS DESCRIPTION
int

The number of rows that matched criteria.

Source code in src/protean/port/dao.py
190
191
192
193
194
195
196
197
198
199
200
201
@abstractmethod
def delete_all(self, session: SessionProtocol, criteria: Q | None = None) -> int:
    """Delete every row that matches ``criteria``.

    Args:
        session: The session to delete in.
        criteria: The filter conditions. ``None`` deletes every row of the
            table or index.

    Returns:
        The number of rows that matched ``criteria``.
    """

has_table abstractmethod

has_table() -> bool

Whether the table, index or collection exists in the store.

Source code in src/protean/port/dao.py
203
204
205
@abstractmethod
def has_table(self) -> bool:
    """Whether the table, index or collection exists in the store."""

claim_lock

claim_lock() -> AbstractContextManager[object]

A lock that the portable claim and the portable bounded delete hold while they run.

This default returns contextlib.nullcontext(), which locks nothing. An adapter whose store has no row locks overrides it.

Source code in src/protean/port/dao.py
207
208
209
210
211
212
213
214
def claim_lock(self) -> AbstractContextManager[object]:
    """A lock that the portable claim and the portable bounded delete
    hold while they run.

    This default returns ``contextlib.nullcontext()``, which locks
    nothing. An adapter whose store has no row locks overrides it.
    """
    return nullcontext()

RawQueryDAOPort

Bases: Protocol

A DAO that runs a raw query.

A DAO class subclasses this port when it implements :meth:raw. The provider declares DatabaseCapabilities.RAW_QUERIES.

raw abstractmethod

raw(
    session: SessionProtocol, query: Any, data: Any = None
) -> ResultSet

Run a raw query on the database and return the matching records.

QuerySet.raw() calls this through the DAO service. The query bypasses the Unit of Work. Raise an exception when a result cannot be turned into a record.

PARAMETER DESCRIPTION
session

The session the service supplies.

TYPE: SessionProtocol

query

The query, passed to the database as it is.

TYPE: Any

data

Data to pass along with the query, such as the values for an update statement.

TYPE: Any DEFAULT: None

RETURNS DESCRIPTION
ResultSet

A ResultSet of the storage records the query returned.

Source code in src/protean/port/dao.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
@abstractmethod
def raw(self, session: SessionProtocol, query: Any, data: Any = None) -> ResultSet:
    """Run a raw query on the database and return the matching records.

    ``QuerySet.raw()`` calls this through the ``DAO`` service. The query
    bypasses the Unit of Work. Raise an exception when a result cannot be
    turned into a record.

    Args:
        session: The session the service supplies.
        query: The query, passed to the database as it is.
        data: Data to pass along with the query, such as the values for an
            update statement.

    Returns:
        A ``ResultSet`` of the storage records the query returned.
    """

InsertIfAbsentPort

Bases: Protocol

A DAO that writes a row only when no other row holds its unique key.

A DAO class subclasses this port when it implements both members. The provider declares DatabaseCapabilities.INSERT_IF_ABSENT, and DAO.save_if_absent then writes through these members instead of checking the key and saving in two steps.

The unique key is the values of the fields of each Index the entity declares with unique=True and no where predicate. Each member makes the check and the write one atomic step.

insert_if_absent abstractmethod

insert_if_absent(
    session: SessionProtocol, model: Any
) -> bool

Write model as a new row unless another row holds one of its unique keys.

RETURNS DESCRIPTION
bool

True when the row was written, False when another row holds

bool

a key. Nothing is written in that case.

Source code in src/protean/port/dao.py
256
257
258
259
260
261
262
263
264
@abstractmethod
def insert_if_absent(self, session: SessionProtocol, model: Any) -> bool:
    """Write ``model`` as a new row unless another row holds one of its
    unique keys.

    Returns:
        ``True`` when the row was written, ``False`` when another row holds
        a key. Nothing is written in that case.
    """

update_if_absent abstractmethod

update_if_absent(
    session: SessionProtocol,
    model: Any,
    *,
    expected_version: int | None = None,
) -> bool

Write model over its stored row unless another row holds one of its unique keys.

Checks expected_version as :meth:DAOPort.update does.

RETURNS DESCRIPTION
bool

True when the row was written, False when another row holds

bool

a key. Nothing is written in that case.

Source code in src/protean/port/dao.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
@abstractmethod
def update_if_absent(
    self,
    session: SessionProtocol,
    model: Any,
    *,
    expected_version: int | None = None,
) -> bool:
    """Write ``model`` over its stored row unless another row holds one of
    its unique keys.

    Checks ``expected_version`` as :meth:`DAOPort.update` does.

    Returns:
        ``True`` when the row was written, ``False`` when another row holds
        a key. Nothing is written in that case.
    """

NativeClaimPort

Bases: Protocol

A DAO that claims rows in one statement.

A DAO class subclasses this port when it implements :meth:claim. :meth:protean.infra.dao.DAO.claim calls it when the provider declares DatabaseCapabilities.NATIVE_CLAIM, and calls the portable claim otherwise.

claim abstractmethod

claim(
    session: SessionProtocol,
    criteria: Q,
    claim_fields: Mapping[str, Any],
    limit: int,
    order_by: Sequence[str] = (),
    hold_back: HoldBack | None = None,
) -> list[Any]

Claim rows with the promises :meth:protean.infra.dao.DAO.claim states, and return the claimed entities.

limit is at least 1.

Source code in src/protean/port/dao.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@abstractmethod
def claim(
    self,
    session: SessionProtocol,
    criteria: Q,
    claim_fields: Mapping[str, Any],
    limit: int,
    order_by: Sequence[str] = (),
    hold_back: HoldBack | None = None,
) -> list[Any]:
    """Claim rows with the promises :meth:`protean.infra.dao.DAO.claim`
    states, and return the claimed entities.

    ``limit`` is at least 1.
    """

ClaimCandidatesPort

Bases: Protocol

A DAO that leaves held rows out of a claim's candidate page.

A DAO class subclasses this port when it implements :meth:claim_candidates. The portable claim reads its pages through it when the provider declares DatabaseCapabilities.FILTERED_CLAIM_CANDIDATES and the claim has a hold_back.

claim_candidates abstractmethod

claim_candidates(
    session: SessionProtocol,
    criteria: Q,
    limit: int,
    offset: int,
    order_by: Sequence[str],
    hold_back: HoldBack,
) -> list[Any]

Read one page of claim candidates.

Returns up to limit entities matching criteria in order_by order, skipping the first offset, and leaves out rows that hold_back holds. It must not leave out a row that the claim could take.

Source code in src/protean/port/dao.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
@abstractmethod
def claim_candidates(
    self,
    session: SessionProtocol,
    criteria: Q,
    limit: int,
    offset: int,
    order_by: Sequence[str],
    hold_back: HoldBack,
) -> list[Any]:
    """Read one page of claim candidates.

    Returns up to ``limit`` entities matching ``criteria`` in ``order_by``
    order, skipping the first ``offset``, and leaves out rows that
    ``hold_back`` holds. It must not leave out a row that the claim could
    take.
    """

BoundedDeletePort

Bases: Protocol

A DAO that deletes up to limit rows in one operation.

A DAO class subclasses this port when it implements :meth:delete_top. :meth:protean.infra.dao.DAO.delete_top calls it when the provider declares DatabaseCapabilities.BOUNDED_DELETE, and calls the portable bounded delete otherwise.

delete_top abstractmethod

delete_top(
    session: SessionProtocol,
    criteria: Q,
    limit: int,
    order_by: str | None = None,
) -> int

Delete rows with the promises :meth:protean.infra.dao.DAO.delete_top states.

limit is at least 1.

Source code in src/protean/port/dao.py
349
350
351
352
353
354
355
356
357
358
359
360
361
@abstractmethod
def delete_top(
    self,
    session: SessionProtocol,
    criteria: Q,
    limit: int,
    order_by: str | None = None,
) -> int:
    """Delete rows with the promises :meth:`protean.infra.dao.DAO.delete_top`
    states.

    ``limit`` is at least 1.
    """

DAO

Protean wraps each adapter DAO in the DAO service. A repository holds the service as _dao.

The entity-level operations on one entity class's rows, built on the database adapter's DAOPort.

The lifecycle methods (get, save, create, update, delete) work on entities: they convert between entities and models, check versions, track the Unit of Work, and call the adapter in the session :meth:session_scope picks.

PARAMETER DESCRIPTION
domain

The domain this DAO belongs to.

TYPE: Domain

provider

The database provider the adapter belongs to. It supplies standalone sessions and ends them.

TYPE: Any

adapter

The adapter's DAO for the entity class.

TYPE: DAOPort

RAISES DESCRIPTION
ConfigurationError

provider declares a flag in DatabaseCapabilities whose port adapter's class does not subclass.

Source code in src/protean/infra/dao.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
def __init__(self, domain: Domain, provider: Any, adapter: DAOPort) -> None:
    _check_flag_ports(provider, adapter)

    #: The domain the DAO belongs to.
    self.domain = domain

    #: The provider that supplies sessions to the adapter.
    self.provider = provider

    #: The adapter's DAO, which reads and writes the rows.
    self._adapter = adapter

    #: The entity class the DAO stores.
    self.entity_cls: type[BaseEntity] = adapter.entity_cls

    #: The adapter's database model class for ``entity_cls``.
    self.database_model_cls: type[DatabaseModelPort] = adapter.database_model_cls

    #: The table, index or store key the entity's rows live under.
    self.schema_name: str = adapter.schema_name

    #: An empty query object that can be used to begin filtering/querying operations
    #: on the underlying data store.
    self.query = QuerySet(self, domain, self.entity_cls)

    #: Tracks whether the DAO needs to operate outside any active Unit of Work transactions.
    self._outside_uow = False

session_scope

session_scope() -> Iterator[SessionProtocol]

Yield the session an operation runs in, and end it when standalone.

Inside a Unit of Work, unless :meth:outside_uow was called, it yields the Unit of Work's session for the provider and ends nothing: the Unit of Work commits or rolls it back.

Otherwise it yields provider.new_session(). When the block exits normally, it commits the session through provider.commit. When the block or the commit raises an Exception, it rolls the session back through provider.rollback and re-raises. It always closes the session.

Source code in src/protean/infra/dao.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
@contextmanager
def session_scope(self) -> Iterator[SessionProtocol]:
    """Yield the session an operation runs in, and end it when standalone.

    Inside a Unit of Work, unless :meth:`outside_uow` was called, it yields
    the Unit of Work's session for the provider and ends nothing: the Unit
    of Work commits or rolls it back.

    Otherwise it yields ``provider.new_session()``. When the block exits
    normally, it commits the session through ``provider.commit``. When the
    block or the commit raises an ``Exception``, it rolls the session back
    through ``provider.rollback`` and re-raises. It always closes the
    session.
    """
    if not self._is_standalone:
        yield current_uow.get_session(self.provider.name)
        return

    session = self.provider.new_session()
    try:
        yield session
        self.provider.commit(session)
    except Exception:  # any failure rolls back, then re-raises
        self.provider.rollback(session)
        raise
    finally:
        session.close()

outside_uow

outside_uow() -> DAO

When called, the DAO is instructed to work outside active transactions.

Source code in src/protean/infra/dao.py
694
695
696
697
698
699
def outside_uow(self) -> DAO:
    """When called, the DAO is instructed to work outside active transactions."""
    self._outside_uow = True

    # Return the DAO object to support method chaining
    return self

fetch

fetch(
    criteria: Q,
    *,
    offset: int = 0,
    limit: int = 10,
    order_by: Sequence[str] = (),
    with_total: bool = True,
    fields: list[str] | None = None,
) -> ResultSet

Return one page of the entities that match criteria, read in the session :meth:session_scope picks.

Each entity is marked retrieved. Inside a Unit of Work, each aggregate is tracked in it, or swapped for the instance it already tracks. With fields set, items holds read-only Record objects with those fields, and nothing is tracked. An empty fields selects nothing and returns full entities. With with_total set to False, the adapter may skip computing total.

Source code in src/protean/infra/dao.py
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
def fetch(
    self,
    criteria: Q,
    *,
    offset: int = 0,
    limit: int = 10,
    order_by: Sequence[str] = (),
    with_total: bool = True,
    fields: list[str] | None = None,
) -> ResultSet:
    """Return one page of the entities that match ``criteria``, read in
    the session :meth:`session_scope` picks.

    Each entity is marked retrieved. Inside a Unit of Work, each aggregate
    is tracked in it, or swapped for the instance it already tracks.
    With ``fields`` set, ``items`` holds read-only ``Record`` objects with
    those fields, and nothing is tracked. An empty ``fields`` selects
    nothing and returns full entities. With ``with_total`` set to
    ``False``, the adapter may skip computing ``total``.
    """
    return dao_read.fetch(
        self,
        criteria,
        offset=offset,
        limit=limit,
        order_by=order_by,
        with_total=with_total,
        fields=fields,
    )

count

count(criteria: Q) -> int

Return the number of rows that match criteria.

Source code in src/protean/infra/dao.py
735
736
737
def count(self, criteria: Q) -> int:
    """Return the number of rows that match ``criteria``."""
    return dao_read.count(self, criteria)

raw

raw(query: Any, data: Any = None) -> ResultSet

Run query through the adapter's raw and return the entities, tracked in the Unit of Work as :meth:fetch tracks them.

RAISES DESCRIPTION
NotSupportedError

The provider does not declare RAW_QUERIES.

Source code in src/protean/infra/dao.py
739
740
741
742
743
744
745
746
def raw(self, query: Any, data: Any = None) -> ResultSet:
    """Run ``query`` through the adapter's ``raw`` and return the
    entities, tracked in the Unit of Work as :meth:`fetch` tracks them.

    Raises:
        NotSupportedError: The provider does not declare ``RAW_QUERIES``.
    """
    return dao_read.raw(self, query, data)

has_table

has_table() -> bool

Whether the adapter's table, collection or index exists.

Source code in src/protean/infra/dao.py
748
749
750
def has_table(self) -> bool:
    """Whether the adapter's table, collection or index exists."""
    return self._adapter.has_table()

update_all

update_all(criteria: Q, values: Mapping[str, Any]) -> int

Write values to every row that matches criteria.

.. warning::

This is an **internal framework method** reserved for
infrastructure needs (outbox, projection rebuilds). It bypasses
domain validation, invariants, and the Unit of Work's tracking.
Do not call it from domain-level code.
RETURNS DESCRIPTION
int

The number of rows that matched criteria. The Elasticsearch

int

adapter returns 0 when values is empty.

Source code in src/protean/infra/dao.py
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
def update_all(self, criteria: Q, values: Mapping[str, Any]) -> int:
    """Write ``values`` to every row that matches ``criteria``.

    .. warning::

        This is an **internal framework method** reserved for
        infrastructure needs (outbox, projection rebuilds). It bypasses
        domain validation, invariants, and the Unit of Work's tracking.
        Do not call it from domain-level code.

    Returns:
        The number of rows that matched ``criteria``. The Elasticsearch
        adapter returns ``0`` when ``values`` is empty.
    """
    with self.session_scope() as session:
        return self._adapter.update_all(session, criteria, values)

delete_all

delete_all(criteria: Q | None = None) -> int

Delete every row that matches criteria, or every row when criteria is None.

.. warning::

This is an **internal framework method** reserved for
infrastructure needs (outbox, projection rebuilds, table cleanup).
It bypasses domain validation, invariants, and the Unit of Work's
tracking. Do not call it from domain-level code.
RETURNS DESCRIPTION
int

The number of rows that matched criteria.

RAISES DESCRIPTION
Exception

The adapter's error, logged and re-raised.

Source code in src/protean/infra/dao.py
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def delete_all(self, criteria: Q | None = None) -> int:
    """Delete every row that matches ``criteria``, or every row when
    ``criteria`` is ``None``.

    .. warning::

        This is an **internal framework method** reserved for
        infrastructure needs (outbox, projection rebuilds, table cleanup).
        It bypasses domain validation, invariants, and the Unit of Work's
        tracking. Do not call it from domain-level code.

    Returns:
        The number of rows that matched ``criteria``.

    Raises:
        Exception: The adapter's error, logged and re-raised.
    """
    try:
        with self.session_scope() as session:
            return self._adapter.delete_all(session, criteria)
    except Exception as exc:
        logger.error(f"Failed deletion of all records because of {exc}")
        raise

claim

claim(
    criteria: Q,
    claim_fields: Mapping[str, Any],
    limit: int,
    order_by: str | Sequence[str] | None = None,
    hold_back: HoldBack | None = None,
) -> list[BaseEntity]

Claim up to limit rows that match criteria and return them.

Each claimed row gets claim_fields written to it, and the returned entities show that post-claim state. The claim is committed before the method returns, so call it outside an active Unit of Work. Inside one, the write waits for the Unit of Work to commit, and other workers do not see the claim until then.

Every implementation keeps these promises:

  • No two callers claim the same row. A caller that loses a race for a row does not get it.
  • With hold_back, a grouped row is claimed only when every earlier row of its group that matches hold_back.holds is claimed by the same call. A row locked by another caller holds the rows behind it.
  • On an aggregate, each claimed row's _version advances by one, and the returned entity carries the new version, so it can be saved as it is. A later claim of the row advances the version again, and the repository's version check then refuses a save of the entity the earlier claim returned.

claim_fields must make a claimed row stop matching criteria. The call may wait briefly on a row another caller has locked. How a lost race shows up depends on the backend; see ADR-0013.

PARAMETER DESCRIPTION
criteria

Selects the rows that can be claimed.

TYPE: Q

claim_fields

Values to write on each claimed row.

TYPE: Mapping[str, Any]

limit

The most rows to claim. 0 or less claims none.

TYPE: int

order_by

A key, or a list of keys applied in turn, such as ["-priority", "created_at"]. A - prefix sorts that key descending.

TYPE: str | Sequence[str] | None DEFAULT: None

hold_back

Keeps a grouped row back until the earlier rows of its group are claimed with it. None claims the top rows with no grouping.

TYPE: HoldBack | None DEFAULT: None

RETURNS DESCRIPTION
list[BaseEntity]

The claimed entities, with claim_fields applied.

Source code in src/protean/infra/dao.py
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
def claim(
    self,
    criteria: Q,
    claim_fields: Mapping[str, Any],
    limit: int,
    order_by: str | Sequence[str] | None = None,
    hold_back: HoldBack | None = None,
) -> list[BaseEntity]:
    """Claim up to ``limit`` rows that match ``criteria`` and return them.

    Each claimed row gets ``claim_fields`` written to it, and the returned
    entities show that post-claim state. The claim is committed before the
    method returns, so call it **outside** an active Unit of Work. Inside
    one, the write waits for the Unit of Work to commit, and other workers
    do not see the claim until then.

    Every implementation keeps these promises:

    - No two callers claim the same row. A caller that loses a race for a
      row does not get it.
    - With ``hold_back``, a grouped row is claimed only when every earlier
      row of its group that matches ``hold_back.holds`` is claimed by the
      same call. A row locked by another caller holds the rows behind it.
    - On an aggregate, each claimed row's ``_version`` advances by one,
      and the returned entity carries the new version, so it can be saved
      as it is. A later claim of the row advances the version again, and
      the repository's version check then refuses a save of the entity
      the earlier claim returned.

    ``claim_fields`` must make a claimed row stop matching ``criteria``.
    The call may wait briefly on a row another caller has locked. How a
    lost race shows up depends on the backend; see ADR-0013.

    Args:
        criteria: Selects the rows that can be claimed.
        claim_fields: Values to write on each claimed row.
        limit: The most rows to claim. ``0`` or less claims none.
        order_by: A key, or a list of keys applied in turn, such as
            ``["-priority", "created_at"]``. A ``-`` prefix sorts that key
            descending.
        hold_back: Keeps a grouped row back until the earlier rows of its
            group are claimed with it. ``None`` claims the top rows with no
            grouping.

    Returns:
        The claimed entities, with ``claim_fields`` applied.

    """
    if limit <= 0:
        return []

    order = _order_keys(order_by)
    if _uses_adapter_operation(self, DatabaseCapabilities.NATIVE_CLAIM):
        adapter = cast(NativeClaimPort, self._adapter)
        with self.session_scope() as session:
            return adapter.claim(
                session, criteria, claim_fields, limit, order, hold_back
            )
    return portable_claim(self, criteria, claim_fields, limit, order, hold_back)

delete_top

delete_top(
    criteria: Q, limit: int, order_by: str | None = None
) -> int

Delete up to limit rows that match criteria.

Large cleanups use this to delete in fixed-size batches.

.. warning::

Like :meth:`delete_all`, this is an **internal framework method**
reserved for infrastructure needs (outbox cleanup, table pruning).
It bypasses domain validation, invariants, and the Unit of Work's
tracking. Do not call it from domain-level code.
PARAMETER DESCRIPTION
criteria

Selects the rows that can be deleted.

TYPE: Q

limit

The most rows to delete. 0 or less deletes none.

TYPE: int

order_by

One sort key, such as "-priority", that decides which rows go first.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
int

The number of rows deleted, at most limit.

Source code in src/protean/infra/dao.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
def delete_top(
    self,
    criteria: Q,
    limit: int,
    order_by: str | None = None,
) -> int:
    """Delete up to ``limit`` rows that match ``criteria``.

    Large cleanups use this to delete in fixed-size batches.

    .. warning::

        Like :meth:`delete_all`, this is an **internal framework method**
        reserved for infrastructure needs (outbox cleanup, table pruning).
        It bypasses domain validation, invariants, and the Unit of Work's
        tracking. Do not call it from domain-level code.

    Args:
        criteria: Selects the rows that can be deleted.
        limit: The most rows to delete. ``0`` or less deletes none.
        order_by: One sort key, such as ``"-priority"``, that decides which
            rows go first.

    Returns:
        The number of rows deleted, at most ``limit``.
    """
    if limit <= 0:
        return 0

    if _uses_adapter_operation(self, DatabaseCapabilities.BOUNDED_DELETE):
        adapter = cast(BoundedDeletePort, self._adapter)
        with self.session_scope() as session:
            return adapter.delete_top(session, criteria, limit, order_by)
    return portable_delete_top(self, criteria, limit, order_by)

get

get(identifier: Any) -> BaseEntity

Return the one entity whose identity is identifier.

RAISES DESCRIPTION
ObjectNotFoundError

No entity has the identifier.

TooManyObjectsError

More than one entity has the identifier.

Source code in src/protean/infra/dao.py
892
893
894
895
896
897
898
899
def get(self, identifier: Any) -> BaseEntity:
    """Return the one entity whose identity is ``identifier``.

    Raises:
        ObjectNotFoundError: No entity has the identifier.
        TooManyObjectsError: More than one entity has the identifier.
    """
    return dao_read.get(self, identifier)

find_by

find_by(**kwargs: Any) -> BaseEntity

Return the one entity whose attributes equal kwargs.

RAISES DESCRIPTION
ObjectNotFoundError

No entity matches.

TooManyObjectsError

More than one entity matches.

Source code in src/protean/infra/dao.py
901
902
903
904
905
906
907
908
def find_by(self, **kwargs: Any) -> BaseEntity:
    """Return the one entity whose attributes equal ``kwargs``.

    Raises:
        ObjectNotFoundError: No entity matches.
        TooManyObjectsError: More than one entity matches.
    """
    return dao_read.find_by(self, **kwargs)

exists

exists(excludes_: dict[str, Any], **filters: Any) -> bool

Return whether any entity matches filters and none of excludes_.

Source code in src/protean/infra/dao.py
910
911
912
913
def exists(self, excludes_: dict[str, Any], **filters: Any) -> bool:
    """Return whether any entity matches ``filters`` and none of
    ``excludes_``."""
    return dao_read.exists(self, excludes_, **filters)

create

create(*args: Any, **kwargs: Any) -> BaseEntity

Create a new record in the data store.

Performs validations for unique attributes before creating the entity

Returns the created entity object.

Throws ValidationError for validation failures on attribute values or uniqueness constraints.

:param args: Dictionary object containing the object's data. :param kwargs: named attribute names and values

Source code in src/protean/infra/dao.py
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
def create(self, *args: Any, **kwargs: Any) -> BaseEntity:
    """Create a new record in the data store.

    Performs validations for unique attributes before creating the entity

    Returns the created entity object.

    Throws `ValidationError` for validation failures on attribute values or uniqueness constraints.

    :param args: Dictionary object containing the object's data.
    :param kwargs: named attribute names and values
    """
    logger.debug(
        f"Creating new `{self.entity_cls.__name__}` object using data {kwargs}"
    )

    try:
        # Build the entity from input arguments
        # Raises validation errors, if any, at this point
        entity_obj = self.entity_cls(*args, **kwargs)

        # Check unique fields, write the row and reflect auto-increment
        # values. Raises validation errors if unique constraints are violated.
        self._write_insert(entity_obj, if_absent=False)

        # Set Entity status to saved to let everybody know it has been persisted
        entity_obj.state_.mark_saved()

        # Track aggregate at the UoW level, to be able to perform actions on UoW commit,
        #   like persisting events raised by the aggregate.
        if current_uow and entity_obj.element_type == DomainObjects.AGGREGATE:
            current_uow._add_to_identity_map(entity_obj, saved=True)

        return entity_obj
    except ValidationError as exc:
        logger.error(f"Failed creating entity because of {exc}")
        raise

save

save(entity_obj: Any, *, apply_hooks: bool = True) -> Any

Persist a fully formed entity: create it if it was never saved, else update it.

PARAMETER DESCRIPTION
entity_obj

The entity to persist.

TYPE: Any

apply_hooks

When False, skip the pre-persist hooks (auto_now/auto_now_add stamping and aggregate enrichers) for a raw write, such as a bulk migration that must not touch audit fields. The optimistic-concurrency version check still applies.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Any

The saved entity.

RAISES DESCRIPTION
ValidationError

A field value or a uniqueness constraint fails validation.

Source code in src/protean/infra/dao.py
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
def save(self, entity_obj: Any, *, apply_hooks: bool = True) -> Any:
    """Persist a fully formed entity: create it if it was never saved, else
    update it.

    Args:
        entity_obj: The entity to persist.
        apply_hooks: When ``False``, skip the pre-persist hooks
            (``auto_now``/``auto_now_add`` stamping and aggregate
            enrichers) for a raw write, such as a bulk migration that must
            not touch audit fields. The optimistic-concurrency version
            check still applies.

    Returns:
        The saved entity.

    Raises:
        ValidationError: A field value or a uniqueness constraint fails
            validation.
    """
    return self._save(entity_obj, apply_hooks=apply_hooks, if_absent=False)

save_if_absent

save_if_absent(
    entity_obj: Any, *, apply_hooks: bool = True
) -> Any

Save entity_obj unless another row already holds its unique key.

The unique key is the values of the fields of each Index declared with unique=True and no where predicate. This method does not check an index with a None among those values, and leaves such a row to the database's own rule for NULLs. When the entity declares no such index, this is :meth:save.

When the provider declares INSERT_IF_ABSENT, the adapter checks the key and writes the row as one step, so a writer that loses a race also gets None. The write runs inside the adapter's claim_lock(). A ValidationError from the save also returns None when another row holds the key, because a key field that is also declared unique=True fails its check before the write. The pre-persist hooks run before the adapter checks the key, so on None the entity keeps its auto_now stamps and its enrichers' changes; only the aggregate's version is put back.

Inside a Unit of Work the memory adapter only stages the row. When another session commits a row with the same key first, the Unit of Work's commit drops this row after this method has returned the entity, and records it in the session's dropped_rows.

Otherwise this method checks for the key, then saves. Two writers that check at the same moment can both pass the check. A store with a unique index on the key then rejects the second write with its own error. A store with no such index, such as Elasticsearch, keeps both rows.

PARAMETER DESCRIPTION
entity_obj

The entity to persist.

TYPE: Any

apply_hooks

Passed to :meth:save.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Any

The saved entity, or None when another row holds the unique key.

Any

Nothing is written in that case.

RAISES DESCRIPTION
ValidationError

save rejected the entity, and no other row holds the unique key.

Source code in src/protean/infra/dao.py
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
def save_if_absent(self, entity_obj: Any, *, apply_hooks: bool = True) -> Any:
    """Save ``entity_obj`` unless another row already holds its unique key.

    The unique key is the values of the fields of each ``Index`` declared
    with ``unique=True`` and no ``where`` predicate. This method does not
    check an index with a ``None`` among those values, and leaves such a
    row to the database's own rule for NULLs. When the entity declares no
    such index, this is :meth:`save`.

    When the provider declares ``INSERT_IF_ABSENT``, the adapter checks the
    key and writes the row as one step, so a writer that loses a race also
    gets ``None``. The write runs inside the adapter's ``claim_lock()``.
    A ``ValidationError`` from the save also returns ``None`` when another
    row holds the key, because a key field that is also declared
    ``unique=True`` fails its check before the write. The pre-persist
    hooks run before the adapter checks the key, so on ``None`` the entity
    keeps its ``auto_now`` stamps and its enrichers' changes; only the
    aggregate's version is put back.

    Inside a Unit of Work the memory adapter only stages the row. When
    another session commits a row with the same key first, the Unit of
    Work's commit drops this row after this method has returned the
    entity, and records it in the session's ``dropped_rows``.

    Otherwise this method checks for the key, then saves. Two writers that
    check at the same moment can both pass the check. A store with a unique
    index on the key then rejects the second write with its own error. A
    store with no such index, such as Elasticsearch, keeps both rows.

    Args:
        entity_obj: The entity to persist.
        apply_hooks: Passed to :meth:`save`.

    Returns:
        The saved entity, or ``None`` when another row holds the unique key.
        Nothing is written in that case.

    Raises:
        ValidationError: ``save`` rejected the entity, and no other row
            holds the unique key.
    """
    if not _uses_adapter_operation(self, DatabaseCapabilities.INSERT_IF_ABSENT):
        return self._save_if_key_free(entity_obj, apply_hooks=apply_hooks)

    version = (
        entity_obj._version
        if entity_obj.element_type == DomainObjects.AGGREGATE
        else None
    )
    with self._adapter.claim_lock():
        try:
            return self._save(entity_obj, apply_hooks=apply_hooks, if_absent=True)
        except _UniqueKeyTaken:
            pass
        except ValidationError as exc:
            if not self._unique_key_taken(entity_obj):
                _log_save_failure(exc)
                raise
        # ``_save`` raises before it marks the entity saved or tracks it
        # in the Unit of Work, so only the version advance is left to undo.
        if version is not None:
            entity_obj._version = version
        return None

update

update(
    entity_obj: Any,
    *data: Any,
    apply_hooks: bool = True,
    **kwargs: Any,
) -> BaseEntity

Apply a field patch to an existing entity and persist it.

.. deprecated:: 0.18.0 The patch-and-persist path is deprecated and is removed in v0.20.0. Load the aggregate, invoke a behaviour method that applies the change, and persist it with repository.add() instead.

Applies the values, checks uniqueness, then persists the entity the way :meth:save does. An aggregate update advances its version, stamps auto_now fields, and runs pre-persist enrichers.

Takes the values as a dictionary or as keyword arguments::

>>> dao.update(user, {'age': 10})
>>> dao.update(user, age=10)

apply_hooks is a reserved keyword argument. To patch a field named apply_hooks, use the dictionary form (dao.update(user, {'apply_hooks': ...})).

PARAMETER DESCRIPTION
entity_obj

The persisted entity to update.

TYPE: Any

*data

A dictionary of values to apply.

TYPE: Any DEFAULT: ()

apply_hooks

When False, skip the pre-persist hooks (auto_now stamping and enrichers). The optimistic-concurrency version check still applies. See :meth:save.

TYPE: bool DEFAULT: True

**kwargs

Values to apply, as keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
BaseEntity

The updated entity.

RAISES DESCRIPTION
ObjectNotFoundError

entity_obj was never persisted.

ValidationError

A field value or a uniqueness constraint fails validation.

ExpectedVersionError

The stored aggregate has a newer version.

Source code in src/protean/infra/dao.py
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
@deprecated_from_registry("dao_update")
def update(
    self,
    entity_obj: Any,
    *data: Any,
    apply_hooks: bool = True,
    **kwargs: Any,
) -> BaseEntity:
    """Apply a field patch to an existing entity and persist it.

    .. deprecated:: 0.18.0
        The patch-and-persist path is deprecated and is removed in v0.20.0.
        Load the aggregate, invoke a behaviour method that applies the
        change, and persist it with ``repository.add()`` instead.

    Applies the values, checks uniqueness, then persists the entity the
    way :meth:`save` does. An aggregate update advances its version, stamps
    ``auto_now`` fields, and runs pre-persist enrichers.

    Takes the values as a dictionary or as keyword arguments::

        >>> dao.update(user, {'age': 10})
        >>> dao.update(user, age=10)

    ``apply_hooks`` is a reserved keyword argument. To patch a field named
    ``apply_hooks``, use the dictionary form
    (``dao.update(user, {'apply_hooks': ...})``).

    Args:
        entity_obj: The persisted entity to update.
        *data: A dictionary of values to apply.
        apply_hooks: When ``False``, skip the pre-persist hooks
            (``auto_now`` stamping and enrichers). The optimistic-concurrency
            version check still applies. See :meth:`save`.
        **kwargs: Values to apply, as keyword arguments.

    Returns:
        The updated entity.

    Raises:
        ObjectNotFoundError: ``entity_obj`` was never persisted.
        ValidationError: A field value or a uniqueness constraint fails
            validation.
        ExpectedVersionError: The stored aggregate has a newer version.
    """
    return self._apply_update(entity_obj, *data, apply_hooks=apply_hooks, **kwargs)

delete

delete(entity_obj: Any) -> Any

Delete a record in the data store.

Performs validations before data deletion.

Returns the deleted entity object.

Throws ObjectNotFoundError if the object was not found in the data store.

:param entity_obj: Entity object to be deleted from data store

Source code in src/protean/infra/dao.py
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
def delete(self, entity_obj: Any) -> Any:
    """Delete a record in the data store.

    Performs validations before data deletion.

    Returns the deleted entity object.

    Throws ObjectNotFoundError if the object was not found in the data store.

    :param entity_obj: Entity object to be deleted from data store
    """
    try:
        if not entity_obj.state_.is_destroyed:
            model_obj = self.database_model_cls.from_entity(entity_obj)
            with self.session_scope() as session:
                self._adapter.delete(session, model_obj)

            # Set Entity status to destroyed to let everybody know the object is no longer referable
            entity_obj.state_.mark_destroyed()

        return entity_obj
    except Exception as exc:  # logs any delete failure, then re-raises
        logger.error(f"Failed entity deletion because of {exc}")
        raise

LookupPort

Bases: Protocol

One comparison in a filter, such as name == "John".

source is the left side of the comparison and target the right side. The SQL and Elasticsearch lookups receive a field name as source, and the memory lookups receive the stored value of that field.

How a lookup becomes a query is private to the adapter that runs it. An adapter's lookup base class subclasses this Protocol explicitly, and the base class constructor sets source, target and database_model_cls. The Protocol supplies no constructor body, so a subclass without its own constructor builds without these attributes.

Source code in src/protean/port/dao.py
415
416
417
418
419
420
421
def __init__(
    self,
    source: Any,
    target: Any,
    *,
    database_model_cls: type[DatabaseModelPort] | None = None,
) -> None: ...

lookup_name class-attribute

lookup_name: str

The name a filter key uses after __, such as "icontains".

REQUIRED_LOOKUPS module-attribute

REQUIRED_LOOKUPS: frozenset[str] = frozenset(
    {
        "exact",
        "iexact",
        "contains",
        "icontains",
        "startswith",
        "endswith",
        "gt",
        "gte",
        "lt",
        "lte",
        "in",
        "isnull",
    }
)

The lookup names every database provider registers. The provider registry raises ConfigurationError for a provider class that lacks any of them.