Exemplo n.º 1
0
    def test_can_append_two_instances_first_is_empty(self):
        p = Pypher()
        p2 = Pypher()
        p2.two

        p.append(p2)

        exp = 'two'
        exp2 = 'two'
        s = str(p)
        s2 = str(p2)

        self.assertEqual(exp, s)
        self.assertEqual(exp2, s2)
Exemplo n.º 2
0
    def test_can_append_two_instances(self):
        p = Pypher()
        p2 = Pypher()
        p.one
        p2.two

        p.append(p2)

        exp = 'one two'
        exp2 = 'two'
        s = str(p)
        s2 = str(p2)

        self.assertEqual(exp, s)
        self.assertEqual(exp2, s2)
Exemplo n.º 3
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
Exemplo n.º 4
0
    def save_relationship(self, entity, ensure_unique=False):
        """this method handles creating and saving relationships.
        It will hanle quite a few situations. 
        Given the structure:

        (start)-[rel]->[end]

        We can have:
        * A new start node
        * An existing start node
        * A new rel
        * An existing rel
        * A new end node
        * An existing end node

        Each start, rel, and end could have uniqueness assigned to it
        * start/end could have unique properties
        * rel could have unique relationships

        A Chyper query should be generated that looks something like this,
        depending on the settings for each of the nodes:

        MERGE (n_0:Node {`key`: val})
        ON CREATE SET n_0.key = val, n_0.key2 = val2
        ON MATCH SET n_0.key = val, n_0.key2 = val2
        CREATE (n_0)-[r_0:RelLabel, {`key`: someVal}]->(n_1:Node {`key`: val})
        RETURN n_0, n_1, r_0
        """
        start = entity.start
        start_properties = {}
        end = entity.end
        end_properties = {}
        props = self._properties(entity)

        if start is None or end is None:
            raise Exception('The relationship must have a start and end node')

        if not isinstance(start, Node):
            start = Node(id=start)

        if not isinstance(end, Node):
            end = Node(id=end)

        VM.set_query_var(start)
        VM.set_query_var(end)
        VM.set_query_var(entity)

        rel = Pypher()

        if start not in self.matched_entities:
            if start.id is not None:
                self._update_properties(start)
                self.matches.append(self._node_by_id(start))
            else:
                start_properties = self._properties(start)

            self.matched_entities.append(start)
            self.returns.append(start.query_variable)

        if end not in self.matched_entities:
            if end.id is not None:
                self._update_properties(end)
                self.matches.append(self._node_by_id(end))
            else:
                end_properties = self._properties(end)

            self.matched_entities.append(end)
            self.returns.append(end.query_variable)

        if entity.id is None:
            if start.id is not None:
                rel = rel.node(start.query_variable)
            else:
                start_query = Query(start, self.params)
                start_query.build_save_pypher()

                if len(start_query.creates):
                    rel.append(*start_query.creates)
                elif len(start_query.merges):
                    has_matches = len(self.matches) > 0
                    start_merge = Pypher()
                    start_merge.MERGE(*start_query.merges)

                    if start_query.on_create_sets:
                        start_merge.OnCreateSet(*start_query.on_create_sets)

                    if start_query.on_match_sets:
                        start_merge.OnMatchSet(*start_query.on_match_sets)

                    self.before_matches.append(start_merge)
                    rel.node(start.query_variable)

            rel.rel(entity.query_variable,
                    labels=entity.labels,
                    direction='out',
                    **props)

            if end.id is not None:
                rel.node(end.query_variable)
            else:
                end_query = Query(end, self.params)
                end_query.build_save_pypher()

                if len(end_query.creates):
                    rel.append(*end_query.creates)
                elif len(end_query.merges):
                    end_merge = Pypher().MERGE(*end_query.merges)

                    if end_query.on_create_sets:
                        end_merge.OnCreateSet(*end_query.on_create_sets)

                    if end_query.on_match_sets:
                        end_merge.OnMatchSet(*end_query.on_match_sets)

                    self.before_matches.append(end_merge)
                    rel.node(end.query_variable)

            if ensure_unique:
                self.merges.append(rel)
            else:
                self.creates.append(rel)
        else:
            _id = VM.get_next(entity, 'id')
            _id = Param(_id, entity.id)

            if start.id is not None:
                rel = rel.node(start.query_variable)
            else:
                start_query = Query(start, self.params)
                start_query.build_save_pypher()

                if len(start_query.creates):
                    rel.append(*start_query.creates)
                elif len(start_query.merges):
                    start_merge = Pypher().MERGE(*start_query.merges)

                    if start_query.on_create_sets:
                        start_merge.OnCreateSet(*start_query.on_create_sets)

                    if start_query.on_match_sets:
                        start_merge.OnMatchSet(*start_query.on_match_sets)

                    if len(self.matches):
                        self.matches[-1].append(start_merge)
                    else:
                        self.matches.append(start_merge)

                    rel.node(start.query_variable)

            rel.rel(entity.query_variable,
                    labels=entity.labels,
                    direction='out')

            if end.id is not None:
                rel.node(end.query_variable)
            else:
                end_query = Query(end, self.params)
                end_query.build_save_pypher()

                if len(end_query.creates):
                    rel.append(*end_query.creates)
                elif len(end_query.merges):
                    end_merge = Pypher().MERGE(*end_query.merges)

                    if end_query.on_create_sets:
                        end_merge.OnCreateSet(*end_query.on_create_sets)

                    if end_query.on_match_sets:
                        end_merge.OnMatchSet(*end_query.on_match_sets)

                    if len(self.matches):
                        self.matches[-1].append(end_merge)
                    else:
                        self.matches.append(end_merge)

                    rel.node(end.query_variable)

            rel.WHERE(__.ID(entity.query_variable) == _id)
            self._update_properties(entity)
            self.matches.append(rel)

        self.returns.append(entity.query_variable)

        return self