Exemple #1
0
    def mod_data(self, model_class, search_filter, data_obj):
        # validate data_obj
        if type(data_obj) is not dict:
            raise Exception('data_obj is not dict!')
        for field in data_obj:
            if not has_field(model_class, field):
                msg = "Model does not have field '{0}'".format(field)
                raise Exception(msg)

        session = getattr(model_class, '__session__')
        db_type = getattr(model_class, '__db_type__', 'sqlorm')

        # create query from query string
        query = self._search_data(model_class, search_filter)

        if db_type == 'sqlorm':
            relations = update_relations(model_class, query, data_obj)
            field_list = frozenset(data_obj) ^ relations
            data = dict((field, data_obj[field]) for field in field_list)

            # Special case: if there are any dates, convert the string form of
            # the date into an instance of the Python ``datetime`` object.
            data = strings_to_dates(model_class, data)

            try:
                # Let's update all instances present in the query
                num_modified = 0
                session.begin()
                if data:
                    for item in query.all():
                        for field, value in data.items():
                            setattr(item, field, value)
                        num_modified += 1
                session.commit()
            except Exception as exception:
                _LOGGER.exception(str(exception))
        elif db_type == 'mongo':
            try:
                filters = QueryBuilder.create_mongokit_filters(
                    model_class, search_filter)
                session.collection.update(filters, {'$set': data_obj},
                                          multi=True, safe=True)
            except Exception as exception:
                _LOGGER.exception(str(exception))
        else:
            pass
Exemple #2
0
 def del_data(self, model_class, search_filter):
     session = getattr(model_class, '__session__')
     db_type = getattr(model_class, '__db_type__', 'sqlorm')
     if db_type == 'sqlorm':
         query = self._search_data(model_class, search_filter)
         try:
             session.begin()
             query.delete(synchronize_session=False)
             session.commit()
         except sqlalchemy.exc.IntegrityError as exception:
             _LOGGER.warn('ORM IntergirtError:%s' % exception)
     elif db_type == 'mongo':
         try:
             filters = QueryBuilder.create_mongokit_filters(model_class,
                                                            search_filter)
             session.collection.remove(filters, safe=True)
         except Exception as e:
             _LOGGER.warn('delete error, %s', e)