Search in sources :

Example 6 with RowOperation

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

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 7 with RowOperation

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

the class ReadMe method readme.

public void readme(String url, String user, String password) {
    // get the AoJ DataSourceFactory
    DataSourceFactory factory = DataSourceFactory.newFactory("com.oracle.adbaoverjdbc.DataSourceFactory");
    // get a DataSource and a Session
    try (DataSource ds = factory.builder().url(url).username(user).password(password).build();
        Session conn = ds.getSession(t -> System.out.println("ERROR: " + t.getMessage()))) {
        // get a TransactionCompletion
        TransactionCompletion trans = conn.transactionCompletion();
        // select the EMPNO of CLARK
        CompletionStage<Integer> idF = conn.<Integer>rowOperation("select empno, ename from emp where ename = ? for update").set("1", "CLARK", AdbaType.VARCHAR).collect(Collector.of(() -> new int[1], (a, r) -> {
            a[0] = r.at("empno").get(Integer.class);
        }, (l, r) -> null, a -> a[0])).submit().getCompletionStage();
        // update CLARK to work in department 50
        conn.<Long>rowCountOperation("update emp set deptno = ? where empno = ?").set("1", 50, AdbaType.INTEGER).set("2", idF, AdbaType.INTEGER).apply(c -> {
            if (c.getCount() != 1L) {
                trans.setRollbackOnly();
                throw new SqlException("updated wrong number of rows", null, null, -1, null, -1);
            }
            return c.getCount();
        }).onError(t -> t.printStackTrace()).submit();
        // resume normal execution if there were any errors
        conn.catchErrors();
        // commit (or rollback) the transaction
        conn.commitMaybeRollback(trans);
    }
    // wait for the async tasks to complete before exiting
    ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.MINUTES);
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) SqlException(jdk.incubator.sql2.SqlException) DataSource(jdk.incubator.sql2.DataSource) CompletionStage(java.util.concurrent.CompletionStage) DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) ForkJoinPool(java.util.concurrent.ForkJoinPool) AdbaType(jdk.incubator.sql2.AdbaType) Collector(java.util.stream.Collector) Session(jdk.incubator.sql2.Session) TransactionCompletion(jdk.incubator.sql2.TransactionCompletion) DataSourceFactory(jdk.incubator.sql2.DataSourceFactory) SqlException(jdk.incubator.sql2.SqlException) TransactionCompletion(jdk.incubator.sql2.TransactionCompletion) DataSource(jdk.incubator.sql2.DataSource) Session(jdk.incubator.sql2.Session)

Example 8 with RowOperation

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

the class CountOperation method executeQuery.

/**
 * Execute the SQL query, process the returned count, and return the result of
 * processing the returned count.
 *
 * @param ignore not used
 * @return the result of processing the count
 */
private T executeQuery(Object ignore) {
    checkCanceled();
    try {
        if (autoKeyColNames != null)
            jdbcStatement = session.prepareStatement(sqlString, autoKeyColNames);
        else
            jdbcStatement = session.prepareStatement(sqlString);
        setParameters.forEach((String k, ParameterValue v) -> {
            v.set(jdbcStatement, k);
        });
        group.logger.log(Level.FINE, () -> "executeLargeUpdate(\"" + sqlString + "\")");
        long c = jdbcStatement.executeLargeUpdate();
        if (autoKeyColNames != null) {
            // Get the DML Returning resultset
            ResultSet rs = jdbcStatement.getGeneratedKeys();
            // Set the resultset and complete the future, so RowOperation process the result
            rowOperation.setResultSet(rs);
        }
        return countProcessor.apply(com.oracle.adbaoverjdbc.Result.newRowCount(c));
    } catch (SQLException ex) {
        throw new SqlException(ex.getMessage(), ex, ex.getSQLState(), ex.getErrorCode(), sqlString, -1);
    }
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) SqlException(jdk.incubator.sql2.SqlException)

Example 9 with RowOperation

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

the class MultiOperationTest method multiRowOperation.

/**
 * Execute a query returning a single result.
 */
@Test
public void multiRowOperation() {
    fail("TODO: Fix this test");
    DataSourceFactory factory = DataSourceFactory.newFactory(FACTORY_NAME);
    try (DataSource ds = factory.builder().url(URL).username(USER).password(PASSWORD).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());
        });
        RowOperation rowOp = multiOp.<Integer>rowOperation();
        multiOp.submit();
        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().get(TestConfig.getTimeout().toMillis(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        fail(e.getMessage());
        e.printStackTrace();
    }
}
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) MultiOperation(jdk.incubator.sql2.MultiOperation) RowOperation(jdk.incubator.sql2.RowOperation) SqlException(jdk.incubator.sql2.SqlException) DataSource(jdk.incubator.sql2.DataSource) Session(jdk.incubator.sql2.Session) Result(jdk.incubator.sql2.Result) Test(org.junit.Test)

Example 10 with RowOperation

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

the class RowOperationTest method testColumnIteration.

/**
 * Verify {@link com.oracle.adbaoverjdbc.Result.RowColumn}'s implementation
 * of Iterable<Column>.
 */
@Test
public void testColumnIteration() throws Exception {
    try (DataSource ds = getDataSource();
        Session se = ds.getSession()) {
        AtomicInteger rowCount = new AtomicInteger();
        ArrayList<String> result = se.<ArrayList<String>>rowOperation("SELECT * FROM " + TEST_TABLE).collect(ArrayList<String>::new, (ls, rc) -> {
            int rowIndex = rowCount.getAndIncrement();
            assertEquals(rowIndex, rc.rowNumber());
            assertEquals(TEST_COLUMNS.length - 1, rc.numberOfValuesRemaining());
            int colIndex = 0;
            for (Column co : rc) {
                colIndex++;
                validateColumn(rowIndex, co, colIndex, 0, TEST_COLUMNS.length);
                validateColumn(rowIndex, co.clone(), colIndex, 0, TEST_COLUMNS.length);
                ls.add(co.get(String.class));
            }
            assertEquals(TEST_COLUMNS.length, colIndex);
        }).timeout(getTimeout()).submit().getCompletionStage().toCompletableFuture().get();
        assertEquals(TEST_DATA[0].length, rowCount.get());
        for (int i = 0; i < TEST_DATA.length; i++) {
            for (int j = 0; j < TEST_DATA[0].length; j++) {
                assertEquals(TEST_DATA[j][i], result.get((i * TEST_DATA.length) + j));
            }
        }
    }
}
Also used : AfterClass(org.junit.AfterClass) BeforeClass(org.junit.BeforeClass) Column(jdk.incubator.sql2.Result.Column) AdbaType(jdk.incubator.sql2.AdbaType) Test(org.junit.Test) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) DataSource(jdk.incubator.sql2.DataSource) TestConfig(com.oracle.adbaoverjdbc.test.TestConfig) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ForkJoinPool(java.util.concurrent.ForkJoinPool) Collector(java.util.stream.Collector) Assert(org.junit.Assert) NoSuchElementException(java.util.NoSuchElementException) Session(jdk.incubator.sql2.Session) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Column(jdk.incubator.sql2.Result.Column) ArrayList(java.util.ArrayList) 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