Search in sources :

Example 1 with RowOperation

use of jdk.incubator.sql2.RowOperation in project oracle-db-examples by oracle.

the class MultiOperationTest method multiRowOperationWithRowHandler.

/**
 * Execute a query returning a single result.
 */
@Test
public void multiRowOperationWithRowHandler() {
    fail("TODO: Fix this test");
    Properties props = new Properties();
    DataSourceFactory factory = DataSourceFactory.newFactory(FACTORY_NAME);
    try (DataSource ds = factory.builder().url(URL).username(USER).password(PASSWORD).sessionProperty(JDBC_CONNECTION_PROPERTIES, props).build();
        Session session = ds.getSession(t -> fail("ERROR: " + t.getMessage()))) {
        assertNotNull(session);
        MultiOperation multiOp = session.multiOperation("select * from forum_user").onError(t -> {
            fail(t.toString());
        });
        BiConsumer<Integer, RowOperation<Integer>> rowHandler = (resNum, rowOp) -> {
            assertTrue(resNum > 0);
            rowOp.collect(Collector.<Result.RowColumn, int[], Integer>of(() -> new int[1], (int[] a, Result.RowColumn r) -> {
                a[0] = a[0] + r.at("sal").get(Integer.class);
            }, (l, r) -> l, a -> (Integer) a[0])).onError(t -> {
                fail(t.toString());
            }).submit().getCompletionStage().thenAccept(n -> {
                assertTrue((long) n > 0);
            }).toCompletableFuture();
        };
        multiOp.onRows(rowHandler).submit().getCompletionStage().toCompletableFuture().get(TestConfig.getTimeout().toMillis(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Also used : DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) BeforeClass(org.junit.BeforeClass) RowOperation(jdk.incubator.sql2.RowOperation) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) SqlException(jdk.incubator.sql2.SqlException) OperationGroup(jdk.incubator.sql2.OperationGroup) Flow(java.util.concurrent.Flow) BiConsumer(java.util.function.BiConsumer) Collector(java.util.stream.Collector) Session(jdk.incubator.sql2.Session) AfterClass(org.junit.AfterClass) Properties(java.util.Properties) JDBC_CONNECTION_PROPERTIES(com.oracle.adbaoverjdbc.JdbcConnectionProperties.JDBC_CONNECTION_PROPERTIES) AdbaType(jdk.incubator.sql2.AdbaType) Test(org.junit.Test) RowPublisherOperation(jdk.incubator.sql2.RowPublisherOperation) TransactionCompletion(jdk.incubator.sql2.TransactionCompletion) Date(java.sql.Date) TimeUnit(java.util.concurrent.TimeUnit) DataSource(jdk.incubator.sql2.DataSource) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Result(jdk.incubator.sql2.Result) RowCountOperation(jdk.incubator.sql2.RowCountOperation) ForkJoinPool(java.util.concurrent.ForkJoinPool) MultiOperation(jdk.incubator.sql2.MultiOperation) Assert(org.junit.Assert) Submission(jdk.incubator.sql2.Submission) DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) Properties(java.util.Properties) RowOperation(jdk.incubator.sql2.RowOperation) SqlException(jdk.incubator.sql2.SqlException) DataSource(jdk.incubator.sql2.DataSource) Result(jdk.incubator.sql2.Result) MultiOperation(jdk.incubator.sql2.MultiOperation) Session(jdk.incubator.sql2.Session) Test(org.junit.Test)

Example 2 with RowOperation

use of jdk.incubator.sql2.RowOperation in project oracle-db-examples by oracle.

the class SessionTest method testAbort.

/**
 * Verifies the following behavior:
 * <br>
 * (1) If lifecycle is Session.Lifecycle.NEW, Session.Lifecycle.OPEN,
 * Session.Lifecycle.INACTIVE or Session.Lifecycle.CLOSING ->
 * Session.Lifecycle.ABORTING.[Spec: {@link Session#abort()}]
 * <br>
 * (2) If lifecycle is Session.Lifecycle.ABORTING or Session.Lifecycle.
 * CLOSED this is a no-op. [Spec: {@link Session#abort()}]
 *
 * @throws java.lang.Exception
 */
@Test
public void testAbort() throws Exception {
    DataSource ds = DataSourceFactory.newFactory(getDataSourceFactoryName()).builder().url(getUrl()).username(getUser()).password(getPassword()).sessionProperty(AdbaSessionProperty.TRANSACTION_ISOLATION, TransactionIsolation.SERIALIZABLE).build();
    Session se1 = ds.builder().build();
    TestLifecycleListener se1LifecycleListener = new TestLifecycleListener();
    se1.registerLifecycleListener(se1LifecycleListener);
    Submission<?> se1Submission = se1.submit();
    se1.attachOperation().submit();
    // Create a record which two sessions will try to update.
    se1.rowCountOperation("INSERT INTO " + ABORT_TABLE_1 + " VALUES ('a')").submit();
    se1.commitMaybeRollback(se1.transactionCompletion());
    // Session 1 acquires a lock on the record.
    se1.rowCountOperation("UPDATE " + ABORT_TABLE_1 + " SET c='b' WHERE c='a'").submit();
    se1.<List<String>>rowOperation("SELECT * FROM " + ABORT_TABLE_1).collect(Collectors.mapping(row -> row.at(1).get(String.class), Collectors.toList())).timeout(getTimeout()).submit().getCompletionStage().toCompletableFuture().get();
    // Session 2 gets blocked acquiring a lock on the same record.
    Session se2 = ds.builder().build();
    Submission<?> se2Submission = se2.submit();
    se2.attachOperation().submit();
    Submission<Long> blockedSubmission = se2.<Long>rowCountOperation("UPDATE " + ABORT_TABLE_1 + " SET c='z' WHERE c='a'").apply(count -> count.getCount()).timeout(getTimeout()).submit();
    // Session 1 is aborted so that session 2 can proceed.
    se1.abort();
    // (2)
    se1.abort();
    // (1)
    LifecycleEvent[] expectedEvents = { new LifecycleEvent(se1, Lifecycle.NEW, Lifecycle.ATTACHED), new LifecycleEvent(se1, Lifecycle.ATTACHED, Lifecycle.ABORTING), new LifecycleEvent(se1, Lifecycle.ABORTING, Lifecycle.CLOSED) };
    for (LifecycleEvent expected : expectedEvents) {
        LifecycleEvent actual = se1LifecycleListener.record.poll(getTimeout().toMillis(), TimeUnit.MILLISECONDS);
        if (actual == null)
            fail("Timeout waiting for lifecycle event: " + expected);
        assertEquals(expected, actual);
    }
    long unblockedResult = blockedSubmission.getCompletionStage().toCompletableFuture().get();
    assertEquals(1L, unblockedResult);
    se2.rollback();
    se2.close();
    se1Submission.getCompletionStage().toCompletableFuture().handle((r, e) -> {
        assertNotNull(e);
        return null;
    }).get(getTimeout().toMillis(), TimeUnit.MILLISECONDS);
    se2Submission.getCompletionStage().toCompletableFuture().handle((r, e) -> {
        assertNull(e);
        return null;
    }).get(getTimeout().toMillis(), TimeUnit.MILLISECONDS);
}
Also used : DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) BeforeClass(org.junit.BeforeClass) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) TestConfig(com.oracle.adbaoverjdbc.test.TestConfig) OperationGroup(jdk.incubator.sql2.OperationGroup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AdbaSessionProperty(jdk.incubator.sql2.AdbaSessionProperty) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) TransactionIsolation(jdk.incubator.sql2.AdbaSessionProperty.TransactionIsolation) Assert.fail(org.junit.Assert.fail) Session(jdk.incubator.sql2.Session) AfterClass(org.junit.AfterClass) Validation(jdk.incubator.sql2.Session.Validation) Assert.assertNotNull(org.junit.Assert.assertNotNull) Lifecycle(jdk.incubator.sql2.Session.Lifecycle) Assert.assertTrue(org.junit.Assert.assertTrue) BlockingQueue(java.util.concurrent.BlockingQueue) Test(org.junit.Test) LifecycleEvent(com.oracle.adbaoverjdbc.test.SessionTest.TestLifecycleListener.LifecycleEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) TransactionCompletion(jdk.incubator.sql2.TransactionCompletion) TransactionOutcome(jdk.incubator.sql2.TransactionOutcome) Operation(jdk.incubator.sql2.Operation) SessionLifecycleListener(jdk.incubator.sql2.Session.SessionLifecycleListener) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) DataSource(jdk.incubator.sql2.DataSource) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Builder(jdk.incubator.sql2.Session.Builder) Assert.assertFalse(org.junit.Assert.assertFalse) Submission(jdk.incubator.sql2.Submission) Assert.assertEquals(org.junit.Assert.assertEquals) LifecycleEvent(com.oracle.adbaoverjdbc.test.SessionTest.TestLifecycleListener.LifecycleEvent) List(java.util.List) DataSource(jdk.incubator.sql2.DataSource) Session(jdk.incubator.sql2.Session) Test(org.junit.Test)

Example 3 with RowOperation

use of jdk.incubator.sql2.RowOperation in project oracle-db-examples by oracle.

the class MultiOperation method processChildRowOperation.

/**
 * Process next resultset. Get the child operation from the queue (if any submitted) and pass
 * the resultset to it for the processing. If no child operation in the queue then process resultset
 * with the help of user supplied row handler or the default one. Wait for the child operation or
 * the handler to process all rows of a resultset.
 *
 * @return the completion stage of the child operation.
 * @throws SQLException
 */
private CompletionStage<T> processChildRowOperation() throws SQLException {
    // Get the result set
    ResultSet resultSet = jdbcStatement.getResultSet();
    // Remove child operation, if any exist
    Operation operationFromQueue = resultOperations.poll();
    // Keep as effective final, because it uses in lambda expression
    Operation operation;
    boolean onRowsHandler = (operationFromQueue == null);
    if (onRowsHandler) {
        // Handle using onRows handler.
        operation = new MultiRowOperation<T>(session, group, true);
    } else
        operation = operationFromQueue;
    if (!(operation instanceof ChildRowOperation)) {
        // Throw invalid state
        throw new IllegalStateException("TODO");
    }
    // Trigger child operation to process the resultset
    resultStage = ((ChildRowOperation) operation).setResultSet(resultSet, resultStage);
    if (onRowsHandler)
        resultStage = resultStage.thenRun(() -> rowsHandler.accept(resultNum, (RowOperation<T>) operation));
    // Then again move to moreResult stage to process next resultset.
    return resultStage.thenComposeAsync(((ChildRowOperation) operation)::resultProcessed, getExecutor()).thenComposeAsync(this::checkForMoreResults, getExecutor());
}
Also used : ResultSet(java.sql.ResultSet) RowOperation(jdk.incubator.sql2.RowOperation) RowPublisherOperation(jdk.incubator.sql2.RowPublisherOperation) Operation(jdk.incubator.sql2.Operation) RowCountOperation(jdk.incubator.sql2.RowCountOperation) RowOperation(jdk.incubator.sql2.RowOperation)

Example 4 with RowOperation

use of jdk.incubator.sql2.RowOperation in project oracle-db-examples by oracle-samples.

the class MultiOperationTest method multiRowOperationWithRowHandler.

/**
 * Execute a query returning a single result.
 */
@Test
public void multiRowOperationWithRowHandler() {
    fail("TODO: Fix this test");
    Properties props = new Properties();
    DataSourceFactory factory = DataSourceFactory.newFactory(FACTORY_NAME);
    try (DataSource ds = factory.builder().url(URL).username(USER).password(PASSWORD).sessionProperty(JDBC_CONNECTION_PROPERTIES, props).build();
        Session session = ds.getSession(t -> fail("ERROR: " + t.getMessage()))) {
        assertNotNull(session);
        MultiOperation multiOp = session.multiOperation("select * from forum_user").onError(t -> {
            fail(t.toString());
        });
        BiConsumer<Integer, RowOperation<Integer>> rowHandler = (resNum, rowOp) -> {
            assertTrue(resNum > 0);
            rowOp.collect(Collector.<Result.RowColumn, int[], Integer>of(() -> new int[1], (int[] a, Result.RowColumn r) -> {
                a[0] = a[0] + r.at("sal").get(Integer.class);
            }, (l, r) -> l, a -> (Integer) a[0])).onError(t -> {
                fail(t.toString());
            }).submit().getCompletionStage().thenAccept(n -> {
                assertTrue((long) n > 0);
            }).toCompletableFuture();
        };
        multiOp.onRows(rowHandler).submit().getCompletionStage().toCompletableFuture().get(TestConfig.getTimeout().toMillis(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Also used : DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) BeforeClass(org.junit.BeforeClass) RowOperation(jdk.incubator.sql2.RowOperation) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) SqlException(jdk.incubator.sql2.SqlException) OperationGroup(jdk.incubator.sql2.OperationGroup) Flow(java.util.concurrent.Flow) BiConsumer(java.util.function.BiConsumer) Collector(java.util.stream.Collector) Session(jdk.incubator.sql2.Session) AfterClass(org.junit.AfterClass) Properties(java.util.Properties) JDBC_CONNECTION_PROPERTIES(com.oracle.adbaoverjdbc.JdbcConnectionProperties.JDBC_CONNECTION_PROPERTIES) AdbaType(jdk.incubator.sql2.AdbaType) Test(org.junit.Test) RowPublisherOperation(jdk.incubator.sql2.RowPublisherOperation) TransactionCompletion(jdk.incubator.sql2.TransactionCompletion) Date(java.sql.Date) TimeUnit(java.util.concurrent.TimeUnit) DataSource(jdk.incubator.sql2.DataSource) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Result(jdk.incubator.sql2.Result) RowCountOperation(jdk.incubator.sql2.RowCountOperation) ForkJoinPool(java.util.concurrent.ForkJoinPool) MultiOperation(jdk.incubator.sql2.MultiOperation) Assert(org.junit.Assert) Submission(jdk.incubator.sql2.Submission) DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) Properties(java.util.Properties) RowOperation(jdk.incubator.sql2.RowOperation) SqlException(jdk.incubator.sql2.SqlException) DataSource(jdk.incubator.sql2.DataSource) Result(jdk.incubator.sql2.Result) MultiOperation(jdk.incubator.sql2.MultiOperation) Session(jdk.incubator.sql2.Session) Test(org.junit.Test)

Example 5 with RowOperation

use of jdk.incubator.sql2.RowOperation in project oracle-db-examples by oracle-samples.

the class SessionOperationGroupTest method catchOperationTest.

/**
 * Verify {@link Session#catchErrors()} and {@link Session#catchOperation()}
 * creates and/or submits a catch operation.
 * @throws Exception
 */
@Test
public void catchOperationTest() throws Exception {
    try (DataSource ds = TestConfig.getDataSource();
        Session se = ds.getSession()) {
        AtomicBoolean gotErr = new AtomicBoolean();
        se.operation("SELECT COUNT(*) FROM gg" + TABLE).timeout(getTimeout()).onError(err -> gotErr.set(true)).submit();
        CompletableFuture<Boolean> gotSkipped = se.operation("SELECT COUNT(*) FROM " + TABLE).timeout(getTimeout()).submit().getCompletionStage().toCompletableFuture().handle((nil, err) -> {
            return err instanceof CompletionException && err.getCause() instanceof SqlSkippedException;
        });
        List<Integer> count = se.catchErrors().<List<Integer>>rowOperation("SELECT COUNT(*) FROM " + TABLE).collect(Collectors.mapping(row -> row.at(1).get(Integer.class), Collectors.toList())).timeout(getTimeout()).submit().getCompletionStage().toCompletableFuture().get();
        assertTrue(gotErr.get());
        assertTrue(gotSkipped.get());
        assertNotNull(count);
        assertEquals(1, count.size());
        assertEquals(0, count.get(0).intValue());
        // Repeat using catchOperation() rather than catchErrors()
        AtomicBoolean gotErr2 = new AtomicBoolean();
        se.operation("SELECT COUNT(*) FROM gg" + TABLE).timeout(getTimeout()).onError(err -> gotErr2.set(true)).submit();
        CompletableFuture<Boolean> gotSkipped2 = se.operation("SELECT COUNT(*) FROM " + TABLE).timeout(getTimeout()).submit().getCompletionStage().toCompletableFuture().handle((nil, err) -> {
            return err instanceof CompletionException && err.getCause() instanceof SqlSkippedException;
        });
        se.catchOperation().submit();
        List<Integer> count2 = se.<List<Integer>>rowOperation("SELECT COUNT(*) FROM " + TABLE).collect(Collectors.mapping(row -> row.at(1).get(Integer.class), Collectors.toList())).timeout(getTimeout()).submit().getCompletionStage().toCompletableFuture().get();
        assertTrue(gotErr2.get());
        assertTrue(gotSkipped2.get());
        assertNotNull(count2);
        assertEquals(1, count2.size());
        assertEquals(0, count2.get(0).intValue());
    }
}
Also used : BeforeClass(org.junit.BeforeClass) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) TestConfig(com.oracle.adbaoverjdbc.test.TestConfig) BiConsumer(java.util.function.BiConsumer) Collector(java.util.stream.Collector) Session(jdk.incubator.sql2.Session) SqlSkippedException(jdk.incubator.sql2.SqlSkippedException) AfterClass(org.junit.AfterClass) Assert.assertNotNull(org.junit.Assert.assertNotNull) AdbaType(jdk.incubator.sql2.AdbaType) Assert.assertTrue(org.junit.Assert.assertTrue) Set(java.util.Set) Test(org.junit.Test) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) TransactionOutcome(jdk.incubator.sql2.TransactionOutcome) BinaryOperator(java.util.function.BinaryOperator) ArrayRowCountOperation(jdk.incubator.sql2.ArrayRowCountOperation) TimeUnit(java.util.concurrent.TimeUnit) DataSource(jdk.incubator.sql2.DataSource) List(java.util.List) Result(jdk.incubator.sql2.Result) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) Collections(java.util.Collections) Submission(jdk.incubator.sql2.Submission) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SqlSkippedException(jdk.incubator.sql2.SqlSkippedException) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) List(java.util.List) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DataSource(jdk.incubator.sql2.DataSource) Session(jdk.incubator.sql2.Session) Test(org.junit.Test)

Aggregations

TimeUnit (java.util.concurrent.TimeUnit)14 DataSource (jdk.incubator.sql2.DataSource)14 Session (jdk.incubator.sql2.Session)14 AfterClass (org.junit.AfterClass)12 BeforeClass (org.junit.BeforeClass)12 Test (org.junit.Test)12 List (java.util.List)10 CompletableFuture (java.util.concurrent.CompletableFuture)10 Collector (java.util.stream.Collector)10 AdbaType (jdk.incubator.sql2.AdbaType)10 DataSourceFactory (jdk.incubator.sql2.DataSourceFactory)10 Submission (jdk.incubator.sql2.Submission)10 TransactionCompletion (jdk.incubator.sql2.TransactionCompletion)10 TestConfig (com.oracle.adbaoverjdbc.test.TestConfig)8 ArrayList (java.util.ArrayList)8 ForkJoinPool (java.util.concurrent.ForkJoinPool)8 OperationGroup (jdk.incubator.sql2.OperationGroup)8 SqlException (jdk.incubator.sql2.SqlException)8 CompletionStage (java.util.concurrent.CompletionStage)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6