Search in sources :

Example 6 with Result

use of org.neo4j.driver.Result in project neo4j by neo4j.

the class BoltStateHandlerTest method triesAgainOnSessionExpired.

@Test
public void triesAgainOnSessionExpired() throws Exception {
    Session sessionMock = mock(Session.class);
    Result resultMock = mock(Result.class);
    Record recordMock = mock(Record.class);
    Value valueMock = mock(Value.class);
    Driver driverMock = stubResultSummaryInAnOpenSession(resultMock, sessionMock, "neo4j-version");
    when(resultMock.list()).thenReturn(singletonList(recordMock));
    when(valueMock.toString()).thenReturn("999");
    when(recordMock.get(0)).thenReturn(valueMock);
    when(sessionMock.run(any(Query.class))).thenThrow(new SessionExpiredException("leaderswitch")).thenReturn(resultMock);
    OfflineBoltStateHandler boltStateHandler = new OfflineBoltStateHandler(driverMock);
    boltStateHandler.connect();
    BoltResult boltResult = boltStateHandler.runCypher("RETURN 999", new HashMap<>()).get();
    verify(driverMock, times(2)).session(any());
    verify(sessionMock, times(2)).run(any(Query.class));
    assertEquals("999", boltResult.getRecords().get(0).get(0).toString());
}
Also used : Query(org.neo4j.driver.Query) HashMap(java.util.HashMap) Value(org.neo4j.driver.Value) Driver(org.neo4j.driver.Driver) FakeDriver(org.neo4j.shell.test.bolt.FakeDriver) Record(org.neo4j.driver.Record) SessionExpiredException(org.neo4j.driver.exceptions.SessionExpiredException) Session(org.neo4j.driver.Session) FakeSession(org.neo4j.shell.test.bolt.FakeSession) Result(org.neo4j.driver.Result) Test(org.junit.Test)

Example 7 with Result

use of org.neo4j.driver.Result in project neo4j by neo4j.

the class BoltStateHandlerTest method shouldKeepOneBookmarkPerDatabase.

@SuppressWarnings("OptionalGetWithoutIsPresent")
@Test
public void shouldKeepOneBookmarkPerDatabase() throws CommandException {
    ConnectionConfig config = new ConnectionConfig("bolt", "", -1, "", "", Encryption.DEFAULT, "database1");
    Bookmark db1Bookmark = InternalBookmark.parse("db1");
    Bookmark db2Bookmark = InternalBookmark.parse("db2");
    // A couple of these mock calls are now redundant with what is called in stubResultSummaryInAnOpenSession
    Result resultMock = mock(Result.class);
    Session db1SessionMock = mock(Session.class);
    when(db1SessionMock.isOpen()).thenReturn(true);
    when(db1SessionMock.lastBookmark()).thenReturn(db1Bookmark);
    when(db1SessionMock.run("CALL db.ping()")).thenReturn(resultMock);
    Session db2SessionMock = mock(Session.class);
    when(db2SessionMock.isOpen()).thenReturn(true);
    when(db2SessionMock.lastBookmark()).thenReturn(db2Bookmark);
    when(db2SessionMock.run("CALL db.ping()")).thenReturn(resultMock);
    Driver driverMock = stubResultSummaryInAnOpenSession(resultMock, db1SessionMock, "Neo4j/9.4.1-ALPHA", "database1");
    when(driverMock.session(any())).thenAnswer(arg -> {
        SessionConfig sc = (SessionConfig) arg.getArguments()[0];
        switch(sc.database().get()) {
            case "database1":
                return db1SessionMock;
            case "database2":
                return db2SessionMock;
            default:
                return null;
        }
    });
    BoltStateHandler handler = new OfflineBoltStateHandler(driverMock);
    // When
    handler.connect(config);
    // Then no bookmark yet for db1
    verify(driverMock).session(SessionConfig.builder().withDefaultAccessMode(AccessMode.WRITE).withDatabase("database1").build());
    // When
    handler.setActiveDatabase("database2");
    // Then no bookmark yet for db2
    verify(driverMock).session(SessionConfig.builder().withDefaultAccessMode(AccessMode.WRITE).withDatabase("database2").build());
    // When
    handler.setActiveDatabase("database1");
    // Then use bookmark for db1
    verify(driverMock).session(SessionConfig.builder().withDefaultAccessMode(AccessMode.WRITE).withDatabase("database1").withBookmarks(db1Bookmark).build());
    // When
    handler.setActiveDatabase("database2");
    // Then use bookmark for db2
    verify(driverMock).session(SessionConfig.builder().withDefaultAccessMode(AccessMode.WRITE).withDatabase("database2").withBookmarks(db2Bookmark).build());
}
Also used : InternalBookmark(org.neo4j.driver.internal.InternalBookmark) Bookmark(org.neo4j.driver.Bookmark) Driver(org.neo4j.driver.Driver) FakeDriver(org.neo4j.shell.test.bolt.FakeDriver) SessionConfig(org.neo4j.driver.SessionConfig) ConnectionConfig(org.neo4j.shell.ConnectionConfig) Result(org.neo4j.driver.Result) Session(org.neo4j.driver.Session) FakeSession(org.neo4j.shell.test.bolt.FakeSession) Test(org.junit.Test)

Example 8 with Result

use of org.neo4j.driver.Result in project neo4j by neo4j.

the class ProcedureTest method callsSimplisticProcedure.

@Test
void callsSimplisticProcedure(Neo4j neo4j) {
    try (Driver driver = GraphDatabase.driver(neo4j.boltURI(), configuration());
        Session session = driver.session()) {
        Result result = session.run("CALL " + procedureNamespace + ".theAnswer()");
        assertThat(result.single().get("value").asLong()).isEqualTo(42L);
    }
}
Also used : Driver(org.neo4j.driver.Driver) Session(org.neo4j.driver.Session) Result(org.neo4j.driver.Result) Test(org.junit.jupiter.api.Test)

Example 9 with Result

use of org.neo4j.driver.Result in project beam by apache.

the class Neo4jIOIT method testLargeWriteUnwind.

@Test
public void testLargeWriteUnwind() throws Exception {
    final int startId = 5000;
    final int endId = 6000;
    // Create 1000 IDs
    List<Integer> idList = new ArrayList<>();
    for (int id = startId; id < endId; id++) {
        idList.add(id);
    }
    PCollection<Integer> idCollection = largeWriteUnwindPipeline.apply(Create.of(idList));
    // Every row is represented by a Map<String, Object> in the parameters map.
    // We accumulate the rows and 'unwind' those to Neo4j for performance reasons.
    // 
    SerializableFunction<Integer, Map<String, Object>> parametersFunction = id -> ImmutableMap.of("id", id, "name", "Casters", "firstName", "Matt");
    // 1000 rows with a batch size of 123 should trigger most scenarios we can think of
    // We've put a unique constraint on Something.id
    // 
    Neo4jIO.WriteUnwind<Integer> read = Neo4jIO.<Integer>writeUnwind().withDriverConfiguration(Neo4jTestUtil.getDriverConfiguration(containerHostname, containerPort)).withSessionConfig(SessionConfig.forDatabase(Neo4jTestUtil.NEO4J_DATABASE)).withBatchSize(123).withUnwindMapName("rows").withCypher("UNWIND $rows AS row CREATE(n:Something { id : row.id })").withParametersFunction(parametersFunction).withCypherLogging();
    idCollection.apply(read);
    // Now run this pipeline
    // 
    PipelineResult pipelineResult = largeWriteUnwindPipeline.run();
    Assert.assertEquals(PipelineResult.State.DONE, pipelineResult.getState());
    // 
    try (Driver driver = Neo4jTestUtil.getDriver(containerHostname, containerPort)) {
        try (Session session = Neo4jTestUtil.getSession(driver, true)) {
            List<Integer> values = session.readTransaction(tx -> {
                List<Integer> v = null;
                int nrRows = 0;
                Result result = tx.run("MATCH(n:Something) RETURN count(n), min(n.id), max(n.id)");
                while (result.hasNext()) {
                    Record record = result.next();
                    v = Arrays.asList(record.get(0).asInt(), record.get(1).asInt(), record.get(2).asInt(), ++nrRows);
                }
                return v;
            });
            Assert.assertNotNull(values);
            assertThat(values, contains(endId - startId, startId, endId - 1, 1));
        }
    }
}
Also used : Session(org.neo4j.driver.Session) Arrays(java.util.Arrays) SerializableCoder(org.apache.beam.sdk.coders.SerializableCoder) BeforeClass(org.junit.BeforeClass) IsIterableContainingInOrder.contains(org.hamcrest.collection.IsIterableContainingInOrder.contains) DockerImageName(org.testcontainers.utility.DockerImageName) IsIterableContainingInAnyOrder.containsInAnyOrder(org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder) PipelineResult(org.apache.beam.sdk.PipelineResult) RunWith(org.junit.runner.RunWith) SerializableFunction(org.apache.beam.sdk.transforms.SerializableFunction) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) ArrayList(java.util.ArrayList) Create(org.apache.beam.sdk.transforms.Create) Map(java.util.Map) TestPipeline(org.apache.beam.sdk.testing.TestPipeline) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Row(org.apache.beam.sdk.values.Row) DoFn(org.apache.beam.sdk.transforms.DoFn) AfterClass(org.junit.AfterClass) Driver(org.neo4j.driver.Driver) Neo4jContainer(org.testcontainers.containers.Neo4jContainer) PAssert(org.apache.beam.sdk.testing.PAssert) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) PCollection(org.apache.beam.sdk.values.PCollection) Schema(org.apache.beam.sdk.schemas.Schema) Result(org.neo4j.driver.Result) List(java.util.List) Rule(org.junit.Rule) SessionConfig(org.neo4j.driver.SessionConfig) ParDo(org.apache.beam.sdk.transforms.ParDo) Assert(org.junit.Assert) Collections(java.util.Collections) Record(org.neo4j.driver.Record) ArrayList(java.util.ArrayList) PipelineResult(org.apache.beam.sdk.PipelineResult) Driver(org.neo4j.driver.Driver) PipelineResult(org.apache.beam.sdk.PipelineResult) Result(org.neo4j.driver.Result) Record(org.neo4j.driver.Record) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) Map(java.util.Map) Session(org.neo4j.driver.Session) Test(org.junit.Test)

Example 10 with Result

use of org.neo4j.driver.Result in project beam by apache.

the class Neo4jIOIT method testWriteUnwind.

@Test
public void testWriteUnwind() throws Exception {
    PCollection<String> stringsCollections = writeUnwindPipeline.apply(Create.of(Arrays.asList("one", "two", "three")));
    // Every row is represented by a Map<String, Object> in the parameters map.
    // We accumulate the rows and 'unwind' those to Neo4j for performance reasons.
    // 
    SerializableFunction<String, Map<String, Object>> parametersMapper = name -> Collections.singletonMap("name", name);
    Neo4jIO.WriteUnwind<String> read = Neo4jIO.<String>writeUnwind().withDriverConfiguration(Neo4jTestUtil.getDriverConfiguration(containerHostname, containerPort)).withSessionConfig(SessionConfig.forDatabase(Neo4jTestUtil.NEO4J_DATABASE)).withBatchSize(5000).withUnwindMapName("rows").withCypher("UNWIND $rows AS row MERGE(n:Num { name : row.name })").withParametersFunction(parametersMapper).withCypherLogging();
    stringsCollections.apply(read);
    // Now run this pipeline
    // 
    PipelineResult pipelineResult = writeUnwindPipeline.run();
    Assert.assertEquals(PipelineResult.State.DONE, pipelineResult.getState());
    // 
    try (Driver driver = Neo4jTestUtil.getDriver(containerHostname, containerPort)) {
        try (Session session = Neo4jTestUtil.getSession(driver, true)) {
            List<String> names = session.readTransaction(tx -> {
                List<String> list = new ArrayList<>();
                Result result = tx.run("MATCH(n:Num) RETURN n.name");
                while (result.hasNext()) {
                    Record record = result.next();
                    list.add(record.get(0).asString());
                }
                return list;
            });
            assertThat(names, containsInAnyOrder("one", "two", "three"));
        }
    }
}
Also used : Session(org.neo4j.driver.Session) Arrays(java.util.Arrays) SerializableCoder(org.apache.beam.sdk.coders.SerializableCoder) BeforeClass(org.junit.BeforeClass) IsIterableContainingInOrder.contains(org.hamcrest.collection.IsIterableContainingInOrder.contains) DockerImageName(org.testcontainers.utility.DockerImageName) IsIterableContainingInAnyOrder.containsInAnyOrder(org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder) PipelineResult(org.apache.beam.sdk.PipelineResult) RunWith(org.junit.runner.RunWith) SerializableFunction(org.apache.beam.sdk.transforms.SerializableFunction) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) ArrayList(java.util.ArrayList) Create(org.apache.beam.sdk.transforms.Create) Map(java.util.Map) TestPipeline(org.apache.beam.sdk.testing.TestPipeline) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Row(org.apache.beam.sdk.values.Row) DoFn(org.apache.beam.sdk.transforms.DoFn) AfterClass(org.junit.AfterClass) Driver(org.neo4j.driver.Driver) Neo4jContainer(org.testcontainers.containers.Neo4jContainer) PAssert(org.apache.beam.sdk.testing.PAssert) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) PCollection(org.apache.beam.sdk.values.PCollection) Schema(org.apache.beam.sdk.schemas.Schema) Result(org.neo4j.driver.Result) List(java.util.List) Rule(org.junit.Rule) SessionConfig(org.neo4j.driver.SessionConfig) ParDo(org.apache.beam.sdk.transforms.ParDo) Assert(org.junit.Assert) Collections(java.util.Collections) Record(org.neo4j.driver.Record) ArrayList(java.util.ArrayList) PipelineResult(org.apache.beam.sdk.PipelineResult) Driver(org.neo4j.driver.Driver) PipelineResult(org.apache.beam.sdk.PipelineResult) Result(org.neo4j.driver.Result) Record(org.neo4j.driver.Record) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) Map(java.util.Map) Session(org.neo4j.driver.Session) Test(org.junit.Test)

Aggregations

Result (org.neo4j.driver.Result)29 Test (org.junit.Test)19 Session (org.neo4j.driver.Session)16 Driver (org.neo4j.driver.Driver)13 StringContains.containsString (org.hamcrest.core.StringContains.containsString)8 BoltResult (org.neo4j.shell.state.BoltResult)8 ListBoltResult (org.neo4j.shell.state.ListBoltResult)8 FakeDriver (org.neo4j.shell.test.bolt.FakeDriver)8 FakeSession (org.neo4j.shell.test.bolt.FakeSession)8 Record (org.neo4j.driver.Record)7 SessionConfig (org.neo4j.driver.SessionConfig)5 ClientException (org.neo4j.driver.exceptions.ClientException)5 SessionExpiredException (org.neo4j.driver.exceptions.SessionExpiredException)5 Query (org.neo4j.driver.Query)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Test (org.junit.jupiter.api.Test)3 Value (org.neo4j.driver.Value)3 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2