Search in sources :

Example 6 with Connection

use of io.r2dbc.spi.Connection in project spring-framework by spring-projects.

the class SingleConnectionFactoryUnitTests method shouldNotSuppressClose.

@Test
void shouldNotSuppressClose() {
    SingleConnectionFactory factory = new SingleConnectionFactory("r2dbc:h2:mem:///foo", false);
    Connection connection = factory.create().block();
    StepVerifier.create(connection.close()).verifyComplete();
    StepVerifier.create(connection.setTransactionIsolationLevel(IsolationLevel.READ_COMMITTED)).verifyError(R2dbcNonTransientResourceException.class);
    factory.destroy();
}
Also used : Connection(io.r2dbc.spi.Connection) H2Connection(io.r2dbc.h2.H2Connection) Test(org.junit.jupiter.api.Test)

Example 7 with Connection

use of io.r2dbc.spi.Connection in project spring-framework by spring-projects.

the class R2dbcTransactionManagerUnitTests method testRollback.

@Test
void testRollback() {
    AtomicInteger commits = new AtomicInteger();
    when(connectionMock.commitTransaction()).thenReturn(Mono.fromRunnable(commits::incrementAndGet));
    AtomicInteger rollbacks = new AtomicInteger();
    when(connectionMock.rollbackTransaction()).thenReturn(Mono.fromRunnable(rollbacks::incrementAndGet));
    TransactionalOperator operator = TransactionalOperator.create(tm);
    ConnectionFactoryUtils.getConnection(connectionFactoryMock).doOnNext(connection -> {
        throw new IllegalStateException();
    }).as(operator::transactional).as(StepVerifier::create).verifyError(IllegalStateException.class);
    assertThat(commits).hasValue(0);
    assertThat(rollbacks).hasValue(1);
    verify(connectionMock).isAutoCommit();
    verify(connectionMock).beginTransaction();
    verify(connectionMock).rollbackTransaction();
    verify(connectionMock).close();
    verifyNoMoreInteractions(connectionMock);
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) ConnectionFactory(io.r2dbc.spi.ConnectionFactory) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) StepVerifier(reactor.test.StepVerifier) TransactionDefinition(org.springframework.transaction.TransactionDefinition) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) BDDMockito.when(org.mockito.BDDMockito.when) BDDMockito.verify(org.mockito.BDDMockito.verify) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionSynchronization(org.springframework.transaction.reactive.TransactionSynchronization) BDDMockito.never(org.mockito.BDDMockito.never) R2dbcBadGrammarException(io.r2dbc.spi.R2dbcBadGrammarException) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) Mono(reactor.core.publisher.Mono) BDDMockito.verifyNoMoreInteractions(org.mockito.BDDMockito.verifyNoMoreInteractions) Connection(io.r2dbc.spi.Connection) Test(org.junit.jupiter.api.Test) TransactionSynchronizationManager(org.springframework.transaction.reactive.TransactionSynchronizationManager) IsolationLevel(io.r2dbc.spi.IsolationLevel) Assertions.fail(org.assertj.core.api.Assertions.fail) BDDMockito.mock(org.mockito.BDDMockito.mock) Statement(io.r2dbc.spi.Statement) BDDMockito.reset(org.mockito.BDDMockito.reset) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.jupiter.api.Test)

Example 8 with Connection

use of io.r2dbc.spi.Connection in project spring-framework by spring-projects.

the class ScriptUtils method executeSqlScript.

/**
 * Execute the given SQL script.
 * <p>Statement separators and comments will be removed before executing
 * individual statements within the supplied script.
 * <p><strong>Warning</strong>: this method does <em>not</em> release the
 * provided {@link Connection}.
 * @param connection the R2DBC connection to use to execute the script; already
 * configured and ready to use
 * @param resource the resource (potentially associated with a specific encoding)
 * to load the SQL script from
 * @param dataBufferFactory the factory to create data buffers with
 * @param continueOnError whether or not to continue without throwing an exception
 * in the event of an error
 * @param ignoreFailedDrops whether or not to continue in the event of specifically
 * an error on a {@code DROP} statement
 * @param commentPrefixes the prefixes that identify single-line comments in the
 * SQL script (typically "--")
 * @param separator the script statement separator; defaults to
 * {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to
 * {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort; may be set to
 * {@value #EOF_STATEMENT_SEPARATOR} to signal that the script contains a
 * single statement without a separator
 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter
 * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter
 * @throws ScriptException if an error occurred while executing the SQL script
 * @see #DEFAULT_STATEMENT_SEPARATOR
 * @see #FALLBACK_STATEMENT_SEPARATOR
 * @see #EOF_STATEMENT_SEPARATOR
 * @see org.springframework.r2dbc.connection.ConnectionFactoryUtils#getConnection
 * @see org.springframework.r2dbc.connection.ConnectionFactoryUtils#releaseConnection
 */
public static Mono<Void> executeSqlScript(Connection connection, EncodedResource resource, DataBufferFactory dataBufferFactory, boolean continueOnError, boolean ignoreFailedDrops, String[] commentPrefixes, @Nullable String separator, String blockCommentStartDelimiter, String blockCommentEndDelimiter) throws ScriptException {
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL script from " + resource);
    }
    long startTime = System.currentTimeMillis();
    Mono<String> inputScript = readScript(resource, dataBufferFactory, separator).onErrorMap(IOException.class, ex -> new CannotReadScriptException(resource, ex));
    AtomicInteger statementNumber = new AtomicInteger();
    Flux<Void> executeScript = inputScript.flatMapIterable(script -> {
        String separatorToUse = separator;
        if (separatorToUse == null) {
            separatorToUse = DEFAULT_STATEMENT_SEPARATOR;
        }
        if (!EOF_STATEMENT_SEPARATOR.equals(separatorToUse) && !containsStatementSeparator(resource, script, separatorToUse, commentPrefixes, blockCommentStartDelimiter, blockCommentEndDelimiter)) {
            separatorToUse = FALLBACK_STATEMENT_SEPARATOR;
        }
        return splitSqlScript(resource, script, separatorToUse, commentPrefixes, blockCommentStartDelimiter, blockCommentEndDelimiter);
    }).concatMap(statement -> {
        statementNumber.incrementAndGet();
        return runStatement(statement, connection, resource, continueOnError, ignoreFailedDrops, statementNumber);
    });
    if (logger.isDebugEnabled()) {
        executeScript = executeScript.doOnComplete(() -> {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
        });
    }
    return executeScript.onErrorMap(ex -> !(ex instanceof ScriptException), ex -> new UncategorizedScriptException("Failed to execute database script from resource [" + resource + "]", ex)).then();
}
Also used : DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) LineNumberReader(java.io.LineNumberReader) Mono(reactor.core.publisher.Mono) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Connection(io.r2dbc.spi.Connection) Flux(reactor.core.publisher.Flux) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) EncodedResource(org.springframework.core.io.support.EncodedResource) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Result(io.r2dbc.spi.Result) Log(org.apache.commons.logging.Log) Nullable(org.springframework.lang.Nullable) LogFactory(org.apache.commons.logging.LogFactory) InputStream(java.io.InputStream) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 9 with Connection

use of io.r2dbc.spi.Connection in project spring-framework by spring-projects.

the class R2dbcTransactionManagerUnitTests method testRollbackFails.

@Test
@SuppressWarnings("unchecked")
void testRollbackFails() {
    when(connectionMock.rollbackTransaction()).thenReturn(Mono.defer(() -> Mono.error(new R2dbcBadGrammarException("Commit should fail"))), Mono.empty());
    TransactionalOperator operator = TransactionalOperator.create(tm);
    operator.execute(reactiveTransaction -> {
        reactiveTransaction.setRollbackOnly();
        return ConnectionFactoryUtils.getConnection(connectionFactoryMock).doOnNext(connection -> connection.createStatement("foo")).then();
    }).as(StepVerifier::create).verifyError(IllegalTransactionStateException.class);
    verify(connectionMock).isAutoCommit();
    verify(connectionMock).beginTransaction();
    verify(connectionMock).createStatement("foo");
    verify(connectionMock, never()).commitTransaction();
    verify(connectionMock).rollbackTransaction();
    verify(connectionMock).close();
    verifyNoMoreInteractions(connectionMock);
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) ConnectionFactory(io.r2dbc.spi.ConnectionFactory) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) StepVerifier(reactor.test.StepVerifier) TransactionDefinition(org.springframework.transaction.TransactionDefinition) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) BDDMockito.when(org.mockito.BDDMockito.when) BDDMockito.verify(org.mockito.BDDMockito.verify) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionSynchronization(org.springframework.transaction.reactive.TransactionSynchronization) BDDMockito.never(org.mockito.BDDMockito.never) R2dbcBadGrammarException(io.r2dbc.spi.R2dbcBadGrammarException) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) Mono(reactor.core.publisher.Mono) BDDMockito.verifyNoMoreInteractions(org.mockito.BDDMockito.verifyNoMoreInteractions) Connection(io.r2dbc.spi.Connection) Test(org.junit.jupiter.api.Test) TransactionSynchronizationManager(org.springframework.transaction.reactive.TransactionSynchronizationManager) IsolationLevel(io.r2dbc.spi.IsolationLevel) Assertions.fail(org.assertj.core.api.Assertions.fail) BDDMockito.mock(org.mockito.BDDMockito.mock) Statement(io.r2dbc.spi.Statement) BDDMockito.reset(org.mockito.BDDMockito.reset) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) R2dbcBadGrammarException(io.r2dbc.spi.R2dbcBadGrammarException) Test(org.junit.jupiter.api.Test)

Example 10 with Connection

use of io.r2dbc.spi.Connection in project spring-framework by spring-projects.

the class TransactionAwareConnectionFactoryProxyUnitTests method shouldEmitBoundConnection.

@Test
void shouldEmitBoundConnection() {
    when(connectionMock1.beginTransaction()).thenReturn(Mono.empty());
    when(connectionMock1.commitTransaction()).thenReturn(Mono.empty());
    when(connectionMock1.close()).thenReturn(Mono.empty());
    TransactionalOperator rxtx = TransactionalOperator.create(tm);
    AtomicReference<Connection> transactionalConnection = new AtomicReference<>();
    TransactionAwareConnectionFactoryProxy proxyCf = new TransactionAwareConnectionFactoryProxy(connectionFactoryMock);
    ConnectionFactoryUtils.getConnection(connectionFactoryMock).doOnNext(transactionalConnection::set).flatMap(connection -> proxyCf.create().doOnNext(wrappedConnection -> assertThat(((Wrapped<?>) wrappedConnection).unwrap()).isSameAs(connection))).as(rxtx::transactional).flatMapMany(Connection::close).as(StepVerifier::create).verifyComplete();
    verifyNoInteractions(connectionMock2);
    verifyNoInteractions(connectionMock3);
    verify(connectionFactoryMock, times(1)).create();
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) ConnectionFactory(io.r2dbc.spi.ConnectionFactory) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) StepVerifier(reactor.test.StepVerifier) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) BDDMockito.times(org.mockito.BDDMockito.times) Mono(reactor.core.publisher.Mono) AtomicReference(java.util.concurrent.atomic.AtomicReference) BDDMockito.when(org.mockito.BDDMockito.when) Connection(io.r2dbc.spi.Connection) Test(org.junit.jupiter.api.Test) BDDMockito.verify(org.mockito.BDDMockito.verify) Wrapped(io.r2dbc.spi.Wrapped) BDDMockito.mock(org.mockito.BDDMockito.mock) BDDMockito.verifyNoInteractions(org.mockito.BDDMockito.verifyNoInteractions) Wrapped(io.r2dbc.spi.Wrapped) Connection(io.r2dbc.spi.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.jupiter.api.Test)

Aggregations

Connection (io.r2dbc.spi.Connection)11 Test (org.junit.jupiter.api.Test)10 Mono (reactor.core.publisher.Mono)6 StepVerifier (reactor.test.StepVerifier)6 H2Connection (io.r2dbc.h2.H2Connection)5 ConnectionFactory (io.r2dbc.spi.ConnectionFactory)5 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 BeforeEach (org.junit.jupiter.api.BeforeEach)4 BDDMockito.mock (org.mockito.BDDMockito.mock)4 BDDMockito.verify (org.mockito.BDDMockito.verify)4 BDDMockito.when (org.mockito.BDDMockito.when)4 IsolationLevel (io.r2dbc.spi.IsolationLevel)3 R2dbcBadGrammarException (io.r2dbc.spi.R2dbcBadGrammarException)3 Statement (io.r2dbc.spi.Statement)3 Assertions.fail (org.assertj.core.api.Assertions.fail)3 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)3 ArgumentMatchers.anyBoolean (org.mockito.ArgumentMatchers.anyBoolean)3 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)3 BDDMockito.never (org.mockito.BDDMockito.never)3