Esempio n. 1
0
def import_model(model, db_name, server, port, user, password):
    client = OrientDB(server, port)
    client.connect(user, password)

    client.db_open(db_name, user, password, DB_TYPE_GRAPH)
    edges = create_vertices(model, client)
    create_edges(edges, client)

    client.db_close(db_name)
def main():
    argument_spec = dict(host=dict(required=True),
                         port=dict(required=False, type=int, default=2424),
                         user=dict(required=False, default="root"),
                         password=dict(required=False,
                                       default="root",
                                       no_log=True),
                         state=dict(required=False,
                                    choices=["present", "absent"],
                                    default="present"),
                         database=dict(required=True),
                         type=dict(choices=["document", "graph"],
                                   default="document"),
                         storage_type=dict(choices=["plocal", "memory"],
                                           default="plocal"))

    module = AnsibleModule(argument_spec=argument_spec, )

    client = OrientDB(host=module.params["host"], port=module.params["port"])

    try:
        client.connect(user=module.params["user"],
                       password=module.params["password"])

        if module.params["state"].lower() == "present":
            client.db_create(name=module.params["database"],
                             type=module.params["type"],
                             storage=module.params["storage_type"])
        else:
            client.db_drop(module.params["database"])
        module.exit_json(changed=True)
    except PyOrientDatabaseException as e:
        if "already exists" in str(e):
            module.exit_json(changed=False, result=str(e))
    except PyOrientCommandException as e:
        if "does not exist" in str(e):
            module.exit_json(changed=False, result=str(e))
    finally:
        client.db_close()
Esempio n. 3
0
def load_schema(client: OrientDB) -> None:
    """Read the schema file and apply the specified SQL updates to the client."""
    project_root = path.dirname(path.dirname(path.abspath(__file__)))
    file_path = path.join(project_root, "test_data_tools/schema.sql")
    sql_files = glob(file_path)
    if len(sql_files) > 1:
        raise AssertionError(
            u"Multiple schema files found. Expected single `schema.sql` "
            u"in graphql-compiler/graphql_compiler/tests/test_data_tools/"
        )
    if len(sql_files) == 0 or sql_files[0] != file_path:
        raise AssertionError(
            u"Schema file not found. Expected graphql-compiler/graphql_compiler/"
            u"tests/test_data_tools/schema.sql"
        )

    with open(file_path, "r") as update_file:
        for line in update_file:
            sanitized = line.strip()
            if len(sanitized) == 0 or sanitized[0] == "#":
                # comment or empty line, ignore
                continue

            client.command(sanitized)
 def __init__(self, host_name:str, db_user_name:str, db_user_password:str, db_name:str, db_port:int=2424):
     """
     Constructor of DbDelegate.
     :param host_name: the dns name or ip address of the db located. For example, "locahost", "127.0.0.1"
     :param db_user_name: login user name.
     :param db_user_password: login user password.
     :param db_name: database name.
     :param db_port: connection port, by default, it is 2424.
     """
     self.host_name = host_name
     self.db_user_name = db_user_name
     self.db_user_password = db_user_password
     self.db_name = db_name
     self.db_port = db_port
     self._cn:OrientDB = OrientDB(self.host_name, self.db_port)
     self._section_token = None
Esempio n. 5
0
def get_test_graph(graph_name):
    """Generate the test database and return the pyorient client."""
    url = get_orientdb_url(graph_name)
    config = Config.from_url(url, ORIENTDB_USER, ORIENTDB_PASSWORD, initial_drop=True)
    Graph(config, strict=True)

    client = OrientDB('localhost', ORIENTDB_PORT)
    client.connect(ORIENTDB_USER, ORIENTDB_PASSWORD)
    client.db_open(graph_name, ORIENTDB_USER, ORIENTDB_PASSWORD, db_type=DB_TYPE_GRAPH)

    load_schema(client)
    generate_data(client)

    return client
Esempio n. 6
0
def get_test_orientdb_graph(
    graph_name: str,
    load_schema_func: Callable[[OrientDB], None],
    generate_data_func: Callable[[OrientDB], None],
) -> OrientDB:
    """Generate the test database and return the pyorient client."""
    url = get_orientdb_url(graph_name)
    config = Config.from_url(url,
                             ORIENTDB_USER,
                             ORIENTDB_PASSWORD,
                             initial_drop=True)
    Graph(config, strict=True)

    client = OrientDB(host="localhost", port=ORIENTDB_PORT)
    client.connect(ORIENTDB_USER, ORIENTDB_PASSWORD)
    client.db_open(graph_name,
                   ORIENTDB_USER,
                   ORIENTDB_PASSWORD,
                   db_type=DB_TYPE_GRAPH)

    load_schema_func(client)
    generate_data_func(client)

    return client
def main():
    argument_spec = dict(
        host=dict(required=True),
        port=dict(type=int, default=2424),
        user=dict(default="root"),
        password=dict(default="root", no_log=True),
        database=dict(),
        storage_type=dict(choices=["plocal", "memory"]),
        db_list=dict(type=bool),
        db_size=dict(type=bool),
        db_exists=dict(type=bool),
        db_count_records=dict(type=bool),
        check_default_credentials=dict(type=bool),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_if=(
            ("db_size", True, ["database"]),
            ("db_exists", True, ["database", "storage_type"]),
            ("db_count_records", True, ["database"]),
        ),
        mutually_exclusive=[(
            "db_list",
            "db_size",
            "db_exists",
            "db_count_records",
            "check_default_credentials",
        )],
    )

    client = OrientDB(host=module.params["host"], port=module.params["port"])

    try:
        client.connect(user=module.params["user"],
                       password=module.params["password"])

        if module.params["db_list"]:
            module.exit_json(
                databases=client.db_list().__getattr__("databases"))
        elif module.params["db_size"]:
            client.db_open(
                module.params["database"],
                module.params["user"],
                module.params["password"],
            )
            module.exit_json(size=client.db_size())
        elif module.params["db_exists"]:
            module.exit_json(exist=client.db_exists(
                module.params["database"], type=module.params["storage_type"]))
        elif module.params["db_count_records"]:
            client.db_open(
                module.params["database"],
                module.params["user"],
                module.params["password"],
            )
            module.exit_json(count=client.db_count_records())
        elif module.params["check_default_credentials"]:
            _db_list = []
            # Check for Default Login
            for i in client.db_list().__getattr__("databases"):
                try:
                    client.db_open(i, "admin", "admin")
                    _db_list.append(i)
                    client.db_close()
                except:  # nopep8 #nosec
                    pass
            module.exit_json(default_credential_dbs=_db_list)
        else:
            module.fail_json(msg="unknown options are passed")
    except Exception as e:
        module.fail_json(msg=str(e))
    finally:
        client.db_close()
Esempio n. 8
0
def create_db(db_name, server, port, user, password):
    """
    Create a new database and populate it with the base types
    """
    client = OrientDB(server, port)
    client.connect(user, password)

    client.db_create(db_name, DB_TYPE_GRAPH, STORAGE_TYPE_MEMORY)

    for key, value in types.items():
        client.command("create class %s extends V" % value)

    for edge_type in edge_types:
        client.command("create class %s extends E" % edge_type)

    client.db_close(db_name)
Esempio n. 9
0
def init_db_data(host: str, port: int, root_password: str, db_name: str,
                 xml_files: Optional[List[str]] = None, client: OrientDB = None) -> pyorient.OrientDB:
    if xml_files is not None:
        for filepath in xml_files:
            load_xml_into_db(host, port, root_password, filepath, db_name)

    if client is None:
        client = pyorient.OrientDB(host, port)
        client.connect('root', root_password)

    if client.db_exists(db_name):
        client.db_open(db_name, 'admin', 'admin')

    else:
        client.db_create(db_name, pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY)

    client.db_open(db_name, 'admin', 'admin')
    client.command('CREATE CLASS BBNEvaluationInput EXTENDS V')
    client.command('CREATE PROPERTY BBNEvaluationInput.jsonData STRING')

    client.command('CREATE CLASS BBNEvaluationOutput EXTENDS V')
    client.command('CREATE PROPERTY BBNEvaluationOutput.jsonData STRING')
    client.command('CREATE PROPERTY BBNEvaluationOutput.finalState STRING')
    client.command('CREATE PROPERTY BBNEvaluationOutput.finalStateInfo STRING')

    # client.coommand('CREATE CLASS DAUInventory EXTENDS V')
    return client
Esempio n. 10
0
def add_connections(newConnections):

    client_ = OrientDB(configuration.get_prop('srv_addr'),
                       configuration.get_prop('srv_port'))
    client_.connect(configuration.get_prop('user'),
                    configuration.get_prop('pass'))
    client_.db_open(configuration.get_prop('db_name'),
                    configuration.get_prop('user'),
                    configuration.get_prop('pass'))

    for links in newConnections:

        v1 = client_.query('SELECT FROM Site WHERE url = "%s"' % (links[0]), 1)
        if (len(v1) == 0):
            client_.command('CREATE VERTEX Site SET url = "%s"' % (links[0]))

        v2 = client_.query('SELECT FROM Site WHERE url = "%s"' % (links[1]), 1)
        if (len(v2) == 0):
            client_.command('CREATE VERTEX Site SET url = "%s"' % (links[1]))

        count = newConnections[links]

        edge_query = client_.query(
            'SELECT FROM links_to WHERE out in (SELECT @rid FROM Site WHERE url = "%s") '
            'and in in (SELECT @rid FROM Site WHERE url = "%s")' %
            (links[0], links[1]))

        if (len(edge_query) == 0):
            client_.command(
                'CREATE EDGE links_to FROM (SELECT FROM Site WHERE url = "%s") '
                'TO (SELECT FROM Site WHERE url = "%s") SET count = %d' %
                (links[0], links[1], count))
        else:
            edge = edge_query[0].oRecordData
            new_count = edge['count'] + count
            client_.command('UPDATE %s SET count = %d' %
                            (edge_query[0]._rid, new_count))
Esempio n. 11
0
def _get_orientdb_client():
    """Return a connection to the graph."""
    client = OrientDB(graph_config.host, graph_config.port, graph_config.serialization_type)
    client.connect(graph_config.user, graph_config.cred)
    client.db_open(graph_config.db_name, graph_config.user, graph_config.cred)
    return client
Esempio n. 12
0
from pyorient import OrientDB
import pyorient
from socket_config import Socket
import db_atributes
socket = Socket("orientDB", 2424)
try:
    print("here")
    socket.connect()
    client = OrientDB(socket)
    session_id = client.connect("root", "password")  #get session id
    client.db_open("test", "root", "password")  #open db
    for item in db_atributes.orient_classes(
    ):  #create a classes and atributes of new class if not exists based on db atributes file
        client.command("CREATE CLASS " + item['name'] +
                       " IF NOT EXISTS EXTENDS " + item['classType'])
        for prop in item['atributes']:
            client.command("CREATE PROPERTY " + item['name'] + "." +
                           prop['name'] + " IF NOT EXISTS " + prop['types'])
except Exception as e:
    print(e)
    socket.connect()
    client = OrientDB(socket)
    session_id = client.connect("root", "password")  #get session id
    if not client.db_exists(
            "test"
    ):  #if exeption is for non created db  lets create the db and classes with atributes based on db_atributes file
        client.db_create("test", pyorient.DB_TYPE_GRAPH,
                         pyorient.STORAGE_TYPE_PLOCAL)
        client.db_open("test", "root", "password")
    for item in db_atributes.orient_classes():
        client.command("CREATE CLASS " + item['name'] +
    def _init_db_data(self,
                      db_name: str,
                      xml_files: Optional[List[str]] = None,
                      client: pyorient.OrientDB = None) -> pyorient.OrientDB:
        if xml_files is not None:
            for filepath in xml_files:
                json.dump(self.config, open(SWRI_CONFIG_FILE, 'w'), indent=4)

                importer = OrientDBXMLImporter(databaseName=db_name,
                                               configFile=SWRI_CONFIG_FILE,
                                               mdlFile=filepath)

                importer.import_xml()
                importer.orientDB_helper.close_database()

        if client is None:
            client = pyorient.OrientDB(self.host, self.port)
            client.connect('root', self.root_password)

        if client.db_exists(db_name):
            client.db_open(db_name, 'admin', 'admin')
        else:
            client.db_create(db_name, pyorient.DB_TYPE_GRAPH,
                             pyorient.STORAGE_TYPE_MEMORY)

        client.db_open(db_name, 'admin', 'admin')
        client.command('CREATE CLASS BBNEvaluationData EXTENDS V')
        client.command(
            'CREATE PROPERTY BBNEvaluationData.inputJsonData STRING')
        client.command(
            'CREATE PROPERTY BBNEvaluationData.outputJsonData STRING')
        client.command('CREATE PROPERTY BBNEvaluationData.currentState STRING')
        client.command(
            'CREATE PROPERTY BBNEvaluationData.currentStateInfo STRING')
        return client