11package io.sdkman.broker.adapter.secondary.persistence
22
33import arrow.core.Either
4- import arrow.core.flatMap
54import arrow.core.getOrElse
6- import arrow.core.left
7- import arrow.core.right
85import arrow.core.toOption
96import io.sdkman.broker.domain.repository.HealthCheckFailure
107import io.sdkman.broker.domain.repository.HealthCheckSuccess
@@ -18,8 +15,11 @@ class PostgresHealthRepository(private val dataSource: DataSource) : HealthRepos
1815 private val logger = LoggerFactory .getLogger(this ::class .java)
1916
2017 override fun checkConnectivity (): Either <HealthCheckFailure , HealthCheckSuccess > =
21- Either .catch { dataSource.connection }
22- .flatMap { executeHealthCheck(it) }
18+ Either .catch {
19+ dataSource.connection.use { connection ->
20+ executeHealthCheck(connection).getOrElse { throw it }
21+ }
22+ }
2323 .map { HealthCheckSuccess }
2424 .mapLeft { exception ->
2525 logger.error(" PostgreSQL health check failed: {}" , exception.message, exception)
@@ -35,11 +35,13 @@ class PostgresHealthRepository(private val dataSource: DataSource) : HealthRepos
3535 private fun ResultSet.isHealthCheckSuccessful (): Boolean = this .next() && this .getInt(1 ) == 1
3636
3737 private fun executeHealthCheck (connection : Connection ): Either <RuntimeException , Unit > =
38- Either .catch { connection.prepareStatement(" SELECT 1" ) }.flatMap { statement ->
39- Either .catch { statement.executeQuery() }.flatMap { resultSet: ResultSet ->
40- when {
41- resultSet.isHealthCheckSuccessful() -> Unit .right()
42- else -> RuntimeException (" PostgreSQL health check query did not return expected result" ).left()
38+ Either .catch {
39+ connection.prepareStatement(" SELECT 1" ).use { statement ->
40+ statement.executeQuery().use { resultSet ->
41+ when {
42+ resultSet.isHealthCheckSuccessful() -> Unit
43+ else -> throw RuntimeException (" PostgreSQL health check query did not return expected result" )
44+ }
4345 }
4446 }
4547 }.mapLeft { RuntimeException (it) }
0 commit comments