Source

graphalchemy / graphalchemy / mixins / elements.py

# -*- coding: utf-8 -*-
'''graph element mixins'''

from stuf.utils import both, getcls, lazy, clsname

__all__ = ('ElementMixin', 'NodesMixin')


class ElementMixin(object):

    '''graph element'''

    def __init__(self, element=None, **kw):
        '''
        init

        @param element: graph element (default: None)
        '''
        # element direction
        self.direction = kw.pop('direction', 'outgoing')
        super(ElementMixin, self).__init__(element, **kw)

    @lazy
    def id(self):
        '''graph element id'''
        return self._p.id(self.source)

    @both
    def links(self):
        '''sequence of all links'''
        return self._links(self, getcls(self))

    def _source(self, this):
        '''
        synchronized data structure

        @param this: this element
        '''
        return self._r.properties(this)

    def _refresh(self):
        '''refresh original'''
        super(ElementMixin, self).sync()
        # reset links collector
        self.links.reset()

    def index_by(self, index=None, *indexed):
        '''
        index properties on a graph element

        @param index: graph index label (default: None)
        @param *indexed: properties to index
        '''
        self._p.index_many(index, self, indexed)

    def index_under(self, index, key, value):
        '''
        index one property of a graph element

        @param index: graph index label
        @param key: graph element property key
        @param value: graph element property value
        '''
        self._p.index_one(index, key, value, self)


class NodeMixin(object):

    '''node element'''

    def __repr__(self):
        return '{0}: {1}'.format(
            clsname(self), super(NodeMixin, self).__repr__(),
        )

    @lazy
    def _p(self):
        return self.session.nodes

    @lazy
    def nodes(self):
        '''connector to all nodes linked to this node'''
        return self._nodes(self, getcls(self))

    def _refresh(self):
        '''refresh node objects'''
        super(NodeMixin, self)._refresh()
        # reset nodes connector
        self.nodes.reset()

    def deep_dump(self):
        '''
        serialize this node, its outgoing related nodes, and their outgoing
        related nodes
        '''
        return self.copy(id=self.id, nodes=self.nodes.deep_dump())

    def dump(self):
        '''serialize this node and outgoing related nodes'''
        return self.copy(id=self.id)

    def link(self, link, node, **kw):
        '''
        link this node to another node

        @param link: kind of link
        @param node: the other node
        @param **kw: link properties
        '''
        self.session.links.create(link, self, node, kw)