soev for developers

warren.storage.document_store

Document store: the document store interface and its MongoDB and in-memory implementations.

Classes

MemoryDocumentStore

classMemoryDocumentStore(*, collection_name, doc_id_field='doc_id', unique_indexes=None, name=None)

Document store held in a dict. Single-process, gone at exit.

Takes the same doc_id_field / unique_indexes keywords as MongoDBDocumentStore so either can sit under DefaultResultsStore and RetryWorker. The default doc_id_field is "doc_id", not "_id". Pass it explicitly when the two stores must be interchangeable.

Documents are deep-copied on the way in and on the way out. A database gives callers that isolation for free; a dict does not, and a worker mutating a document it just read must not change stored state.

The doc id field and each unique index are backed by a hash index, so uniqueness is checked in constant time instead of by scanning the collection. Values of indexed fields must be hashable. As on MongoDB, an update that would duplicate a unique key is rejected, here with DocumentAlreadyExistsError.

query supports flat equality only, which is everything the framework itself issues. A query operator raises instead of silently matching nothing.

paramcollection_namestr
paramdoc_id_fieldstr
= 'doc_id'
paramunique_indexeslist[IndexSpec] | None
= None
paramnamestr | None
= None
methodinsertasync (doc, overwrite_existing=False) -> str
paramdocdict
paramoverwrite_existingbool
= False
methodupsert_manyasync (docs) -> list[str | None]
paramdocslist[dict]
methodupdateasync (doc_id, updates) -> None
paramdoc_idstr
paramupdatesdict
methodexistsasync (doc_id) -> bool
paramdoc_idstr
methodget_documentasync (doc_id) -> dict
paramdoc_idstr
methodqueryasync (params, *, sort_by=None) -> AsyncGenerator[dict, None]
paramparamsdict
paramsort_bystr | None
= None
methoddeleteasync (doc_id, *, expected=None) -> bool
paramdoc_idstr
paramexpecteddict | None
= None
methodget_document_type() -> str
methodget_doc_id_field() -> str
methodhas_unique_indexasync (index_spec) -> bool
paramindex_specIndexSpec

MongoDBDocumentStore

classMongoDBDocumentStore(client, *, database_name, collection_name, doc_id_field='_id', fields_to_index=None, unique_indexes=None, name=None, scoped_database=None)

Async MongoDB implementation of DocumentStoreInterface.

Uses pymongo's AsyncMongoClient for non-blocking I/O. Provides document storage using MongoDB as the backend. Supports custom document ID fields and automatic index creation.

Requires calling await setup() after construction to create indexes. create_default_results_store and create_binary_results_store call it for the store that they create.

Initialize the MongoDB document store.

paramclientAsyncMongoClient

Async MongoDB client instance.

paramdatabase_namestr

Name of the database to use.

paramcollection_namestr

Name of the collection to use.

paramdoc_id_fieldstr
= '_id'

Field name to use as document ID. Defaults to "_id".

paramfields_to_indexlist[IndexSpec] | None
= None

List of index specifications. Each can be a single field name (str) or a tuple of field names for composite indexes.

paramunique_indexeslist[IndexSpec] | None
= None

List of index specifications that should be unique. Each can be a single field name (str) or a tuple of field names.

paramnamestr | None
= None

Optional name for logging purposes.

paramscoped_databaseScopedDatabase | None
= None

Resolve the database from the scope of the current handler (database_name is then not used). The indexes of each scope database are created when the scope is first used, and setup() does nothing.

methodsetupasync () -> None

Create indexes on configured fields.

Must be called after construction before using the store. create_default_results_store and create_binary_results_store call it for the store that they create.

methodinsertasync (doc, overwrite_existing=False) -> str

Insert a document into the document store.

paramdocdict

Document to insert.

paramoverwrite_existingbool
= False

If True, replace existing document with same unique key. If unique_indexes are configured, uses the first unique index as the upsert key. Otherwise, uses the doc_id_field.

Returns

str

Document ID of the inserted document.

Raises:

  • DocumentAlreadyExistsError: If overwrite_existing is False and the document has the same ID or the same values for a unique index as a stored document.
  • ValueError: If the ID is empty, or is not a valid ObjectId when doc_id_field is "_id".
methodupsert_manyasync (docs) -> list[str | None]

Upsert rows in one unordered bulk write, preserving MongoDB IDs.

paramdocslist[dict]
methodupdateasync (doc_id, updates) -> None

Update a document with the given updates.

paramdoc_idstr

ID of the document to update.

paramupdatesdict

Dictionary of field updates to apply.

Raises:

  • ValueError: If doc_id is None, empty, or invalid format.
  • DocumentNotFoundError: If document with doc_id does not exist.
methodexistsasync (doc_id) -> bool

Check if a document exists in the store.

paramdoc_idstr

ID of the document to check.

Returns

bool

True if document exists, False otherwise.

Raises:

  • ValueError: If doc_id is None, empty, or invalid format.
methoddeleteasync (doc_id, *, expected=None) -> bool

Delete a document by its ID.

paramdoc_idstr

ID of the document to delete.

paramexpecteddict | None
= None

Additional field values required for deletion.

Returns

bool

True if document existed and was deleted, False if document was not found.

Raises:

  • ValueError: If doc_id is None, empty, or invalid format.
methodget_documentasync (doc_id) -> dict

Retrieve a document by its ID.

paramdoc_idstr

ID of the document to retrieve.

Returns

dict

The document as a dictionary.

Raises:

  • ValueError: If doc_id is None, empty, or invalid format.
  • DocumentNotFoundError: If document with doc_id does not exist.
methodqueryasync (params, *, sort_by=None) -> AsyncGenerator[dict, None]

Query documents matching the given parameters.

paramparamsdict

MongoDB query parameters.

paramsort_bystr | None
= None

Optional field to sort by in ascending order.

Returns

AsyncGenerator[dict, None]

Async generator yielding matching documents.

methodget_document_type() -> str

Returns the document type identifier for this store.

Returns

str

The collection name.

methodget_doc_id_field() -> str

Returns the field name used for document IDs.

Returns

str

The configured doc_id_field.

methodhas_unique_indexasync (index_spec) -> bool

Check if a unique index exists on the given field(s).

paramindex_specIndexSpec

Single field name or tuple of field names for composite index.

Returns

bool

True if a unique index exists on exactly these fields.

Protocols

DocumentStoreInterface

protocolDocumentStoreInterface

Async document store interface.

All I/O methods are async — implementations must use non-blocking drivers (e.g., pymongo.AsyncMongoClient) to avoid blocking the event loop.

Accessor methods (get_document_type, get_doc_id_field) are sync because they return stored config values with no I/O.

methodinsertasync (doc, overwrite_existing=False) -> str

Insert a document into the document store and return its ID.

paramdocdict

Document to insert.

paramoverwrite_existingbool
= False

Allow overwrite of existing document if True.

Returns

str

Document ID.

Raises:

  • DocumentAlreadyExistsError: If overwrite_existing is False and the document has the same ID or the same values for a unique index as a stored document.
  • ValueError: If the ID is empty, or is not a valid ObjectId when doc_id_field is "_id".
methodupsert_manyasync (docs) -> list[str | None]

Replace rows by unique key, returning IDs where the backend provides them.

paramdocslist[dict]
methodupdateasync (doc_id, updates) -> None

Update document with document id with given updates.

paramdoc_idstr

Document ID.

paramupdatesdict

Fields to set. Fields that are not named stay as they are. Use top-level keys only: a dotted key is a nested path on MongoDB and a literal key in memory.

Raises:

  • DocumentNotFoundError: if document id does not exist.
methodexistsasync (doc_id) -> bool

Check if document id exists.

paramdoc_idstr

Document ID.

Returns

bool

True if document id exists.

methodget_documentasync (doc_id) -> dict

Get document with document id.

paramdoc_idstr

Document ID.

Returns

dict

Document dict.

Raises:

  • DocumentNotFoundError: if document id does not exist.
methodquery(params, *, sort_by=None) -> AsyncGenerator[dict, None]

Query document store.

Returns an async generator — callers use async for doc in store.query(params).

paramparamsdict

Query parameters.

paramsort_bystr | None
= None

Optional field to sort by in ascending order.

Returns

AsyncGenerator[dict, None]

Async generator of documents found.

methoddeleteasync (doc_id, *, expected=None) -> bool

Delete a document by its ID.

paramdoc_idstr

Document ID.

paramexpecteddict | None
= None

Additional field values required for deletion.

Returns

bool

True if document existed and was deleted, False if it was not found or expected values did not match.

methodget_document_type() -> str

Returns the document type identifier for this store.

Returns

str

Document type identifier (e.g., collection name).

methodget_doc_id_field() -> str

Returns the field name used for document IDs.

Returns

str

Field name containing document IDs.

methodhas_unique_indexasync (index_spec) -> bool

Check if a unique index exists on the given field(s).

paramindex_specIndexSpec

Single field name or tuple of field names for composite index.

Returns

bool

True if a unique index exists on exactly these fields.

Type aliases

DocId

type aliasDocId = Union[ObjectId, str]

IndexSpec

type aliasIndexSpec = Union[str, tuple[str, ...]]

Errors

DocumentAlreadyExistsError

errorDocumentAlreadyExistsError

DocumentNotFoundError

errorDocumentNotFoundError

No document with the given ID exists in the document store.

Raised by document stores. Resolvers and the fetcher raise a different class, warren.storage.documents.DocumentNotFoundError. A handler that catches one class does not catch the other.

On this page