Skip to content

Query system

Protean's query system provides a database-agnostic way to filter, sort, and paginate aggregates. This page explains the internal architecture, the layered design, how Q objects form expression trees, how lookups are resolved by database providers, and how QuerySets achieve lazy evaluation.

For practical usage, see the Retrieving Aggregates guide.


Architecture

The query system is organized as a chain of layers, each with a distinct responsibility:

Application code
    │
    ▼
Repository           Domain-facing API: add(), get(), custom methods
    │
    ▼
DAO service          Database-facing API: filter, create, update, delete
    │
    ▼
QuerySet             Lazy query builder: chains filter/exclude/limit/order_by
    │
    ▼
Provider             Database connection manager, lookup registry
    │
    ▼
Database             Actual storage (Memory, PostgreSQL, Elasticsearch, ...)

Repository → DAO

Every repository has a _dao property that provides access to the Data Access Object. The DAO is constructed lazily and cached:

BaseRepository._dao
    → DAO(domain, provider, adapter)
        adapter = provider.dao_for(entity_cls, model_cls)
            → ConcreteDAO(provider, entity_cls, model_cls)

The DAO service wraps the adapter DAO that the provider returns. The service picks the session for each operation and passes it to the adapter. The adapter runs the operation in that session and never commits it. The Elasticsearch adapter, whose store has no transactions, ignores the session and writes at once.

The repository exposes methods named in domain terms (add, get, query, find_by, and custom methods). The adapter DAO exposes methods named in database terms (filter, count, insert, update, delete). The DAO service's fetch calls the adapter's filter, its count calls count, and its save methods call insert, update and delete. Custom repository methods use self.query and self.find_by (which delegate to the internal _dao) to build queries.

Key source files:

  • src/protean/core/repository.py: BaseRepository with add(), get(), _dao property, and _sync_children() for cascading child entities.
  • src/protean/infra/dao.py: the DAO service with lifecycle methods (get, find_by, exists, create, save, update, delete).
  • src/protean/infra/dao_read.py: the service's read path (fetch, count, raw, get, find_by, exists).
  • src/protean/port/dao.py: DAOPort, with the methods concrete adapters implement (filter, count, insert, update, delete), and the optional ports such as RawQueryDAOPort.

DAO → QuerySet

The DAO's .query property returns a fresh QuerySet instance. The QuerySet is the primary query-building interface:

# fragment
# DAO.__init__()
self.query = QuerySet(self, domain, self.entity_cls)

Each QuerySet method (filter, exclude, limit, offset, order_by) returns a clone of the QuerySet with the new criteria applied. The original QuerySet is never mutated. This clone-on-write design enables safe chaining:

# fragment
base = dao.query.filter(country="CA")       # QuerySet 1
adults = base.filter(age__gte=18)            # QuerySet 2 (clone of 1)
children = base.filter(age__lt=18)           # QuerySet 3 (clone of 1)
# base, adults, and children are all independent

Key source file: src/protean/core/queryset.py

QuerySet → Provider → Database

When a QuerySet is evaluated (via .all(), iteration, len(), etc.), it calls the DAO service's fetch. fetch calls the adapter's filter in the session session_scope picks: the Unit of Work's session inside a Unit of Work, or a new session it commits and closes outside one. After the session_scope block exits, fetch turns each row into an entity and, inside a Unit of Work, tracks each aggregate in it:

# fragment
results = dao.fetch(
    self._criteria,                 # Q object tree
    offset=self._offset,            # int
    limit=self._limit,              # int or None
    order_by=self._order_by,        # list of strings
    with_total=with_total,          # bool
    fields=self._only_fields,       # list of strings, or None
)

The concrete DAO implementation (e.g., DictDAO for memory, SADAO for SQLAlchemy) recursively walks the Q object tree, resolves each lookup using the provider's lookup registry, and builds a database-specific query.

filter accepts a with_total flag (default True). When with_total is False, the caller only needs ResultSet.items. Adapters may then skip an expensive total-count computation (such as SQL's separate wrapped COUNT query) and report only the size of the returned page. Adapters that derive the total for free (memory, Elasticsearch) may continue to populate it.

filter also accepts an optional fields argument (a list of attribute names) set via QuerySet.only(). When fields is present, the adapter fetches only those columns (SQLAlchemy load_only, Elasticsearch _source filtering; the memory store selects when building the result). fetch then builds read-only Record objects through the model's to_records instead of materializing entities. A Record never enters the entity layer, so the field-selection path runs no invariants and does no event-position sync or Unit of Work tracking. Skipping that work keeps the field-selection path cheap and leaves the domain model uncompromised.

Counting takes a lighter path that bypasses filter entirely. count() on a QuerySet calls the DAO service's count, which calls the adapter's count in the session session_scope picks, with only the Q object tree. The concrete DAO issues a single SELECT COUNT(*) (SQLAlchemy func.count(), memory len over the filtered set, Elasticsearch's _count API) with no projection wrapper and no entity materialization. offset, limit, and order_by are ignored, since none of them affect the row count.


Q objects: the expression tree

Q objects (protean.utils.query.Q) represent filter criteria as a tree structure. Internally, the QuerySet passes Q objects to the DAO, and the DAO turns them into a query for the database.

Tree structure

A Q object extends Node, which holds:

  • children: A list of leaf tuples (field_name, value) or nested Node/Q instances.
  • connector: "AND" or "OR", determining how children are combined.
  • negated: A boolean flag that negates the node. In a query filter, each child is negated before the connector combines them, and a nested node is negated as a whole. In a partial index (Index(where=...)), the combined children are negated as one expression.
# fragment
Q(name="John", age=3)
# Node(connector=AND, children=[("age", 3), ("name", "John")])
# Note: kwargs are sorted alphabetically

Combining Q objects

Q objects support three operators that build the tree:

Operator Connector Example
& AND Q(a=1) & Q(b=2)
| OR Q(a=1) | Q(b=2)
~ Negate ~Q(a=1)

Combining two Q objects creates a new parent node:

Q(name="John") & Q(age__gte=18)

→ Node(connector=AND)
    ├── Node(connector=AND, children=[("name", "John")])
    └── Node(connector=AND, children=[("age__gte", 18)])
Q(country="CA") | Q(country="US")

→ Node(connector=OR)
    ├── Node(connector=AND, children=[("country", "CA")])
    └── Node(connector=AND, children=[("country", "US")])

Negation builds a new node with the negated flag set. A single condition becomes a direct child of the new node:

~Q(country="US")

→ Node(connector=AND, negated=True, children=[("country", "US")])

A node with several conditions stays whole as a nested child:

~Q(country="US", age__gte=18)

→ Node(connector=AND, negated=True)
    └── Node(connector=AND, children=[("age__gte", 18), ("country", "US")])

A negated node negates each of its conditions, and it negates each nested node as a whole. So ~(Q(a=1) & Q(b=2)) and ~Q(a=1, b=2) mean "not both". exclude(a=1, b=2) builds one negated node that holds both conditions, so it drops a record that matches either one.

Squashing

The Node.add() method applies squashing, when combining two nodes with the same connector, it flattens the children into one level instead of nesting. This keeps the tree shallow for simple AND/AND or OR/OR combinations:

# fragment
Q(a=1) & Q(b=2) & Q(c=3)

# Without squashing:  AND(AND(a=1, b=2), c=3)   [nested]
# With squashing:     AND(a=1, b=2, c=3)         [flat]

Key source file: src/protean/utils/query.py


Lookup resolution

When a query uses a lookup suffix like age__gte=18, the system needs to resolve gte into a concrete comparison operation for the target database.

Parsing the lookup key

split_lookup_key in protean.utils.query splits a composite key into the field name and the lookup name. The provider's get_lookup then returns the lookup class registered under that name:

# fragment
split_lookup_key("age__gte")
# → ("age", "gte")

split_lookup_key("name")
# → ("name", "exact")  # default when no suffix

provider.get_lookup("gte")
# → GteLookup

get_lookup raises NotImplementedError naming the lookup and the provider when no lookup is registered under the name, or when the registered class does not subclass LookupPort.

Lookup registration

Each database provider registers its own lookup implementations using RegisterLookupMixin:

# fragment
class SADatabase(BaseDatabase, RawQueryDatabasePort):
    ...

# During adapter initialization:
SADatabase.register_lookup(ExactLookup)
SADatabase.register_lookup(ContainsLookup)
SADatabase.register_lookup(GteLookup)
# etc.

LookupPort

Every lookup subclasses LookupPort from protean.port.dao. The Port lists only what the framework relies on:

# fragment
class LookupPort(Protocol):
    lookup_name: ClassVar[str]   # e.g., "exact", "gte", "contains"
    source: Any                  # LHS of the comparison
    target: Any                  # RHS: comparison value
    database_model_cls: type[DatabaseModelPort] | None

    def __init__(self, source, target, *, database_model_cls=None) -> None: ...

How a lookup becomes a query is private to the adapter that runs it, so each adapter's lookup base class declares its own evaluation method. The memory adapter's MemoryLookup declares evaluate(), which compares a stored value with the filter value and returns a boolean. Its source is the stored value of the field. The SQL and Elasticsearch DefaultLookup classes declare as_expression(), which returns a SQLAlchemy expression or an Elasticsearch query. Their source is the field name, and they keep process_source() and process_target() to turn the two sides into what the expression needs.

Each database adapter provides its own implementations. For example, the memory adapter's Exact lookup checks Python equality, while SQLAlchemy's Exact lookup produces a SQLAlchemy column == value expression.

Some lookups must evaluate even when the source value is absent. The isnull lookup (Q(field__isnull=True/False)) is the canonical example: to match rows where a field is None, the predicate has to run against a None source. The memory adapter marks such lookups with a null_safe = True class attribute so _evaluate_lookup still applies them instead of short-circuiting when the source value is None. SQLAlchemy and Elasticsearch translate isnull to IS NULL / IS NOT NULL and the exists query respectively. isnull is one of the required lookups every adapter must register, since core framework machinery such as the outbox poll path depends on it.

By default a lookup's target is a literal value. An F("other_field") target instead names another column of the same row, turning the predicate into a column-to-column comparison (retry_count < max_retries). SQLAlchemy's process_target resolves F to the column object so the comparison renders as native SQL. The memory adapter resolves it per record to the referenced attribute before it builds the lookup. The Elasticsearch adapter's process_target raises NotImplementedError, since the equivalent needs a Painless script query. Because the memory and SQLAlchemy adapters each resolve F in one place, each comparison lookup on those adapters accepts an F target without per-lookup changes. The outbox poll and claim paths use F to push retry_count < max_retries into the database.

Lookup support across adapters

Every adapter registers the same core set of lookups, REQUIRED_LOOKUPS in protean.port.dao. The provider registry raises ConfigurationError for a provider class that lacks one, naming the missing lookups. A filter on a lookup the provider does not register raises NotImplementedError. Beyond that core set, support varies by adapter, but the contract is the same everywhere: an unsupported lookup fails loudly and never silently returns wrong results.

Lookup Memory SQLAlchemy Elasticsearch
exact / iexact ✅ ✅ ✅
contains / icontains ✅ ✅ ✅
startswith / endswith ✅ ✅ ✅
gt / gte / lt / lte ✅ ✅ ✅
in ✅ ✅ ✅
isnull ✅ ✅ ✅
any (array) ✅ ✅ (native array) ✅
overlap (array) ✅ ✅ (native array) ✅
F() column ref ✅ ✅ ❌

The twelve lookups above any are universal and exercised by the cross-adapter conformance suites under tests/adapters/database/generic/ and tests/repository/. The array lookups any and overlap match documents whose array field shares an element with the given values. SQLAlchemy maps them to native array operators (= ANY(...) and &&), so they need a backend with array columns such as PostgreSQL. Elasticsearch renders both as a terms query, because its fields are natively multivalued. The in-memory store compares elements by equality without hashing them, so it supports unhashable items such as dicts. F() column references work on the memory and SQLAlchemy adapters but not on Elasticsearch. Full-text (search), geospatial, and vector-similarity lookups are backend-specific and are not part of the portable contract.

Key source files:

  • src/protean/port/dao.py: LookupPort and REQUIRED_LOOKUPS.
  • src/protean/utils/query.py: split_lookup_key and RegisterLookupMixin.
  • src/protean/infra/registry.py: the required-lookup check.
  • src/protean/adapters/database/memory.py: Memory lookup implementations.
  • src/protean/adapters/database/sqlalchemy.py: SQLAlchemy lookup implementations.

Field name translation

QuerySet translates between field names (what domain code uses) and attribute names (what the database stores). This happens transparently in _filter_or_exclude:

# fragment
# User writes:
dao.query.filter(user_id="123")

# QuerySet resolves:
# field_name="user_id" → attribute_name="user_reference_id"
# Final criteria sent to DAO: user_reference_id="123"

Because QuerySet translates the names, a field name can differ from its database column name (via the referenced_as option on fields), and query code does not need to know the column name.

The same translation applies to order_by:

# fragment
dao.query.order_by("-user_id")
# → Resolved to order_by=["-user_reference_id"]

Indexes back the query paths

The query system decides how to ask; indexes decide how fast the database answers. Every filter or sort beyond a primary-key lookup needs a matching index or the database resorts to a full scan.

Protean keeps that knowledge in the domain layer: an aggregate declares the indexes its query paths need with the indexes= decorator option, alongside its fields and invariants. This mirrors the ports-and-adapters split the query system already follows: the portable Q/QuerySet API on one side, the adapter-specific SQL on the other. You declare portable indexes (composite, descending, unique) on the aggregate, and every SQL adapter honors them. For storage-specific tuning (GIN, BRIN, expression indexes), you use Index.from_sql on the model. A partial index whose where= predicate is a Q object reuses the same expression tree, compiled to the dialect's partial-index clause.

See Indexes for the API and ADR-0014 for the rationale.


Lazy evaluation and caching

QuerySets use a lazy evaluation strategy:

  1. Building phase: filter(), exclude(), limit(), offset(), order_by() all clone the QuerySet and modify the clone's internal state. No database call occurs.

  2. Evaluation trigger: The database is queried only when you actually need data. Triggers include:

    • .all(): Explicit evaluation
    • __iter__: for item in queryset
    • __len__: len(queryset)
    • __bool__: bool(queryset) or if queryset:
    • __getitem__: queryset[0] or queryset[1:5]
    • __contains__: item in queryset
    • Property access, .total, .items, .first, .last, .has_next, .has_prev
  3. Caching: After evaluation, results are stored in _result_cache. Subsequent property access returns cached data without re-querying. Call .all() to force a fresh query (it sets _result_cache = None before querying).


ResultSet

The ResultSet class wraps raw database results, preventing DAO-specific data structures from leaking into the domain layer:

# fragment
class ResultSet:
    offset: int          # current page offset
    limit: int | None    # requested page size (None = unlimited)
    total: int           # total matching records
    items: list          # entity objects in current page

    # Properties
    has_prev → bool      # offset > 0 and items exist
    has_next → bool      # more pages exist (always False when unlimited)
    first → entity|None  # items[0] if items, else None
    last → entity|None   # items[-1] if items, else None
    page → int           # current page number (1-indexed)
    page_size → int|None # alias for limit
    total_pages → int    # math.ceil(total / limit), 0 when empty

The DAO service's fetch and raw, which all() and raw() on QuerySet call, convert raw database results (dicts or model objects) into domain entity objects via DatabaseModel.to_entity(). They then mark each entity as retrieved (entity.state_.mark_retrieved()) and add each aggregate to the active Unit of Work's identity map. When the identity map already holds an aggregate, they return that instance in place of the copy they just loaded.

When you read a QuerySet without calling all() (iterating it, indexing it, or reading first, last or items), the QuerySet returns a deep copy of the cached results. Changing one result therefore does not change the next read. Inside a Unit of Work, aggregates are the exception: a read returns the instance the identity map tracks, the same instance that all() and get() return. Other results, such as entities that are not aggregates, are still copied.

The cache belongs to the transaction it was filled in, or to no transaction when it was filled outside a Unit of Work. The QuerySet runs the query again when you read it in a different transaction. Two examples are a QuerySet evaluated before a Unit of Work began and then read inside it, and a QuerySet read again after its Unit of Work ended. The read then returns what is stored now, and the aggregates it loads are tracked by the current Unit of Work.

Key source file: src/protean/core/queryset.py


ReadOnlyQuerySet

ReadOnlyQuerySet is a QuerySet subclass that blocks mutation methods. It is returned by domain.view_for().query to enforce CQRS read-only access on projections.

Blocked methods: update() and delete(). Both raise NotSupportedError.

Read methods work identically: filter(), exclude(), order_by(), limit(), offset(), all(), raw(), and all properties.

Because _clone() uses self.__class__(), each clone keeps the type of the QuerySet it came from. Chaining .filter() on a ReadOnlyQuerySet returns another ReadOnlyQuerySet.

# fragment
# domain.view_for().query returns a ReadOnlyQuerySet
view = domain.view_for(OrderSummary)
qs = view.query

# All read operations work
results = qs.filter(status="shipped").order_by("-placed_at").limit(20).all()

# Mutation attempts raise NotSupportedError
qs.update(status="cancelled")      # raises NotSupportedError
qs.delete()                        # raises NotSupportedError

Key source file: src/protean/core/queryset.py


Raw connection access

For queries that cannot be expressed through QuerySet or ReadOnlyQuerySet (e.g., database-specific aggregation pipelines, full-text search, or direct cache operations), domain.connection_for() provides the underlying connection object:

# fragment
conn = domain.connection_for(OrderSummary)
# conn is now the raw SQLAlchemy session, Elasticsearch client,
# Redis client, etc., depending on the projection's backing store

This is the escape hatch. It bypasses Protean's query abstraction entirely and hands you the technology-specific client. The method automatically routes to the correct provider or cache based on the projection's meta options (database or cache).

Key source file: src/protean/domain/__init__.py


Entity state tracking

When the repository/DAO layer loads, saves, or deletes entities, each entity's state_ property (an _EntityState instance) tracks its lifecycle state:

State Meaning Triggered by
is_new Not yet persisted Entity creation
is_persisted Has been saved at least once mark_saved() / mark_retrieved()
is_changed Has unsaved modifications mark_changed() (via __setattr__)
is_destroyed Has been deleted mark_destroyed()

The repository uses these flags to determine persistence strategy:

  • is_new → INSERT (via dao.create())
  • is_persisted and is_changed → UPDATE (via dao.update())
  • is_persisted and not is_changed → skip (idempotent)

Key source file: src/protean/core/entity.py


Version tracking

Aggregates use a _version field for optimistic concurrency control. When saving an aggregate, the DAO checks that the version in the database matches the version on the entity. If they differ (another process updated the aggregate in the meantime), an ExpectedVersionError is raised.

# fragment
# In DAO.save():
if entity_obj.element_type == DomainObjects.AGGREGATE:
    expected_version = self._validate_and_update_version(entity_obj)

The service passes expected_version to the adapter's update, which checks the stored version and writes in one step.

Key source file: src/protean/infra/dao.py