Skip to content

Commit a813edd

Browse files
authored
Add insert_many method to State model for bulk insertion with fingerprint generation (#260)
* Add insert_many method to State model for bulk insertion with fingerprint generation - Introduced an `insert_many` class method in the State model to handle bulk state insertions while ensuring that fingerprints are generated for states that require them. - Updated the `_generate_fingerprint` method to maintain existing functionality for individual state insertions. - Enhanced the overall integrity of state management by ensuring consistent fingerprint generation during bulk operations. * Refactor state.py to remove unused List import - Removed the unused List import from the state.py file to clean up the code and improve readability. This change helps maintain a more efficient and organized codebase. * Refactor fingerprint generation in insert_many method of State model - Updated the insert_many method to always generate fingerprints for all states, removing the conditional check for does_unites. This change simplifies the logic and ensures consistent fingerprint generation for all state insertions.
1 parent d582f47 commit a813edd

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

state-manager/app/models/db/state.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from ..state_status_enum import StateStatusEnum
44
from pydantic import Field
55
from beanie import Insert, PydanticObjectId, Replace, Save, before_event
6+
from pymongo.results import InsertManyResult
67
from typing import Any, Optional
78
import hashlib
89
import json
@@ -21,6 +22,7 @@ class State(BaseDatabaseModel):
2122
parents: dict[str, PydanticObjectId] = Field(default_factory=dict, description="Parents of the state")
2223
does_unites: bool = Field(default=False, description="Whether this state unites other states")
2324
state_fingerprint: str = Field(default="", description="Fingerprint of the state")
25+
2426
@before_event([Insert, Replace, Save])
2527
def _generate_fingerprint(self):
2628
if not self.does_unites:
@@ -42,6 +44,15 @@ def _generate_fingerprint(self):
4244
ensure_ascii=True, # normalized non-ASCII escapes
4345
).encode("utf-8")
4446
self.state_fingerprint = hashlib.sha256(payload).hexdigest()
47+
48+
@classmethod
49+
async def insert_many(cls, documents: list["State"]) -> InsertManyResult:
50+
"""Override insert_many to ensure fingerprints are generated before insertion."""
51+
# Generate fingerprints for states that need them
52+
for state in documents:
53+
state._generate_fingerprint()
54+
55+
return await super().insert_many(documents) # type: ignore
4556

4657
class Settings:
4758
indexes = [

0 commit comments

Comments
 (0)