Issue with read-only embedded postgres DB using spring boot and flyway migrations

534 Views Asked by At

Use case I am trying to have 2 datasources in my application. One for read-only connection and another for read-write connection.

Configuration I have configured my JPA repositories to use different connections. In my IT case, I have the following configuration in my application.yaml

spring:
  datasource:
    url: jdbc:postgresql://127.0.0.1:5432/app
    username: postgres
    password:
  jpa:
    show-sql: false
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQL95Dialect
        jdbc:
          lob:
            non_contextual_creation: true

Issue in local build

When I run the test in my local, the test fails while trying to create the readOnlyDataSource with the error

Caused by: org.postgresql.util.PSQLException: FATAL: database "app" does not exist

Where as when I change the DB url to jdbc:postgresql://127.0.0.1:5432/postgres, the local test passes. Beans are getting created properly.

Issue in CI build

In CI build though, no matter the DB name as app or postgres , the test fails with

Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'readOnlyDataSource' threw exception; nested exception is org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

I have flyway migrations defined, and I can see in the logs that migrations ran successfully once with the primary read-write datasource. After created the read only connection, seeing the log migrations are up to date, so I think it didn't try to run again using RO connection.

Also I have used @Primary on my read-write configuration, so that flyway knows to use that datasource for its migrations and not the read-only connection.

@Bean(name = ["primaryDataSource"])
    @Primary
    @ConfigurationProperties("spring.datasource.configuration")
    fun primaryDataSource(dataSourceProperties: DataSourceProperties): HikariDataSource {
        return dataSourceProperties.initializeDataSourceBuilder()
            .type(HikariDataSource::class.java)
            .build()
    }

Is there any restrictions on having read-only connection with embedded postgres?

0

There are 0 best solutions below