Example #1
0
class RelatedEntityQuery(_BaseQuery):
    def __init__(self,
                 direction='out',
                 relationship_entity=None,
                 relationship_type=None,
                 relationship_properties=None,
                 start_entity=None,
                 end_entity=None,
                 params=None,
                 single_relationship=False,
                 start_query_variable='start_node',
                 relationship_query_variable='relt',
                 end_query_variable='end_node'):
        super(RelatedEntityQuery, self).__init__()

        self.direction = direction
        self.relationship_entity = relationship_entity
        self.relationship_type = relationship_type
        self.start_query_variable = start_query_variable
        self.relationship_query_variable = relationship_query_variable
        self.end_query_variable = end_query_variable
        self._start_entity = None
        self.start_entity = start_entity
        self._end_entity = None
        self.end_entity = end_entity
        self.relationship_properties = relationship_properties or {}
        self.params = params
        self.skip = None
        self.limit = 1 if single_relationship else None

    def reset(self):
        super(RelatedEntityQuery, self).reset()

        self.skip = None
        self.limit = None

        if self.start_entity:
            self.start_entity.query_variable = self.start_query_variable
            VM.set_query_var(self.start_entity)

        if self.end_entity:
            self.end_entity.query_variable = self.end_query_variable
            VM.set_query_var(self.end_entity)

    def _get_relationship_entity(self):
        return self._relationship_entity

    def _set_relationship_entity(self, relationship):
        if relationship is not None and not isinstance(relationship,
                                                       Relationship):
            raise AttributeError('Must be an <Relationship> and not'
                                 ' a <{t}>'.format(t=type(relationship)))

        self._relationship_entity = relationship

        return self

    relationship_entity = property(_get_relationship_entity,
                                   _set_relationship_entity)

    def _get_start_entity(self):
        return self._start_entity

    def _set_start_entity(self, entity):
        if entity is not None and not isinstance(entity, Node):
            raise AttributeError('entity must be a Node instance')

        if entity:
            entity.query_variable = self.start_query_variable
            VM.set_query_var(entity)

        self._start_entity = entity

    start_entity = property(_get_start_entity, _set_start_entity)

    def _get_end_entity(self):
        return self._end_entity

    def _set_end_entity(self, entity):
        if entity is not None and not isinstance(entity, Node):
            raise AttributeError('entity must be a Node instance')

        if entity:
            entity.query_variable = self.end_query_variable
            VM.set_query_var(entity)

        self._end_entity = entity

    end_entity = property(_get_end_entity, _set_end_entity)

    def _build_start(self):
        pypher = Pypher()

        if self.start_entity.id is not None:
            qv = self.start_entity.query_variable
            where = __.ID(qv) == self.start_entity.id

            pypher.NODE(qv)
            self.wheres.append(where)
        else:
            pypher.NODE(self.start_query_variable,
                        labels=self.start_entity.labels)

        return pypher

    def _build_end(self):
        pypher = Pypher()
        qv = self.end_query_variable
        labels = None

        if self.end_entity:
            qv = self.end_entity.query_variable
            labels = self.end_entity.labels

        pypher.NODE(qv, labels=labels)
        self.returns.append(qv)

        return pypher

    def _build_relationship(self):
        pypher = Pypher()

        if self.relationship_entity:
            self.relationship_entity.query_variable =\
                self.relationship_query_variable
            VM.set_query_var(self.relationship_entity)

            pypher.relationship(self.relationship_entity.query_variable,
                                direction=self.direction,
                                labels=self.relationship_entity.labels,
                                **self.relationship_properties)
        else:
            pypher.relationship(direction=self.direction,
                                labels=self.relationship_type)

        return pypher

    def query(self, return_relationship=False, returns=None):
        if not self.start_entity:
            raise RelatedQueryException(('Related objects must have a'
                                         ' start entity'))

        self.pypher = Pypher()
        pypher = self.pypher

        self.matches.insert(0, self._build_end())
        self.matches.insert(0, self._build_relationship())
        self.matches.insert(0, self._build_start())

        self.pypher.MATCH

        for match in self.matches:
            self.pypher.append(match)

        if self.wheres:
            self.pypher.WHERE.CAND(*self.wheres)

        if return_relationship:
            ret = getattr(__, self.relationship_query_variable)
            self.returns = [
                ret,
            ]

        returns = returns or self.returns

        self.pypher.RETURN(*returns)

        if self.orders:
            self.pypher.ORDER.BY(*self.orders)

        if self.skip is not None:
            self.pypher.SKIP(self.skip)

        if self.limit is not None:
            self.pypher.LIMIT(self.limit)

        self.reset()

        return str(pypher), pypher.bound_params

    def connect(self, entity, properties=None):
        if not self.start_entity:
            message = ('The relationship {} does not have a start'
                       ' entity'.format(self.relationship_entity
                                        or self.relationship_type))

            raise RelatedQueryException(('The relationship {} does not '))

        if self.start_entity == entity:
            msg = ('the start entity {} cannot be the same as the'
                   ' end entity'.format(entity))
            raise RelatedQueryException(msg)

        start = self.start_entity
        end = entity

        if self.direction == 'in':
            start, end = end, start

        kwargs = {
            'start': start,
            'end': end,
            'properties': properties,
        }

        if self.relationship_entity:
            return self.relationship_entity.__class__(**kwargs)

        kwargs['labels'] = self.relationship_type

        return Relationship(**kwargs)

    def delete(self, entity):
        if isinstance(entity, Relationship):
            if entity.id is not None:
                query = Query(entity)

                return query.delete()
            elif entity.end and hasattr(entity.end, 'id'):
                self.matches.insert(0, self._build_end())
                self.matches.insert(0, self._build_relationship())
                self.matches.insert(0, self._build_start())

                self.pypher.MATCH

                for match in self.matches:
                    self.pypher.append(match)

                self.pypher.DETACH.DELETE(self.relationship_query_variable)
                self.reset()

                return str(self.pypher), self.pypher.bound_params

    def delete_by_entity_id(self, *ids):
        if not ids:
            msg = 'There must be ids passed in to the delete method'
            raise AttributeError(msg)

        def _build_start():
            pypher = Pypher()

            if self.start_entity.id is not None:
                qv = self.start_entity.query_variable
                where = __.ID(qv) == self.start_entity.id

                pypher.NODE(qv)
                self.wheres.append(where)
            else:
                pypher.NODE(self.start_query_variable)

            return pypher

        self.pypher = Pypher()
        self.matches.insert(0, self._build_end())
        self.matches.insert(0, self._build_relationship())
        self.matches.insert(0, _build_start())

        self.pypher.MATCH

        for match in self.matches:
            self.pypher.append(match)

        id_params = []

        for i in ids:
            key = 'end_id_{}'.format(i)
            id_params.append(Param(key, i))

        self.wheres.append(__.ID(self.end_query_variable).IN(*id_params))
        _id = __.ID(self.start_query_variable)

        if self.start_entity.id is not None:
            self.wheres.append(_id == self.start_entity.id)
        # else:
        #     wheres.append(_id)

        self.pypher.WHERE.CAND(*self.wheres)
        self.pypher.DELETE(self.relationship_query_variable)
        self.reset()

        return str(self.pypher), self.pypher.bound_params