Ejemplo n.º 1
0
def test_simple_index_nx_to_memgraph(memgraph: Memgraph):
    graph = nx.Graph()
    graph.add_nodes_from([
        (1, {
            "labels": "L1",
            "num": 123
        }),
        (2, {
            "labels": "L1",
            "num": 123
        }),
        (3, {
            "labels": ["L1", "L2", "L3"],
            "num": 123
        }),
    ])
    graph.add_edges_from([(1, 2), (1, 3)])
    expected_indexes = {
        MemgraphIndex("L1", "id"),
        MemgraphIndex("L2", "id"),
        MemgraphIndex("L3", "id"),
    }

    for query in nx_to_cypher(graph, NetworkXCypherConfig(create_index=True)):
        memgraph.execute(query)
    actual_indexes = set(memgraph.get_indexes())

    assert actual_indexes == expected_indexes
Ejemplo n.º 2
0
def connect_to_memgraph(memgraph_ip, memgraph_port):
    memgraph = Memgraph(host=memgraph_ip, port=int(memgraph_port))
    while True:
        try:
            if memgraph._get_cached_connection().is_active():
                return memgraph
        except:
            sleep(1)
Ejemplo n.º 3
0
def _insert_queries(queries: List[str], host: str, port: int, username: str, password: str, encrypted: bool) -> None:
    """Used by multiprocess insertion of nx into memgraph, works on a chunk of queries."""
    memgraph = Memgraph(host, port, username, password, encrypted)
    while len(queries) > 0:
        try:
            query = queries.pop()
            memgraph.execute(query)
        except mgclient.DatabaseError as e:
            queries.append(query)
            logging.getLogger(__file__).warning(f"Ignoring database error: {e}")
            continue
Ejemplo n.º 4
0
def test_drop_trigger(memgraph: Memgraph):
    trigger = MemgraphTrigger(
        name="test_trigger",
        event_type=TriggerEventType.CREATE,
        event_object=TriggerEventObject.ALL,
        execution_phase=TriggerExecutionPhase.BEFORE,
        statement="CREATE (:Node)",
    )

    memgraph.create_trigger(trigger)
    memgraph.drop_trigger(trigger)
    assert len(memgraph.get_triggers()) == 0
Ejemplo n.º 5
0
def test_create_get_trigger(memgraph: Memgraph):
    trigger = MemgraphTrigger(
        name="test_trigger",
        event_type=TriggerEventType.CREATE,
        event_object=TriggerEventObject.ALL,
        execution_phase=TriggerExecutionPhase.BEFORE,
        statement="CREATE (:Node)",
    )

    memgraph.create_trigger(trigger)
    assert any(
        map(lambda t: t["trigger name"] == "test_trigger",
            memgraph.get_triggers()))
Ejemplo n.º 6
0
def _check_for_index_hint(
    host: str = "127.0.0.1",
    port: int = 7687,
    username: str = "",
    password: str = "",
    encrypted: bool = False,
):
    """Check if the there are indexes, if not show warnings."""
    memgraph = Memgraph(host, port, username, password, encrypted)
    indexes = memgraph.get_indexes()
    if len(indexes) == 0:
        logging.getLogger(__file__).warning(
            "Be careful you do not have any indexes set up, the queries will take longer than expected!"
        )
Ejemplo n.º 7
0
def test_edges_mapping(populated_memgraph: Memgraph):
    query = "MATCH ()-[e]->() RETURN e"
    expected_edges = [
        Relationship(
            _id=0,
            _type="Relation",
            _start_node_id=0,
            _end_node_id=1,
            id=0,
            name="name1",
        ),
        Relationship(
            _id=1,
            _type="Relation",
            _start_node_id=1,
            _end_node_id=2,
            id=1,
            num=100,
        ),
        Relationship(
            _id=2,
            _type="Relation",
            _start_node_id=2,
            _end_node_id=0,
            id=2,
            data=[1, 2, 3],
        ),
    ]

    actual_edges = [
        r["e"] for r in populated_memgraph.execute_and_fetch(query)
    ]

    compare_edges(actual_edges, expected_edges)
Ejemplo n.º 8
0
def test_nodes_mapping(populated_memgraph: Memgraph):
    query = "MATCH (n) RETURN n"
    expected_nodes = [
        Node(
            _id=0,
            _node_labels={"Node"},
            id=0,
            name="name1",
        ),
        Node(
            _id=1,
            _node_labels={"Node"},
            id=1,
            data=[1, 2, 3],
        ),
        Node(
            _id=2,
            _node_labels={"Node"},
            id=2,
            data={
                "a": 1,
                "b": "abc"
            },
        ),
    ]

    actual_nodes = [
        r["n"] for r in populated_memgraph.execute_and_fetch(query)
    ]

    compare_nodes(actual_nodes, expected_nodes)
Ejemplo n.º 9
0
def test_nx_to_memgraph(memgraph: Memgraph):
    graph = nx.Graph()
    expected_nodes = [
        (1, {
            "labels": "L1",
            "num": 123
        }),
        (2, {
            "labels": "L1",
            "num": 123
        }),
        (3, {
            "labels": ["L1", "L2", "L3"],
            "num": 123
        }),
    ]
    expected_edges = [(1, 2, {
        "type": "E1",
        "num": 3.14
    }), (1, 3, {
        "type": "E2",
        "num": 123
    })]
    graph.add_nodes_from(expected_nodes)
    graph.add_edges_from(expected_edges)

    for query in nx_to_cypher(graph):
        memgraph.execute(query)

    actual_nodes = list(
        memgraph.execute_and_fetch("MATCH (n) RETURN n ORDER BY n.id"))
    assert len(actual_nodes) == 3
    for i, node in enumerate(actual_nodes):
        assert node["n"]._properties["id"] == expected_nodes[i][0]
        if isinstance(expected_nodes[i][1]["labels"], (list, tuple)):
            assert node["n"]._labels == set(expected_nodes[i][1]["labels"])
        else:
            assert node["n"]._labels == {expected_nodes[i][1]["labels"]}
        assert node["n"]._properties["num"] == expected_nodes[i][1]["num"]

    actual_edges = list(
        memgraph.execute_and_fetch("MATCH ()-[e]->() RETURN e"))
    assert len(actual_edges) == 2
    for i, edge in enumerate(actual_edges):
        assert edge["e"]._type == expected_edges[i][2]["type"]
        assert edge["e"]._properties["num"] == expected_edges[i][2]["num"]
Ejemplo n.º 10
0
def test_simple_nx_to_memgraph(memgraph: Memgraph):
    graph = nx.Graph()
    graph.add_nodes_from([1, 2, 3])
    graph.add_edges_from([(1, 2), (1, 3)])

    for query in nx_to_cypher(graph):
        memgraph.execute(query)

    actual_nodes = list(
        memgraph.execute_and_fetch("MATCH (n) RETURN n ORDER BY n.id"))
    assert len(actual_nodes) == 3
    for i, node in enumerate(actual_nodes):
        assert node["n"]._properties["id"] == i + 1
        assert node["n"]._labels == set()

    actual_edges = list(
        memgraph.execute_and_fetch("MATCH ()-[e]->() RETURN e"))
    assert len(actual_edges) == 2
    for i, edge in enumerate(actual_edges):
        assert edge["e"]._type == "TO"
Ejemplo n.º 11
0
def _create_n_user_objects(n: int) -> None:
    db = Memgraph()
    SQLitePropertyDatabase("./tests/on_disk_storage.db", db)
    huge_string = "I LOVE MEMGRAPH" * 1000
    for _ in range(n):
        id_ = random.randint(1, 2 * n)
        try:
            user1 = User(id=id_, huge_string=huge_string).save(db)
            assert user1.huge_string == huge_string
        except mgclient.DatabaseError:  # Memgraph collision happened
            continue
        except GQLAlchemyError as e:
            print("Error when saving a node.")
            print(traceback.format_exc())
            print(list(db.execute_and_fetch("match (a) return a;")))
            print(list(db.execute_and_fetch("show constraint info;")))
            raise e
        try:
            user2 = User(id=id_).load(db)
            assert user2.huge_string == huge_string
        except mgclient.DatabaseError:  # Memgraph collision happened
            continue
        except GQLAlchemyError as e:
            print("Error in loading a node.")
            print(traceback.format_exc())
            print(list(db.execute_and_fetch("match (a) return a;")))
            print(list(db.execute_and_fetch("show constraint info;")))
            raise e
Ejemplo n.º 12
0
def test_path_mapping(populated_memgraph: Memgraph):
    query = "MATCH p = ({id: 0})-[*]->({id: 3}) RETURN p"
    expected_nodes = [
        Node(_id=0, _node_labels={"Node"}, id=0),
        Node(_id=1, _node_labels={"Node"}, id=1),
        Node(_id=2, _node_labels={"Node"}, id=2),
        Node(_id=2, _node_labels={"Node"}, id=3),
    ]
    expected_relationships = [
        Relationship(
            _id=0,
            _type="Relation",
            _start_node_id=0,
            _end_node_id=1,
            id=0,
        ),
        Relationship(
            _id=1,
            _type="Relation",
            _start_node_id=1,
            _end_node_id=2,
            id=1,
        ),
        Relationship(
            _id=2,
            _type="Relation",
            _start_node_id=2,
            _end_node_id=3,
            id=2,
        ),
    ]

    actual_paths = [
        r["p"] for r in populated_memgraph.execute_and_fetch(query)
    ]
    assert len(actual_paths) == 1
    actual_path = actual_paths[0]

    compare_nodes(actual_path._nodes, expected_nodes)
    compare_edges(actual_path._relationships, expected_relationships)
Ejemplo n.º 13
0
from gqlalchemy import Memgraph, Node, Field
from typing import Optional

db = Memgraph()


class User(Node):
    name: str = Field(index=True, exists=True, unique=True, db=db)


class Stream(User):
    id: str = Field(index=True, exists=True, unique=True, db=db)
    followers: Optional[int] = Field()


def test_multiple_inheritance():
    user = User(name="Kate").save(db)
    streamer = Stream(id=7, name="Ivan", followers=172).save(db)
    assert "name" in Stream.__fields__
    assert user.name == "Kate"
    assert streamer.name == "Ivan"
    assert streamer.followers == 172
    assert User.labels == {"User"}
    assert Stream.labels == {"Streamer", "User"}
    assert user._labels == {"User"}
    assert streamer._labels == {"Streamer", "User"}
    assert "name" in Stream.__fields__
Ejemplo n.º 14
0
def clear_db():
    db = Memgraph()
    db.drop_database()
    on_disk_db = SQLitePropertyDatabase("./tests/on_disk_storage.db")
    on_disk_db.drop_database()
Ejemplo n.º 15
0
def test_automatic_deserialisation_from_database():
    db = Memgraph()

    db.execute("create (:Person {id: 1, name: 'person'});")
    db.execute("create (:Alice {id: 8, name: 'alice'});")
    db.execute("match (a:Alice) match(b:Person) create (a)-[:FRIENDS]->(b);")

    result = list(db.execute_and_fetch("match (a)-[r]->(b) return a, r, b"))
    for node in result:
        a = node["a"]
        assert isinstance(a, Alice)
        assert a.id == 8
        assert a.name == "alice"
        assert a._node_labels == {"Alice"}
        assert isinstance(a._node_id, int)
        assert a._properties == {"id": 8, "name": "alice"}
        assert isinstance(a._id, int)

        r = node["r"]
        assert isinstance(r, Friends)
        assert r._type == "FRIENDS"
        assert isinstance(r._relationship_id, int)
        assert isinstance(r._start_node_id, int)
        assert isinstance(r._end_node_id, int)
        assert r._properties == {}
        assert isinstance(r._id, int)

        b = node["b"]
        assert isinstance(b, Person)
        assert b.id == 1
        assert b.name == "person"
        assert b._node_labels == {"Person"}
        assert isinstance(b._node_id, int)
        assert b._properties == {"id": 1, "name": "person"}
        assert isinstance(b._id, int)

    db.drop_database()
Ejemplo n.º 16
0
def stream_exists(stream: str, memgraph: Memgraph) -> bool:
    return stream in memgraph.get_streams()
Ejemplo n.º 17
0
def test_path_deserialisation():
    db = Memgraph()
    db.execute("create (:Person {id: 1, name: 'person'});")
    db.execute("create (:Alice {id: 8, name: 'alice'});")
    db.execute("match (a:Alice) match(b:Person) create (a)-[:FRIENDS]->(b);")
    result = list(db.execute_and_fetch("MATCH p = ()-[*1]-() RETURN p"))
    path = result[0]["p"]
    assert isinstance(path, Path)
    assert len(path._nodes) == 2
    assert len(path._relationships) == 1
    db.drop_database()
Ejemplo n.º 18
0
def memgraph() -> Memgraph:
    memgraph = Memgraph()
    memgraph.ensure_indexes([])
    memgraph.ensure_constraints([])
    memgraph.drop_database()
    return memgraph
Ejemplo n.º 19
0
def cleanup_trigger():
    yield
    memgraph = Memgraph()
    memgraph.execute("DROP TRIGGER test_trigger;")
Ejemplo n.º 20
0
def test_big_nx_to_memgraph(memgraph: Memgraph, random_nx_graph: nx.Graph):
    for query in nx_to_cypher(random_nx_graph,
                              NetworkXCypherConfig(create_index=True)):
        memgraph.execute(query)
Ejemplo n.º 21
0
def test_huge_nx_to_memgraph_parallel_with_index(
        memgraph: Memgraph, big_random_nx_graph: nx.Graph):
    memgraph.create_index(MemgraphIndex("Label", "id"))

    nx_graph_to_memgraph_parallel(big_random_nx_graph)
Ejemplo n.º 22
0
def test_big_nx_to_memgraph_with_manual_index(memgraph: Memgraph,
                                              random_nx_graph: nx.Graph):
    memgraph.create_index(MemgraphIndex("Label", "id"))

    for query in nx_to_cypher(random_nx_graph):
        memgraph.execute(query)
Ejemplo n.º 23
0
def populated_memgraph(dataset_file: str) -> Memgraph:
    memgraph = Memgraph()
    memgraph.ensure_indexes([])
    memgraph.ensure_constraints([])
    memgraph.drop_database()
    with get_data_dir().joinpath(dataset_file).open("r") as dataset:
        for query in dataset:
            memgraph.execute(query)

    yield memgraph

    memgraph.drop_database()
Ejemplo n.º 24
0
def query(command: str) -> Iterator[Dict[str, Any]]:
    """Queries Memgraph database and returns iterator of results"""
    db = Memgraph()
    yield from db.execute_and_fetch(command)
Ejemplo n.º 25
0
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest

from gqlalchemy import SQLitePropertyDatabase, Memgraph, Node, Field, Relationship
from typing import Optional

memgraph = Memgraph()
db = SQLitePropertyDatabase("./tests/on_disk_storage.db", memgraph)


class User(Node):
    id: int = Field(unique=True, index=True, db=memgraph)
    huge_string: Optional[str] = Field(on_disk=True)


class FriendTo(Relationship, type="FRIEND_TO"):
    huge_string: Optional[str] = Field(on_disk=True)


@pytest.fixture
def clear_db():
    memgraph = Memgraph()
Ejemplo n.º 26
0
def clear_db():
    db = Memgraph()
    db.drop_database()