def test_convert_many_of_different_type(self): names = ["name_1", "name_2"] models = [Sample(name=names[0]), Library(name=names[1])] converted = convert_to_sqlalchemy_models(models) self.assertEquals([x.name for x in converted], [x.name for x in models]) self.assertIsInstance(converted[0], SQLAlchemySample) self.assertIsInstance(converted[1], SQLAlchemyLibrary)
def _set_association(self, associate: Union[InternalIdModel, Iterable[InternalIdModel]], associate_with: InternalIdModel, relationship_property_name: str): """ Associates the given models to another model, linked to via the specified relationship property. :param associate: the models to associate :param associate_with: the model to associate with :param relationship_property_name: the property on `associate_with` in which the relationship is expressed """ if associate_with.internal_id is None: raise ValueError("Model to associate with must have an internal ID: %s" % associate_with) if isinstance(associate, InternalIdModel): associate = [associate] session = self._database_connector.create_session() sqlalchemy_associated_with_type = get_equivalent_sqlalchemy_model_type(associate_with.__class__) assert sqlalchemy_associated_with_type is not None # sqlalchemy_associated_with_type = SQLAlchemyStudy results = session.query(sqlalchemy_associated_with_type). \ filter(sqlalchemy_associated_with_type.internal_id == associate_with.internal_id).all() if len(results) != 1: raise ValueError("Model to associate with does not exist:\n%s" % associate_with) # FIXME: SQLAlchemy wants to insert the `associate` records. Could not find out how to stop this so hacking by # deleting from the database. If the given model is not in sync with the database this will lead to data # loss. sqlalchemy_associate_type = get_equivalent_sqlalchemy_model_type(associate[0].__class__) assert sqlalchemy_associate_type is not None for associate_element in associate: session.query(sqlalchemy_associate_type).\ filter(sqlalchemy_associate_type.internal_id == associate_element.internal_id).\ delete() sqlalchemy_associate = convert_to_sqlalchemy_models(associate) for result in results: for sqlalchemy_associate_element in sqlalchemy_associate: current_relationship = getattr(result, relationship_property_name) if sqlalchemy_associate_element not in current_relationship: setattr(result, relationship_property_name, current_relationship + sqlalchemy_associate) session.commit() session.close()
def test_convert_many_of_same_type(self): names = ["name_1", "name_2"] models = [Sample(name=names[0]), Sample(name=names[1])] converted = convert_to_sqlalchemy_models(models) self.assertEquals([x.name for x in converted], [x.name for x in models])