Exemple #1
0
    def testRegistry(self):
        g = self.g
        schema_registry = g.build_mapping(declarative_node(), declarative_relationship(), auto_plural=True)
        assert all(c in schema_registry for c in ['animal', 'food', 'eats'])

        assert type(schema_registry['animal'].specie) == String

        # Plurals not communicated to schema; postprocess registry before
        # include() if you have a better solution than auto_plural.
        assert schema_registry['food'].registry_plural != Food.registry_plural
        g.clear_registry()
        assert len(g.registry) == 0
        g.include(schema_registry)

        assert set(g.registry.keys()) == set(['food', 'dislikes', 'eats', 'beverage', 'animal', 'drinks'])

        rat = g.animal.create(name='rat', specie='rodent')
        mouse = g.animal.create(name='mouse', specie='rodent')
        rat_class = g.registry['animal']
        queried_rat = g.query(rat_class).filter(
            rat_class.name.endswith('at') | (rat_class.name == 'tiger')).one()

        assert rat == queried_rat

        # try again, to make sure that brokers get cleared correctly
        schema_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(schema_registry)
        assert set(g.registry.keys()) == set(['food', 'dislikes', 'eats', 'beverage', 'animal', 'drinks'])
Exemple #2
0
    def testRegistry(self):
        g = self.g
        schema_registry = g.build_mapping(declarative_node(), declarative_relationship(), auto_plural=True)
        assert all(c in schema_registry for c in ['animal', 'food', 'eats'])

        assert type(schema_registry['animal'].species) == String

        # Plurals not communicated to schema; postprocess registry before
        # include() if you have a better solution than auto_plural.
        assert schema_registry['food'].registry_plural != Food.registry_plural
        g.clear_registry()
        assert len(g.registry) == 0
        g.include(schema_registry)

        assert set(g.registry.keys()) == set(['food', 'dislikes', 'eats', 'beverage', 'animal', 'drinks'])

        rat = g.animal.create(name='rat', species='rodent')
        mouse = g.animal.create(name='mouse', species='rodent')
        rat_class = g.registry['animal']
        queried_rat = g.query(rat_class).filter(
            rat_class.name.endswith('at') | (rat_class.name == 'tiger')).one()

        assert rat == queried_rat

        # try again, to make sure that brokers get cleared correctly
        schema_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(schema_registry)
        assert set(g.registry.keys()) == set(['food', 'dislikes', 'eats', 'beverage', 'animal', 'drinks'])
Exemple #3
0
def class_from_json(stx: Dict, graph: Graph):
    id_ = stx.pop('id_')
    if stx['type'] == 'relationship':
        graph_class = declarative.declarative_relationship()
        class_name = stx['relationship_type'].replace('-', '_')
        props = {
            'id_': String(nullable=False),
            'label': class_name,
        }
    else:
        graph_class = declarative.declarative_node()
        class_name = stx['type'].replace('-', '')
        props = {
            'id_': String(nullable=False),
            'element_type': class_name,
            'element_plural': class_name + 's'
        }
    for k, v in stx.items():
        if k in prop_map:
            props[k] = prop_map[k]
        elif isinstance(v, list):
            props[k] = EmbeddedList()
        elif isinstance(v, str):
            props[k] = String()
        elif isinstance(v, int):
            props[k] = Integer()
        elif isinstance(v, float):
            props[k] = Float()
        else:
            print(f'Need a property mapping for {k}: {props[k]}')

    new_cls = type(class_name, (graph_class, ), props)
    graph.create_class(new_cls)
    return new_cls
Exemple #4
0
    def testAbstractFlag(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        self.assertTrue(database_registry['AbstractClass'].abstract)
        self.assertFalse(database_registry['ConcreteClass'].abstract)
Exemple #5
0
    def testCustomFields(self):
        g = self.g

        database_registry = g.build_mapping(declarative_node(),
                                            declarative_relationship(),
                                            auto_plural=True)
        g.clear_registry()
        g.include(database_registry)
        if g.server_version > (
                2, 2, 0
        ):  # Ugly! TODO Isolate version at which behaviour was changed
            self.assertEquals(
                {
                    'test_field_1': 'test_string_one',
                    'test_field_2': 'test string two'
                }, g.registry['classfieldvertex'].class_fields)
            self.assertEquals({'test_field_1': 'test string two'},
                              g.registry['classfieldedge'].class_fields)
        else:
            self.assertEquals(
                {
                    'test_field_1': 'test_string_one',
                    'test_field_2': '"test string two"'
                }, g.registry['classfieldvertex'].class_fields)
            self.assertEquals({'test_field_1': '"test string two"'},
                              g.registry['classfieldedge'].class_fields)
        self.assertEquals({}, g.registry['classfieldvertex2'].class_fields)
Exemple #6
0
    def testStrictness(self):
        g = self.g

        # Unknown properties get silently dropped by default
        pentium = g.cpu.create(name='Pentium', version=6)
        loaded_pentium = g.get_vertex(pentium._id)
        # Version is not defined in cpu
        assert not hasattr(pentium, 'version')

        # But in strict mode they generate errors
        g = self.g = Graph(Config.from_url('hardware',
                                           'root',
                                           'root',
                                           initial_drop=False),
                           strict=True)
        g.include(
            g.build_mapping(declarative_node(),
                            declarative_relationship(),
                            auto_plural=True))
        with self.assertRaises(AttributeError):
            pentium = g.cpu.create(name='Pentium', version=6)

        pentium = g.x86cpu.create(name='Pentium', version=6)
        self.assertEquals('Pentium', pentium.name)
        self.assertEquals(6, pentium.version)
Exemple #7
0
    def testAbstractFlag(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        self.assertTrue(database_registry['AbstractClass'].abstract)
        self.assertFalse(database_registry['ConcreteClass'].abstract)
def _initialize_graph_connection(config):
    """Initialize a graph connection with the given configuration."""
    graph = Graph(config, strict=True)
    base_node = declarative_node()
    base_relationship = declarative_relationship()
    graph.include(
        graph.build_mapping(base_node, base_relationship, auto_plural=True))
    return graph
Exemple #9
0
    def testRegistryLoading(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(database_registry)

        manufactures_cls = g.registry['manufactures']
        assert type(manufactures_cls.in_) == Link
        assert manufactures_cls.in_.linked_to == g.registry['cpu']
Exemple #10
0
    def testRegistryLoading(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(database_registry)

        manufactures_cls = g.registry['manufactures']
        assert type(manufactures_cls.in_) == Link
        assert manufactures_cls.in_.linked_to == g.registry['cpu']
Exemple #11
0
def _initialize_graph_connection(config, initial_drop=False):
    """Initialize a graph connection with the given configuration."""
    local_config = deepcopy(config)
    local_config.initial_drop = initial_drop

    graph = Graph(local_config, strict=True)
    base_node = declarative_node()
    base_relationship = declarative_relationship()
    graph.include(
        graph.build_mapping(base_node, base_relationship, auto_plural=True))
    return graph
Exemple #12
0
    def testCustomFields(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(database_registry)
        self.assertEquals(
            {'test_field_1': 'test string one', 'test_field_2': 'test string two'},
            g.registry['classfieldvertex'].class_fields)
        self.assertEquals({}, g.registry['classfieldvertex2'].class_fields)
        self.assertEquals(
            {'test_field_1': 'test string two'},
            g.registry['classfieldedge'].class_fields)
Exemple #13
0
    def testCustomFields(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(database_registry)
        self.assertEquals(
            {'test_field_1': 'test_string_one', 'test_field_2': '"test string two"'},
            g.registry['classfieldvertex'].class_fields)
        self.assertEquals({}, g.registry['classfieldvertex2'].class_fields)
        self.assertEquals(
            {'test_field_1': '"test string two"'},
            g.registry['classfieldedge'].class_fields)
def get_pyorient_client():
    db_url = ''.join([
        'plocal://', server_config.ORIENTDB_HOST, ':2424', '/',
        server_config.ORIENTDB_DB
    ])
    graph = Graph(Config.from_url(db_url, server_config.ORIENTDB_USER,
                                  server_config.ORIENTDB_PASSWORD),
                  strict=True)

    graph.include(
        graph.build_mapping(declarative_node(),
                            declarative_relationship(),
                            auto_plural=False))

    return graph
Exemple #15
0
    def testDefaultData(self):
        g = self.g

        g.client.command('CREATE CLASS DefaultEmbeddedNode EXTENDS V')
        g.client.command('CREATE CLASS DefaultData')
        g.client.command('CREATE PROPERTY DefaultData.normal Boolean')
        g.client.command('CREATE PROPERTY DefaultEmbeddedNode.name String')
        g.client.command(
            'CREATE PROPERTY DefaultEmbeddedNode.info EmbeddedList DefaultData'
        )

        try:
            g.client.command('ALTER PROPERTY DefaultData.normal DEFAULT 0')
        except PyOrientSQLParsingException as e:
            if "Unknown property attribute 'DEFAULT'" in e.errors[0]:
                # The current OrientDB version (<2.1) doesn't allow default values.
                # Simply skip this test, there's nothing we can test here.
                return
            else:
                raise

        base_node = declarative_node()
        base_relationship = declarative_relationship()
        g.include(
            g.build_mapping(base_node, base_relationship, auto_plural=True))

        node = g.DefaultEmbeddedNode.create(name='default_embedded')
        node.info = [{}]

        try:
            node.save()
        except PyOrientCommandException as e:
            if 'incompatible type is used.' in e.errors[0]:
                # The current OrientDB version (<2.1.5) doesn't allow embedded classes,
                # only embedded primitives (e.g. String or Int).
                # Simply skip this test, there's nothing we can test here.
                return
            else:
                raise

        # On the next load, the node should have:
        # 'info' = [{'normal': False}]
        node = g.DefaultEmbeddedNode.query().one()
        self.assertIn('normal', node.info[0])
        self.assertIs(node.info[0]['normal'], False)
Exemple #16
0
    def testDefaultData(self):
        g = self.g

        g.client.command('CREATE CLASS DefaultEmbeddedNode EXTENDS V')
        g.client.command('CREATE CLASS DefaultData')
        g.client.command('CREATE PROPERTY DefaultData.normal Boolean')
        g.client.command('CREATE PROPERTY DefaultEmbeddedNode.name String')
        g.client.command('CREATE PROPERTY DefaultEmbeddedNode.info EmbeddedList DefaultData')

        try:
            g.client.command('ALTER PROPERTY DefaultData.normal DEFAULT 0')
        except PyOrientSQLParsingException as e:
            if "Unknown property attribute 'DEFAULT'" in e.errors[0]:
                # The current OrientDB version (<2.1) doesn't allow default values.
                # Simply skip this test, there's nothing we can test here.
                return
            else:
                raise

        base_node = declarative_node()
        base_relationship = declarative_relationship()
        g.include(g.build_mapping(base_node, base_relationship, auto_plural=True))

        node = g.DefaultEmbeddedNode.create(name='default_embedded')
        node.info = [{}]

        try:
            node.save()
        except PyOrientCommandException as e:
            if 'incompatible type is used.' in e.errors[0]:
                # The current OrientDB version (<2.1.5) doesn't allow embedded classes,
                # only embedded primitives (e.g. String or Int).
                # Simply skip this test, there's nothing we can test here.
                return
            else:
                raise

        # On the next load, the node should have:
        # 'info' = [{'normal': False}]
        node = g.DefaultEmbeddedNode.query().one()
        self.assertIn('normal', node.info[0])
        self.assertIs(node.info[0]['normal'], False)
Exemple #17
0
    def testStrictness(self):
        g = self.g

        # Unknown properties get silently dropped by default
        pentium = g.cpu.create(name='Pentium', version=6)
        loaded_pentium = g.get_vertex(pentium._id)
        # Version is not defined in cpu
        assert not hasattr(pentium, 'version')

        # But in strict mode they generate errors
        g = self.g = Graph(Config.from_url('hardware', 'root', 'root'
                                           , initial_drop=False), strict=True)
        g.include(g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True))
        with self.assertRaises(AttributeError):
            pentium = g.cpu.create(name='Pentium', version=6)

        pentium = g.x86cpu.create(name='Pentium', version=6)
        self.assertEquals('Pentium', pentium.name)
        self.assertEquals(6, pentium.version)
Exemple #18
0
    def testCustomFields(self):
        g = self.g

        database_registry = g.build_mapping(
            declarative_node(), declarative_relationship(), auto_plural=True)
        g.clear_registry()
        g.include(database_registry)
        if g.server_version > (2,2,0): # Ugly! TODO Isolate version at which behaviour was changed
            self.assertEquals(
                {'test_field_1': 'test_string_one', 'test_field_2': 'test string two'},
                g.registry['classfieldvertex'].class_fields)
            self.assertEquals(
                {'test_field_1': 'test string two'},
                g.registry['classfieldedge'].class_fields)
        else:
            self.assertEquals(
                {'test_field_1': 'test_string_one', 'test_field_2': '"test string two"'},
                g.registry['classfieldvertex'].class_fields)
            self.assertEquals(
                {'test_field_1': '"test string two"'},
                g.registry['classfieldedge'].class_fields)
        self.assertEquals({}, g.registry['classfieldvertex2'].class_fields)
Exemple #19
0
def db_setup(HOST: str, USER: str, dbname: str, PASSW: str, PORT: str,
             keep: bool):
    """sets up database
    :param HOST: OGM Graph ref
    :param USER: OGM Graph ref
    :param dbname: OGM Graph ref
    :param PASSW: OGM Graph ref
    :param PORT: OGM Graph ref
    :param keep: boolean value to keep or destroy database
    """
    print('(connecting to db)')
    clear_database = ''
    if (not keep):
        clear_database = input(
            'Are you sure you want to delete the database? (Y/N)')

    if clear_database in ['Y', 'y', 'Yes', 'yes', 'YES']:
        print('(dropping database)')
        g = Graph(Config.from_url(dbname, USER, PASSW, initial_drop=True))
        g.create_all(Node.registry)
        g.create_all(Relationships.registry)
    else:
        print('(keeping database)')
        g = Graph(Config.from_url(dbname, USER, PASSW, initial_drop=False))
        SchemaNode = declarative_node()
        SchemaRelationship = declarative_relationship()
        classes_from_schema = g.build_mapping(SchemaNode,
                                              SchemaRelationship,
                                              auto_plural=True)
        g.include(classes_from_schema)

    g.client.command(
        "ALTER DATABASE DATETIMEFORMAT \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\"")

    print('our db g', g)
    return g
Exemple #20
0
import unittest
import decimal
import os.path

from pyorient.ogm import Graph, Config
from pyorient.groovy import GroovyScripts

from pyorient.ogm.declarative import declarative_node, declarative_relationship
from pyorient.ogm.property import String, Decimal, Float, UUID

from pyorient.ogm.what import expand, in_, out, distinct

AnimalsNode = declarative_node()
AnimalsRelationship = declarative_relationship()


class Animal(AnimalsNode):
    element_type = 'animal'
    element_plural = 'animals'

    name = String(nullable=False, unique=True)
    specie = String(nullable=False)


class Food(AnimalsNode):
    element_type = 'food'
    element_plural = 'foods'

    name = String(nullable=False, unique=True)
    color = String(nullable=False)
Exemple #21
0
import unittest
import decimal
import os.path
from datetime import datetime

from pyorient import PyOrientCommandException, PyOrientSQLParsingException
from pyorient.ogm import Graph, Config
from pyorient.groovy import GroovyScripts

from pyorient.ogm.declarative import declarative_node, declarative_relationship
from pyorient.ogm.property import (
    String, Date, DateTime, Decimal, Double, Integer, EmbeddedMap, EmbeddedSet,
    Link, UUID)
from pyorient.ogm.what import expand, in_, out, distinct, sysdate

AnimalsNode = declarative_node()
AnimalsRelationship = declarative_relationship()

class Animal(AnimalsNode):
    element_type = 'animal'
    element_plural = 'animals'

    name = String(nullable=False, unique=True)
    specie = String(nullable=False)

class Food(AnimalsNode):
    element_type = 'food'
    element_plural = 'foods'

    name = String(nullable=False, unique=True)
    color = String(nullable=False)
Exemple #22
0
import unittest
import decimal
import os.path

from pyorient.ogm import Graph, Config
from pyorient.groovy import GroovyScripts

from pyorient.ogm.declarative import declarative_node, declarative_relationship
from pyorient.ogm.property import String, Decimal, Float, UUID

from pyorient.ogm.what import expand, in_, out, distinct

AnimalsNode = declarative_node()
AnimalsRelationship = declarative_relationship()


class Animal(AnimalsNode):
    element_type = "animal"
    element_plural = "animals"

    name = String(nullable=False, unique=True)
    specie = String(nullable=False)


class Food(AnimalsNode):
    element_type = "food"
    element_plural = "foods"

    name = String(nullable=False, unique=True)
    color = String(nullable=False)
Exemple #23
0
from pyorient.ogm import declarative
from pyorient.ogm.property import String, Boolean, DateTime, EmbeddedList
import time
import datetime

Node = declarative.declarative_node()
Relationship = declarative.declarative_relationship()


class Host(Node):
    element_plural = 'hosts'

    hostname = String(nullable=False, indexed=True, unique=True)
    branch = String()
    os = String()
    discovered = DateTime()
    ip_address = EmbeddedList(String())
    listen_ports = EmbeddedList(String())
    unreachable = Boolean()

    def to_dict(self):
        props = {
            key: value if type(value) != datetime.datetime else int(
                time.mktime(value.utctimetuple()) * 1000)
            for key, value in self._props.iteritems()
        }
        props.update({"id": self._id})
        return props


class ExternalHost(Node):
Exemple #24
0
import unittest
import decimal
import os.path
from datetime import datetime

from pyorient.ogm import Graph, Config
from pyorient.groovy import GroovyScripts

from pyorient.ogm.declarative import declarative_node, declarative_relationship
from pyorient.ogm.property import String, DateTime, Decimal, Float, UUID

from pyorient.ogm.what import expand, in_, out, distinct

AnimalsNode = declarative_node()
AnimalsRelationship = declarative_relationship()


class Animal(AnimalsNode):
    element_type = 'animal'
    element_plural = 'animals'

    name = String(nullable=False, unique=True)
    specie = String(nullable=False)


class Food(AnimalsNode):
    element_type = 'food'
    element_plural = 'foods'

    name = String(nullable=False, unique=True)
    color = String(nullable=False)
Exemple #25
0
 class Bar(declarative_node()):
     pass
Exemple #26
0
 class Foo(declarative_node()):
     pass
Exemple #27
0
import unittest
import decimal
import os.path
from datetime import datetime

from pyorient.ogm import Graph, Config
from pyorient.groovy import GroovyScripts

from pyorient.ogm.declarative import declarative_node, declarative_relationship
from pyorient.ogm.property import String, DateTime, Decimal, Float, UUID

from pyorient.ogm.what import expand, in_, out, distinct

AnimalsNode = declarative_node()
AnimalsRelationship = declarative_relationship()

class Animal(AnimalsNode):
    element_type = 'animal'
    element_plural = 'animals'

    name = String(nullable=False, unique=True)
    specie = String(nullable=False)

class Food(AnimalsNode):
    element_type = 'food'
    element_plural = 'foods'

    name = String(nullable=False, unique=True)
    color = String(nullable=False)

class Eats(AnimalsRelationship):
Exemple #28
0
class Node(declarative_node(), NeuroarchNodeMixin):
    element_type = 'Node'
    element_plural = 'Nodes'
Exemple #29
0
import unittest
import decimal
import os.path
from datetime import datetime

from pyorient import PyOrientCommandException, PyOrientSQLParsingException
from pyorient.ogm import Graph, Config
from pyorient.groovy import GroovyScripts

from pyorient.ogm.declarative import declarative_node, declarative_relationship
from pyorient.ogm.property import (
    String, Date, DateTime, Decimal, Double, Integer, EmbeddedMap, EmbeddedSet,
    Link, UUID)
from pyorient.ogm.what import expand, in_, out, distinct, sysdate

AnimalsNode = declarative_node()
AnimalsRelationship = declarative_relationship()


class Animal(AnimalsNode):
    element_type = 'animal'
    element_plural = 'animals'

    name = String(nullable=False, unique=True)
    species = String(nullable=False)


class Food(AnimalsNode):
    element_type = 'food'
    element_plural = 'foods'
Exemple #30
0
from pyorient.ogm import Graph, Config
from pyorient.ogm.declarative import declarative_node, declarative_relationship

NodeBase = declarative_node()
RelationshipBase = declarative_relationship()

graph: Graph = None


def is_connected():
    global graph
    return graph is not None


def get_graph():
    return graph


def connect_database(host, user, password, is_initial_drop=False):
    global graph
    graph = Graph(Config.from_url(host, user, password, is_initial_drop))


def refresh_models():
    global graph
    graph.create_all(NodeBase.registry)
    graph.create_all(RelationshipBase.registry)


def attach_models():
    global graph