io.r2dbc.spi.ConnectionFactory Java Examples

The following examples show how to use io.r2dbc.spi.ConnectionFactory. 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: CloudConfig.java    From cf-butler with Apache License 2.0 8 votes vote down vote up
@Bean
@ConditionalOnProperty(VCAP_SERVICE_VARIABLE)
ConnectionFactory connectionFactory() {
    R2dbcProperties properties = r2dbcProperties();
    ConnectionFactoryOptions.Builder builder = ConnectionFactoryOptions
            .parse(properties.getUrl()).mutate();
    String username = properties.getUsername();
    if (StringUtils.hasText(username)) {
        builder.option(ConnectionFactoryOptions.USER, username);
    }
    String password = properties.getPassword();
    if (StringUtils.hasText(password)) {
        builder.option(ConnectionFactoryOptions.PASSWORD, password);
    }
    String databaseName = properties.getName();
    if (StringUtils.hasText(databaseName)) {
        builder.option(ConnectionFactoryOptions.DATABASE, databaseName);
    }
    if (properties.getProperties() != null) {
        properties.getProperties()
                .forEach((key, value) -> builder
                        .option(Option.valueOf(key), value));
    }
    return ConnectionFactories.get(builder.build());
}
 
Example #2
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 #3
Source File: DatasourceConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) {
    
    ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl());
    Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);
    if ( !StringUtil.isNullOrEmpty(properties.getUser())) {
        ob = ob.option(USER, properties.getUser());
    }

    if ( !StringUtil.isNullOrEmpty(properties.getPassword())) {
        ob = ob.option(PASSWORD, properties.getPassword());
    }
    
    ConnectionFactory cf = ConnectionFactories.get(ob.build());
    return cf;
}
 
Example #4
Source File: AbstractR2DBCDatabaseContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
protected void runTestQuery(ConnectionFactory connectionFactory) {
    try {
        int expected = 42;
        Number result = Flux
            .usingWhen(
                connectionFactory.create(),
                connection -> connection.createStatement(createTestQuery(expected)).execute(),
                Connection::close
            )
            .flatMap(it -> it.map((row, meta) -> (Number) row.get(0)))
            .blockFirst();

        assertThat(result)
            .isNotNull()
            .returns(expected, Number::intValue);
    } finally {
        if (connectionFactory instanceof Closeable) {
            Mono.from(((Closeable) connectionFactory).close()).block();
        }
    }
}
 
Example #5
Source File: DatabaseConfig.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@Override
    @Bean
    public ConnectionFactory connectionFactory() {
        //ConnectionFactory factory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");

        //see: https://github.com/spring-projects/spring-data-r2dbc/issues/269
//        return new H2ConnectionFactory(
//                H2ConnectionConfiguration.builder()
//                        //.inMemory("testdb")
//                        .file("./testdb")
//                        .username("user")
//                        .password("password").build()
//        );

        return H2ConnectionFactory.inMemory("testdb");
    }
 
Example #6
Source File: DatabaseConfig.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Bean
public ConnectionFactory connectionFactory() {
    //ConnectionFactory factory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
    return new PostgresqlConnectionFactory(
            PostgresqlConnectionConfiguration.builder()
                    .host("localhost")
                    .database("test")
                    .username("user")
                    .password("password").build()
    );
}
 
Example #7
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 6 votes vote down vote up
@Override
public ConnectionFactory connectionFactory() {
	PostgresqlConnectionConfiguration config = PostgresqlConnectionConfiguration
		.builder()
		.host("localhost")
		.password("0rd3rs")
		.username("orders")
		.database("orders")
		.build();
	return new PostgresqlConnectionFactory(config);
}
 
Example #8
Source File: DatasourceConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public CommandLineRunner initDatabase(ConnectionFactory cf) {

    return (args) ->
      Flux.from(cf.create())
          .flatMap(c -> 
            Flux.from(c.createBatch()
              .add("drop table if exists Account")
              .add("create table Account(" +
                "id IDENTITY(1,1)," +
                "iban varchar(80) not null," +
                "balance DECIMAL(18,2) not null)")
              .add("insert into Account(iban,balance)" +
                "values('BR430120980198201982',100.00)")
              .add("insert into Account(iban,balance)" +
                "values('BR430120998729871000',250.00)")
              .execute())
            .doFinally((st) -> c.close())
          )
          .log()
          .blockLast();
}
 
Example #9
Source File: SpringDataR2dbcApp.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Bean
public static ConnectionFactory spannerConnectionFactory() {
  ConnectionFactory connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
      .option(Option.valueOf("project"), GCP_PROJECT)
      .option(DRIVER, DRIVER_NAME)
      .option(INSTANCE, SPANNER_INSTANCE)
      .option(DATABASE, SPANNER_DATABASE)
      .build());

  return connectionFactory;
}
 
Example #10
Source File: ConnectionFactoryConfig.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
@Bean
@Override
public ConnectionFactory connectionFactory() {
  return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
      .host(POSTGRE_SQL_CONTAINER.getContainerIpAddress())
      .port(POSTGRE_SQL_CONTAINER.getMappedPort(POSTGRESQL_PORT))
      .database(POSTGRE_SQL_CONTAINER.getDatabaseName())
      .username(POSTGRE_SQL_CONTAINER.getUsername())
      .password(POSTGRE_SQL_CONTAINER.getPassword())
      .build());
}
 
Example #11
Source File: SpannerR2dbcDialectProvider.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<R2dbcDialect> getDialect(ConnectionFactory connectionFactory) {
  if (connectionFactory.getMetadata().getName().equals(SpannerConnectionFactoryMetadata.NAME)) {
    return Optional.of(new SpannerR2dbcDialect());
  }
  return Optional.empty();
}
 
Example #12
Source File: SpannerQueryUtil.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a DML query and returns the rows updated.
 */
static int executeDmlQuery(ConnectionFactory connectionFactory, String sql) {
  Connection connection = Mono.from(connectionFactory.create()).block();

  Mono.from(connection.beginTransaction()).block();
  int rowsUpdated = Mono.from(connection.createStatement(sql).execute())
      .flatMap(result -> Mono.from(result.getRowsUpdated()))
      .block();
  Mono.from(connection.commitTransaction()).block();

  return rowsUpdated;
}
 
Example #13
Source File: AbstractR2DBCDatabaseContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public final void testGetOptions() {
    try (T container = createContainer()) {
        container.start();

        ConnectionFactory connectionFactory = ConnectionFactories.get(getOptions(container));
        runTestQuery(connectionFactory);
    }
}
 
Example #14
Source File: SpannerQueryUtil.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a read query and runs the provided {@code mappingFunction} on the elements returned.
 */
static <T> List<T> executeReadQuery(
    ConnectionFactory connectionFactory,
    String sql,
    BiFunction<Row, RowMetadata, T> mappingFunction) {

  return Mono.from(connectionFactory.create())
      .map(connection -> connection.createStatement(sql))
      .flatMapMany(statement -> statement.execute())
      .flatMap(spannerResult -> spannerResult.map(mappingFunction))
      .collectList()
      .block();
}
 
Example #15
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public ConnectionFactory connectionFactory() {
	return new PostgresqlConnectionFactory(
		PostgresqlConnectionConfiguration
			.builder()
			.password("0rd3rs")
			.username("orders")
			.host("localhost")
			.database("orders")
			.applicationName("orders")
			.build()
	);
}
 
Example #16
Source File: Hidden.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Override
public ConnectionFactory create(ConnectionFactoryOptions options) {
    options = sanitize(options);
    options = removeProxying(options);

    return new TestcontainersR2DBCConnectionFactory(options);
}
 
Example #17
Source File: R2DBCDatabaseContainerProvider.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Nullable
default ConnectionFactoryMetadata getMetadata(ConnectionFactoryOptions options) {
    ConnectionFactoryOptions.Builder builder = options.mutate();
    if (!options.hasOption(ConnectionFactoryOptions.HOST)) {
        builder.option(ConnectionFactoryOptions.HOST, "localhost");
    }
    if (!options.hasOption(ConnectionFactoryOptions.PORT)) {
        builder.option(ConnectionFactoryOptions.PORT, 65535);
    }

    ConnectionFactory connectionFactory = ConnectionFactories.find(builder.build());
    return connectionFactory != null ? connectionFactory.getMetadata() : null;
}
 
Example #18
Source File: SpannerConnectionFactoryProviderTest.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateFactoryWithUrl() {
  ConnectionFactoryOptions optionsWithUrl =
      ConnectionFactoryOptions.builder()
          .option(DRIVER, DRIVER_NAME)
          .option(URL, "r2dbc:spanner://spanner.googleapis.com:443/projects/"
              + "myproject/instances/myinstance/databases/mydatabase")
          .build();

  ConnectionFactory spannerConnectionFactory =
      this.spannerConnectionFactoryProvider.create(optionsWithUrl);
  assertThat(spannerConnectionFactory).isNotNull();
  assertThat(spannerConnectionFactory).isInstanceOf(SpannerConnectionFactory.class);
}
 
Example #19
Source File: R2dbcConfig.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory() {
    return ConnectionFactories.get(ConnectionFactoryOptions.builder()
            .option(DRIVER,"pool")
            .option(PROTOCOL,"postgresql")
            .option(HOST, host)
            .option(PORT, port)
            .option(USER, username)
            .option(PASSWORD, password)
            .option(DATABASE, name)
            .build());
}
 
Example #20
Source File: SpannerConnectionFactoryProvider.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Override
public ConnectionFactory create(ConnectionFactoryOptions connectionFactoryOptions) {

  SpannerConnectionConfiguration config = createConfiguration(connectionFactoryOptions);

  if (this.client == null) {
    // GrpcClient should only be instantiated if/when a SpannerConnectionFactory is needed.
    this.client = new GrpcClient(config.getCredentials());
  }
  return new SpannerConnectionFactory(this.client, config);
}
 
Example #21
Source File: SpannerConnectionFactoryProviderTest.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreate() {
  ConnectionFactory spannerConnectionFactory =
      this.spannerConnectionFactoryProvider.create(SPANNER_OPTIONS);
  assertThat(spannerConnectionFactory).isNotNull();
  assertThat(spannerConnectionFactory).isInstanceOf(SpannerConnectionFactory.class);
}
 
Example #22
Source File: AbstractR2DBCDatabaseContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Test
public final void testGetMetadata() {
    ConnectionFactory connectionFactory = ConnectionFactories.get(createR2DBCUrl());
    ConnectionFactoryMetadata metadata = connectionFactory.getMetadata();
    assertThat(metadata).isNotNull();
}
 
Example #23
Source File: TestcontainersR2DBCConnectionFactoryTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
private static void close(ConnectionFactory connectionFactory) {
    Mono.from(((Closeable) connectionFactory).close()).block();
}
 
Example #24
Source File: R2dbcConfig.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Bean
public DatabaseClient databaseClient(ConnectionFactory connectionFactory) {
    return DatabaseClient.create(connectionFactory);
}
 
Example #25
Source File: DbmsSettings.java    From cf-butler with Apache License 2.0 4 votes vote down vote up
@Autowired
public DbmsSettings(ConnectionFactory factory) {
    this.factory = factory;
}
 
Example #26
Source File: ConnectionFactoryConfig.java    From spring-data-examples with Apache License 2.0 4 votes vote down vote up
@Bean
public ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) {
  return new R2dbcTransactionManager(connectionFactory);
}
 
Example #27
Source File: ReactiveAccountDao.java    From tutorials with MIT License 4 votes vote down vote up
public ReactiveAccountDao(ConnectionFactory connectionFactory) {
    this.connectionFactory = connectionFactory;
}
 
Example #28
Source File: AbstractR2DBCDatabaseContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Test
public final void testUrlSupport() {
    ConnectionFactory connectionFactory = ConnectionFactories.get(createR2DBCUrl());
    runTestQuery(connectionFactory);
}
 
Example #29
Source File: ConnectionPublisher.java    From testcontainers-java with MIT License 4 votes vote down vote up
ConnectionPublisher(Supplier<CompletableFuture<ConnectionFactory>> futureSupplier) {
    this.futureSupplier = futureSupplier;
}
 
Example #30
Source File: DataSourceConfiguration.java    From event-sourcing-microservices-example with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public ConnectionFactory connectionFactory() {
	return getPostgresqlConnectionFactory();
}