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());
}
}
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);
}
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());
}
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());
}
}
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());
}
}
Aggregations