def _save_state(self) -> None: """ Save current document state. Internal method :return: None """ if self.use_state_management(): self._saved_state = get_dict(self)
async def insert_one( cls: Type[DocType], document: DocType, session: Optional[ClientSession] = None, bulk_writer: "BulkWriter" = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ) -> Optional[DocType]: """ Insert one document to the collection :param document: Document - document to insert :param session: ClientSession - pymongo session :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: InsertRules - hot to manage link fields :return: DocType """ if not isinstance(document, cls): raise TypeError( "Inserting document must be of the original document class") if bulk_writer is None: return await document.insert(link_rule=link_rule, session=session) else: if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert with bulk writing not supported") bulk_writer.add_operation( Operation( operation=InsertOne, first_query=get_dict(document, to_db=True), object_class=type(document), )) return None
async def insert( self: DocType, *, link_rule: WriteRules = WriteRules.DO_NOTHING, session: Optional[ClientSession] = None, ) -> DocType: """ Insert the document (self) to the collection :return: Document """ if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, ]: if isinstance(value, Document): await value.insert(link_rule=WriteRules.WRITE) if field_info.link_type == LinkTypes.LIST: for obj in value: if isinstance(obj, Document): await obj.insert(link_rule=WriteRules.WRITE) result = await self.get_motor_collection().insert_one(get_dict( self, to_db=True), session=session) new_id = result.inserted_id if not isinstance(new_id, self.__fields__["id"].type_): new_id = self.__fields__["id"].type_(new_id) self.id = new_id return self
def get_changes(self) -> Dict[str, Any]: # TODO search deeply changes = {} if self.is_changed: current_state = get_dict(self) for k, v in self._saved_state.items(): # type: ignore if v != current_state[k]: changes[k] = current_state[k] return changes
async def test_bson_encoders_filed_types(): custom = DocumentWithBsonEncodersFiledsTypes( color="7fffd4", timestamp=datetime.datetime.utcnow()) encoded = get_dict(custom) assert isinstance(encoded["timestamp"], str) c = await custom.insert() c_fromdb = await DocumentWithBsonEncodersFiledsTypes.get(c.id) assert c_fromdb.color.as_hex() == c.color.as_hex() assert isinstance(c_fromdb.timestamp, datetime.datetime) assert c_fromdb.timestamp, custom.timestamp
async def insert( self: DocType, session: Optional[ClientSession] = None ) -> DocType: """ Insert the document (self) to the collection :return: Document """ result = await self.get_motor_collection().insert_one( get_dict(self), session=session ) new_id = result.inserted_id if not isinstance(new_id, self.__fields__["id"].type_): new_id = self.__fields__["id"].type_(new_id) self.id = new_id return self
async def insert_many( cls: Type[DocType], documents: List[DocType], session: Optional[ClientSession] = None, ) -> InsertManyResult: """ Insert many documents to the collection :param documents: List["Document"] - documents to insert :param session: ClientSession - pymongo session :return: InsertManyResult """ documents_list = [get_dict(document) for document in documents] return await cls.get_motor_collection().insert_many( documents_list, session=session, )
async def insert_one( cls: Type[DocType], document: DocType, session: Optional[ClientSession] = None, ) -> InsertOneResult: """ Insert one document to the collection :param document: Document - document to insert :param session: ClientSession - pymongo session :return: InsertOneResult """ if not isinstance(document, cls): raise TypeError( "Inserting document must be of the original document class" ) return await cls.get_motor_collection().insert_one( get_dict(document), session=session )
async def insert_many( cls: Type[DocType], documents: List[DocType], session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ) -> InsertManyResult: """ Insert many documents to the collection :param documents: List["Document"] - documents to insert :param session: ClientSession - pymongo session :param link_rule: InsertRules - how to manage link fields :return: InsertManyResult """ if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert not supported for insert many method") documents_list = [ get_dict(document, to_db=True) for document in documents ] return await cls.get_motor_collection().insert_many( documents_list, session=session, )
def get_changes(self) -> Dict[str, Any]: return self._collect_updates( self._saved_state, get_dict(self, to_db=True) # type: ignore )
def is_changed(self) -> bool: if self._saved_state == get_dict(self, to_db=True): return False return True