From 0c8f8276c8f4235236872966d2ee81f3e7d46a79 Mon Sep 17 00:00:00 2001 From: Thiago Salvatore Date: Mon, 10 Jun 2024 16:43:50 -0300 Subject: [PATCH] Allow unordered parameter on BulkWriter --- beanie/odm/bulk.py | 7 +++++-- tests/odm/documents/test_bulk_write.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/beanie/odm/bulk.py b/beanie/odm/bulk.py index 48ec020ce..38a6117c1 100644 --- a/beanie/odm/bulk.py +++ b/beanie/odm/bulk.py @@ -43,9 +43,12 @@ class Config: class BulkWriter: - def __init__(self, session: Optional[ClientSession] = None): + def __init__( + self, session: Optional[ClientSession] = None, ordered: bool = True + ): self.operations: List[Operation] = [] self.session = session + self.ordered = ordered async def __aenter__(self): return self @@ -78,7 +81,7 @@ async def commit(self) -> Optional[BulkWriteResult]: requests.append(query) return await obj_class.get_motor_collection().bulk_write( # type: ignore - requests, session=self.session + requests, session=self.session, ordered=self.ordered ) return None diff --git a/tests/odm/documents/test_bulk_write.py b/tests/odm/documents/test_bulk_write.py index 050365e8f..e61bcbd5b 100644 --- a/tests/odm/documents/test_bulk_write.py +++ b/tests/odm/documents/test_bulk_write.py @@ -62,6 +62,28 @@ async def test_update(documents, document_not_inserted): ) +async def test_unordered_update(documents, document): + await documents(5) + doc = await DocumentTestModel.find_one(DocumentTestModel.test_int == 0) + doc.test_int = 100 + with pytest.raises(BulkWriteError): + async with BulkWriter(ordered=False) as bulk_writer: + await DocumentTestModel.insert_one( + document, bulk_writer=bulk_writer + ) + await doc.save_changes(bulk_writer=bulk_writer) + + assert len(await DocumentTestModel.find_all().to_list()) == 6 + assert ( + len( + await DocumentTestModel.find( + DocumentTestModel.test_int == 100 + ).to_list() + ) + == 1 + ) + + async def test_delete(documents, document_not_inserted): await documents(5) doc = await DocumentTestModel.find_one(DocumentTestModel.test_int == 0)