io.r2dbc.spi.Result Java Examples

The following examples show how to use io.r2dbc.spi.Result. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestcontainersR2DBCConnectionFactoryTest.java    From testcontainers-java with MIT License 7 votes vote down vote up
@Test
public void reusesUntilConnectionFactoryIsClosed() {
    String url = "r2dbc:tc:postgresql:///db?TC_IMAGE_TAG=10-alpine";
    ConnectionFactory connectionFactory = ConnectionFactories.get(url);

    Integer updated = Flux
        .usingWhen(
            connectionFactory.create(),
            connection -> {
                return Mono
                    .from(connection.createStatement("CREATE TABLE test(id integer PRIMARY KEY)").execute())
                    .thenMany(connection.createStatement("INSERT INTO test(id) VALUES(123)").execute())
                    .flatMap(Result::getRowsUpdated);
            },
            Connection::close
        )
        .blockFirst();

    assertThat(updated).isEqualTo(1);

    Flux<Long> select = Flux
        .usingWhen(
            Flux.defer(connectionFactory::create),
            connection -> {
                return Flux
                    .from(connection.createStatement("SELECT COUNT(*) FROM test").execute())
                    .flatMap(it -> it.map((row, meta) -> (Long) row.get(0)));
            },
            Connection::close
        );

    Long rows = select.blockFirst();

    assertThat(rows).isEqualTo(1);

    close(connectionFactory);

    Assertions
        .assertThatThrownBy(select::blockFirst)
        .isInstanceOf(PostgresqlException.class)
        // relation "X" does not exists
        // https://github.com/postgres/postgres/blob/REL_10_0/src/backend/utils/errcodes.txt#L349
        .returns("42P01", e -> ((PostgresqlException) e).getErrorDetails().getCode());
}
 
Example #2
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 6 votes vote down vote up
@Test
default void batch() {
    getJdbcOperations().execute("INSERT INTO test VALUES (100)");

    Mono.from(getConnectionFactory().create())
        .flatMapMany(connection -> Flux.from(connection

            .createBatch()
            .add("INSERT INTO test VALUES(200)")
            .add("SELECT value FROM test")
            .execute())

            .concatWith(close(connection)))
        .flatMap(Result::getRowsUpdated)
        .then()
        .as(StepVerifier::create)
        .verifyComplete();
}
 
Example #3
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 6 votes vote down vote up
@Test
default void sameAutoCommitLeavesTransactionUnchanged() {
    Mono.from(getConnectionFactory().create())
        .flatMapMany(connection ->
            Flux.from(connection.setAutoCommit(false))
                .thenMany(connection.beginTransaction())
                .thenMany(connection.createStatement("INSERT INTO test VALUES(200)").execute())
                .flatMap(Result::getRowsUpdated)
                .thenMany(connection.setAutoCommit(false))
                .thenMany(connection.rollbackTransaction())
                .thenMany(connection.createStatement("SELECT value FROM test").execute())
                .flatMap(it -> it.map((row, metadata) -> row.get("value")))
                .concatWith(close(connection))
        )
        .as(StepVerifier::create)
        .verifyComplete();
}
 
Example #4
Source File: SpannerStatementTest.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
@Test
public void readOneResultSetQueryTest() {
  PartialResultSet p1 = PartialResultSet.newBuilder().setMetadata(
      this.resultSetMetadata
  ).setChunkedValue(false)
      .addValues(this.a1)
      .addValues(this.a2).build();

  Flux<PartialResultSet> inputs = Flux.just(p1);

  when(this.mockClient.executeStreamingSql(
      same(this.mockContext), any(), any(), any())).thenReturn(inputs);

  Mono<Result> resultMono =
      Mono.from(new SpannerStatement(
          this.mockClient, this.mockContext, "SELECT * FROM table", TEST_CONFIG).execute());

  StepVerifier.create(resultMono.flatMap(r -> Mono.from(r.getRowsUpdated())))
      .expectNext(0)
      .verifyComplete();
  StepVerifier.create(resultMono.flatMapMany(r -> r
      .map((row, meta) -> row.get(0, Boolean.class).toString() + "-" + row.get(1, String.class))))
      .expectNext("false-abc")
      .verifyComplete();
}
 
Example #5
Source File: SpannerTestKit.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
@Override
@Test
public void changeAutoCommitCommitsTransaction() {
  Mono.from(getConnectionFactory().create())
      .flatMapMany(connection ->
          Flux.from(connection.setAutoCommit(false))
              .thenMany(connection.beginTransaction())
              // DML syntax fix adding column list
              .thenMany(connection.createStatement(
                  "INSERT INTO test (value) VALUES(200)").execute())
              .flatMap(Result::getRowsUpdated)
              .thenMany(connection.setAutoCommit(true))
              .thenMany(connection.createStatement("SELECT value FROM test").execute())
              .flatMap(it -> it.map((row, metadata) -> row.get("value")))
              .concatWith(close(connection))
      )
      .as(StepVerifier::create)
      // Cloud Spanner only has a 64 bit "integer"
      .expectNext(200L)
      .as("autoCommit(true) committed the transaction. Expecting a value to be present")
      .verifyComplete();
}
 
Example #6
Source File: SpannerTestKit.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
@Override
@Test
public void sameAutoCommitLeavesTransactionUnchanged() {
  Mono.from(getConnectionFactory().create())
      .flatMapMany(connection ->
          Flux.from(connection.setAutoCommit(false))
              .thenMany(connection.beginTransaction())
              .thenMany(connection.createStatement(
                  "INSERT INTO test (value) VALUES(200)").execute())
              .flatMap(Result::getRowsUpdated)
              .thenMany(connection.setAutoCommit(false))
              .thenMany(connection.rollbackTransaction())
              .thenMany(connection.createStatement("SELECT value FROM test").execute())
              .flatMap(it -> it.map((row, metadata) -> row.get("value")))
              .concatWith(close(connection))
      )
      .as(StepVerifier::create)
      .verifyComplete();
}
 
Example #7
Source File: SpannerIT.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoopUpdate() {
  Result result = Mono.from(connectionFactory.create())
      .delayUntil(c -> c.beginTransaction())
      .flatMap(c -> Mono.from(c.createStatement(
          "UPDATE BOOKS set author = 'blah2' where title = 'asdasdf_dont_exist'").execute()))
      .block();

  int rowsUpdated = Mono.from(result.getRowsUpdated()).block();
  assertThat(rowsUpdated).isEqualTo(0);

  List<String> rowsReturned =
      Flux.from(result.map((row, metadata) -> row.toString()))
          .collectList()
          .block();
  assertThat(rowsReturned).isEmpty();
}
 
Example #8
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 6 votes vote down vote up
@Test
default void changeAutoCommitCommitsTransaction() {
    Mono.from(getConnectionFactory().create())
        .flatMapMany(connection ->
            Flux.from(connection.setAutoCommit(false))
                .thenMany(connection.beginTransaction())
                .thenMany(connection.createStatement("INSERT INTO test VALUES(200)").execute())
                .flatMap(Result::getRowsUpdated)
                .thenMany(connection.setAutoCommit(true))
                .thenMany(connection.createStatement("SELECT value FROM test").execute())
                .flatMap(it -> it.map((row, metadata) -> row.get("value")))
                .concatWith(close(connection))
        )
        .as(StepVerifier::create)
        .expectNext(200).as("autoCommit(true) committed the transaction. Expecting a value to be present")
        .verifyComplete();
}
 
Example #9
Source File: QueryIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static <T> Flux<Optional<T>> extractOptionalField(Result result, Type type) {
    if (type instanceof Class<?>) {
        return Flux.from(result.map((row, metadata) -> Optional.ofNullable(row.get(0, (Class<T>) type))));
    }
    return Flux.from(result.map((row, metadata) -> Optional.ofNullable(((MySqlRow) row).get(0, (ParameterizedType) type))));
}
 
Example #10
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 5 votes vote down vote up
@Test
default void clobInsert() {
    Mono.from(getConnectionFactory().create())
        .flatMapMany(connection -> {
            Statement statement = connection.createStatement(String.format("INSERT INTO clob_test VALUES (%s)", getPlaceholder(0)));
            bind(statement, getIdentifier(0), Clob.from(Mono.just("test-value")));
            return Flux.from(statement.execute())
                .flatMap(Result::getRowsUpdated)
                .concatWith(close(connection));
        })
        .as(StepVerifier::create)
        .expectNextCount(1).as("rows inserted")
        .verifyComplete();
}
 
Example #11
Source File: SpannerStatement.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<? extends Result> execute() {
  if (this.statementType == StatementType.DDL) {
    return this.client
        .executeDdl(
            this.config.getFullyQualifiedDatabaseName(),
            Collections.singletonList(this.sql),
            this.config.getDdlOperationTimeout(),
            this.config.getDdlOperationPollInterval())
        .map(operation -> new SpannerResult(Flux.empty(), Mono.just(0)));
  } else if (this.statementType == StatementType.DML && !this.ctx.isTransactionPartitionedDml()) {

    List<ExecuteBatchDmlRequest.Statement> dmlStatements =
        this.statementBindings.getBindings().stream()
            .map(struct ->
                ExecuteBatchDmlRequest.Statement.newBuilder()
                    .setSql(this.sql)
                    .setParams(struct)
                    .putAllParamTypes(this.statementBindings.getTypes())
                    .build())
            .collect(Collectors.toList());

    return this.client.executeBatchDml(this.ctx, dmlStatements)
        .map(partialResultSet -> Math.toIntExact(partialResultSet.getStats().getRowCountExact()))
        .map(rowCount -> new SpannerResult(Flux.empty(), Mono.just(rowCount)));
  }

  Flux<Struct> structFlux = Flux.fromIterable(this.statementBindings.getBindings());
  return structFlux.flatMap(this::runStreamingSql);
}
 
Example #12
Source File: SpannerBatch.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<? extends Result> execute() {
  return this.client.executeBatchDml(this.ctx, this.statements)
      .map(resultSet -> {
        int count = Math.toIntExact(resultSet.getStats().getRowCountExact());
        return new SpannerResult(Flux.empty(), Mono.just(count));
      });
}
 
Example #13
Source File: QueryIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static <T> Flux<Optional<T>> extractOptionalField(Result result, Type type) {
    if (type instanceof Class<?>) {
        return Flux.from(result.map((row, metadata) -> Optional.ofNullable(row.get(0, (Class<T>) type))));
    }
    return Flux.from(result.map((row, metadata) -> Optional.ofNullable(((MySqlRow) row).get(0, (ParameterizedType) type))));
}
 
Example #14
Source File: QueryIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
static Flux<Integer> extractId(Result result) {
    return Flux.from(result.map((row, metadata) -> row.get(0, Integer.class)));
}
 
Example #15
Source File: IntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
static Mono<Integer> extractRowsUpdated(Result result) {
    return Mono.from(result.getRowsUpdated());
}
 
Example #16
Source File: MockBatch.java    From r2dbc-spi with Apache License 2.0 4 votes vote down vote up
private MockBatch(Flux<Result> results) {
    this.results = Assert.requireNonNull(results, "results must not be null");
}
 
Example #17
Source File: MockBatch.java    From r2dbc-spi with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<Result> execute() {
    return this.results;
}
 
Example #18
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 4 votes vote down vote up
static Mono<List<Integer>> extractColumns(Result result) {
    return Flux.from(result
        .map((row, rowMetadata) -> row.get("value", Integer.class)))
        .collectList();
}
 
Example #19
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 4 votes vote down vote up
static Mono<Integer> extractRowsUpdated(Result result) {
    return Mono.from(result.getRowsUpdated());
}
 
Example #20
Source File: IntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
static Mono<Integer> extractRowsUpdated(Result result) {
    return Mono.from(result.getRowsUpdated());
}
 
Example #21
Source File: MockStatement.java    From r2dbc-spi with Apache License 2.0 4 votes vote down vote up
private MockStatement(Flux<Result> results) {
    this.results = Assert.requireNonNull(results, "results must not be null");
}
 
Example #22
Source File: MockStatement.java    From r2dbc-spi with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<Result> execute() {
    return this.results;
}
 
Example #23
Source File: QueryIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
static Flux<Integer> extractId(Result result) {
    return Flux.from(result.map((row, metadata) -> row.get(0, Integer.class)));
}