Search in sources :

Example 6 with CompositeAutoCloseable

use of com.cadenzauk.core.lang.CompositeAutoCloseable in project siesta by cadenzauk.

the class JdbcSqlExecutorTest method streamWhenExecuteThrows.

@Test
void streamWhenExecuteThrows() throws SQLException {
    CompositeAutoCloseable closeable = new CompositeAutoCloseable();
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(preparedStatement.executeQuery()).thenThrow(new SQLException("No permission"));
    JdbcSqlExecutor sut = JdbcSqlExecutor.of(dataSource);
    String sql = "select name from foo where bar = 'fred'";
    calling(() -> {
        try (Stream<String> stream = sut.stream(connection, sql, toArray(), rowMapper, closeable)) {
            return stream.collect(Collectors.toList());
        }
    }).shouldThrow(RuntimeException.class).withCause(SQLException.class).withMessage(is("No permission"));
    verify(connection).prepareStatement(sql);
    verify(preparedStatement).executeQuery();
    verify(preparedStatement).setFetchSize(0);
    verify(preparedStatement).close();
    verifyNoMoreInteractions(connection, preparedStatement, resultSet, rowMapper);
}
Also used : CompositeAutoCloseable(com.cadenzauk.core.lang.CompositeAutoCloseable) SQLException(java.sql.SQLException) Stream(java.util.stream.Stream) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test) MockitoTest(com.cadenzauk.core.MockitoTest)

Example 7 with CompositeAutoCloseable

use of com.cadenzauk.core.lang.CompositeAutoCloseable in project siesta by cadenzauk.

the class ExceptionIntegrationTest method lockTimeoutOnInsert.

@Test
void lockTimeoutOnInsert() {
    assumeTrue(dialect.supportsLockTimeout(), "Database does not support lock timeouts.");
    Database database = TestDatabase.testDatabase(dataSource);
    SalesAreaRow salesArea = SalesAreaRow.newBuilder().salesAreaId(newId()).salesAreaName("NZ").build();
    try (CompositeAutoCloseable closer = new CompositeAutoCloseable()) {
        Transaction transaction1 = closer.add(database.beginTransaction());
        database.insert(transaction1, salesArea);
        Transaction transaction2 = closer.add(database.beginTransaction());
        closer.add(database.withLockTimeout(transaction2, 0, TimeUnit.MILLISECONDS));
        calling(() -> database.insert(transaction2, salesArea)).shouldThrow(RuntimeSqlException.class).with(subclass(LockingException.class)).withMessage(startsWith("Locking failure while executing 'insert into"));
        transaction2.rollback();
    }
}
Also used : CompositeAutoCloseable(com.cadenzauk.core.lang.CompositeAutoCloseable) TestDatabase(com.cadenzauk.siesta.model.TestDatabase) IncorrectSalesAreaRow(com.cadenzauk.siesta.model.IncorrectSalesAreaRow) SalesAreaRow(com.cadenzauk.siesta.model.SalesAreaRow) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 8 with CompositeAutoCloseable

use of com.cadenzauk.core.lang.CompositeAutoCloseable in project siesta by cadenzauk.

the class LockingIntegrationTest method performUpdate.

private boolean performUpdate(boolean setLockTimeout, Database database, long id, Synchronization synchronization) {
    try (CompositeAutoCloseable closeable = new CompositeAutoCloseable()) {
        synchronization.waitToSelect();
        Transaction transaction = closeable.add(database.beginTransaction());
        Optional<Integer> currentRevision = database.from(LockTestRow.class).select(LockTestRow::revision).where(LockTestRow::id).isEqualTo(id).optional(transaction);
        LOG.info("Current revision = {}", currentRevision);
        Optional<Integer> uncommittedRevision = database.from(LockTestRow.class).select(LockTestRow::revision).where(LockTestRow::id).isEqualTo(id).withIsolation(IsolationLevel.UNCOMMITTED_READ).optional(transaction);
        LOG.info("Uncommitted revision = {}", uncommittedRevision);
        if (uncommittedRevision.orElse(0) > currentRevision.orElse(0)) {
            LOG.info("Updated by another transaction - could bail at this point", currentRevision, uncommittedRevision);
        }
        synchronization.waitToUpdate();
        if (setLockTimeout) {
            closeable.add(database.withLockTimeout(transaction, 0, TimeUnit.SECONDS));
        }
        int updateCount = currentRevision.map(curr -> database.update(LockTestRow.class).set(LockTestRow::updatedBy).to(Thread.currentThread().getName()).set(LockTestRow::revision).to(curr + 1).where(LockTestRow::id).isEqualTo(id).and(LockTestRow::revision).isEqualTo(curr).execute(transaction)).orElseGet(() -> database.insert(transaction, new LockTestRow(id, 1, Thread.currentThread().getName())));
        LOG.info("Update count = {}", updateCount);
        if (updateCount == 0) {
            synchronization.finished();
            return false;
        }
        synchronization.waitToCommit();
        transaction.commit();
        LOG.info("Committed");
        synchronization.finished();
        return true;
    } catch (RuntimeSqlException e) {
        LOG.error("Update failed", e);
        synchronization.updateFailed();
        return false;
    }
}
Also used : Logger(org.slf4j.Logger) LockTestRow(com.cadenzauk.siesta.model.LockTestRow) TestDatabase(com.cadenzauk.siesta.model.TestDatabase) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) CompositeAutoCloseable(com.cadenzauk.core.lang.CompositeAutoCloseable) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) RuntimeSqlException(com.cadenzauk.core.sql.RuntimeSqlException) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) RuntimeSqlException(com.cadenzauk.core.sql.RuntimeSqlException) CompositeAutoCloseable(com.cadenzauk.core.lang.CompositeAutoCloseable) LockTestRow(com.cadenzauk.siesta.model.LockTestRow)

Example 9 with CompositeAutoCloseable

use of com.cadenzauk.core.lang.CompositeAutoCloseable in project siesta by cadenzauk.

the class JdbcSqlExecutorTest method streamWhenNextThrows.

@Test
void streamWhenNextThrows() throws SQLException {
    CompositeAutoCloseable closeable = new CompositeAutoCloseable();
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.next()).thenReturn(true).thenThrow(new SQLException("Connection lost"));
    when(rowMapper.mapRow(resultSet)).thenReturn("Fred");
    JdbcSqlExecutor sut = JdbcSqlExecutor.of(dataSource);
    String sql = "select name from foo where bar = ?";
    calling(() -> {
        try (Stream<String> stream = sut.stream(connection, sql, toArray("Bob", "Burt"), rowMapper, closeable)) {
            return stream.collect(Collectors.toList());
        }
    }).shouldThrow(RuntimeSqlException.class).withCause(SQLException.class).withMessage(is("Connection lost"));
    verify(connection).prepareStatement(sql);
    verify(preparedStatement).executeQuery();
    verify(preparedStatement).setObject(1, "Bob");
    verify(preparedStatement).setObject(2, "Burt");
    verify(preparedStatement).setFetchSize(0);
    verify(preparedStatement).close();
    verify(resultSet, times(2)).next();
    verify(resultSet).close();
    verify(rowMapper).mapRow(resultSet);
    verifyNoMoreInteractions(connection, preparedStatement, resultSet, rowMapper);
}
Also used : CompositeAutoCloseable(com.cadenzauk.core.lang.CompositeAutoCloseable) SQLException(java.sql.SQLException) Stream(java.util.stream.Stream) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test) MockitoTest(com.cadenzauk.core.MockitoTest)

Example 10 with CompositeAutoCloseable

use of com.cadenzauk.core.lang.CompositeAutoCloseable in project siesta by cadenzauk.

the class JdbcSqlExecutorTest method streamWhenMapperThrows.

@Test
void streamWhenMapperThrows() throws SQLException {
    CompositeAutoCloseable closeable = new CompositeAutoCloseable();
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.next()).thenReturn(true);
    when(rowMapper.mapRow(resultSet)).thenReturn("Fred").thenThrow(new IllegalArgumentException("Exception while mapping"));
    JdbcSqlExecutor sut = JdbcSqlExecutor.of(dataSource);
    String sql = "select name from foo where bar = ?";
    calling(() -> {
        try (Stream<String> stream = sut.stream(connection, sql, toArray("Bob", "Burt"), rowMapper, closeable)) {
            return stream.collect(Collectors.toList());
        }
    }).shouldThrow(IllegalArgumentException.class).withMessage(is("Exception while mapping"));
    verify(connection).prepareStatement(sql);
    verify(preparedStatement).executeQuery();
    verify(preparedStatement).setObject(1, "Bob");
    verify(preparedStatement).setObject(2, "Burt");
    verify(preparedStatement).setFetchSize(0);
    verify(preparedStatement).close();
    verify(resultSet, times(2)).next();
    verify(resultSet).close();
    verify(rowMapper, times(2)).mapRow(resultSet);
    verifyNoMoreInteractions(connection, preparedStatement, resultSet, rowMapper);
}
Also used : CompositeAutoCloseable(com.cadenzauk.core.lang.CompositeAutoCloseable) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test) MockitoTest(com.cadenzauk.core.MockitoTest)

Aggregations

CompositeAutoCloseable (com.cadenzauk.core.lang.CompositeAutoCloseable)12 Test (org.junit.jupiter.api.Test)11 MockitoTest (com.cadenzauk.core.MockitoTest)6 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 TestDatabase (com.cadenzauk.siesta.model.TestDatabase)4 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)4 IncorrectSalesAreaRow (com.cadenzauk.siesta.model.IncorrectSalesAreaRow)3 SalesAreaRow (com.cadenzauk.siesta.model.SalesAreaRow)3 SQLException (java.sql.SQLException)2 Stream (java.util.stream.Stream)2 RuntimeSqlException (com.cadenzauk.core.sql.RuntimeSqlException)1 Tuple2 (com.cadenzauk.core.tuple.Tuple2)1 Database (com.cadenzauk.siesta.Database)1 IntegrationTest (com.cadenzauk.siesta.IntegrationTest)1 LockTestRow (com.cadenzauk.siesta.model.LockTestRow)1 Connection (java.sql.Connection)1 Optional (java.util.Optional)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 TimeUnit (java.util.concurrent.TimeUnit)1 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)1