Skip to content

BaseDatabaseModel

Base class for database models, the schemas that map aggregates to a specific storage technology. Database models are typically auto-generated but can be customized for adapter-specific optimizations.

Bases: Element, OptionsMixin

Base class for database models, which map an aggregate, entity or projection to the schema of one kind of database.

Protean generates a default database model for every aggregate. Declare one with @domain.database_model only to change the mapping, for example the table name or adapter-specific field types. See the custom database models guide.

A subclass must implement from_entity(). The default to_entity() maps each attribute back by name, using referenced_as when it is set. Override to_entity() only when the storage needs special handling.

A concrete subclass satisfies DatabaseModelPort, which lists the class methods the framework calls on an adapter's model class.

Meta Options

Option Type Description
part_of type or str The aggregate, entity or projection this model maps. Required. A string names the element and is resolved at domain.init().
database_type str The database type this model applies to (e.g. "sqlite", "elasticsearch"), not a provider name. Without it, the model is used for any database type that has no model of its own.
schema_name str Override the storage table/collection name.

derive_schema_name classmethod

derive_schema_name() -> str

Derive the storage table/collection name.

Uses meta_.schema_name if explicitly set, otherwise falls back to the schema name of the associated aggregate or entity.

RETURNS DESCRIPTION
str

The resolved schema name.

TYPE: str

Source code in src/protean/core/database_model.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@classmethod
def derive_schema_name(cls) -> str:
    """Derive the storage table/collection name.

    Uses ``meta_.schema_name`` if explicitly set, otherwise falls back
    to the schema name of the associated aggregate or entity.

    Returns:
        str: The resolved schema name.
    """
    if hasattr(cls.meta_, "schema_name") and cls.meta_.schema_name:
        return cast(str, cls.meta_.schema_name)
    else:
        return cast(str, cls.meta_.part_of.meta_.schema_name)

from_entity abstractmethod classmethod

from_entity(entity: Any) -> Any

Convert a domain entity/aggregate into a database model instance.

Implementors should extract field values from the domain object and map them to the database-specific representation.

PARAMETER DESCRIPTION
entity

The domain entity or aggregate to convert.

TYPE: BaseEntity

RETURNS DESCRIPTION
Any

The database model instance ready for persistence.

Source code in src/protean/core/database_model.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@classmethod
@abstractmethod
def from_entity(cls, entity: Any) -> Any:
    """Convert a domain entity/aggregate into a database model instance.

    Implementors should extract field values from the domain object and
    map them to the database-specific representation.

    Args:
        entity (BaseEntity): The domain entity or aggregate to convert.

    Returns:
        The database model instance ready for persistence.
    """

to_entity classmethod

to_entity(item: Any) -> BaseEntity

Convert a database record back into a domain entity/aggregate.

Iterates entity attributes, applies referenced_as remapping, and reconstructs the domain object. Adapters with storage-specific reconstruction needs (e.g. Elasticsearch meta.id extraction) should override this method entirely.

Source code in src/protean/core/database_model.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@classmethod
def to_entity(cls, item: Any) -> "BaseEntity":
    """Convert a database record back into a domain entity/aggregate.

    Iterates entity attributes, applies ``referenced_as`` remapping,
    and reconstructs the domain object.  Adapters with storage-specific
    reconstruction needs (e.g. Elasticsearch ``meta.id`` extraction)
    should override this method entirely.
    """
    item_dict: dict[str, Any] = {}
    for attr_name, attr_obj in attributes(cls.meta_.part_of).items():
        referenced_as = attr_obj.referenced_as
        if referenced_as:
            # ``field_name`` is always populated for a registered field
            # (set by ``Field.__set_name__``); the ``or attr_name`` fallback
            # only satisfies the ``str | None`` type and is never taken at
            # runtime for fields returned by ``attributes()``.
            field_name = attr_obj.field_name or attr_name
            item_dict[field_name] = cls._get_value(item, referenced_as)
        else:
            item_dict[attr_name] = cls._get_value(item, attr_name)
    return cast("BaseEntity", cls.meta_.part_of(**item_dict))

to_records classmethod

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

Build read-only Record objects from storage records, holding only the selected fields.

QuerySet.only uses this. It builds no domain entities, so no validation or invariant runs. Adapters with storage-specific record access override this method.

PARAMETER DESCRIPTION
items

The raw storage records the adapter's filter returned.

TYPE: list[Any]

fields

Attribute names to read from each record. Each record is keyed by these names.

TYPE: list[str]

RETURNS DESCRIPTION
list[Record]

One Record per item, in the order of items.

Source code in src/protean/core/database_model.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
@classmethod
def to_records(cls, items: list[Any], fields: list[str]) -> list[Record]:
    """Build read-only [`Record`][protean.core.queryset.Record] objects
    from storage records, holding only the selected fields.

    [`QuerySet.only`][protean.core.queryset.QuerySet.only] uses this. It
    builds no domain entities, so no validation or invariant runs.
    Adapters with storage-specific record access override this method.

    Args:
        items: The raw storage records the adapter's ``filter`` returned.
        fields: Attribute names to read from each record. Each record is
            keyed by these names.

    Returns:
        One ``Record`` per item, in the order of ``items``.
    """
    attrs = attributes(cls.meta_.part_of)
    entity_name = cls.meta_.part_of.__name__
    # Records are keyed by the attribute name the caller selected (what
    # they passed to ``only()``); the value is read from the storage key,
    # honouring ``referenced_as``. Resolve both once for the batch.
    resolved = [
        (attr_name, attrs[attr_name].referenced_as or attr_name)
        for attr_name in fields
    ]
    # A uuid identity is a string in Python (ADR-0021). This read-optimized
    # path bypasses entity construction (and its identity coercion), so an
    # adapter that returns a native UUID for the id column (e.g. SQLAlchemy's
    # GUID type) would surface one here; coerce the identity field itself.
    id_f = id_field(cls.meta_.part_of)
    id_name = id_f.field_name if id_f is not None else None
    records = []
    for item in items:
        data = {}
        for key, source in resolved:
            value = cls._get_value(item, source)
            if key == id_name:
                value = _coerce_uuid_to_str(value)
            data[key] = value
        records.append(Record(entity_name, data))
    return records