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 | |
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 | |
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 | |
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 | |
rollback
abstractmethod
rollback(session: SessionProtocol) -> None
Roll back session.
Source code in src/protean/port/database.py
253 254 255 | |
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 | |
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 | |
ping
abstractmethod
ping() -> bool
Whether the database is reachable.
Source code in src/protean/port/database.py
275 276 277 | |
health
abstractmethod
health() -> DatabaseHealth
The provider's health record.
Source code in src/protean/port/database.py
279 280 281 | |
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 | |
clear
abstractmethod
clear() -> None
Remove every record from the provider's store.
Source code in src/protean/port/database.py
290 291 292 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
RawQueryDatabasePort
Bases: DatabasePort, Protocol
The raw-query member, unlocked by DatabaseCapabilities.RAW_QUERIES.
Source code in src/protean/port/database.py
219 220 221 | |
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 | |
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 | |
__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 | |
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 | |
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 | |
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 carrymeta_.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
|
|
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 | |
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 | |
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 | |
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 | |
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 | |
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:
|
criteria
|
The filter conditions.
TYPE:
|
offset
|
The number of matching rows to skip.
TYPE:
|
limit
|
The most rows to return.
TYPE:
|
order_by
|
Keys to sort by, applied in turn. A
TYPE:
|
with_total
|
When
TYPE:
|
fields
|
Column names to fetch, set by
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResultSet
|
A |
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 | |
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 | |
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 | |
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
|
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 | |
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 |
int
|
return |
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 | |
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 | |
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:
|
criteria
|
The filter conditions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
The number of rows that matched |
Source code in src/protean/port/dao.py
190 191 192 193 194 195 196 197 198 199 200 201 | |
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 | |
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 | |
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:
|
query
|
The query, passed to the database as it is.
TYPE:
|
data
|
Data to pass along with the query, such as the values for an update statement.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResultSet
|
A |
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 | |
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
|
|
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 | |
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
|
|
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 | |
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 | |
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 | |
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 | |
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:
|
provider
|
The database provider the adapter belongs to. It supplies standalone sessions and ends them.
TYPE:
|
adapter
|
The adapter's DAO for the entity class.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError
|
|
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 | |
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 | |
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 | |
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 | |
count
count(criteria: Q) -> int
Return the number of rows that match criteria.
Source code in src/protean/infra/dao.py
735 736 737 | |
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 |
Source code in src/protean/infra/dao.py
739 740 741 742 743 744 745 746 | |
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 | |
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 |
int
|
adapter returns |
Source code in src/protean/infra/dao.py
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 | |
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 |
| 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 | |
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 matcheshold_back.holdsis claimed by the same call. A row locked by another caller holds the rows behind it. - On an aggregate, each claimed row's
_versionadvances 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:
|
claim_fields
|
Values to write on each claimed row.
TYPE:
|
limit
|
The most rows to claim.
TYPE:
|
order_by
|
A key, or a list of keys applied in turn, such as
TYPE:
|
hold_back
|
Keeps a grouped row back until the earlier rows of its
group are claimed with it.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[BaseEntity]
|
The claimed entities, with |
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 | |
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:
|
limit
|
The most rows to delete.
TYPE:
|
order_by
|
One sort key, such as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
The number of rows deleted, at most |
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 | |
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 | |
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 | |
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 | |
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 | |
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:
|
apply_hooks
|
When
TYPE:
|
| 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 | |
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:
|
apply_hooks
|
Passed to :meth:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
The saved entity, or |
Any
|
Nothing is written in that case. |
| RAISES | DESCRIPTION |
|---|---|
ValidationError
|
|
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 | |
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:
|
*data
|
A dictionary of values to apply.
TYPE:
|
apply_hooks
|
When
TYPE:
|
**kwargs
|
Values to apply, as keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BaseEntity
|
The updated entity. |
| RAISES | DESCRIPTION |
|---|---|
ObjectNotFoundError
|
|
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 | |
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 | |
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 | |
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.