Example #1
0
    def test_from_db(self):
        self.assertIsNone(model_util.from_db(None))

        _tor = db_model.Torrent()
        _tor['name'] = 'fake.torrent'

        _pub_tor = model_util.from_db(_tor)
        self.assertIsInstance(_pub_tor, api_model.Torrent)

        _mf = db_model.MediaFile()
        _mf['filename'] = 'media.mp4'
        _mf['file_ext'] = '.mp4'
        _mf['torrent_id'] = _tor.id

        _pub_mf = model_util.from_db(_mf)
        self.assertIsInstance(_pub_mf, api_model.MediaFile)
Example #2
0
    def fetch(self, entity_type, pk):
        """Fetch the instance using primary key from the database.

        :param entity_type: the model type
        :param pk: primary key value
        """
        _model = getattr(db_model, entity_type.__name__)
        session = self._engine_facade.session
        with session.begin():
            _row = session.query(_model).get(pk)
        return model_util.from_db(_row)
Example #3
0
    def bulk_create(self, instances):
        """Save the instances in bulk to the database.

        :param list instances: a list of instance of modeled data object
        """
        if not instances:
            return
        _instances = [model_util.to_db(item) for item in instances]

        session = self._engine_facade.session
        with session.begin():
            session.add_all(_instances)
        for _row in _instances:
            yield model_util.from_db(_row)
Example #4
0
    def fetch_by(self, entity_type, qfilter):
        """Fetch the instance(s) based on filter from the database.

        :param entity_type: the model type
        :param qfilter: query filter to determine which rows to update
        """
        _model = getattr(db_model, entity_type.__name__)
        session = self._engine_facade.session
        with session.begin():
            transformer = db_model.QueryTransformer(_model,
                                                    session.query(_model))
            _query = transformer.apply_filter(qfilter)
            for _row in _query.all():
                yield model_util.from_db(_row)
Example #5
0
    def save(self, instance):
        """Save the instance to the database

        :param instance: an instance of modeled data object
        """
        _model = getattr(db_model, instance.__class__.__name__)
        session = self._engine_facade.session
        with session.begin():
            _pk = getattr(instance, instance.PK_NAME)
            if _pk is not None:
                _row = session.query(_model).get(_pk)
                _row = model_util.to_db(instance, _row)
            else:
                _row = model_util.to_db(instance)
                session.add(_row)
            _row.save(session)
        return model_util.from_db(_row)